LCOV - code coverage report
Current view: top level - src - ds18b20.c (source / functions) Coverage Total Hit
Test: stm32-async-1wire core coverage Lines: 92.0 % 50 46
Test Date: 2026-11-28 11:52:24 Functions: 60.0 % 5 3
Branches: 87.5 % 24 21

             Branch data     Line data    Source code
       1                 :             : #include "ds18b20.h"
       2                 :             : #include "ds18b20_internal.h"
       3                 :             : #include "onewire.h"
       4                 :             : /* The driver needs two CMSIS compiler spellings (__WEAK, __STATIC_FORCEINLINE)
       5                 :             :  * and nothing else from CMSIS; this private shim supplies them without pulling
       6                 :             :  * in a device header. See src/ow_compiler.h. */
       7                 :             : #include "ow_compiler.h"
       8                 :             : /* The driver schedules the bus waits and kicks its own state machine through
       9                 :             :  * the engine; that bridge is library-internal. See src/ow_glue.h. */
      10                 :             : #include "ow_glue.h"
      11                 :             : /* Intra-stack instrumentation, not a layer leak: stats emission needs
      12                 :             :  * driver-owned concepts (device ROM, DS18B20_TEMP_ERROR_*) that the onewire
      13                 :             :  * layer must not know, so the driver is the rightful emitter. Compiles away
      14                 :             :  * when OW_STATS_ENABLE=0. */
      15                 :             : #include "ow_stats.h"
      16                 :             : 
      17                 :             : /* Private sizing, context/phase types, flag bits and res_config_byte()
      18                 :             :  * live in src/ds18b20_internal.h shared with the four parts. */
      19                 :             : 
      20                 :             : #define DS18B20_DRIVER_BUILD 1
      21                 :             : 
      22                 :             : /* DS18B20_ctx_t / ds18b20_txn_ctx_t and their flag bits live in
      23                 :             :  * src/ds18b20_internal.h; the static instances follow. */
      24                 :             : 
      25                 :             : /**
      26                 :             :  * @defgroup DS18B20_Private_Variables DS18B20 Private Variables
      27                 :             :  * @{
      28                 :             :  */
      29                 :             : 
      30                 :             : /** @brief Global driver context instance */
      31                 :             : static DS18B20_ctx_t ctx;
      32                 :             : 
      33                 :             : /* Packing guard: the context layout is hand-packed (u8 phases, flag bytes,
      34                 :             :  * no padding). If a field is added, update this number knowingly — every
      35                 :             :  * byte here is .bss on all families. */
      36                 :             : _Static_assert(sizeof(ctx) == 84, "driver context must stay 84 bytes");
      37                 :             : 
      38                 :             : /* RCR guard: every DS18B20 pass must fit one 8-bit RCR window (256 slots). */
      39                 :             : _Static_assert(DS18B20_MATCH_SLOTS <= ONEWIRE_MAX_SLOTS,
      40                 :             :                "Match ROM write must fit one RCR window");
      41                 :             : _Static_assert(DS18B20_SCRATCHPAD_BITS <= ONEWIRE_MAX_SLOTS,
      42                 :             :                "scratchpad read must fit one RCR window");
      43                 :             : _Static_assert(DS18B20_SCRATCHPAD_LEN <= ONEWIRE_MAX_READ_BYTES,
      44                 :             :                "scratchpad length must fit one read pass");
      45                 :             : 
      46                 :             : /** @brief Global single-command transaction context instance */
      47                 :             : static ds18b20_txn_ctx_t txn_ctx;
      48                 :             : 
      49                 :             : /* Packing guard: pointer/wait first, flag byte last — 24 bytes, no padding.
      50                 :             :  * Firmware-only: on the host the pointer is 8 bytes wide. */
      51                 :             : #ifndef HOST_BUILD
      52                 :             : _Static_assert(sizeof(txn_ctx) == 24, "transaction context must stay 24 bytes");
      53                 :             : #endif
      54                 :             : 
      55                 :             : _Static_assert(DS18B20_RES_SLOTS_MAX <= ONEWIRE_MAX_SLOTS,
      56                 :             :                "longest txn write must fit one RCR window");
      57                 :             : 
      58                 :             : /**
      59                 :             :  * @}
      60                 :             :  */
      61                 :             : 
      62                 :             : /**
      63                 :             :  * @defgroup DS18B20_Private_Functions DS18B20 Private Functions
      64                 :             :  * @{
      65                 :             :  */
      66                 :             : 
      67                 :             : /**
      68                 :             :  * @brief Default weak implementation for busy indicator (e.g. LED toggling during measurement)
      69                 :             :  * @param[in] action 0 = idle, non-zero = busy
      70                 :             :  */
      71                 :           0 : __WEAK void ds18b20_busy(unsigned action) {
      72                 :             :     (void)action;
      73                 :             :     // Default implementation - empty (no LED control)
      74                 :           0 : }
      75                 :             : 
      76                 :             : /**
      77                 :             :  * @brief Default weak implementation for measurement completion callback
      78                 :             :  * @param[in] temp_tenths Temperature value in tenths of degrees Celsius, or error code
      79                 :             :  */
      80                 :           0 : __WEAK void ds18b20_complete(int16_t temp_tenths) {
      81                 :             :     (void)temp_tenths;
      82                 :             :     // Default implementation - empty (no temperature handling)
      83                 :           0 : }
      84                 :             : 
      85                 :             : /**
      86                 :             :  * @brief Calculate Dallas/Maxim CRC-8 over a byte buffer
      87                 :             :  * @param[in] data Input buffer
      88                 :             :  * @param[in] len Number of bytes to process
      89                 :             :  * @return CRC-8 checksum value
      90                 :             :  * @note Delegates to the shared 1-Wire layer (same Dallas/Maxim algorithm).
      91                 :             :  */
      92                 :       11100 : uint8_t ds18b20_crc8(const uint8_t* data, uint8_t len) {
      93                 :       11100 :     return onewire_crc8(data, len);
      94                 :             : }
      95                 :             : 
      96                 :             : /**
      97                 :             :  * @brief Calculate CRC8 checksum for DS18B20 scratchpad data validation
      98                 :             :  * @return CRC8 checksum value
      99                 :             :  */
     100                 :             : __STATIC_FORCEINLINE uint8_t check_scratchpad_crc(void) {
     101                 :         875 :     return ds18b20_crc8(ctx.scratchpad, DS18B20_CRC8_BYTES);
     102                 :             : }
     103                 :             : 
     104                 :             : /**
     105                 :             :  * @brief Decode pulse durations into scratchpad bytes using bit timing analysis
     106                 :             :  * @note Branchless implementation: accumulates bits into native-width variable,
     107                 :             :  *       then writes once per byte. Relies on union aliasing invariant — see DS18B20_ctx_t.
     108                 :             :  */
     109                 :             : __STATIC_FORCEINLINE void decode_scratchpad(void) {
     110                 :             :     /* Captured pulse durations (volatile, written by the read DMA) carry one
     111                 :             :      * bit each; onewire_decode_pulses() recovers the scratchpad bytes. */
     112                 :        1075 :     onewire_decode_pulses(ctx.scratchpad, ctx.pulse, DS18B20_SCRATCHPAD_LEN);
     113                 :        1075 : }
     114                 :             : 
     115                 :             : /**
     116                 :             :  * @brief Convert raw temperature data from scratchpad to tenths of degrees Celsius
     117                 :             :  * @return Temperature value in tenths of degrees Celsius
     118                 :             :  */
     119                 :             : __STATIC_FORCEINLINE int16_t decode_temperature(void) {
     120                 :             :     // Combine LSB and MSB of temperature register (bytes 0 and 1)
     121                 :         875 :     int16_t raw = (int16_t)((ctx.scratchpad[1] << 8) | ctx.scratchpad[0]);
     122                 :             :     // Convert to tenths of degrees Celsius (raw value in 1/16th degrees):
     123                 :             :     // multiply by 10 and divide by 16 with round-half-away-from-zero so the
     124                 :             :     // sign is preserved for small negative values (raw = -1 would otherwise
     125                 :             :     // truncate to 0 and report +0.0 °C for a temperature below freezing).
     126   [ +  +  -  + ]:         875 :     return (int16_t)(((int32_t)raw * 10 + ((raw < 0) ? -8 : 8)) / 16);
     127                 :             : }
     128                 :             : 
     129                 :             : /**
     130                 :             :  * @brief Map a conversion resolution to its exact DS18B20 conversion time
     131                 :             :  * @param[in] res Resolution in bits (9..12)
     132                 :             :  * @return The datasheet conversion time in microseconds
     133                 :             :  * @note DS18B20 datasheet conversion times: 9-bit 93.75ms, 10-bit 187.5ms,
     134                 :             :  *       11-bit 375ms, 12-bit 750ms. The driver states the duration; how the
     135                 :             :  *       timer is programmed to produce it is the engine's business.
     136                 :             :  */
     137                 :             : __STATIC_FORCEINLINE uint32_t resolution_wait_us(uint8_t res) {
     138                 :         786 :     switch (res) {
     139                 :          50 :     case 9:
     140                 :          50 :         return 93750u; /* 93.75ms */
     141                 :          25 :     case 10:
     142                 :          25 :         return 187500u; /* 187.5ms */
     143                 :          25 :     case 11:
     144                 :          25 :         return 375000u; /* 375ms */
     145                 :         686 :     case 12:
     146                 :             :     default:
     147                 :         686 :         return 750000u; /* 750ms */
     148                 :             :     }
     149                 :             : }
     150                 :             : 
     151                 :             : /**
     152                 :             :  * @brief Wait for temperature conversion to complete
     153                 :             :  * @note Non-blocking - starts a timer that generates an update event when the
     154                 :             :  *       conversion of the currently configured resolution (ctx.resolution)
     155                 :             :  *       is guaranteed finished: 93.75ms (9 bit) .. 750ms (12 bit).
     156                 :             :  */
     157                 :             : __STATIC_FORCEINLINE void wait_conversion(void) {
     158   [ +  +  +  +  :        1572 :     ow_start_wait(resolution_wait_us(ctx.resolution));
             +  -  -  + ]
     159                 :         786 : }
     160                 :             : 
     161                 :             : /**
     162                 :             :  * @}
     163                 :             :  */
     164                 :             : 
     165                 :             : /* Include-only driver parts: the four functional modules of the
     166                 :             :  * DS18B20 driver live in their own translation units of this file and
     167                 :             :  * are compiled in here so the whole driver stays one object file. Each
     168                 :             :  * part owns its private state (DS18B20_DRIVER_BUILD gate above) and is
     169                 :             :  * guarded so it cannot be compiled standalone (it would miss the shared
     170                 :             :  * ctx/txn_ctx/res_ctx/dev_roms statics below, whose types and the
     171                 :             :  * cross-part leaf res_config_byte() live in src/ds18b20_internal.h).
     172                 :             :  *
     173                 :             :  * The include order is load-bearing: every part references file-scope
     174                 :             :  * declarations from the parts included above it (txn uses res_config_byte
     175                 :             :  * from resolution; search uses txn_ctx, and measure uses dev_roms/dev_count
     176                 :             :  * from search). clang-format must not alphabetise these lines. */
     177                 :             : /* Phase enums are stored packed in uint8_t context fields (see above); all
     178                 :             :  * values must fit. If a state is ever added past 255, the packing — not just
     179                 :             :  * the asserts — needs revisiting. */
     180                 :             : _Static_assert(DS18B20_ST_DECODE <= 255, "state enum must fit uint8_t packing");
     181                 :             : _Static_assert(DS18B20_TXN_DONE <= 255, "txn phase enum must fit uint8_t packing");
     182                 :             : /* Phase pulse workspace: one shared buffer reused by the mutually exclusive
     183                 :             :  * bus-owner phases, instead of a dedicated static per phase.
     184                 :             :  *
     185                 :             :  * @warning CRITICAL INVARIANT: the four members alias the same storage.
     186                 :             :  *          Each phase rebuilds its member in full before use, and the
     187                 :             :  *          ownership guards (measurement/search/resolution/transaction reject
     188                 :             :  *          while another owns the timer) guarantee no phase reads a member
     189                 :             :  *          outside its own ownership window:
     190                 :             :  *          - cmd: shared by the CONVERT and REQUEST command builds, which are
     191                 :             :  *            strictly sequential (CONVERT completes via bus_done before
     192                 :             :  *            REQUEST builds); build_skip_cmd() rewrites all entries plus the
     193                 :             :  *            trailing release on every call.
     194                 :             :  *          - res: rebuilt by build_res_pulses() on every set_resolution call;
     195                 :             :  *            live only while the resolution change owns the timer.
     196                 :             :  *          - txn: rebuilt by txn_build_pulses() on every txn_start; live only
     197                 :             :  *            while the command transaction owns the timer.
     198                 :             :  *          - addr: rebuilt in FULL by build_addr_cmd() on every addressed
     199                 :             :  *            operation (prefix re-encoded from ctx.selected_rom plus the
     200                 :             :  *            command byte plus the trailing release); live only while the
     201                 :             :  *            owning write owns the timer. Per-operation rebuild (not once
     202                 :             :  *            per selection) is what makes union membership safe: a
     203                 :             :  *            transaction between two measurements may reuse the storage.
     204                 :             :  *          Deliberately EXCLUDED (same storage must NOT be shared):
     205                 :             :  *          - dev_roms: the scan device table must survive across measurement
     206                 :             :  *            cycles, and 4_scan_mode runs a resolution write between search
     207                 :             :  *            and scan rounds.
     208                 :             :  *          - onewire.c search buffers: separate translation unit (generic
     209                 :             :  *            1-Wire layer), so they cannot see this static; and there is
     210                 :             :  *            nothing to overlay with inside onewire.c either (rom/prev_leaf
     211                 :             :  *            must persist across the whole search, pulses only during CMD —
     212                 :             :  *            all within one search run). Audited 2026-10-07.
     213                 :             :  *          - txn raw[]/flags, res/measure state bytes: read after completion
     214                 :             :  *            by the app and test accessors, so they stay in their structs.
     215                 :             :  */
     216                 :             : static union {
     217                 :             :     ow_pulse_t cmd[DS18B20_DMA_TRANSFERS + 1]; /**< CONVERT/REQUEST command builds (shared, sequential) */
     218                 :             :     ow_pulse_t res[DS18B20_RES_SLOTS_MAX + 1]; /**< resolution config writes */
     219                 :             :     ow_pulse_t txn[DS18B20_RES_SLOTS_MAX + 1]; /**< command transaction builds */
     220                 :             :     ow_pulse_t addr[DS18B20_MATCH_SLOTS + 1]; /**< addressed (Match ROM) command builds, rebuilt per op */
     221                 :             : } phase_pulses;
     222                 :             : 
     223                 :             : /* B1 guards: the trailing ONEWIRE_RELEASE_PULSE consumed by the CCR3-feed
     224                 :             :  * DMA's final transfer must always be present. Keep the per-member asserts
     225                 :             :  * even though all members share storage: each documents the size contract
     226                 :             :  * of the phase that fills it. */
     227                 :             : _Static_assert(sizeof(phase_pulses.cmd) >= DS18B20_DMA_TRANSFERS + 1,
     228                 :             :                "phase cmd must be DS18B20_DMA_TRANSFERS + 1 to hold the trailing "
     229                 :             :                "bus-release pulse consumed by the 1-Wire layer");
     230                 :             : _Static_assert(sizeof(phase_pulses.res) >= DS18B20_RES_SLOTS_MAX + 1,
     231                 :             :                "phase res must be DS18B20_RES_SLOTS_MAX + 1 to hold the trailing "
     232                 :             :                "bus-release pulse consumed by the 1-Wire layer");
     233                 :             : _Static_assert(sizeof(phase_pulses.txn) >= DS18B20_RES_SLOTS_MAX + 1,
     234                 :             :                "phase txn must be DS18B20_RES_SLOTS_MAX + 1 to hold the trailing "
     235                 :             :                "bus-release pulse consumed by the 1-Wire layer");
     236                 :             : _Static_assert(sizeof(phase_pulses.addr) >= DS18B20_MATCH_SLOTS + 1,
     237                 :             :                "phase addr must be DS18B20_MATCH_SLOTS + 1 to hold the trailing "
     238                 :             :                "bus-release pulse consumed by the 1-Wire layer");
     239                 :             : 
     240                 :             : /**
     241                 :             :  * @brief Build the full Match ROM command table (0x55 + selected ROM + cmd)
     242                 :             :  * @param[in] cmd_byte Command byte to send after the ROM address
     243                 :             :  * @note Fills phase_pulses.addr in full on every call: the prefix depends
     244                 :             :  *       only on the selected device, but rebuilding it per operation (instead
     245                 :             :  *       of once per selection) is what lets the table live in the shared
     246                 :             :  *       phase union — a transaction running between two measurements may
     247                 :             :  *       reuse the same storage, and the next operation rebuilds before use.
     248                 :             :  *       Cost is one synchronous re-encode (~72 slots, microseconds) per
     249                 :             :  *       addressed operation; the 1-Wire timings are milliseconds.
     250                 :             :  */
     251                 :             : __STATIC_FORCEINLINE void build_addr_cmd(uint8_t cmd_byte) {
     252                 :         725 :     ow_pulse_t* p = phase_pulses.addr;
     253                 :             :     ow_encode_match_rom(&p, ctx.selected_rom);
     254                 :         725 :     onewire_encode_byte(&phase_pulses.addr[DS18B20_PREFIX_SLOTS], cmd_byte);
     255                 :         725 :     phase_pulses.addr[DS18B20_MATCH_SLOTS] = ONEWIRE_RELEASE_PULSE;
     256                 :         725 : }
     257                 :             : // clang-format off
     258                 :             : #include "ds18b20_resolution.c"
     259                 :             : #include "ds18b20_txn.c"
     260                 :             : #include "ds18b20_search.c"
     261                 :             : #include "ds18b20_measure.c"
     262                 :             : // clang-format on
     263                 :             : 
     264                 :             : /**
     265                 :             :  * @defgroup DS18B20_Public_Functions DS18B20 Public Functions
     266                 :             :  * @{
     267                 :             :  */
     268                 :             : 
     269                 :             : /**
     270                 :             :  * @brief Initialize DS18B20 driver - configure clocks and peripherals
     271                 :             :  * @pre Call exactly once after MCU reset, after the system clock is configured
     272                 :             :  *      and before any 1-Wire bus operation or DS18B20 driver activity.
     273                 :             :  * @note Calls onewire_init(), which takes exclusive ownership of the shared
     274                 :             :  *       TIM1/DMA/GPIO resources for the lifetime of the driver (until reset),
     275                 :             :  *       and parks the driver at DS18B20_ST_IDLE: nothing runs until the
     276                 :             :  *       application calls ds18b20_start_measure() or a search API.
     277                 :             :  * @warning This function is a bootstrap operation, not a reinitialization hook.
     278                 :             :  *          A second call before any bus operation re-applies the idle setup;
     279                 :             :  *          during activity it does not stop or fully reset the timer, DMA,
     280                 :             :  *          low-power or DS18B20 software state. Starting a new driver lifecycle
     281                 :             :  *          requires an MCU reset.
     282                 :             :  */
     283                 :        1952 : void ds18b20_init(void) {
     284                 :        1952 :     onewire_init();
     285                 :             :     // No resolution change or command transaction running after init; the
     286                 :             :     // DS18B20 powers up at 12 bit (750ms conversion), so wait for exactly that
     287                 :             :     // until a scratchpad read or set_resolution tells us otherwise.
     288                 :        1952 :     res_ctx.flags |= DS18B20_RES_FLAG_FINISHED;
     289                 :        1952 :     txn_ctx.flags |= DS18B20_TXN_FLAG_FINISHED;
     290                 :        1952 :     ctx.resolution = DS18B20_RES_DEFAULT;
     291                 :        1952 :     ctx.scan_index = 0;
     292                 :             :     // External power is the default wiring assumption; parasite-powered
     293                 :             :     // setups opt in explicitly via ds18b20_set_parasite(). The flag byte
     294                 :             :     // starts clear (address_mode/scan_mode/parasite all zero).
     295                 :        1952 :     ctx.flags = 0u;
     296                 :        1952 : }
     297                 :             : 
     298                 :             : /**
     299                 :             :  * @brief Select which DS18B20 device to measure by its ROM address
     300                 :             :  * @param[in] rom Pointer to the 8-byte ROM address (LSB first), or NULL to
     301                 :             :  *                return to Skip ROM (broadcast) addressing
     302                 :             :  * @note With a non-NULL address, the state machine sends Match ROM (0x55)
     303                 :             :  *       plus the device address before each command, so only that device
     304                 :             :  *       responds. Pass NULL (or a freshly initialised driver) to keep the
     305                 :             :  *       legacy single-sensor Skip ROM behaviour. The address should come from
     306                 :             :  *       the non-blocking device search (ds18b20_search_*).
     307                 :             :  * @note The selection is applied only between measurement cycles (driver
     308                 :             :  *       IDLE). Calls made while a cycle is running are ignored, including from
     309                 :             :  *       the per-device scan callback (which the driver invokes at
     310                 :             :  *       DS18B20_ST_DECODE mid-round): a select() there is rejected and the
     311                 :             :  *       scan round continues. Applying a select mid-cycle would change
     312                 :             :  *       ctx.selected_rom out from under the in-flight cycle, so the next
     313                 :             :  *       addressed operation of that cycle would rebuild its Match ROM table
     314                 :             :  *       for the wrong device. Re-call at IDLE (e.g. from
     315                 :             :  *       ds18b20_complete() in single-device mode, or between rounds) to switch
     316                 :             :  *       addressing.
     317                 :             :  */
     318                 :         925 : void ds18b20_select(const uint8_t* rom) {
     319                 :             :     /* Select is accepted only when no bus transaction is in flight, i.e. at
     320                 :             :      * driver IDLE. The per-device scan callback runs at DS18B20_ST_DECODE
     321                 :             :      * mid-round: a select() there is rejected so it cannot interrupt the
     322                 :             :      * in-progress scan. To leave scan mode, call select() between measurement
     323                 :             :      * rounds (at IDLE) or from the single-device ds18b20_complete() callback
     324                 :             :      * (which runs at IDLE). */
     325         [ +  + ]:         925 :     if (ctx.current_state != DS18B20_ST_IDLE) {
     326                 :          50 :         return;
     327                 :             :     }
     328         [ +  + ]:         875 :     if ((txn_ctx.flags & DS18B20_TXN_FLAG_FINISHED) == 0u) {
     329                 :             :         // A command transaction is running - reject to keep its addressing.
     330                 :          25 :         return;
     331                 :             :     }
     332         [ +  + ]:         850 :     if ((res_ctx.flags & DS18B20_RES_FLAG_FINISHED) == 0u) {
     333                 :             :         // A resolution change is running - reject to keep its addressing.
     334                 :          25 :         return;
     335                 :             :     }
     336         [ +  + ]:         825 :     if (onewire_search_active()) {
     337                 :             :         // The device search owns the timer - reject to keep its addressing.
     338                 :          25 :         return;
     339                 :             :     }
     340                 :             :     // Explicit single-device addressing: leave simultaneous-conversion mode.
     341                 :         800 :     ctx.flags &= (uint8_t)~DS18B20_FLAG_SCAN_MODE;
     342         [ +  + ]:         800 :     if (rom == 0) {
     343                 :          50 :         ctx.flags &= (uint8_t)~DS18B20_FLAG_ADDRESS_MODE;
     344                 :          50 :         return;
     345                 :             :     }
     346         [ +  + ]:        6750 :     for (uint8_t i = 0; i < DS18B20_ROM_BYTES; i++) {
     347                 :        6000 :         ctx.selected_rom[i] = rom[i];
     348                 :             :     }
     349                 :             :     /* The Match ROM table itself is rebuilt from selected_rom on every
     350                 :             :      * addressed operation (build_addr_cmd), so select only stores the ROM. */
     351                 :         750 :     ctx.flags |= DS18B20_FLAG_ADDRESS_MODE;
     352                 :             : }
     353                 :             : 
     354                 :             : /**
     355                 :             :  * @}
     356                 :             :  */
        

Generated by: LCOV version 2.0-1