LCOV - code coverage report
Current view: top level - src - onewire.c (source / functions) Coverage Total Hit
Test: stm32-async-1wire core coverage Lines: 95.6 % 205 196
Test Date: 2026-11-28 11:52:24 Functions: 96.6 % 29 28
Branches: 89.2 % 111 99

             Branch data     Line data    Source code
       1                 :             : #include "onewire.h"
       2                 :             : #include "ow_glue.h"
       3                 :             : #include "ow_port.h"
       4                 :             : #include "ow_profile.h"
       5                 :             : 
       6                 :             : #include <string.h>
       7                 :             : 
       8                 :             : #if OW_STATS_ENABLE
       9                 :             : /* Weak fallback for a build that links the engine without ow_stats.c (the
      10                 :             :  * ds2431-only test): the port always calls the overrun hook. */
      11                 :           0 : __attribute__((weak)) void ow_stats_capture_overrun(void) {}
      12                 :             : #endif
      13                 :             : 
      14                 :             : /* Reject-path contract: out-of-range sizes fail soft (return 0) in every
      15                 :             :  * build. Under the test harness the violation additionally traps via
      16                 :             :  * assert, so a test feeding a bad size fails loudly instead of silently
      17                 :             :  * passing. Assert lives only here (never in firmware): __assert_func pulls
      18                 :             :  * fprintf/__sf into the image (~5 KB text, ~400 B .bss), which the exact
      19                 :             :  * RAM budgets would otherwise silently absorb.
      20                 :             :  * Test: tests/test/test_param_guard.c (release-semantics variant). */
      21                 :             : #if defined(DS18B20_TEST_HARNESS) || defined(OW_TEST_PARAM_GUARD)
      22                 :             : #include <assert.h>
      23                 :             : #define ONEWIRE_PARAM_CHECK(cond) \
      24                 :             :     do {                          \
      25                 :             :         assert(cond);             \
      26                 :             :     } while (0)
      27                 :             : #else
      28                 :             : #define ONEWIRE_PARAM_CHECK(cond) ((void)0)
      29                 :             : #endif
      30                 :             : 
      31                 :             : /**
      32                 :             :  * @defgroup ONEWIRE_Private_Constants ONEWIRE Private Constants
      33                 :             :  * @{
      34                 :             :  */
      35                 :             : 
      36                 :             : /** @brief Minimum reset pulse duration in microseconds */
      37                 :             : #define RESET_PULSE_MIN 480U
      38                 :             : /** @brief Maximum reset pulse duration in microseconds */
      39                 :             : #define RESET_PULSE_MAX 540U
      40                 :             : /** @brief Minimum presence pulse positive width in microseconds */
      41                 :             : #define POSITIVE_WIDTH_MIN 15U
      42                 :             : /** @brief Maximum presence pulse positive width in microseconds */
      43                 :             : #define POSITIVE_WIDTH_MAX 60U
      44                 :             : /** @brief Minimum presence pulse negative width in microseconds */
      45                 :             : #define NEGATIVE_WIDTH_MIN 60U
      46                 :             : /** @brief Maximum presence pulse negative width in microseconds */
      47                 :             : #define NEGATIVE_WIDTH_MAX 240U
      48                 :             : /** @brief Calculated minimum presence pulse timing */
      49                 :             : #define PRESENCE_PULSE_MIN (RESET_PULSE_MIN + POSITIVE_WIDTH_MIN + NEGATIVE_WIDTH_MIN)
      50                 :             : /** @brief Calculated maximum presence pulse timing */
      51                 :             : #define PRESENCE_PULSE_MAX (RESET_PULSE_MAX + POSITIVE_WIDTH_MAX + NEGATIVE_WIDTH_MAX)
      52                 :             : /** @brief CRC8 polynomial of the Dallas/Maxim 1-Wire algorithm */
      53                 :             : #define ONEWIRE_CRC8_POLY 0x8C
      54                 :             : /** @brief CRC16 polynomial of the Maxim 1-Wire algorithm (reflected 0x8005) */
      55                 :             : #define ONEWIRE_CRC16_POLY 0xA001u
      56                 :             : 
      57                 :             : /* Hardware contract: TIM1 RCR is 8-bit (RCR = slots - 1), so one pass is
      58                 :             :  * limited to 256 slots / 32 bytes. Locks the public limits against drift. */
      59                 :             : _Static_assert(ONEWIRE_MAX_SLOTS == 256u, "ONEWIRE_MAX_SLOTS must match 8-bit TIM1 RCR");
      60                 :             : _Static_assert(ONEWIRE_MAX_READ_BYTES == 32u, "ONEWIRE_MAX_READ_BYTES must be 256 slots / 8 bits");
      61                 :             : _Static_assert(ONEWIRE_ROM_BITS <= ONEWIRE_MAX_SLOTS, "search ROM pass must fit one RCR window");
      62                 :             : 
      63                 :             : /** @} */
      64                 :             : 
      65                 :             : /** @brief Read pulse durations reloaded by DMA for the merged search operation
      66                 :             :  *        (the CCR3 feed DMA reads from this). Entry 0 is loaded at the CH2
      67                 :             :  *        end-of-slot compare at the end of slot 1 and sets the read slot 2
      68                 :             :  *        length, entry 1 sets slot 3, and ONEWIRE_RELEASE_PULSE is written
      69                 :             :  *        during slot 3 so the one-pulse timer stops with the line released to
      70                 :             :  *        idle HIGH (hardware bus release). */
      71                 :             : static const ow_pulse_t search_read_pulse[3] = {ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_RELEASE_PULSE};
      72                 :             : 
      73                 :             : /** @brief Pre-encoded Search ROM command (0xF0), LSB-first, plus the trailing
      74                 :             :  *         ONEWIRE_RELEASE_PULSE the CCR3-feed DMA consumes as its final
      75                 :             :  *         transfer (hardware bus release). The command byte never changes, so
      76                 :             :  *         it lives in flash instead of the RAM search context — same pattern
      77                 :             :  *         as search_read_pulse above.
      78                 :             :  *  @note 0xF0 = 0b11110000, sent LSB-first: 0,0,0,0,1,1,1,1. */
      79                 :             : static const ow_pulse_t search_cmd_rom[ONEWIRE_BITS_PER_BYTE + 1] = {
      80                 :             :     ONEWIRE_ZERO_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ZERO_PULSE,
      81                 :             :     ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE,
      82                 :             :     ONEWIRE_RELEASE_PULSE};
      83                 :             : 
      84                 :             : /** @brief Pre-encoded Alarm Search command (0xEC), same layout as above.
      85                 :             :  *  @note 0xEC = 0b11101100, sent LSB-first: 0,0,1,1,0,1,1,1. */
      86                 :             : static const ow_pulse_t search_cmd_alarm[ONEWIRE_BITS_PER_BYTE + 1] = {
      87                 :             :     ONEWIRE_ZERO_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE,
      88                 :             :     ONEWIRE_ZERO_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE,
      89                 :             :     ONEWIRE_RELEASE_PULSE};
      90                 :             : 
      91                 :             : /**
      92                 :             :  * @defgroup ONEWIRE_Private_Variables ONEWIRE Private Variables
      93                 :             :  * @{
      94                 :             :  */
      95                 :             : 
      96                 :             : /** @brief Capture buffer for the merged search write+read operation
      97                 :             :  * @note Holds [write-slot capture, id pulse, cmp pulse]. The CH4 input capture
      98                 :             :  *       runs for the whole timer pass, so the write-slot capture lands in entry
      99                 :             :  *       0 as well; id/cmp are decoded from the pulse durations in entries 1
     100                 :             :  *       and 2. */
     101                 :             : static volatile uint16_t search_pulse3[3];
     102                 :             : 
     103                 :             : /** @brief Pulse capture buffer used by the search engine for bus resets and
     104                 :             :  *         plain id/cmp pair reads (the merged write+read uses search_pulse3). */
     105                 :             : static volatile uint16_t search_pair_pulse[OW_PORT_CAPTURE_BUF_SIZE];
     106                 :             : 
     107                 :             : /** @brief Search state machine phases */
     108                 :             : typedef enum {
     109                 :             :     ONEWIRE_SEARCH_RESET, /**< reset scheduled; check presence, send the search command */
     110                 :             :     ONEWIRE_SEARCH_CMD, /**< search command sent; prepare first bit iteration */
     111                 :             :     ONEWIRE_SEARCH_READ_PAIR, /**< first id/cmp pair read; compute and write direction */
     112                 :             :     ONEWIRE_SEARCH_WRITE_READ, /**< merged direction write + next pair read completed */
     113                 :             :     ONEWIRE_SEARCH_WRITE_DIR, /**< final direction written; advance bit counters */
     114                 :             :     ONEWIRE_SEARCH_DONE, /**< search finished; restore the owner state */
     115                 :             : } onewire_search_phase_t;
     116                 :             : 
     117                 :             : /**
     118                 :             :  * @brief Non-blocking search context
     119                 :             :  * @note Holds the loop counters of the search algorithm. The search command
     120                 :             :  *       itself is NOT built here: 0xF0/0xEC never change, so the pre-encoded
     121                 :             :  *       flash tables search_cmd_rom/search_cmd_alarm feed the DMA directly.
     122                 :             :  */
     123                 :             : typedef struct {
     124                 :             :     uint8_t phase; /**< Current phase of the search state machine (onewire_search_phase_t values, packed) */
     125                 :             :     uint8_t command; /**< Search command byte (0xF0 Search ROM / 0xEC Alarm Search): selects the flash table */
     126                 :             :     uint8_t family; /**< 1-Wire family code to accept, or 0 to accept every family */
     127                 :             :     uint8_t rom[ONEWIRE_ROM_BYTES]; /**< ROM being assembled (bit by bit) */
     128                 :             :     uint8_t id_bit_number; /**< Current bit position (1..64) */
     129                 :             :     uint8_t last_discrepancy; /**< Last discrepancy point (Maxim algorithm; fits uint8_t: <= 64) */
     130                 :             :     uint8_t last_zero; /**< Last position where the '0' branch was taken (fits uint8_t: <= 64) */
     131                 :             :     uint8_t found; /**< Number of accepted devices found */
     132                 :             :     uint8_t max; /**< Maximum number of devices to report */
     133                 :             :     uint8_t flags; /**< ONEWIRE_SEARCH_FLAG_* bits (finished/prev_leaf_valid) */
     134                 :             :     uint8_t prev_leaf[ONEWIRE_ROM_BYTES]; /**< ROM of the preceding completed walk */
     135                 :             :     onewire_search_sink_t sink; /**< Per-device callback */
     136                 :             : } onewire_search_ctx_t;
     137                 :             : 
     138                 :             : /** @brief Set once the search has completed */
     139                 :             : #define ONEWIRE_SEARCH_FLAG_FINISHED (1u << 0)
     140                 :             : /** @brief Set once prev_leaf holds the previous pass's ROM */
     141                 :             : #define ONEWIRE_SEARCH_FLAG_PREV_LEAF_VALID (1u << 1)
     142                 :             : 
     143                 :             : /** @brief Global search context instance */
     144                 :             : static onewire_search_ctx_t search_ctx;
     145                 :             : 
     146                 :             : /* Packing guard: 32 bytes, no padding on any family.
     147                 :             :  * Firmware-only: on the host the sink pointer is 8 bytes wide. */
     148                 :             : #ifndef HOST_BUILD
     149                 :             : _Static_assert(sizeof(search_ctx) == 32, "search context must stay 32 bytes");
     150                 :             : #endif
     151                 :             : 
     152                 :             : _Static_assert(ONEWIRE_SEARCH_DONE <= 255, "search phase enum must fit uint8_t packing");
     153                 :             : 
     154                 :             : /* Internal pulse buffers must always fit one RCR window (+ trailing release). */
     155                 :             : _Static_assert(sizeof(search_cmd_rom) / sizeof(search_cmd_rom[0]) == ONEWIRE_BITS_PER_BYTE + 1u,
     156                 :             :                "flash Search ROM table must be 8 slots + trailing release");
     157                 :             : _Static_assert(sizeof(search_cmd_alarm) / sizeof(search_cmd_alarm[0]) == ONEWIRE_BITS_PER_BYTE + 1u,
     158                 :             :                "flash Alarm Search table must be 8 slots + trailing release");
     159                 :             : _Static_assert(OW_PORT_CAPTURE_BUF_SIZE <= ONEWIRE_MAX_SLOTS,
     160                 :             :                "search pair capture must fit one RCR window");
     161                 :             : 
     162                 :             : /** @} */
     163                 :             : 
     164                 :             : /**
     165                 :             :  * @defgroup ONEWIRE_Bus_Impl ONEWIRE Non-Blocking Bus Primitives
     166                 :             :  * @{
     167                 :             :  */
     168                 :             : 
     169                 :        2708 : void onewire_init(void) {
     170                 :             :     // No search running after init: lets the slave driver own the timer until
     171                 :             :     // the application starts a search.
     172                 :        2708 :     search_ctx.flags |= ONEWIRE_SEARCH_FLAG_FINISHED;
     173                 :             :     // Enable clocks, configure the timer prescaler, bus pin AF open-drain.
     174                 :             :     ow_port_init();
     175                 :             : #if OW_LOW_POWER
     176                 :             :     // WFE Sleep Triggering: a pending interrupt wakes the core from WFE as an
     177                 :             :     // event even though no ISR is enabled. Done once here; the corresponding
     178                 :             :     // pending bit is cleared by the engine wherever it stops depending on it -
     179                 :             :     // around the sleep and in ow_port_bus_done(). NVIC_EnableIRQ is never
     180                 :             :     // called - the project has no ISR vector for TIM1 at all.
     181                 :        1023 :     SCB->SCR |= SCB_SCR_SEVONPEND_Msk;
     182                 :             : #endif
     183                 :        2708 : }
     184                 :             : 
     185         [ +  + ]:       80160 : uint8_t onewire_bus_done(void) {
     186                 :       80160 :     return ow_port_bus_done();
     187                 :             : }
     188                 :             : 
     189                 :          50 : uint32_t onewire_config_token(void) { return OW_CONFIG_TOKEN; }
     190                 :             : 
     191                 :          86 : uint8_t onewire_clock_ok(uint32_t sysclk_mhz) {
     192                 :             : #if defined(OW_SYSCLK_MHZ)
     193         [ +  + ]:          86 :     return (sysclk_mhz == (uint32_t)(OW_SYSCLK_MHZ)) ? 1u : 0u;
     194                 :             : #else
     195                 :             :     /* Auto-path (SystemCoreClock): the port derives its prescaler from the
     196                 :             :      * same variable, so any nonzero reading is consistent by construction. */
     197                 :             :     return (sysclk_mhz != 0u) ? 1u : 0u;
     198                 :             : #endif
     199                 :             : }
     200                 :             : 
     201                 :        5611 : void onewire_reset(volatile uint16_t* reset_pulses) {
     202                 :             :     ow_port_reset(reset_pulses);
     203                 :        5611 : }
     204                 :             : 
     205         [ -  + ]:        9850 : uint8_t onewire_reset_captured(void) { return ow_port_reset_captured(); }
     206                 :             : 
     207                 :        5200 : uint8_t onewire_present(const volatile uint16_t* pulses, uint8_t captured) {
     208                 :             :     // A device is only proven by the presence edge itself: a reset that captured
     209                 :             :     // just the master-release edge leaves pulses[1] at whatever the shared
     210                 :             :     // buffer held before, and that value may sit inside the presence window.
     211         [ +  + ]:        5200 :     if (captured != OW_PORT_CAPTURE_BUF_SIZE) {
     212                 :         125 :         return 0;
     213                 :             :     }
     214                 :        5075 :     uint16_t reset = pulses[0];
     215                 :        5075 :     uint16_t presence = pulses[1];
     216                 :             :     // Validate that reset pulse duration is within specification
     217                 :             :     // and presence pulse timing indicates a responding device
     218   [ +  +  +  + ]:        4490 :     return (reset >= RESET_PULSE_MIN) && (reset <= RESET_PULSE_MAX) &&
     219   [ +  +  +  + ]:        9565 :            (presence >= PRESENCE_PULSE_MIN) && (presence <= PRESENCE_PULSE_MAX);
     220                 :             : }
     221                 :             : 
     222         [ +  - ]:        1388 : void ow_start_wait(uint32_t us) { ow_port_start_wait(us); }
     223                 :             : 
     224                 :         775 : void ow_timer_kick(void) { ow_port_kick(); }
     225                 :             : 
     226                 :       12133 : uint8_t ow_op_done(void) {
     227                 :       12133 :     uint8_t done = onewire_bus_done();
     228                 :             : #if OW_LOW_POWER
     229   [ +  +  +  + ]:        4527 :     if (!done && onewire_long_wait_pending()) {
     230                 :           9 :         onewire_sleep_until_done();
     231                 :           9 :         done = onewire_bus_done(); /* consume the event that woke us */
     232                 :             :     }
     233                 :             : #endif
     234                 :       12133 :     return done;
     235                 :             : }
     236                 :             : 
     237                 :        4146 : void onewire_strong_pullup(uint8_t on) {
     238         [ +  + ]:        4146 :     ow_port_strong_pullup(on);
     239                 :        4146 : }
     240                 :             : 
     241                 :             : #if OW_LOW_POWER
     242         [ +  + ]:         819 : uint8_t onewire_long_wait_pending(void) {
     243                 :         819 :     return ow_port_long_wait_pending();
     244                 :             : }
     245                 :             : 
     246                 :           9 : void onewire_sleep_until_done(void) {
     247                 :             :     ow_port_sleep_until_done();
     248                 :           9 : }
     249                 :             : #endif
     250                 :             : 
     251                 :        5919 : uint8_t onewire_write_slots(const ow_pulse_t* pulses, uint16_t slots) {
     252   [ +  -  -  + ]:        5919 :     if (slots == 0u || slots > ONEWIRE_MAX_SLOTS) {
     253                 :           0 :         ONEWIRE_PARAM_CHECK(0 && "onewire_write_slots: slots out of range (1..ONEWIRE_MAX_SLOTS)");
     254                 :             :         return 0;
     255                 :             :     }
     256         [ +  - ]:       11838 :     return ow_port_write_slots(pulses, slots);
     257                 :             : }
     258                 :             : 
     259                 :        1134 : uint8_t onewire_write_bit(uint8_t bit) {
     260         [ +  + ]:        1134 :     ow_pulse_t pulse = bit ? ONEWIRE_ONE_PULSE : ONEWIRE_ZERO_PULSE;
     261                 :        1134 :     return onewire_write_slots(&pulse, 1);
     262                 :             : }
     263                 :             : 
     264                 :        1234 : void onewire_read_pair(volatile uint16_t* pair_pulses) {
     265                 :             :     ow_port_read_pair(pair_pulses);
     266                 :        1234 : }
     267                 :             : 
     268                 :        1050 : void onewire_pair_bits(const volatile uint16_t* pair_pulses, uint8_t* id_bit, uint8_t* cmp_bit) {
     269                 :        1050 :     *id_bit = onewire_bit_from_pulse(pair_pulses[0]);
     270                 :        1050 :     *cmp_bit = onewire_bit_from_pulse(pair_pulses[1]);
     271                 :        1050 : }
     272                 :             : 
     273                 :       63159 : void onewire_write_then_read(uint8_t bit) {
     274         [ +  + ]:       63159 :     ow_port_write_then_read(bit, search_pulse3, search_read_pulse);
     275                 :       63159 : }
     276                 :             : 
     277                 :        1788 : uint8_t onewire_read_data(volatile uint8_t* dst, uint8_t bytes) {
     278   [ +  -  -  + ]:        1788 :     if (bytes == 0u || bytes > ONEWIRE_MAX_READ_BYTES) {
     279                 :           0 :         ONEWIRE_PARAM_CHECK(0 && "onewire_read_data: bytes out of range (1..ONEWIRE_MAX_READ_BYTES)");
     280                 :             :         return 0;
     281                 :             :     }
     282         [ +  - ]:        3576 :     return ow_port_read_data(dst, bytes);
     283                 :             : }
     284                 :             : 
     285                 :             : /* Four captured slots are classified per step. The reference rule is
     286                 :             :  * `duration <= ONEWIRE_SHORT_PULSE_MAX`, applied independently per slot; the
     287                 :             :  * packed form below is exact for every 8-bit capture value, not only for the
     288                 :             :  * two widths the bus produces:
     289                 :             :  *
     290                 :             :  *   x = (w & 0x7F7F7F7F) | 0x80808080
     291                 :             :  *       keeps every lane in 128..255, so the subtract can never borrow out of
     292                 :             :  *       a lane and corrupt its neighbour;
     293                 :             :  *   (x - limit) & 0x80808080, inverted, is "lane < limit", i.e. a short pulse;
     294                 :             :  *   & ~w drops the lanes whose capture was 128 or more. Such a lane is a long
     295                 :             :  *       pulse by the rule (limit <= 128, asserted below), and it is the only
     296                 :             :  *       lane that could misreport without the mask, because its capture never
     297                 :             :  *       carried a borrow out of the lane.
     298                 :             :  *
     299                 :             :  * The four flags end up in bit 7 of their lane and are gathered LSB-first, so
     300                 :             :  * the result matches onewire_bit_from_pulse() slot for slot.
     301                 :             :  *
     302                 :             :  * A capture value is a byte: the 8-bit read path truncates at 256 us and the
     303                 :             :  * port asserts that the slot period stays below that. */
     304                 :             : _Static_assert(ONEWIRE_SHORT_PULSE_MAX + 1 <= 0x80,
     305                 :             :                "onewire_decode_pulses: the packed compare needs a threshold <= 128");
     306                 :             : 
     307                 :      173288 : void onewire_decode_pulses(uint8_t* dst, const volatile uint8_t* pulse, uint8_t nbytes) {
     308                 :      173288 :     const uint32_t limit = (uint32_t)(ONEWIRE_SHORT_PULSE_MAX + 1) * 0x01010101u;
     309         [ +  + ]:      360369 :     for (uint8_t byte = 0; byte < nbytes; byte++) {
     310                 :      187081 :         const volatile uint8_t* p = pulse + (uint32_t)byte * ONEWIRE_BITS_PER_BYTE;
     311                 :      187081 :         uint8_t value = 0;
     312         [ +  + ]:      561243 :         for (uint8_t half = 0; half < 2u; half++) {
     313                 :      374162 :             uint32_t w = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) |
     314                 :      374162 :                          ((uint32_t)p[3] << 24);
     315                 :      374162 :             uint32_t x = (w & 0x7F7F7F7Fu) | 0x80808080u;
     316                 :      374162 :             uint32_t t = ((x - limit) & 0x80808080u) ^ 0x80808080u;
     317                 :      374162 :             uint32_t f = t & ~w & 0x80808080u;
     318                 :      374162 :             uint32_t bits = (f >> 7) | (f >> 14) | (f >> 21) | (f >> 28);
     319                 :      374162 :             value = (uint8_t)(value | (uint8_t)((bits & 0x0Fu) << (half * 4u)));
     320                 :      374162 :             p += 4;
     321                 :             :         }
     322                 :      187081 :         dst[byte] = value;
     323                 :             :     }
     324                 :      173288 : }
     325                 :             : 
     326                 :             : /* Pre-encoded slots, four per nibble, LSB-first: row n holds the durations for
     327                 :             :  * bits 0..3 of n. The encoder used to run eight shift/branch rounds per byte;
     328                 :             :  * a byte is now two row copies. The rows are built from the same
     329                 :             :  * ONEWIRE_ONE_PULSE / ONEWIRE_ZERO_PULSE macros as the bit-wise form, so a
     330                 :             :  * timing preset still chooses the waveform and only the way it reaches the
     331                 :             :  * buffer changed. tests/test/test_pulse_encoding.c compares every row against
     332                 :             :  * the bit-wise definition, so a transposed row cannot pass. */
     333                 :             : static const ow_pulse_t encode_nibble[16][4] = {
     334                 :             :     {ONEWIRE_ZERO_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ZERO_PULSE},
     335                 :             :     {ONEWIRE_ONE_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ZERO_PULSE},
     336                 :             :     {ONEWIRE_ZERO_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ZERO_PULSE},
     337                 :             :     {ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ZERO_PULSE},
     338                 :             :     {ONEWIRE_ZERO_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ZERO_PULSE},
     339                 :             :     {ONEWIRE_ONE_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ZERO_PULSE},
     340                 :             :     {ONEWIRE_ZERO_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ZERO_PULSE},
     341                 :             :     {ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ZERO_PULSE},
     342                 :             :     {ONEWIRE_ZERO_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ONE_PULSE},
     343                 :             :     {ONEWIRE_ONE_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ONE_PULSE},
     344                 :             :     {ONEWIRE_ZERO_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ONE_PULSE},
     345                 :             :     {ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ONE_PULSE},
     346                 :             :     {ONEWIRE_ZERO_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE},
     347                 :             :     {ONEWIRE_ONE_PULSE, ONEWIRE_ZERO_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE},
     348                 :             :     {ONEWIRE_ZERO_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE},
     349                 :             :     {ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE, ONEWIRE_ONE_PULSE},
     350                 :             : };
     351                 :             : 
     352                 :       34334 : void onewire_encode_byte(ow_pulse_t* out, uint8_t byte) {
     353                 :       34334 :     const ow_pulse_t* low = encode_nibble[byte & 0x0Fu];
     354                 :       34334 :     const ow_pulse_t* high = encode_nibble[byte >> 4];
     355                 :       34334 :     out[0] = low[0];
     356                 :       34334 :     out[1] = low[1];
     357                 :       34334 :     out[2] = low[2];
     358                 :       34334 :     out[3] = low[3];
     359                 :       34334 :     out[4] = high[0];
     360                 :       34334 :     out[5] = high[1];
     361                 :       34334 :     out[6] = high[2];
     362                 :       34334 :     out[7] = high[3];
     363                 :       34334 : }
     364                 :             : 
     365                 :             : /* Reflected nibble tables for the two polynomials at the top of this file:
     366                 :             :  * entry n is the remainder of processing nibble n from a zero state. Two
     367                 :             :  * lookups replace eight shift/XOR rounds per byte, which is what a ROM check
     368                 :             :  * or a DS2431 scratchpad reply spends its time on. The values are fixed by
     369                 :             :  * the polynomials; the host suite compares both helpers against a bit-wise
     370                 :             :  * reference over every byte value, so a wrong entry cannot pass unnoticed. */
     371                 :             : static const uint8_t crc8_nibble[16] = {0x00, 0x9D, 0x23, 0xBE, 0x46, 0xDB, 0x65, 0xF8,
     372                 :             :                                         0x8C, 0x11, 0xAF, 0x32, 0xCA, 0x57, 0xE9, 0x74};
     373                 :             : 
     374                 :       12100 : uint8_t onewire_crc8(const uint8_t* data, uint8_t len) {
     375                 :       12100 :     uint8_t crc = 0;
     376         [ +  + ]:       60700 :     for (uint8_t i = 0; i < len; i++) {
     377                 :       48600 :         uint8_t in = data[i];
     378                 :       48600 :         crc = (uint8_t)((crc >> 4) ^ crc8_nibble[(crc ^ in) & 0x0Fu]);
     379                 :       48600 :         crc = (uint8_t)((crc >> 4) ^ crc8_nibble[(crc ^ (in >> 4)) & 0x0Fu]);
     380                 :             :     }
     381                 :       12100 :     return crc;
     382                 :             : }
     383                 :             : 
     384                 :             : static const uint16_t crc16_nibble[16] = {0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00,
     385                 :             :                                           0x2800, 0xE401, 0xA001, 0x6C00, 0x7800, 0xB401,
     386                 :             :                                           0x5000, 0x9C01, 0x8801, 0x4400};
     387                 :             : 
     388                 :        5292 : uint16_t onewire_crc16(const uint8_t* data, uint8_t len) {
     389                 :        5292 :     uint16_t crc = 0;
     390         [ +  + ]:       15930 :     for (uint8_t i = 0; i < len; i++) {
     391                 :       10638 :         uint8_t in = data[i];
     392                 :       10638 :         crc = (uint16_t)((crc >> 4) ^ crc16_nibble[(crc ^ in) & 0x0Fu]);
     393                 :       10638 :         crc = (uint16_t)((crc >> 4) ^ crc16_nibble[(crc ^ (in >> 4)) & 0x0Fu]);
     394                 :             :     }
     395                 :        5292 :     return crc;
     396                 :             : }
     397                 :             : 
     398                 :             : /** @} */
     399                 :             : 
     400                 :             : /**
     401                 :             :  * @defgroup ONEWIRE_Search_Impl ONEWIRE Generic Search ROM Engine
     402                 :             :  * @{
     403                 :             :  */
     404                 :             : 
     405                 :             : /**
     406                 :             :  * @brief Process one decoded id/cmp pair: pick a direction, update the ROM,
     407                 :             :  *        and schedule the next hardware operation
     408                 :             :  * @param[in] id_bit Id bit of the current position
     409                 :             :  * @param[in] cmp_bit Complement bit of the current position
     410                 :             :  * @note For all but the last bit the direction write is merged with the read
     411                 :             :  *       of the next pair (ONEWIRE_SEARCH_WRITE_READ); the 64th bit is written
     412                 :             :  *       alone so the device can be finalized.
     413                 :             :  */
     414                 :       64050 : static void onewire_search_advance_bit(uint8_t id_bit, uint8_t cmp_bit) {
     415                 :       64050 :     const uint8_t byte_idx = (search_ctx.id_bit_number - 1) / ONEWIRE_BITS_PER_BYTE;
     416                 :       64050 :     const uint8_t mask = (uint8_t)(1u << ((search_ctx.id_bit_number - 1) % ONEWIRE_BITS_PER_BYTE));
     417                 :             :     uint8_t direction;
     418                 :             : 
     419   [ +  +  +  + ]:       64050 :     if (id_bit && cmp_bit) {
     420                 :             :         // No device follows this path - search tree exhausted
     421                 :          50 :         search_ctx.phase = ONEWIRE_SEARCH_DONE;
     422                 :          50 :         return;
     423                 :             :     }
     424         [ +  + ]:       64000 :     if (id_bit != cmp_bit) {
     425                 :             :         // Single device on this path - its bit fixes the direction
     426                 :       59600 :         direction = id_bit;
     427         [ +  + ]:        4400 :     } else if (search_ctx.id_bit_number < search_ctx.last_discrepancy) {
     428                 :             :         // Follow the previously taken path
     429         [ +  + ]:        2050 :         direction = (search_ctx.rom[byte_idx] & mask) ? 1u : 0u;
     430         [ +  + ]:        2050 :         if (direction == 0) {
     431                 :             :             // Remember the last 0-branch taken at a discrepancy
     432                 :        1900 :             search_ctx.last_zero = search_ctx.id_bit_number;
     433                 :             :         }
     434                 :             :     } else {
     435                 :             :         // At the discrepancy point take the '1' branch first
     436         [ +  + ]:        2350 :         direction = (search_ctx.id_bit_number == search_ctx.last_discrepancy) ? 1u : 0u;
     437         [ +  + ]:        2350 :         if (direction == 0) {
     438                 :             :             // Remember the last 0-branch taken at a discrepancy
     439                 :        2000 :             search_ctx.last_zero = search_ctx.id_bit_number;
     440                 :             :         }
     441                 :             :     }
     442         [ +  + ]:       64000 :     if (direction) {
     443                 :       14525 :         search_ctx.rom[byte_idx] |= mask;
     444                 :             :     } else {
     445                 :       49475 :         search_ctx.rom[byte_idx] &= (uint8_t)~mask;
     446                 :             :     }
     447         [ +  + ]:       64000 :     if (search_ctx.id_bit_number < ONEWIRE_ROM_BITS) {
     448                 :             :         // Merge the direction write with the read of the next id/cmp pair.
     449                 :       63000 :         onewire_write_then_read(direction);
     450                 :       63000 :         search_ctx.phase = ONEWIRE_SEARCH_WRITE_READ;
     451                 :             :     } else {
     452                 :        1000 :         onewire_write_bit(direction);
     453                 :        1000 :         search_ctx.phase = ONEWIRE_SEARCH_WRITE_DIR;
     454                 :             :     }
     455                 :             : }
     456                 :             : 
     457                 :         993 : void onewire_search_start(onewire_search_sink_t sink, uint8_t max_devices,
     458                 :             :                           uint8_t command, uint8_t family) {
     459         [ +  + ]:         993 :     if ((search_ctx.flags & ONEWIRE_SEARCH_FLAG_FINISHED) == 0u) {
     460                 :          25 :         return; // a search is already running
     461                 :             :     }
     462         [ +  + ]:        8712 :     for (uint8_t i = 0; i < ONEWIRE_ROM_BYTES; i++) {
     463                 :        7744 :         search_ctx.rom[i] = 0;
     464                 :             :     }
     465                 :         968 :     search_ctx.sink = sink;
     466                 :         968 :     search_ctx.max = max_devices;
     467                 :         968 :     search_ctx.found = 0;
     468                 :             :     /* Fresh search: running, previous leaf forgotten. */
     469                 :         968 :     search_ctx.flags &= (uint8_t)~(ONEWIRE_SEARCH_FLAG_FINISHED | ONEWIRE_SEARCH_FLAG_PREV_LEAF_VALID);
     470                 :         968 :     search_ctx.last_discrepancy = 0;
     471                 :         968 :     search_ctx.command = command;
     472                 :         968 :     search_ctx.family = family;
     473         [ +  + ]:         968 :     if (max_devices == 0) {
     474                 :          50 :         search_ctx.phase = ONEWIRE_SEARCH_DONE;
     475                 :          50 :         return;
     476                 :             :     }
     477                 :         918 :     search_ctx.phase = ONEWIRE_SEARCH_RESET;
     478                 :         918 :     onewire_reset(search_pair_pulse); // Schedule the first hardware operation
     479                 :             : }
     480                 :             : 
     481                 :       68975 : uint8_t onewire_search_poll(void) {
     482         [ +  + ]:       68975 :     if ((search_ctx.flags & ONEWIRE_SEARCH_FLAG_FINISHED) != 0u) {
     483                 :         225 :         return 1;
     484                 :             :     }
     485                 :             : 
     486         [ +  + ]:       68750 :     if (search_ctx.phase == ONEWIRE_SEARCH_DONE) {
     487                 :             :         // No hardware operation is pending at the end of the search: the timer
     488                 :             :         // stays idle until the owner asks for the next operation (a new search
     489                 :             :         // schedules its own reset, a measurement calls ow_timer_kick()).
     490                 :         800 :         search_ctx.flags |= ONEWIRE_SEARCH_FLAG_FINISHED;
     491                 :         800 :         return 1;
     492                 :             :     }
     493                 :             : 
     494                 :             :     // Wait for the currently scheduled hardware operation to complete.
     495                 :             :     // This is a non-blocking poll, not a busy-wait.
     496         [ +  + ]:       67950 :     if (!onewire_bus_done()) {
     497                 :         750 :         return 0;
     498                 :             :     }
     499                 :             : 
     500                 :             :     OW_PROFILE_WORK_BEGIN();
     501   [ +  +  +  +  :       67200 :     switch (search_ctx.phase) {
                +  -  - ]
     502                 :        1100 :     case ONEWIRE_SEARCH_RESET:
     503                 :             :         // Reset completed: a presence pulse means at least one device is on
     504                 :             :         // the bus, so start a new search pass with the search command
     505                 :             :         // (0xF0 Search ROM / 0xEC Alarm Search). The command tables are
     506                 :             :         // pre-encoded in flash; only these two protocol commands ever reach
     507                 :             :         // this layer (ds18b20_search_start/alarm_search_start pass the
     508                 :             :         // DS18B20_* constants, and the tests/fuzz cover both).
     509         [ +  + ]:        1100 :         if (!ow_has_presence(search_pair_pulse)) {
     510                 :          50 :             search_ctx.phase = ONEWIRE_SEARCH_DONE;
     511                 :          50 :             break;
     512                 :             :         }
     513         [ +  + ]:        1050 :         if (search_ctx.command == ONEWIRE_SEARCH_ROM) {
     514                 :         775 :             onewire_write_slots(search_cmd_rom, ONEWIRE_BITS_PER_BYTE);
     515                 :             :         } else {
     516                 :         275 :             onewire_write_slots(search_cmd_alarm, ONEWIRE_BITS_PER_BYTE);
     517                 :             :         }
     518                 :        1050 :         search_ctx.phase = ONEWIRE_SEARCH_CMD;
     519                 :        1050 :         break;
     520                 :             : 
     521                 :        1050 :     case ONEWIRE_SEARCH_CMD:
     522                 :             :         // Search command sent: prepare the first bit iteration and read the
     523                 :             :         // id/cmp pair.
     524                 :        1050 :         search_ctx.id_bit_number = 1;
     525                 :        1050 :         search_ctx.last_zero = 0;
     526                 :        1050 :         onewire_read_pair(search_pair_pulse);
     527                 :        1050 :         search_ctx.phase = ONEWIRE_SEARCH_READ_PAIR;
     528                 :        1050 :         break;
     529                 :             : 
     530                 :        1050 :     case ONEWIRE_SEARCH_READ_PAIR:
     531                 :             :         // First id/cmp pair decoded from the plain two-slot read.
     532                 :             :         {
     533                 :             :             uint8_t id_bit;
     534                 :             :             uint8_t cmp_bit;
     535                 :        1050 :             onewire_pair_bits(search_pair_pulse, &id_bit, &cmp_bit);
     536                 :        1050 :             onewire_search_advance_bit(id_bit, cmp_bit);
     537                 :             :         }
     538                 :        1050 :         break;
     539                 :             : 
     540                 :       63000 :     case ONEWIRE_SEARCH_WRITE_READ:
     541                 :             :         // The merged operation wrote the direction for the previous bit and
     542                 :             :         // captured the id/cmp pair of the current bit into search_pulse3.
     543                 :       63000 :         search_ctx.id_bit_number++;
     544                 :       63000 :         onewire_search_advance_bit(
     545                 :       63000 :             onewire_bit_from_pulse(search_pulse3[1]),
     546                 :       63000 :             onewire_bit_from_pulse(search_pulse3[2]));
     547                 :       63000 :         break;
     548                 :             : 
     549                 :        1000 :     case ONEWIRE_SEARCH_WRITE_DIR:
     550                 :             :         // The final (64th) direction bit was written: the ROM is assembled.
     551                 :        1000 :         search_ctx.id_bit_number++;
     552                 :        1000 :         search_ctx.last_discrepancy = search_ctx.last_zero;
     553         [ +  + ]:        1000 :         if (onewire_crc8(search_ctx.rom, ONEWIRE_ROM_BYTES) != 0) {
     554                 :          75 :             search_ctx.phase = ONEWIRE_SEARCH_DONE;
     555                 :          75 :             break;
     556                 :             :         }
     557                 :             :         // The family filter decides which devices are accepted: only accepted
     558                 :             :         // devices increment the found counter and reach the sink. The sink may
     559                 :             :         // stop the search early with a non-zero return value.
     560   [ +  +  +  + ]:         925 :         if (search_ctx.family == 0u || search_ctx.rom[0] == search_ctx.family) {
     561                 :         850 :             search_ctx.found++;
     562                 :             :             OW_PROFILE_WORK_END();
     563         [ +  - ]:         850 :             uint8_t stop = search_ctx.sink ? search_ctx.sink(search_ctx.rom) : 0u;
     564                 :             :             OW_PROFILE_WORK_BEGIN();
     565         [ +  + ]:         850 :             if (stop) {
     566                 :          50 :                 search_ctx.phase = ONEWIRE_SEARCH_DONE;
     567                 :          50 :                 break;
     568                 :             :             }
     569         [ +  + ]:         800 :             if (search_ctx.found >= search_ctx.max) {
     570                 :         475 :                 search_ctx.phase = ONEWIRE_SEARCH_DONE;
     571                 :         475 :                 break;
     572                 :             :             }
     573                 :             :         }
     574         [ +  + ]:         400 :         if (search_ctx.last_discrepancy == 0) {
     575                 :          50 :             search_ctx.phase = ONEWIRE_SEARCH_DONE;
     576                 :          50 :             break;
     577                 :             :         }
     578                 :             :         // Another device may exist - run another search pass. On a real bus
     579                 :             :         // every walk lands on a leaf the search has not visited before, so a
     580                 :             :         // leaf identical to the previous pass proves the search made no
     581                 :             :         // progress (a CRC-valid ROM rejected by the family filter, or a
     582                 :             :         // hostile/broken slave answering the same profile twice). Terminate
     583                 :             :         // instead of walking the same subtree forever.
     584         [ +  + ]:         350 :         if ((search_ctx.flags & ONEWIRE_SEARCH_FLAG_PREV_LEAF_VALID) != 0u &&
     585         [ -  + ]:         225 :             memcmp(search_ctx.prev_leaf, search_ctx.rom, ONEWIRE_ROM_BYTES) == 0) {
     586                 :           0 :             search_ctx.phase = ONEWIRE_SEARCH_DONE;
     587                 :           0 :             break;
     588                 :             :         }
     589                 :         350 :         memcpy(search_ctx.prev_leaf, search_ctx.rom, ONEWIRE_ROM_BYTES);
     590                 :         350 :         search_ctx.flags |= ONEWIRE_SEARCH_FLAG_PREV_LEAF_VALID;
     591                 :         350 :         onewire_reset(search_pair_pulse);
     592                 :         350 :         search_ctx.phase = ONEWIRE_SEARCH_RESET;
     593                 :         350 :         break;
     594                 :             : 
     595                 :           0 :     case ONEWIRE_SEARCH_DONE:
     596                 :             :         // DONE is handled before the switch (see above); keep as a
     597                 :             :         // no-op so -Wswitch-enum stays satisfied.
     598                 :           0 :         break;
     599                 :             : 
     600                 :           0 :     default:
     601                 :           0 :         break;
     602                 :             :     }
     603                 :             : 
     604                 :             :     OW_PROFILE_WORK_END();
     605                 :       67200 :     return 0;
     606                 :             : }
     607                 :             : 
     608                 :         900 : uint8_t onewire_search_count(void) { return search_ctx.found; }
     609                 :             : 
     610                 :       10913 : uint8_t onewire_search_active(void) { return (uint8_t)((search_ctx.flags & ONEWIRE_SEARCH_FLAG_FINISHED) == 0u); }
     611                 :             : 
     612                 :             : /** @} */
        

Generated by: LCOV version 2.0-1