# HG changeset patch # User Michiel Broek # Date 1695733038 -7200 # Node ID acc1904cd70d913e52351b35f77ce11b12b03f59 # Parent 995557380e5fb676199202ded6824e502d02a4dc Migrated to isp-idf v5.1 diff -r 995557380e5f -r acc1904cd70d components/esp32-owb/CMakeLists.txt --- a/components/esp32-owb/CMakeLists.txt Tue Sep 26 14:56:04 2023 +0200 +++ b/components/esp32-owb/CMakeLists.txt Tue Sep 26 14:57:18 2023 +0200 @@ -1,2 +1,12 @@ -idf_component_register(SRCS owb_rmt.c owb.c owb_gpio.c INCLUDE_DIRS include) +if (NOT IDF_VERSION_MAJOR) + set(IDF_VERSION_MAJOR 3) +endif() +if (IDF_VERSION_MAJOR LESS 5) + message(FATAL_ERROR "Can't build: requires ESP-IDF version 5.0 or above.") +endif() + +set(COMPONENT_ADD_INCLUDEDIRS include) +set(COMPONENT_SRCS "owb.c" "owb_gpio.c" "owb_rmt.c") +set(COMPONENT_REQUIRES "soc" "driver" "esp_rom") +register_component() diff -r 995557380e5f -r acc1904cd70d components/esp32-owb/README.md --- a/components/esp32-owb/README.md Tue Sep 26 14:56:04 2023 +0200 +++ b/components/esp32-owb/README.md Tue Sep 26 14:57:18 2023 +0200 @@ -2,15 +2,20 @@ This is a ESP32-compatible C component for the Maxim Integrated "1-Wire" protocol. -It is written and tested for version 3.0 of the [ESP-IDF](https://github.com/espressif/esp-idf) environment, using the xtensa-esp32-elf toolchain (gcc version 5.2.0, crosstool-ng-1.22.0-80-g6c4433a). +It is written for the `idf.py` target `esp32`, although it may work on other ESP-32 devices with minor modifications. + +It is tested for version 4.4.4 and 5.0.1 of the [ESP-IDF](https://github.com/espressif/esp-idf) environment. -Support for v2.1 is available on the [ESP-IDF_v2.1](https://github.com/DavidAntliff/esp32-owb/tree/ESP-IDF_v2.1) branch. +Legacy support for v2.1 is available on the [ESP-IDF_v2.1](https://github.com/DavidAntliff/esp32-owb/tree/ESP-IDF_v2.1) branch. This is no longer maintained. + +Legacy support for v3.0-v3.3 and v4.1-beta1 is available on the [ESP-IDF_v3.0-3.3_4.1-beta1](https://github.com/DavidAntliff/esp32-owb/tree/ESP-IDF_v3.0-3.3_4.1-beta1) branch. This is no longer maintained. ## Features This library includes: - * External power supply mode (parasitic mode not yet supported). + * External power supply mode. + * Parasitic power mode. * Static (stack-based) or dynamic (malloc-based) memory model. * No globals - support any number of 1-Wire buses simultaneously. * 1-Wire device detection and validation, including search for multiple devices on a single bus. @@ -23,7 +28,10 @@ however this proved to be too unreliable. A second method, using the ESP32's RMT peripheral, results in very accurate read/write timeslots and more reliable operation. -Therefore I highly recommend that you use the RMT driver. The GPIO driver should be considered deprecated. +Therefore I highly recommend that you use the RMT driver. *The GPIO driver is deprecated and will be removed.* + +See documentation for [esp32-ds18b20](https://www.github.com/DavidAntliff/esp32-ds18b20#parasitic-power-mode) +for further information about parasitic power mode, including strong pull-up configuration. ## Documentation @@ -39,16 +47,17 @@ ## Links - * [esp32-ds18b20](https://github.com/DavidAntliff/esp32-ds18b20) - ESP32-compatible DS18B20 Digital Thermometer component for ESP32 + * [esp32-ds18b20](https://github.com/DavidAntliff/esp32-ds18b20) - ESP32-compatible DS18B20 Digital Thermometer + component for ESP32 * [1-Wire Communication Through Software](https://www.maximintegrated.com/en/app-notes/index.mvp/id/126) * [1-Wire Search Algorithm](https://www.maximintegrated.com/en/app-notes/index.mvp/id/187) * [Espressif IoT Development Framework for ESP32](https://github.com/espressif/esp-idf) ## Acknowledgements -Thank you to [Chris Morgan](https://github.com/chmorgan) for his contribution of adding RMT peripheral support for more reliable operation. +Thank you to [Chris Morgan](https://github.com/chmorgan) for his contribution of adding RMT peripheral support for more +reliable operation. Parts of this code are based on references provided to the public domain by Maxim Integrated. "1-Wire" is a registered trademark of Maxim Integrated. - diff -r 995557380e5f -r acc1904cd70d components/esp32-owb/doc/Doxyfile --- a/components/esp32-owb/doc/Doxyfile Tue Sep 26 14:56:04 2023 +0200 +++ b/components/esp32-owb/doc/Doxyfile Tue Sep 26 14:57:18 2023 +0200 @@ -1072,6 +1072,25 @@ VERBATIM_HEADERS = YES +# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the +# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the +# cost of reduced performance. This can be particularly helpful with template +# rich C++ code for which doxygen's built-in parser lacks the necessary type +# information. +# Note: The availability of this option depends on whether or not doxygen was +# generated with the -Duse-libclang=ON option for CMake. +# The default value is: NO. + +CLANG_ASSISTED_PARSING = NO + +# If clang assisted parsing is enabled you can provide the compiler with command +# line options that you would normally use when invoking the compiler. Note that +# the include paths will already be set by doxygen for the files and directories +# specified with INPUT and INCLUDE_PATH. +# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES. + +CLANG_OPTIONS = + #--------------------------------------------------------------------------- # Configuration options related to the alphabetical class index #--------------------------------------------------------------------------- @@ -2195,7 +2214,7 @@ # http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent # Bell Labs. The other options in this section have no effect if this option is # set to NO -# The default value is: NO. +# The default value is: YES. HAVE_DOT = NO @@ -2351,7 +2370,9 @@ # Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order # to make the SVG files visible in IE 9+ (other browsers do not have this # requirement). -# Possible values are: png, jpg, gif, svg, png:gd, png:gd:gd, png:cairo, +# Possible values are: png, png:cairo, png:cairo:cairo, png:cairo:gd, png:gd, +# png:gd:gd, jpg, jpg:cairo, jpg:cairo:gd, jpg:gd, jpg:gd:gd, gif, gif:cairo, +# gif:cairo:gd, gif:gd, gif:gd:gd, svg, png:gd, png:gd:gd, png:cairo, # png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and # png:gdiplus:gdiplus. # The default value is: png. diff -r 995557380e5f -r acc1904cd70d components/esp32-owb/include/owb.h --- a/components/esp32-owb/include/owb.h Tue Sep 26 14:56:04 2023 +0200 +++ b/components/esp32-owb/include/owb.h Tue Sep 26 14:57:18 2023 +0200 @@ -30,7 +30,8 @@ * This component provides structures and functions that are useful for communicating * with devices connected to a Maxim Integrated 1-Wire® bus via a single GPIO. * - * Currently only externally powered devices are supported. Parasitic power is not supported. + * Externally powered and "parasite-powered" devices are supported. + * Please consult your device's datasheet for power requirements. */ #ifndef ONE_WIRE_BUS_H @@ -39,6 +40,7 @@ #include #include #include +#include "driver/gpio.h" #ifdef __cplusplus extern "C" { @@ -46,14 +48,18 @@ // ROM commands -#define OWB_ROM_SEARCH 0xF0 ///< Command ROM search -#define OWB_ROM_READ 0x33 ///< ROM read -#define OWB_ROM_MATCH 0x55 ///< ROM address match -#define OWB_ROM_SKIP 0xCC ///< Skip device -#define OWB_ROM_SEARCH_ALARM 0xEC ///< Search device with alarm set +#define OWB_ROM_SEARCH 0xF0 ///< Perform Search ROM cycle to identify devices on the bus +#define OWB_ROM_READ 0x33 ///< Read device ROM (single device on bus only) +#define OWB_ROM_MATCH 0x55 ///< Address a specific device on the bus by ROM +#define OWB_ROM_SKIP 0xCC ///< Address all devices on the bus simultaneously +#define OWB_ROM_SEARCH_ALARM 0xEC ///< Address all devices on the bus with a set alarm flag #define OWB_ROM_CODE_STRING_LENGTH (17) ///< Typical length of OneWire bus ROM ID as ASCII hex string, including null terminator +#ifndef GPIO_NUM_NC +# define GPIO_NUM_NC (-1) ///< ESP-IDF prior to v4.x does not define GPIO_NUM_NC +#endif + struct owb_driver; /** @@ -63,8 +69,9 @@ { const struct _OneWireBus_Timing * timing; ///< Pointer to timing information bool use_crc; ///< True if CRC checks are to be used when retrieving information from a device on the bus - - const struct owb_driver *driver; + bool use_parasitic_power; ///< True if parasitic-powered devices are expected on the bus + gpio_num_t strong_pullup_gpio; ///< Set if an external strong pull-up circuit is required + const struct owb_driver * driver; ///< Pointer to hardware driver instance } OneWireBus; /** @@ -94,45 +101,45 @@ */ typedef struct { - OneWireBus_ROMCode rom_code; - int last_discrepancy; - int last_family_discrepancy; - int last_device_flag; + OneWireBus_ROMCode rom_code; ///< Device ROM code + int last_discrepancy; ///< Bit index that identifies from which bit the next search discrepancy check should start + int last_family_discrepancy; ///< Bit index that identifies the last discrepancy within the first 8-bit family code of the ROM code + int last_device_flag; ///< Flag to indicate previous search was the last device detected } OneWireBus_SearchState; /** - * @brief Status codes + * @brief Represents the result of OWB API functions. */ typedef enum { - OWB_STATUS_OK, ///< Ok - OWB_STATUS_NOT_INITIALIZED, ///< Init error - OWB_STATUS_PARAMETER_NULL, ///< NULL parameter - OWB_STATUS_DEVICE_NOT_RESPONDING, ///< Device does not respond - OWB_STATUS_CRC_FAILED, ///< CRC error - OWB_STATUS_TOO_MANY_BITS, ///< Too many bits - OWB_STATUS_HW_ERROR ///< Hardware error + OWB_STATUS_NOT_SET = -1, ///< A status value has not been set + OWB_STATUS_OK = 0, ///< Operation succeeded + OWB_STATUS_NOT_INITIALIZED, ///< Function was passed an uninitialised variable + OWB_STATUS_PARAMETER_NULL, ///< Function was passed a null pointer + OWB_STATUS_DEVICE_NOT_RESPONDING, ///< No response received from the addressed device or devices + OWB_STATUS_CRC_FAILED, ///< CRC failed on data received from a device or devices + OWB_STATUS_TOO_MANY_BITS, ///< Attempt to write an incorrect number of bits to the One Wire Bus + OWB_STATUS_HW_ERROR ///< A hardware error occurred } owb_status; /** NOTE: Driver assumes that (*init) was called prior to any other methods */ struct owb_driver { const char* name; - owb_status (*uninitialize)(const OneWireBus * bus); - - owb_status (*reset)(const OneWireBus * bus, bool *is_present); - - /** NOTE: The data is shifted out of the low bits, eg. it is written in the order of lsb to msb */ + owb_status (*reset)(const OneWireBus *bus, bool *is_present); owb_status (*write_bits)(const OneWireBus *bus, uint8_t out, int number_of_bits_to_write); - - /** NOTE: Data is read into the high bits, eg. each bit read is shifted down before the next bit is read */ + owb_status (*write_bytes)(const OneWireBus *bus, uint8_t *bytes, int number_of_bytes_to_write); owb_status (*read_bits)(const OneWireBus *bus, uint8_t *in, int number_of_bits_to_read); + owb_status (*read_bytes)(const OneWireBus *bus, uint64_t *in, int number_of_bytes_to_read); }; +/// @cond ignore +// note: the new owb_rmt driver uses the ESP-IDF's built-in `__containerof()` macro instead of this #define container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) );}) +/// @endcond /** * @brief call to release resources after completing use of the OneWireBus @@ -150,29 +157,82 @@ owb_status owb_use_crc(OneWireBus * bus, bool use_crc); /** + * @brief Enable or disable use of parasitic power on the One Wire Bus. + * This affects how devices signal on the bus, as devices cannot + * signal by pulling the bus low when it is pulled high. + * @param[in] bus Pointer to initialised bus instance. + * @param[in] use_parasitic_power True to enable parasitic power, false to disable. + * @return status + */ +owb_status owb_use_parasitic_power(OneWireBus * bus, bool use_parasitic_power); + +/** + * @brief Enable or disable use of extra GPIO to activate strong pull-up circuit. + * This only has effect if parasitic power mode is enabled. + * signal by pulling the bus low when it is pulled high. + * @param[in] bus Pointer to initialised bus instance. + * @param[in] gpio Set to GPIO number to use, or GPIO_NUM_NC to disable. + * @return status + */ +owb_status owb_use_strong_pullup_gpio(OneWireBus * bus, gpio_num_t gpio); + +/** * @brief Read ROM code from device - only works when there is a single device on the bus. * @param[in] bus Pointer to initialised bus instance. * @param[out] rom_code the value read from the device's rom * @return status */ -owb_status owb_read_rom(const OneWireBus * bus, OneWireBus_ROMCode *rom_code); +owb_status owb_read_rom(const OneWireBus * bus, OneWireBus_ROMCode * rom_code); /** * @brief Verify the device specified by ROM code is present. * @param[in] bus Pointer to initialised bus instance. * @param[in] rom_code ROM code to verify. - * @param[out] is_present set to true if a device is present, false if not + * @param[out] is_present Set to true if a device is present, false if not * @return status */ -owb_status owb_verify_rom(const OneWireBus * bus, OneWireBus_ROMCode rom_code, bool* is_present); +owb_status owb_verify_rom(const OneWireBus * bus, OneWireBus_ROMCode rom_code, bool * is_present); /** * @brief Reset the 1-Wire bus. * @param[in] bus Pointer to initialised bus instance. - * @param[out] a_device_present set to true if at least one device is present on the bus + * @param[out] is_present set to true if at least one device is present on the bus + * @return status + */ +owb_status owb_reset(const OneWireBus * bus, bool * is_present); + +/** + * @brief Read a single bit from the 1-Wire bus. + * @param[in] bus Pointer to initialised bus instance. + * @param[out] out The bit value read from the bus. + * @return status + */ +owb_status owb_read_bit(const OneWireBus * bus, uint8_t * out); + +/** + * @brief Read a single byte from the 1-Wire bus. + * @param[in] bus Pointer to initialised bus instance. + * @param[out] out The byte value read from the bus (lsb only). * @return status */ -owb_status owb_reset(const OneWireBus * bus, bool* a_device_present); +owb_status owb_read_byte(const OneWireBus * bus, uint8_t * out); + +/** + * @brief Read a number of bytes from the 1-Wire bus. + * @param[in] bus Pointer to initialised bus instance. + * @param[in, out] buffer Pointer to buffer to receive read data. + * @param[in] len Number of bytes to read, must not exceed length of receive buffer. + * @return status. + */ +owb_status owb_read_bytes(const OneWireBus * bus, uint8_t * buffer, unsigned int len); + +/** + * @brief Write a bit to the 1-Wire bus. + * @param[in] bus Pointer to initialised bus instance. + * @param[in] bit Value to write (lsb only). + * @return status + */ +owb_status owb_write_bit(const OneWireBus * bus, uint8_t bit); /** * @brief Write a single byte to the 1-Wire bus. @@ -183,23 +243,6 @@ owb_status owb_write_byte(const OneWireBus * bus, uint8_t data); /** - * @brief Read a single byte from the 1-Wire bus. - * @param[in] bus Pointer to initialised bus instance. - * @param[out] out The byte value read from the bus. - * @return status - */ -owb_status owb_read_byte(const OneWireBus * bus, uint8_t *out); - -/** - * @brief Read a number of bytes from the 1-Wire bus. - * @param[in] bus Pointer to initialised bus instance. - * @param[in, out] buffer Pointer to buffer to receive read data. - * @param[in] len Number of bytes to read, must not exceed length of receive buffer. - * @return status. - */ -owb_status owb_read_bytes(const OneWireBus * bus, uint8_t * buffer, size_t len); - -/** * @brief Write a number of bytes to the 1-Wire bus. * @param[in] bus Pointer to initialised bus instance. * @param[in] buffer Pointer to buffer to write data from. @@ -267,6 +310,16 @@ */ char * owb_string_from_rom_code(OneWireBus_ROMCode rom_code, char * buffer, size_t len); +/** + * @brief Enable or disable the strong-pullup GPIO, if configured. + * @param[in] bus Pointer to initialised bus instance. + * @param[in] enable If true, enable the external strong pull-up by setting the GPIO high. + * If false, disable the external strong pull-up by setting the GPIO low. + * @return status + */ +owb_status owb_set_strong_pullup(const OneWireBus * bus, bool enable); + + #include "owb_gpio.h" #include "owb_rmt.h" diff -r 995557380e5f -r acc1904cd70d components/esp32-owb/include/owb_gpio.h --- a/components/esp32-owb/include/owb_gpio.h Tue Sep 26 14:56:04 2023 +0200 +++ b/components/esp32-owb/include/owb_gpio.h Tue Sep 26 14:57:18 2023 +0200 @@ -23,6 +23,16 @@ * SOFTWARE. */ +/** + * @file + * @brief Interface definitions for the ESP32 GPIO driver used to communicate with devices + * on the One Wire Bus. + * + * @deprecated + * This driver is deprecated and may be removed at some stage. It is not recommended for use + * due to issues with imprecise timing. + */ + #pragma once #ifndef OWB_GPIO_H #define OWB_GPIO_H @@ -34,7 +44,7 @@ #endif /** - * @brief 1-wire bus connection on the gpio. + * @brief GPIO driver information */ typedef struct { diff -r 995557380e5f -r acc1904cd70d components/esp32-owb/include/owb_rmt.h --- a/components/esp32-owb/include/owb_rmt.h Tue Sep 26 14:56:04 2023 +0200 +++ b/components/esp32-owb/include/owb_rmt.h Tue Sep 26 14:57:18 2023 +0200 @@ -23,34 +23,79 @@ * SOFTWARE. */ +/** + * @file + * @brief Interface definitions for ESP32 RMT driver used to communicate with devices + * on the One Wire Bus. + * + * This is the recommended driver. + */ + #pragma once #ifndef OWB_RMT_H #define OWB_RMT_H #include "freertos/FreeRTOS.h" #include "freertos/queue.h" -#include "freertos/ringbuf.h" -#include "driver/rmt.h" + +#include "driver/rmt_tx.h" +#include "driver/rmt_rx.h" + +#include "owb.h" // for tyoe OneWireBus #ifdef __cplusplus extern "C" { #endif +/** + * @brief RMT driver information + */ typedef struct { - int tx_channel; ///< RMT channel to use for TX - int rx_channel; ///< RMT channel to use for RX - RingbufHandle_t rb; ///< Ring buffer handle - int gpio; ///< OneWireBus GPIO - OneWireBus bus; ///< OneWireBus instance + rmt_channel_handle_t tx_channel_handle; ///< RMT transmit channel, allocated by RMT driver + rmt_channel_handle_t rx_channel_handle; ///< RMT receive channel, allocated by RMT driver + rmt_encoder_handle_t copy_encoder_handle; ///< RMT built-in data encoder that sends pre-defined symbols + rmt_encoder_handle_t bytes_encoder_handle; ///< RMT built-in data encoder that converts bits into symbols + rmt_symbol_word_t *rx_buffer; ///< RMT receive channel symbol buffer + size_t rx_buffer_size_in_bytes; ///< Size of the RMT received buffer, in bytes + QueueHandle_t rx_queue; ///< xQueue to receive RMT symbols from the `on_recv_done` callback + int gpio; ///< OneWireBus GPIO + OneWireBus bus; ///< OneWireBus instance (see owb.h) } owb_rmt_driver_info; /** * @brief Initialise the RMT driver. - * @return OneWireBus*, pass this into the other OneWireBus public API functions + * @param[in] info Pointer to an uninitialized owb_rmt_driver_info structure. + * Note: the structure must remain in scope for the lifetime of this component. + * @param[in] gpio_num The GPIO number to use as the One Wire bus data line. + * @param tx_channel NOW IGNORED: the new RMT driver allocates channels dynamically. + * @param rx_channel NOW IGNORED: the new RMT driver allocates channels dynamically. + * @return OneWireBus *, pass this into the other OneWireBus public API functions */ -OneWireBus* owb_rmt_initialize(owb_rmt_driver_info *info, uint8_t gpio_num, - rmt_channel_t tx_channel, rmt_channel_t rx_channel); +OneWireBus* owb_rmt_initialize(owb_rmt_driver_info * info, gpio_num_t gpio_num, + /*rmt_channel_t*/ int tx_channel, /* rmt_channel_t*/ int rx_channel); + + +/** + * @brief Legacy RMT channel IDs. + * + * These are no longer used for anything. They are defined here purely so + * that code written for the old rmt driver can still compile. + */ +typedef enum { + RMT_CHANNEL_0, /*!< RMT channel number 0 */ + RMT_CHANNEL_1, /*!< RMT channel number 1 */ + RMT_CHANNEL_2, /*!< RMT channel number 2 */ + RMT_CHANNEL_3, /*!< RMT channel number 3 */ +#if SOC_RMT_CHANNELS_PER_GROUP > 4 + RMT_CHANNEL_4, /*!< RMT channel number 4 */ + RMT_CHANNEL_5, /*!< RMT channel number 5 */ + RMT_CHANNEL_6, /*!< RMT channel number 6 */ + RMT_CHANNEL_7, /*!< RMT channel number 7 */ +#endif + RMT_CHANNEL_MAX /*!< Number of RMT channels */ +} rmt_channel_t; + #ifdef __cplusplus } diff -r 995557380e5f -r acc1904cd70d components/esp32-owb/include/owb_rmt_bus_symbols.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/components/esp32-owb/include/owb_rmt_bus_symbols.h Tue Sep 26 14:57:18 2023 +0200 @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2023 mjcross + * + * SPDX-License-Identifier: MIT +**/ + +#include "owb_rmt_bus_timings.h" + +// RMT transmit channel symbols for the onewire bus signals and conditions +// + +// basic bus levels +// ---------------- +// note: we configure the transmit channel to be hardware inverted, +// so that the bus initialises in the 'released' state +#define OWB_RMT_BUS_ASSERTED 1 +#define OWB_RMT_BUS_RELEASED 0 + +// bus symbols as `rmt_symbol_word_t` +// ---------------------------------- + +// send 'zero' bit +#define OWB_RMT_SYMBOL_0BIT { \ + .level0 = OWB_RMT_BUS_ASSERTED, \ + .duration0 = OWB_TIMING_PARAM_C, \ + .level1 = OWB_RMT_BUS_RELEASED, \ + .duration1 = OWB_TIMING_PARAM_D } + +// send 'one' bit +#define OWB_RMT_SYMBOL_1BIT { \ + .level0 = OWB_RMT_BUS_ASSERTED, \ + .duration0 = OWB_TIMING_PARAM_A, \ + .level1 = OWB_RMT_BUS_RELEASED, \ + .duration1 = OWB_TIMING_PARAM_B } + +// send bus reset +#define OWB_RMT_SYMBOL_RESET { \ + .level0 = OWB_RMT_BUS_ASSERTED, \ + .duration0 = OWB_TIMING_PARAM_H, \ + .level1 = OWB_RMT_BUS_RELEASED, \ + .duration1 = OWB_TIMING_PARAM_I + OWB_TIMING_PARAM_J } + diff -r 995557380e5f -r acc1904cd70d components/esp32-owb/include/owb_rmt_bus_timings.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/components/esp32-owb/include/owb_rmt_bus_timings.h Tue Sep 26 14:57:18 2023 +0200 @@ -0,0 +1,20 @@ +// onewire bus master timings + +// standard rate master timings recommended in the 1-Wire specification +// the values below are the ones recommended by the specification. + +// for the meaning of each parameter, see the following document: +// https://www.analog.com/en/technical-articles/1wire-communication-through-software.html + +// all values in microsec +#define OWB_TIMING_PARAM_A 6 +#define OWB_TIMING_PARAM_B 64 +#define OWB_TIMING_PARAM_C 60 +#define OWB_TIMING_PARAM_D 10 +#define OWB_TIMING_PARAM_E 9 +#define OWB_TIMING_PARAM_F 55 +#define OWB_TIMING_PARAM_G 0 +#define OWB_TIMING_PARAM_H 480 +#define OWB_TIMING_PARAM_I 70 +#define OWB_TIMING_PARAM_J 410 + diff -r 995557380e5f -r acc1904cd70d components/esp32-owb/library.json --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/components/esp32-owb/library.json Tue Sep 26 14:57:18 2023 +0200 @@ -0,0 +1,30 @@ +{ + "name": "esp32-owb", + "keywords": "onewire, 1-wire, bus, sensor, temperature", + "description": "ESP32-compatible C component for the Maxim Integrated 1-Wire protocol.", + "repository": + { + "type": "git", + "url": "https://github.com/DavidAntliff/esp32-owb.git" + }, + "authors": + [ + { + "name": "David Antliff", + "url": "https://github.com/DavidAntliff", + "maintainer": true + }, + { + "name": "Chris Morgan", + "url": "https://github.com/chmorgan" + } + ], + "version": "0.1", + "frameworks": "espidf", + "platforms": "espressif32", + "build": { + "flags": [ + "-I include/" + ] + } +} diff -r 995557380e5f -r acc1904cd70d components/esp32-owb/owb.c --- a/components/esp32-owb/owb.c Tue Sep 26 14:56:04 2023 +0200 +++ b/components/esp32-owb/owb.c Tue Sep 26 14:57:18 2023 +0200 @@ -38,6 +38,7 @@ #include "esp_log.h" #include "sdkconfig.h" #include "driver/gpio.h" +#include "rom/gpio.h" // for gpio_pad_select_gpio() #include "owb.h" #include "owb_gpio.h" @@ -102,7 +103,7 @@ do { crc = _calc_crc(crc, *buffer++); - ESP_LOGD(TAG, "crc 0x%02x, len %d", (int)crc, (int)len); + ESP_LOGD(TAG, "buffer 0x%02x, crc 0x%02x, len %d", (uint8_t)*(buffer - 1), (int)crc, (int)len); } while (--len > 0); return crc; @@ -112,7 +113,7 @@ * @param[out] is_found true if a device was found, false if not * @return status */ -static owb_status _search(const OneWireBus * bus, OneWireBus_SearchState * state, bool *is_found) +static owb_status _search(const OneWireBus * bus, OneWireBus_SearchState * state, bool * is_found) { // Based on https://www.maximintegrated.com/en/app-notes/index.mvp/id/187 @@ -126,7 +127,7 @@ uint8_t search_direction = 0; bool search_result = false; uint8_t crc8 = 0; - owb_status status; + owb_status status = OWB_STATUS_NOT_SET; // if the last call was not the last one if (!state->last_device_flag) @@ -160,21 +161,27 @@ if (id_bit && cmp_id_bit) { break; - } else + } + else { // all devices coupled have 0 or 1 if (id_bit != cmp_id_bit) { search_direction = (id_bit) ? 1 : 0; // bit write value for search - } else + } + else { // if this discrepancy if before the Last Discrepancy // on a previous next then pick the same as last time if (id_bit_number < state->last_discrepancy) + { search_direction = ((state->rom_code.bytes[rom_byte_number] & rom_byte_mask) > 0); + } else + { // if equal to last pick 1, if not then pick 0 search_direction = (id_bit_number == state->last_discrepancy); + } // if 0 was picked then record its position in LastZero if (search_direction == 0) @@ -183,16 +190,22 @@ // check for Last discrepancy in family if (last_zero < 9) + { state->last_family_discrepancy = last_zero; + } } } // set or clear the bit in the ROM byte rom_byte_number // with mask rom_byte_mask if (search_direction == 1) + { state->rom_code.bytes[rom_byte_number] |= rom_byte_mask; + } else + { state->rom_code.bytes[rom_byte_number] &= ~rom_byte_mask; + } // serial number search direction write bit bus->driver->write_bits(bus, search_direction, 1); @@ -211,7 +224,7 @@ } } } - while(rom_byte_number < 8); // loop until through all ROM bytes 0-7 + while (rom_byte_number < 8); // loop until through all ROM bytes 0-7 // if the search was successful then if (!((id_bit_number < 65) || (crc8 != 0))) @@ -221,7 +234,9 @@ // check for last device if (state->last_discrepancy == 0) + { state->last_device_flag = true; + } search_result = true; } @@ -247,12 +262,13 @@ owb_status owb_uninitialize(OneWireBus * bus) { - owb_status status; + owb_status status = OWB_STATUS_NOT_SET; - if(!_is_init(bus)) + if (!_is_init(bus)) { status = OWB_STATUS_NOT_INITIALIZED; - } else + } + else { bus->driver->uninitialize(bus); status = OWB_STATUS_OK; @@ -263,15 +279,17 @@ owb_status owb_use_crc(OneWireBus * bus, bool use_crc) { - owb_status status; + owb_status status = OWB_STATUS_NOT_SET; - if(!bus) + if (!bus) { status = OWB_STATUS_PARAMETER_NULL; - } else if (!_is_init(bus)) + } + else if (!_is_init(bus)) { status = OWB_STATUS_NOT_INITIALIZED; - } else + } + else { bus->use_crc = use_crc; ESP_LOGD(TAG, "use_crc %d", bus->use_crc); @@ -282,19 +300,81 @@ return status; } +owb_status owb_use_parasitic_power(OneWireBus * bus, bool use_parasitic_power) +{ + owb_status status = OWB_STATUS_NOT_SET; + + if (!bus) + { + status = OWB_STATUS_PARAMETER_NULL; + } + else if (!_is_init(bus)) + { + status = OWB_STATUS_NOT_INITIALIZED; + } + else + { + bus->use_parasitic_power = use_parasitic_power; + ESP_LOGD(TAG, "use_parasitic_power %d", bus->use_parasitic_power); + + status = OWB_STATUS_OK; + } + + return status; +} + +owb_status owb_use_strong_pullup_gpio(OneWireBus * bus, gpio_num_t gpio) +{ + owb_status status = OWB_STATUS_NOT_SET; + + if (!bus) + { + status = OWB_STATUS_PARAMETER_NULL; + } + else if (!_is_init(bus)) + { + status = OWB_STATUS_NOT_INITIALIZED; + } + else + { + if (gpio != GPIO_NUM_NC) { + // The strong GPIO pull-up is only activated if parasitic-power mode is enabled + if (!bus->use_parasitic_power) { + ESP_LOGW(TAG, "Strong pull-up GPIO set with parasitic-power disabled"); + } + + gpio_pad_select_gpio(gpio); + gpio_set_direction(gpio, GPIO_MODE_OUTPUT); + } + else + { + gpio_reset_pin(bus->strong_pullup_gpio); + } + + bus->strong_pullup_gpio = gpio; + ESP_LOGD(TAG, "use_strong_pullup_gpio %d", bus->strong_pullup_gpio); + + status = OWB_STATUS_OK; + } + + return status; +} + owb_status owb_read_rom(const OneWireBus * bus, OneWireBus_ROMCode *rom_code) { - owb_status status; + owb_status status = OWB_STATUS_NOT_SET; memset(rom_code, 0, sizeof(OneWireBus_ROMCode)); - if(!bus || !rom_code) + if (!bus || !rom_code) { status = OWB_STATUS_PARAMETER_NULL; - } else if (!_is_init(bus)) + } + else if (!_is_init(bus)) { status = OWB_STATUS_NOT_INITIALIZED; - } else + } + else { bool is_present; bus->driver->reset(bus, &is_present); @@ -311,11 +391,13 @@ ESP_LOGE(TAG, "CRC failed"); memset(rom_code->bytes, 0, sizeof(OneWireBus_ROMCode)); status = OWB_STATUS_CRC_FAILED; - } else + } + else { status = OWB_STATUS_OK; } - } else + } + else { status = OWB_STATUS_OK; } @@ -333,9 +415,9 @@ return status; } -owb_status owb_verify_rom(const OneWireBus * bus, OneWireBus_ROMCode rom_code, bool* is_present) +owb_status owb_verify_rom(const OneWireBus * bus, OneWireBus_ROMCode rom_code, bool * is_present) { - owb_status status; + owb_status status = OWB_STATUS_NOT_SET; bool result = false; if (!bus || !is_present) @@ -349,25 +431,25 @@ else { OneWireBus_SearchState state = { + .rom_code = rom_code, .last_discrepancy = 64, .last_device_flag = false, }; bool is_found = false; - while (!state.last_device_flag && !is_found) + _search(bus, &state, &is_found); + if (is_found) { - _search(bus, &state, &is_found); - if (is_found) + result = true; + for (int i = 0; i < sizeof(state.rom_code.bytes) && result; ++i) { - result = true; - for (int i = 0; i < sizeof(state.rom_code.bytes) && result; ++i) - { - result = rom_code.bytes[i] == state.rom_code.bytes[i]; - ESP_LOGD(TAG, "%02x %02x", rom_code.bytes[i], state.rom_code.bytes[i]); - } - is_found = result; + result = rom_code.bytes[i] == state.rom_code.bytes[i]; + ESP_LOGD(TAG, "%02x %02x", rom_code.bytes[i], state.rom_code.bytes[i]); } + is_found = result; } + ESP_LOGD(TAG, "state.last_discrepancy %d, state.last_device_flag %d, is_found %d", + state.last_discrepancy, state.last_device_flag, is_found); ESP_LOGD(TAG, "rom code %sfound", result ? "" : "not "); *is_present = result; @@ -377,19 +459,116 @@ return status; } -owb_status owb_reset(const OneWireBus * bus, bool* a_device_present) +owb_status owb_reset(const OneWireBus * bus, bool * a_device_present) +{ + owb_status status = OWB_STATUS_NOT_SET; + + if (!bus || !a_device_present) + { + status = OWB_STATUS_PARAMETER_NULL; + } + else if(!_is_init(bus)) + { + status = OWB_STATUS_NOT_INITIALIZED; + } + else + { + status = bus->driver->reset(bus, a_device_present); + } + + return status; +} + +owb_status owb_read_bit(const OneWireBus * bus, uint8_t * out) { - owb_status status; + owb_status status = OWB_STATUS_NOT_SET; - if(!bus || !a_device_present) + if (!bus || !out) + { + status = OWB_STATUS_PARAMETER_NULL; + } + else if (!_is_init(bus)) + { + status = OWB_STATUS_NOT_INITIALIZED; + } + else + { + bus->driver->read_bits(bus, out, 1); + ESP_LOGD(TAG, "owb_read_bit: %02x", *out); + status = OWB_STATUS_OK; + } + + return status; +} + +owb_status owb_read_byte(const OneWireBus * bus, uint8_t * out) +{ + owb_status status = OWB_STATUS_NOT_SET; + + if (!bus || !out) { status = OWB_STATUS_PARAMETER_NULL; - } else if(!_is_init(bus)) + } + else if (!_is_init(bus)) + { + status = OWB_STATUS_NOT_INITIALIZED; + } + else + { + bus->driver->read_bits(bus, out, 8); + ESP_LOGD(TAG, "owb_read_byte: %02x", *out); + status = OWB_STATUS_OK; + } + + return status; +} + +owb_status owb_read_bytes(const OneWireBus * bus, uint8_t * buffer, unsigned int len) +{ + owb_status status = OWB_STATUS_NOT_SET; + + if (!bus || !buffer) + { + status = OWB_STATUS_PARAMETER_NULL; + } + else if (!_is_init(bus)) { status = OWB_STATUS_NOT_INITIALIZED; - } else + } + else { - bus->driver->reset(bus, a_device_present); + for (int i = 0; i < len; ++i) + { + uint8_t out; + bus->driver->read_bits(bus, &out, 8); + buffer[i] = out; + } + + ESP_LOGD(TAG, "owb_read_bytes, len %d:", len); + ESP_LOG_BUFFER_HEX_LEVEL(TAG, buffer, len, ESP_LOG_DEBUG); + + status = OWB_STATUS_OK; + } + + return status; +} + +owb_status owb_write_bit(const OneWireBus * bus, const uint8_t bit) +{ + owb_status status = OWB_STATUS_NOT_SET; + + if (!bus) + { + status = OWB_STATUS_PARAMETER_NULL; + } + else if (!_is_init(bus)) + { + status = OWB_STATUS_NOT_INITIALIZED; + } + else + { + ESP_LOGD(TAG, "owb_write_bit: %02x", bit); + bus->driver->write_bits(bus, bit & 0x01u, 1); status = OWB_STATUS_OK; } @@ -398,16 +577,19 @@ owb_status owb_write_byte(const OneWireBus * bus, uint8_t data) { - owb_status status; + owb_status status = OWB_STATUS_NOT_SET; - if(!bus) + if (!bus) { status = OWB_STATUS_PARAMETER_NULL; - } else if (!_is_init(bus)) + } + else if (!_is_init(bus)) { status = OWB_STATUS_NOT_INITIALIZED; - } else + } + else { + ESP_LOGD(TAG, "owb_write_byte: %02x", data); bus->driver->write_bits(bus, data, 8); status = OWB_STATUS_OK; } @@ -415,62 +597,23 @@ return status; } -owb_status owb_read_byte(const OneWireBus * bus, uint8_t *out) +owb_status owb_write_bytes(const OneWireBus * bus, const uint8_t * buffer, size_t len) { - owb_status status; + owb_status status = OWB_STATUS_NOT_SET; - if(!bus || !out) - { - status = OWB_STATUS_PARAMETER_NULL; - } else if (!_is_init(bus)) - { - status = OWB_STATUS_NOT_INITIALIZED; - } else - { - bus->driver->read_bits(bus, out, 8); - status = OWB_STATUS_OK; - } - - return status; -} - -owb_status owb_read_bytes(const OneWireBus * bus, uint8_t * buffer, unsigned int len) -{ - owb_status status; - - if(!bus || !buffer) + if (!bus || !buffer) { status = OWB_STATUS_PARAMETER_NULL; - } else if (!_is_init(bus)) + } + else if (!_is_init(bus)) { status = OWB_STATUS_NOT_INITIALIZED; - } else + } + else { - for (int i = 0; i < len; ++i) - { - uint8_t out; - bus->driver->read_bits(bus, &out, 8); - buffer[i] = out; - } - - status = OWB_STATUS_OK; - } + ESP_LOGD(TAG, "owb_write_bytes, len %d:", len); + ESP_LOG_BUFFER_HEX_LEVEL(TAG, buffer, len, ESP_LOG_DEBUG); - return status; -} - -owb_status owb_write_bytes(const OneWireBus * bus, const uint8_t * buffer, unsigned int len) -{ - owb_status status; - - if(!bus || !buffer) - { - status = OWB_STATUS_PARAMETER_NULL; - } else if (!_is_init(bus)) - { - status = OWB_STATUS_NOT_INITIALIZED; - } else - { for (int i = 0; i < len; i++) { bus->driver->write_bits(bus, buffer[i], 8); @@ -484,15 +627,17 @@ owb_status owb_write_rom_code(const OneWireBus * bus, OneWireBus_ROMCode rom_code) { - owb_status status; + owb_status status = OWB_STATUS_NOT_SET; - if(!bus) + if (!bus) { status = OWB_STATUS_PARAMETER_NULL; - } else if (!_is_init(bus)) + } + else if (!_is_init(bus)) { status = OWB_STATUS_NOT_INITIALIZED; - } else + } + else { owb_write_bytes(bus, (uint8_t*)&rom_code, sizeof(rom_code)); status = OWB_STATUS_OK; @@ -511,18 +656,20 @@ return _calc_crc_block(crc, data, len); } -owb_status owb_search_first(const OneWireBus * bus, OneWireBus_SearchState * state, bool* found_device) +owb_status owb_search_first(const OneWireBus * bus, OneWireBus_SearchState * state, bool * found_device) { bool result; - owb_status status; + owb_status status = OWB_STATUS_NOT_SET; - if(!bus || !state || !found_device) + if (!bus || !state || !found_device) { status = OWB_STATUS_PARAMETER_NULL; - } else if (!_is_init(bus)) + } + else if (!_is_init(bus)) { status = OWB_STATUS_NOT_INITIALIZED; - } else + } + else { memset(&state->rom_code, 0, sizeof(state->rom_code)); state->last_discrepancy = 0; @@ -537,18 +684,20 @@ return status; } -owb_status owb_search_next(const OneWireBus * bus, OneWireBus_SearchState * state, bool* found_device) +owb_status owb_search_next(const OneWireBus * bus, OneWireBus_SearchState * state, bool * found_device) { - owb_status status; + owb_status status = OWB_STATUS_NOT_SET; bool result = false; - if(!bus || !state || !found_device) + if (!bus || !state || !found_device) { status = OWB_STATUS_PARAMETER_NULL; - } else if (!_is_init(bus)) + } + else if (!_is_init(bus)) { status = OWB_STATUS_NOT_INITIALIZED; - } else + } + else { _search(bus, state, &result); status = OWB_STATUS_OK; @@ -568,3 +717,29 @@ } return buffer; } + +owb_status owb_set_strong_pullup(const OneWireBus * bus, bool enable) +{ + owb_status status = OWB_STATUS_NOT_SET; + + if (!bus) + { + status = OWB_STATUS_PARAMETER_NULL; + } + else if (!_is_init(bus)) + { + status = OWB_STATUS_NOT_INITIALIZED; + } + else + { + if (bus->use_parasitic_power && bus->strong_pullup_gpio != GPIO_NUM_NC) + { + gpio_set_level(bus->strong_pullup_gpio, enable ? 1 : 0); + ESP_LOGD(TAG, "strong pullup GPIO %d", enable); + } // else ignore + + status = OWB_STATUS_OK; + } + + return status; +} diff -r 995557380e5f -r acc1904cd70d components/esp32-owb/owb_gpio.c --- a/components/esp32-owb/owb_gpio.c Tue Sep 26 14:56:04 2023 +0200 +++ b/components/esp32-owb/owb_gpio.c Tue Sep 26 14:57:18 2023 +0200 @@ -38,6 +38,8 @@ #include "esp_log.h" #include "sdkconfig.h" #include "driver/gpio.h" +#include "rom/ets_sys.h" // for ets_delay_us() +#include "rom/gpio.h" // for gpio_pad_select_gpio() #include "owb.h" #include "owb_gpio.h" @@ -63,7 +65,7 @@ { uint32_t A, B, C, D, E, F, G, H, I, J; }; -//// @endcond +/// @endcond // 1-Wire timing delays (standard) in microseconds. // Labels and values are from https://www.maximintegrated.com/en/app-notes/index.mvp/id/126 @@ -85,7 +87,9 @@ ets_delay_us(time_us); } +/// @cond ignore #define info_from_bus(owb) container_of(owb, owb_gpio_driver_info, bus) +/// @endcond /** * @brief Generate a 1-Wire reset (initialization). @@ -259,13 +263,14 @@ .read_bits = _read_bits }; -OneWireBus* owb_gpio_initialize(owb_gpio_driver_info *driver_info, int gpio) +OneWireBus* owb_gpio_initialize(owb_gpio_driver_info * driver_info, int gpio) { - ESP_LOGI(TAG, "%s(): gpio %d\n", __func__, gpio); + ESP_LOGD(TAG, "%s(): gpio %d\n", __func__, gpio); driver_info->gpio = gpio; driver_info->bus.driver = &gpio_function_table; driver_info->bus.timing = &_StandardTiming; + driver_info->bus.strong_pullup_gpio = GPIO_NUM_NC; // platform specific: gpio_pad_select_gpio(driver_info->gpio); diff -r 995557380e5f -r acc1904cd70d components/esp32-owb/owb_rmt.c --- a/components/esp32-owb/owb_rmt.c Tue Sep 26 14:56:04 2023 +0200 +++ b/components/esp32-owb/owb_rmt.c Tue Sep 26 14:57:18 2023 +0200 @@ -1,463 +1,665 @@ -/* -Created by Chris Morgan based on the nodemcu project driver. -Copyright 2017 Chris Morgan - -Ported to ESP32 RMT peripheral for low-level signal generation by Arnim Laeuger. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Much of the code was inspired by Derek Yerger's code, though I don't -think much of that remains. In any event that was.. - (copyleft) 2006 by Derek Yerger - Free to distribute freely. +/** + * Copyright (c) 2023 mjcross + * + * SPDX-License-Identifier: MIT +**/ -The CRC code was excerpted and inspired by the Dallas Semiconductor -sample code bearing this copyright. -//--------------------------------------------------------------------------- -// Copyright (C) 2000 Dallas Semiconductor Corporation, All Rights Reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the "Software"), -// to deal in the Software without restriction, including without limitation -// the rights to use, copy, modify, merge, publish, distribute, sublicense, -// and/or sell copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -// IN NO EVENT SHALL DALLAS SEMICONDUCTOR BE LIABLE FOR ANY CLAIM, DAMAGES -// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. -// -// Except as contained in this notice, the name of Dallas Semiconductor -// shall not be used except as stated in the Dallas Semiconductor -// Branding Policy. -//-------------------------------------------------------------------------- -*/ +#include "esp_log.h" +#include "driver/rmt_tx.h" +#include "driver/rmt_rx.h" #include "owb.h" +#include "owb_rmt_bus_timings.h" +#include "owb_rmt_bus_symbols.h" -#include "driver/rmt.h" -#include "driver/gpio.h" -#include "esp_log.h" +#define OWB_RMT_CLK_HZ 1000000 // run the RMT at 1MHz to get 1us ticks +#define OWB_RMT_TX_MEM_BLOCK_SYMBOLS 64 // size of TX memory block in units of rmt_symbol_word_t (must be even) +#define OWB_RMT_TX_QUEUE_DEPTH 4 // max pending TX transfers +#define OWB_RMT_MAX_READ_BITS 64 // maximum number of bits that will be read at once (used to calculate buffer size) +#define OWB_RMT_RX_MEM_BLOCK_SYMBOLS (OWB_RMT_MAX_READ_BITS + 2) // size of RX memory block in units of rmt_symbol_word_t (must be even) +#define OWB_RMT_RX_MIN_NS 1000 // RMT receive channel glitch rejection threshold (ns) +#define OWB_RMT_TIMEOUT_MS 1000 // timeout threshold for an RMT task (ms) +#define OWB_TIMING_MARGIN 3 // timing variation permitted by our event parsing functions (in microsec) + +// debug parsing of RMT raw symbols +//#define OWB_RMT_DEBUG + +// tag for log messages +static const char * TAG = "owb_rmt"; + + +//------ +// private API functions and constants +//------ -#undef OW_DEBUG +// onewire bus symbols as rmt_symbol_word_t +static const rmt_symbol_word_t owb_rmt_symbol_0bit = OWB_RMT_SYMBOL_0BIT; +static const rmt_symbol_word_t owb_rmt_symbol_1bit = OWB_RMT_SYMBOL_1BIT; +static const rmt_symbol_word_t owb_rmt_symbol_reset = OWB_RMT_SYMBOL_RESET; + +// RMT transmit configuration for the OWB: transmit symbols once then release the bus +static const rmt_transmit_config_t owb_rmt_transmit_config = { + .loop_count = 0, // don't send any repeats + .flags = { + .eot_level = OWB_RMT_BUS_RELEASED // release the bus after the transmission + } +}; + +// RMT receiver configuration for a onewire reset pulse +static const rmt_receive_config_t rx_config_owb_reset = { + .signal_range_min_ns = OWB_RMT_RX_MIN_NS, // glitch rejection threshold (ns) + .signal_range_max_ns = (OWB_TIMING_PARAM_H + OWB_TIMING_PARAM_I) * 1000 // stop condition (ns) +}; + +// RMT receiver configuration for a sequence of onewire data bits +static const rmt_receive_config_t rx_config_owb_bits = { + .signal_range_min_ns = OWB_RMT_RX_MIN_NS, // glitch rejection threshold (ns) + .signal_range_max_ns = (OWB_TIMING_PARAM_A + OWB_TIMING_PARAM_B) * 1000 // stop condition (ns) +}; -// bus reset: duration of low phase [us] -#define OW_DURATION_RESET 480 -// overall slot duration -#define OW_DURATION_SLOT 75 -// write 1 slot and read slot durations [us] -#define OW_DURATION_1_LOW 2 -#define OW_DURATION_1_HIGH (OW_DURATION_SLOT - OW_DURATION_1_LOW) -// write 0 slot durations [us] -#define OW_DURATION_0_LOW 65 -#define OW_DURATION_0_HIGH (OW_DURATION_SLOT - OW_DURATION_0_LOW) -// sample time for read slot -#define OW_DURATION_SAMPLE (15-2) -// RX idle threshold -// needs to be larger than any duration occurring during write slots -#define OW_DURATION_RX_IDLE (OW_DURATION_SLOT + 2) +/** + * @brief Uninstalls a onewire bus driver and releases the associated resources. + * @param bus A previously-initialised OneWireBus. + * @return owb_status OWB_STATUS_OK on success, otherwise an error code (see owb.h) + */ +static owb_status _uninitialize(const OneWireBus *bus) { + + // fetch the parent `owb_rmt_driver_info` structure for `bus` + owb_rmt_driver_info *info = __containerof(bus, owb_rmt_driver_info, bus); // (pointer, type, member) + if (info == NULL) { + ESP_LOGE(TAG, "err uninitialize: no bus container"); + return OWB_STATUS_PARAMETER_NULL; + } + + // release RMT device symbol buffer and queue + free (info->rx_buffer); + vQueueDelete (info->rx_queue); + + // disable and release RMT resources + if (rmt_disable (info->rx_channel_handle) == ESP_OK && + rmt_del_channel (info->rx_channel_handle) == ESP_OK && + rmt_disable (info->tx_channel_handle) == ESP_OK && + rmt_del_channel (info->tx_channel_handle) == ESP_OK && + rmt_del_encoder (info->copy_encoder_handle) == ESP_OK && + rmt_del_encoder (info->bytes_encoder_handle) == ESP_OK ) { + // all resources successfully released + return OWB_STATUS_OK; + } + + // an error occurred + ESP_LOGE(TAG, "err uninitializing"); + return OWB_STATUS_HW_ERROR; +} -static const char * TAG = "owb_rmt"; +/** + * @brief Parses the RMT symbols received during a onewire bus reset. + * @param[in] num_symbols The number of symbols passed. + * @param[in] symbols An array of RMT symbols. + * @param[out] slave_is_present Whether a slave presence signal was detected. + * @return OWB_STATUS_OK if the symbols pass basic valdation; otherwise an error code (see owb.h). + */ +static owb_status _parse_reset_symbols (size_t num_symbols, rmt_symbol_word_t *symbols, bool *slave_is_present) { + *slave_is_present = false; -#define info_of_driver(owb) container_of(owb, owb_rmt_driver_info, bus) + if (num_symbols == 0 || symbols == NULL) { + return OWB_STATUS_PARAMETER_NULL; + } + + #ifdef OWB_RMT_DEBUG + // display raw RMT symbols + ESP_LOGI(TAG, "parse reset: %d symbols", (int)num_symbols); + for (int i = 0; i < num_symbols; i += 1) { + ESP_LOGI (TAG, "\t%u (%uus), %u (%uus)", symbols->level0, symbols->duration0, + symbols->level1, symbols->duration1); + } + #endif -// flush any pending/spurious traces from the RX channel -static void onewire_flush_rmt_rx_buf(const OneWireBus * bus) -{ - void *p; - size_t s; + // check the duration of the reset pulse + if (abs (symbols[0].duration0 - OWB_TIMING_PARAM_H) > OWB_TIMING_MARGIN) { + return OWB_STATUS_HW_ERROR; + } + + // check for a valid 'no slave' event + if (num_symbols == 1 && symbols[0].duration1 == 0) { + *slave_is_present = false; + return OWB_STATUS_OK; + } - owb_rmt_driver_info *i = info_of_driver(bus); + // check for a valid 'slave present' event + if (num_symbols == 2 && // no 'extra' symbols after the presence pulse + symbols[0].duration1 < OWB_TIMING_PARAM_I && // presence pulse must arrive before the sample point + (symbols[1].duration0 + symbols[0].duration1) >= OWB_TIMING_PARAM_I // presence pulse must not finish before the sample point + ) { + *slave_is_present = true; + return OWB_STATUS_OK; + } - while ((p = xRingbufferReceive(i->rb, &s, 0))) - { - ESP_LOGD(TAG, "flushing entry"); - vRingbufferReturnItem(i->rb, p); - } + // anything else is invalid + return OWB_STATUS_HW_ERROR; } -static owb_status _reset(const OneWireBus *bus, bool *is_present) -{ - rmt_item32_t tx_items[1]; - bool _is_present = false; - int res = OWB_STATUS_OK; - owb_rmt_driver_info *i = info_of_driver(bus); - - tx_items[0].duration0 = OW_DURATION_RESET; - tx_items[0].level0 = 0; - tx_items[0].duration1 = 0; - tx_items[0].level1 = 1; +/** + * @brief Parses the RMT symbols received during the transmission of up to 64 onewire bits. + * @param[in] num_symbols The number of symbols passed. + * @param[in] symbols An array of RMT symbols. + * @param[out] result The decoded bits (max 64, lsb first) + * @return int The number of bits decoded + */ +static int _parse_bit_symbols (size_t num_symbols, rmt_symbol_word_t *p_symbol, uint64_t *result) { + *result = 0; + int bit_count = 0; + rmt_symbol_word_t *p_last_symbol = p_symbol + num_symbols; - uint16_t old_rx_thresh; - rmt_get_rx_idle_thresh(i->rx_channel, &old_rx_thresh); - rmt_set_rx_idle_thresh(i->rx_channel, OW_DURATION_RESET+60); + #ifdef OWB_RMT_DEBUG + // display raw RMT symbols + ESP_LOGI(TAG, "parse bits: %d symbols", (int)num_symbols); + #endif - onewire_flush_rmt_rx_buf(bus); - rmt_rx_start(i->rx_channel, true); - if (rmt_write_items(i->tx_channel, tx_items, 1, true) == ESP_OK) - { - size_t rx_size; - rmt_item32_t* rx_items = (rmt_item32_t *)xRingbufferReceive(i->rb, &rx_size, 100 / portTICK_PERIOD_MS); + while (p_symbol < p_last_symbol && bit_count < 64) { + #ifdef OWB_RMT_DEBUG + ESP_LOGI (TAG, "\t%u (%uus), %u (%uus)", p_symbol->level0, p_symbol->duration0, + p_symbol->level1, p_symbol->duration1); + #endif + if (abs (p_symbol->duration0 - OWB_TIMING_PARAM_A) <= OWB_TIMING_MARGIN && + (p_symbol->duration1 == 0 || p_symbol->duration1 >= OWB_TIMING_PARAM_E)) { + // bus was released at the sample point: detect a '1' + *result |= (1ull << bit_count); + bit_count += 1; - if (rx_items) - { - if (rx_size >= (1 * sizeof(rmt_item32_t))) - { -#ifdef OW_DEBUG - ESP_LOGI(TAG, "rx_size: %d", rx_size); + #ifdef OWB_RMT_DEBUG + ESP_LOGI (TAG, "\t\tdetect '1' -> 0x%llx", *result); + #endif - for (int i = 0; i < (rx_size / sizeof(rmt_item32_t)); i++) - { - ESP_LOGI(TAG, "i: %d, level0: %d, duration %d", i, rx_items[i].level0, rx_items[i].duration0); - ESP_LOGI(TAG, "i: %d, level1: %d, duration %d", i, rx_items[i].level1, rx_items[i].duration1); - } -#endif + } else if (p_symbol->duration0 >= (OWB_TIMING_PARAM_A + OWB_TIMING_PARAM_E)) { + // bus was asserted at the sample point: detect a '0' + bit_count += 1; + + #ifdef OWB_RMT_DEBUG + ESP_LOGI (TAG, "\t\tdetect '0' -> 0x%llx", *result); + #endif + } + p_symbol += 1; // next symbol + } + + return bit_count; +} + - // parse signal and search for presence pulse - if ((rx_items[0].level0 == 0) && (rx_items[0].duration0 >= OW_DURATION_RESET - 2)) - { - if ((rx_items[0].level1 == 1) && (rx_items[0].duration1 > 0)) - { - if (rx_items[1].level0 == 0) - { - _is_present = true; - } - } - } - } +/** + * @brief Sends a onewire bus reset pulse and listens for slave presence responses. + * @param[in] bus Points to the OneWireBus structure (see owb.h). + * @param[out] is_present Points to a bool that will receive the detection result. + * @return OWB_STATUS_OK if the call succeeded; otherwise an owb_status error code (see owb.h). + */ +static owb_status _reset (const OneWireBus *bus, bool *is_present) { + + esp_err_t esp_status; - vRingbufferReturnItem(i->rb, (void *)rx_items); - } - else - { - // time out occurred, this indicates an unconnected / misconfigured bus - ESP_LOGE(TAG, "rx_items == 0"); - res = OWB_STATUS_HW_ERROR; - } - } - else - { - // error in tx channel - ESP_LOGE(TAG, "Error tx"); - res = OWB_STATUS_HW_ERROR; + // identify the rmt_driver_info structure that contains `bus` + owb_rmt_driver_info *info = __containerof(bus, owb_rmt_driver_info, bus); + + // start the receiver before the transmitter so that it sees the leading edge of the pulse + esp_status = rmt_receive ( + info->rx_channel_handle, + info->rx_buffer, + info->rx_buffer_size_in_bytes, + &rx_config_owb_reset); + if (esp_status != ESP_OK) { + ESP_LOGE(TAG, "owb_reset: rx err"); + return OWB_STATUS_HW_ERROR; } - rmt_rx_stop(i->rx_channel); - rmt_set_rx_idle_thresh(i->rx_channel, old_rx_thresh); + // encode and transmit the reset pulse using the RMT 'copy' encoder + esp_status = rmt_transmit ( + info->tx_channel_handle, + info->copy_encoder_handle, + &owb_rmt_symbol_reset, + sizeof (owb_rmt_symbol_reset), + &owb_rmt_transmit_config); + if (esp_status != ESP_OK) { + ESP_LOGE(TAG, "owb_reset: tx err"); + return OWB_STATUS_HW_ERROR; + } - *is_present = _is_present; + // wait for the transmission to finish (or timeout with an error) + if (rmt_tx_wait_all_done (info->tx_channel_handle, OWB_RMT_TIMEOUT_MS) != ESP_OK) { + ESP_LOGE(TAG, "owb_reset: tx timeout"); + return OWB_STATUS_DEVICE_NOT_RESPONDING; // tx timeout + } - ESP_LOGD(TAG, "_is_present %d", _is_present); - - return res; + // wait for the recv_done event data from our callback + rmt_rx_done_event_data_t rx_done_event_data; + if (xQueueReceive (info->rx_queue, &rx_done_event_data, pdMS_TO_TICKS(OWB_RMT_TIMEOUT_MS)) != pdTRUE) { + ESP_LOGE(TAG, "owb_reset: no rx symbol"); // rx timeout + return OWB_STATUS_DEVICE_NOT_RESPONDING; + } + + // parse the event data and return the result + return _parse_reset_symbols (rx_done_event_data.num_symbols, rx_done_event_data.received_symbols, is_present); } -static rmt_item32_t _encode_write_slot(uint8_t val) -{ - rmt_item32_t item; +/** + * @brief Writes a number of bytes to the onewire bus (slightly more efficient than sending them individually). + * @param bus A previously-initialised OneWireBus. + * @param bytes The bytes to be sent. + * @param number_of_bytes_to_write How many bytes to send. + * @return owb_status OWB_STATUS_OK on success, otherwise an error code (see owb.h). + */ +static owb_status _write_bytes(const OneWireBus *bus, uint8_t *bytes, int number_of_bytes_to_write) { + esp_err_t esp_status; - item.level0 = 0; - item.level1 = 1; - if (val) - { - // write "1" slot - item.duration0 = OW_DURATION_1_LOW; - item.duration1 = OW_DURATION_1_HIGH; - } - else - { - // write "0" slot - item.duration0 = OW_DURATION_0_LOW; - item.duration1 = OW_DURATION_0_HIGH; + // identify the rmt_driver_info structure that contains `bus` + owb_rmt_driver_info *info = __containerof(bus, owb_rmt_driver_info, bus); + + // encode and transmit the bits using the RMT 'bytes' encoder + esp_status = rmt_transmit ( + info->tx_channel_handle, + info->bytes_encoder_handle, + bytes, + (size_t)number_of_bytes_to_write, + &owb_rmt_transmit_config); + if (esp_status != ESP_OK) { + ESP_LOGE(TAG, "owb_write: tx err"); + return OWB_STATUS_HW_ERROR; } - return item; + // wait for the transmission to finish (or timeout with an error) + if (rmt_tx_wait_all_done (info->tx_channel_handle, OWB_RMT_TIMEOUT_MS) != ESP_OK) { + return OWB_STATUS_DEVICE_NOT_RESPONDING; // tx timeout + } + return OWB_STATUS_OK; } -/** NOTE: The data is shifted out of the low bits, eg. it is written in the order of lsb to msb */ -static owb_status _write_bits(const OneWireBus * bus, uint8_t out, int number_of_bits_to_write) -{ - rmt_item32_t tx_items[number_of_bits_to_write + 1]; - owb_rmt_driver_info *info = info_of_driver(bus); - if (number_of_bits_to_write > 8) - { +/** + * @brief Writes 1-8 bits to the onewire bus. + * @param bus A previously-initialised OneWireBus. + * @param bytes A byte with the bits to be sent (lsb first). + * @param number_of_bits_to_write How many bits to send (maximum 8). + * @return owb_status OWB_STATUS_OK on success, otherwise an error code (see owb.h). + */ +static owb_status _write_bits(const OneWireBus *bus, uint8_t out, int number_of_bits_to_write) { + + // send 8 bits as a byte instead + if (number_of_bits_to_write == 8) { + return _write_bytes (bus, &out, 1); + } + + if (number_of_bits_to_write < 1 || number_of_bits_to_write > 8) { + ESP_LOGE(TAG, "owb_write_bits: bad num of bits (%d)", number_of_bits_to_write); return OWB_STATUS_TOO_MANY_BITS; } - // write requested bits as pattern to TX buffer - for (int i = 0; i < number_of_bits_to_write; i++) - { - tx_items[i] = _encode_write_slot(out & 0x01); - out >>= 1; - } - - // end marker - tx_items[number_of_bits_to_write].level0 = 1; - tx_items[number_of_bits_to_write].duration0 = 0; - - owb_status status; - - if (rmt_write_items(info->tx_channel, tx_items, number_of_bits_to_write+1, true) == ESP_OK) - { - status = OWB_STATUS_OK; - } - else - { - status = OWB_STATUS_HW_ERROR; - ESP_LOGE(TAG, "rmt_write_items() failed"); - } - - return status; -} + // identify the rmt_driver_info structure that contains `bus` + owb_rmt_driver_info *info = __containerof(bus, owb_rmt_driver_info, bus); -static rmt_item32_t _encode_read_slot(void) -{ - rmt_item32_t item; - - // construct pattern for a single read time slot - item.level0 = 0; - item.duration0 = OW_DURATION_1_LOW; // shortly force 0 - item.level1 = 1; - item.duration1 = OW_DURATION_1_HIGH; // release high and finish slot - return item; -} + // send data as individual bits using the `copy` encoder + const rmt_symbol_word_t *symbol_ptr; + esp_err_t esp_status; + for (int b = 0; b < number_of_bits_to_write; b += 1) { + if ((out & (1 << b)) == 0) { + symbol_ptr = &owb_rmt_symbol_0bit; + } else { + symbol_ptr = &owb_rmt_symbol_1bit; + } -/** NOTE: Data is read into the high bits, eg. each bit read is shifted down before the next bit is read */ -static owb_status _read_bits(const OneWireBus * bus, uint8_t *in, int number_of_bits_to_read) -{ - rmt_item32_t tx_items[number_of_bits_to_read + 1]; - uint8_t read_data = 0; - int res = OWB_STATUS_OK; - - owb_rmt_driver_info *info = info_of_driver(bus); - - if (number_of_bits_to_read > 8) - { - ESP_LOGE(TAG, "_read_bits() OWB_STATUS_TOO_MANY_BITS"); - return OWB_STATUS_TOO_MANY_BITS; - } - - // generate requested read slots - for (int i = 0; i < number_of_bits_to_read; i++) - { - tx_items[i] = _encode_read_slot(); + // send bit symbol + esp_status = rmt_transmit ( + info->tx_channel_handle, + info->copy_encoder_handle, + symbol_ptr, + sizeof (rmt_symbol_word_t), + &owb_rmt_transmit_config); + if (esp_status != ESP_OK) { + ESP_LOGE(TAG, "owb_write_bit: tx err"); + return OWB_STATUS_HW_ERROR; + } } - // end marker - tx_items[number_of_bits_to_read].level0 = 1; - tx_items[number_of_bits_to_read].duration0 = 0; - - onewire_flush_rmt_rx_buf(bus); - rmt_rx_start(info->rx_channel, true); - if (rmt_write_items(info->tx_channel, tx_items, number_of_bits_to_read+1, true) == ESP_OK) - { - size_t rx_size; - rmt_item32_t* rx_items = (rmt_item32_t *)xRingbufferReceive(info->rb, &rx_size, portMAX_DELAY); - - if (rx_items) - { -#ifdef OW_DEBUG - for (int i = 0; i < rx_size / 4; i++) - { - ESP_LOGI(TAG, "level: %d, duration %d", rx_items[i].level0, rx_items[i].duration0); - ESP_LOGI(TAG, "level: %d, duration %d", rx_items[i].level1, rx_items[i].duration1); - } -#endif - - if (rx_size >= number_of_bits_to_read * sizeof(rmt_item32_t)) - { - for (int i = 0; i < number_of_bits_to_read; i++) - { - read_data >>= 1; - // parse signal and identify logical bit - if (rx_items[i].level1 == 1) - { - if ((rx_items[i].level0 == 0) && (rx_items[i].duration0 < OW_DURATION_SAMPLE)) - { - // rising edge occured before 15us -> bit 1 - read_data |= 0x80; - } - } - } - read_data >>= 8 - number_of_bits_to_read; - } - - vRingbufferReturnItem(info->rb, (void *)rx_items); - } - else - { - // time out occurred, this indicates an unconnected / misconfigured bus - ESP_LOGE(TAG, "rx_items == 0"); - res = OWB_STATUS_HW_ERROR; - } + // wait for the transmission to finish (or timeout with an error) + if (rmt_tx_wait_all_done (info->tx_channel_handle, OWB_RMT_TIMEOUT_MS) != ESP_OK) { + return OWB_STATUS_DEVICE_NOT_RESPONDING; // tx timeout } - else - { - // error in tx channel - ESP_LOGE(TAG, "Error tx"); - res = OWB_STATUS_HW_ERROR; - } - - rmt_rx_stop(info->rx_channel); - - *in = read_data; - return res; -} - -static owb_status _uninitialize(const OneWireBus *bus) -{ - owb_rmt_driver_info * info = info_of_driver(bus); - - rmt_driver_uninstall(info->tx_channel); - rmt_driver_uninstall(info->rx_channel); return OWB_STATUS_OK; } -static struct owb_driver rmt_function_table = -{ + +/** + * @brief Reads up to 8 bytes from the onewire bus (this is faster than reading individual bits). + * @param bus A previously-initialised OneWireBus. + * @param result The resulting data, stored lsb first in a uint64_t. + * @param number_of_bytes_to_read The number of bytes to read. + * @return owb_status OWB_STATUS_OK on success, otherwise and error code (see owb.h) + */ +static owb_status _read_bytes(const OneWireBus *bus, uint64_t *result_ptr, int number_of_bytes_to_read) { + static uint8_t ff_bytes[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + esp_err_t esp_status; + + if (number_of_bytes_to_read > 8) { + ESP_LOGE(TAG, "owb_read_bytes: max 8"); + return OWB_STATUS_TOO_MANY_BITS; + } + + // identify the rmt_driver_info structure that contains `bus` + owb_rmt_driver_info *info = __containerof(bus, owb_rmt_driver_info, bus); + + // start the receiver before the transmitter so that it sees the first edge + esp_status = rmt_receive ( + info->rx_channel_handle, + info->rx_buffer, + info->rx_buffer_size_in_bytes, + &rx_config_owb_bits); + if (esp_status != ESP_OK) { + ESP_LOGE(TAG, "owb_read_bytes: rx err"); + return OWB_STATUS_HW_ERROR; + } + + // generate read slots + esp_status = rmt_transmit ( + info->tx_channel_handle, + info->bytes_encoder_handle, + ff_bytes, + (size_t)number_of_bytes_to_read, + &owb_rmt_transmit_config); + if (esp_status != ESP_OK) { + ESP_LOGE(TAG, "owb_read_bytes: tx err"); + return OWB_STATUS_HW_ERROR; + } + + // wait for the transmission to finish (or timeout with an error) + if (rmt_tx_wait_all_done (info->tx_channel_handle, OWB_RMT_TIMEOUT_MS) != ESP_OK) { + return OWB_STATUS_DEVICE_NOT_RESPONDING; // tx timeout + } + + // wait for the recv_done event data from our callback + rmt_rx_done_event_data_t rx_done_event_data; + if (xQueueReceive (info->rx_queue, &rx_done_event_data, pdMS_TO_TICKS(OWB_RMT_TIMEOUT_MS)) != pdTRUE) { + ESP_LOGE(TAG, "owb_read_bytes: no rx symbols"); // rx timeout + return OWB_STATUS_DEVICE_NOT_RESPONDING; + } + + // decode upto 64 data bits from the received RMT symbols + if (_parse_bit_symbols(rx_done_event_data.num_symbols, rx_done_event_data.received_symbols, result_ptr) == 0) { + ESP_LOGE(TAG, "owb_read_bytes: no bits"); + } + + return OWB_STATUS_OK; +} + + +/** + * @brief Reads up to 8 bits from the onewire bus. + * @param bus A previously-initialised OneWireBus. + * @param result A byte containing the bits read (lsb first). + * @param number_of_bits_to_read The number of bits to read. + * @return owb_status OWB_STATUS_OK on success, otherwise an error code (see owb.h) + */ +static owb_status _read_bits(const OneWireBus *bus, uint8_t *result, int number_of_bits_to_read) { + esp_err_t esp_status; + + if (number_of_bits_to_read > 8) { + ESP_LOGE(TAG, "owb_read_bits: max 8"); + return OWB_STATUS_TOO_MANY_BITS; + } + + // it's quicker to read 8 bits as a whole byte + if (number_of_bits_to_read == 8) { + uint64_t result_64; + owb_status status; + status = _read_bytes (bus, &result_64, 1); + *result = (uint8_t)result_64; + return status; + } + + // identify the rmt_driver_info structure that contains `bus` + owb_rmt_driver_info *info = __containerof(bus, owb_rmt_driver_info, bus); + + // with the copy encoder then it's most efficient to receive each bit individually + // because we don't accurately know the interval between bits. + // It would be nice to use `rmt_transmit_config.loop_count` here, but it's not supported + // on all chips. In any case the user almost certainly only wants a single bit. + *result = 0; + for (int bit_index = 0; bit_index < number_of_bits_to_read; bit_index += 1) { + + // start the receiver before the transmitter so that it sees the first edge + esp_status = rmt_receive ( + info->rx_channel_handle, + info->rx_buffer, + info->rx_buffer_size_in_bytes, + &rx_config_owb_bits); + if (esp_status != ESP_OK) { + ESP_LOGE(TAG, "owb_read_bits: rx err"); + return OWB_STATUS_HW_ERROR; + } + + // send a '1' symbol to generate a read slot + esp_status = rmt_transmit ( + info->tx_channel_handle, + info->copy_encoder_handle, + &owb_rmt_symbol_1bit, + sizeof (rmt_symbol_word_t), + &owb_rmt_transmit_config); + if (esp_status != ESP_OK) { + ESP_LOGE(TAG, "owb_read_bits: tx err"); + return OWB_STATUS_HW_ERROR; + } + + // wait for the transmission to finish (or timeout with an error) + if (rmt_tx_wait_all_done (info->tx_channel_handle, OWB_RMT_TIMEOUT_MS) != ESP_OK) { + return OWB_STATUS_DEVICE_NOT_RESPONDING; // tx timeout + } + + // wait for the recv_done event data from our callback + rmt_rx_done_event_data_t rx_done_event_data; + if (xQueueReceive (info->rx_queue, &rx_done_event_data, pdMS_TO_TICKS(OWB_RMT_TIMEOUT_MS)) != pdTRUE) { + ESP_LOGE(TAG, "owb_read_bits: no rx symbol"); // rx timeout + return OWB_STATUS_DEVICE_NOT_RESPONDING; + } + + // parse the event data + uint64_t bits = 0; + if (_parse_bit_symbols (rx_done_event_data.num_symbols, rx_done_event_data.received_symbols, &bits) == 0) { + ESP_LOGE(TAG, "owb_read_bits: no bits"); + return OWB_STATUS_HW_ERROR; + } + + // add the bit to `result` (lsb is received first) + if ((bits & 1) != 0) { + *result |= (1 << bit_index); + } + } + + return OWB_STATUS_OK; +} + + +/** + * @brief Handle the RMT `recv_done` event by copying the event data structure to the specified queue. + * @param[in] channel The handle of the RMT channel that generated the event. + * @param[in] edata A pointer to the RMT event data structure (the pointer is valid only within this function). + * @param[in] context A pointer to the user-provided context, in this case the queue handle. + * @return True if sending to the queue caused a higher priority task to unblock; otherwise False. + */ +static bool IRAM_ATTR _recv_done_callback (rmt_channel_handle_t channel, const rmt_rx_done_event_data_t *event_data, void *user_data) { + // Copy a pointer to the event data structure to the queue identified in the user_data. + //* NOTE: this is an interrupt handler so it needs IRAM_ATTR, may only use `ISR` calls and must return promptly. + // + BaseType_t pxHigherPriorityTaskWoken = pdFALSE; + + xQueueSendFromISR ((QueueHandle_t)user_data, event_data, &pxHigherPriorityTaskWoken); + if (pxHigherPriorityTaskWoken == pdTRUE) { + return true; + } + return false; +} + + +//----- +// Public API functions +//----- + +// RMT version of the OWB driver api (will be stored as info->bus->driver) +// +static struct owb_driver rmt_driver_functions = { .name = "owb_rmt", .uninitialize = _uninitialize, .reset = _reset, .write_bits = _write_bits, - .read_bits = _read_bits + .write_bytes = _write_bytes, // new addition to the API + .read_bits = _read_bits, + .read_bytes = _read_bytes // new addition to the API }; -static owb_status _init(owb_rmt_driver_info *info, uint8_t gpio_num, - rmt_channel_t tx_channel, rmt_channel_t rx_channel) -{ - owb_status status = OWB_STATUS_HW_ERROR; - // Ensure the RMT peripheral is not already running - // Note: if using RMT elsewhere, don't call this here, call it at the start of your prgoram instead. - //periph_module_disable(PERIPH_RMT_MODULE); - //periph_module_enable(PERIPH_RMT_MODULE); +// configure and allocate resources +// +OneWireBus* owb_rmt_initialize (owb_rmt_driver_info *info, gpio_num_t gpio_num, int tx_channel, int rx_channel) +{ + //* The function now ignores tx_channel and rx_channel as the new RMT driver allocates channels on demand. + //* The parameters are kept in the call to preserve compatibility with previous versions. + + // the steps to enable the RMT resources are documented in: + // https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/rmt.html - info->bus.driver = &rmt_function_table; - info->tx_channel = tx_channel; - info->rx_channel = rx_channel; - info->gpio = gpio_num; + // Note: keeping the TX and RX initialisations together in one function simplifies the error handling + + (void)tx_channel; // avoid compiler warning about unused parameter + (void)rx_channel; // avoid compiler warning about unused parameter -#ifdef OW_DEBUG - ESP_LOGI(TAG, "RMT TX channel: %d", info->tx_channel); - ESP_LOGI(TAG, "RMT RX channel: %d", info->rx_channel); -#endif + // sanity check + if (info == NULL) { + ESP_LOGE(TAG, "info is NULL"); + goto exit_err; + } + + // ----- receive channel ----- - rmt_config_t rmt_tx; - rmt_tx.channel = info->tx_channel; - rmt_tx.gpio_num = gpio_num; - rmt_tx.mem_block_num = 1; - rmt_tx.clk_div = 80; - rmt_tx.tx_config.loop_en = false; - rmt_tx.tx_config.carrier_en = false; - rmt_tx.tx_config.idle_level = 1; - rmt_tx.tx_config.idle_output_en = true; - rmt_tx.rmt_mode = RMT_MODE_TX; - if (rmt_config(&rmt_tx) == ESP_OK) - { - if (rmt_driver_install(rmt_tx.channel, 0, ESP_INTR_FLAG_LOWMED | ESP_INTR_FLAG_IRAM | ESP_INTR_FLAG_SHARED) == ESP_OK) - { - rmt_config_t rmt_rx; - rmt_rx.channel = info->rx_channel; - rmt_rx.gpio_num = gpio_num; - rmt_rx.clk_div = 80; - rmt_rx.mem_block_num = 1; - rmt_rx.rmt_mode = RMT_MODE_RX; - rmt_rx.rx_config.filter_en = true; - rmt_rx.rx_config.filter_ticks_thresh = 30; - rmt_rx.rx_config.idle_threshold = OW_DURATION_RX_IDLE; - if (rmt_config(&rmt_rx) == ESP_OK) - { - if (rmt_driver_install(rmt_rx.channel, 512, ESP_INTR_FLAG_LOWMED | ESP_INTR_FLAG_IRAM | ESP_INTR_FLAG_SHARED) == ESP_OK) - { - rmt_get_ringbuf_handle(info->rx_channel, &info->rb); - status = OWB_STATUS_OK; - } - else - { - ESP_LOGE(TAG, "failed to install rx driver"); - } - } - else - { - status = OWB_STATUS_HW_ERROR; - ESP_LOGE(TAG, "failed to configure rx, uninstalling rmt driver on tx channel"); - rmt_driver_uninstall(rmt_tx.channel); - } + // channel config + const rmt_rx_channel_config_t rx_channel_config = { + .gpio_num = (int)gpio_num, + .clk_src = RMT_CLK_SRC_APB, // use the APB clock (might reduce during light sleep) + .resolution_hz = OWB_RMT_CLK_HZ, + .mem_block_symbols = (size_t)OWB_RMT_RX_MEM_BLOCK_SYMBOLS, + .flags = { + .invert_in = 0, // don't hardware invert the input + .with_dma = 0, // don't enable DMA + .io_loop_back = 0 // we define the loopback in the tx config } - else - { - ESP_LOGE(TAG, "failed to install tx driver"); - } + }; + + // request channel + //* note: to get a wired-OR bus you must apply the rx_config first, _then_ the rx_config + if (rmt_new_rx_channel (&rx_channel_config, &(info->rx_channel_handle)) != ESP_OK) { + ESP_LOGE(TAG, "err requesting rx_channel"); + goto exit_err; + } + + // create queue for RMT `rx_done` event data struct (from callback) + info->rx_queue = xQueueCreate (1, sizeof (rmt_rx_done_event_data_t)); + if (info->rx_queue == NULL) { + ESP_LOGE(TAG, "err creating rx_queue"); + goto exit_delete_rx_channel; } - else - { - ESP_LOGE(TAG, "failed to configure tx"); + + // allocate rx symbol buffer for RMT driver + info->rx_buffer_size_in_bytes = OWB_RMT_MAX_READ_BITS * sizeof (rmt_symbol_word_t); + info->rx_buffer = (rmt_symbol_word_t *)malloc (info->rx_buffer_size_in_bytes); + if (info->rx_buffer == NULL) { + ESP_LOGE(TAG, "err allocating rx_buffer"); + goto exit_delete_rx_queue; + } + + // register rx channel callback (rx_queue is passed as user context) + const rmt_rx_event_callbacks_t rmt_rx_event_callbacks = { + .on_recv_done = _recv_done_callback + }; + if (rmt_rx_register_event_callbacks (info->rx_channel_handle, &rmt_rx_event_callbacks, info->rx_queue) != ESP_OK) { + ESP_LOGE(TAG, "err registering rx_callbacks"); + goto exit_release_rx_buffer; + } + + // enable channel + if (rmt_enable (info->rx_channel_handle) != ESP_OK) { + ESP_LOGE(TAG, "err enabling rx_channel"); + goto exit_release_rx_buffer; } - // attach GPIO to previous pin - if (gpio_num < 32) - { - GPIO.enable_w1ts = (0x1 << gpio_num); + // ----- transmit channel ----- + + // channel config + const rmt_tx_channel_config_t tx_channel_config = { + .gpio_num = (int)gpio_num, + .clk_src = RMT_CLK_SRC_APB, // use the APB clock (might reduce during light sleep) + .resolution_hz = OWB_RMT_CLK_HZ, + .mem_block_symbols = (size_t)OWB_RMT_TX_MEM_BLOCK_SYMBOLS, + .trans_queue_depth = OWB_RMT_TX_QUEUE_DEPTH, + .flags = { + .invert_out = 1, // invert the output (so that the bus is initially released) + .with_dma = 0, // don't enable DMA + .io_loop_back = 1, // enable reading of actual voltage of output pin + .io_od_mode = 1 // enable open-drain output, so as to achieve a 'wired-OR' bus + } + }; + + // request channel + if (rmt_new_tx_channel (&tx_channel_config, &(info->tx_channel_handle)) != ESP_OK) { + ESP_LOGE(TAG, "err requesting tx_channel"); + goto exit_disable_rx_channel; } - else - { - GPIO.enable1_w1ts.data = (0x1 << (gpio_num - 32)); + + // enable channel + if (rmt_enable (info->tx_channel_handle) != ESP_OK) { + ESP_LOGE(TAG, "err enabling tx_channel"); + goto exit_delete_tx_channel; + } + + // obtain a 'copy' encoder (an RMT built-in used for sending fixed bit patterns) + const rmt_copy_encoder_config_t rmt_copy_encoder_config = {}; // config is "reserved for future expansion" + if (rmt_new_copy_encoder (&rmt_copy_encoder_config, &(info->copy_encoder_handle)) != ESP_OK) { + ESP_LOGE(TAG, "err requesting copy encoder"); + goto exit_disable_tx_channel; } - // attach RMT channels to new gpio pin - // ATTENTION: set pin for rx first since gpio_output_disable() will - // remove rmt output signal in matrix! - rmt_set_pin(info->rx_channel, RMT_MODE_RX, gpio_num); - rmt_set_pin(info->tx_channel, RMT_MODE_TX, gpio_num); - - // force pin direction to input to enable path to RX channel - PIN_INPUT_ENABLE(GPIO_PIN_MUX_REG[gpio_num]); - - // enable open drain - GPIO.pin[gpio_num].pad_driver = 1; - - return status; -} - -OneWireBus * owb_rmt_initialize(owb_rmt_driver_info *info, uint8_t gpio_num, - rmt_channel_t tx_channel, rmt_channel_t rx_channel) -{ - ESP_LOGD(TAG, "%s: gpio_num: %d, tx_channel: %d, rx_channel: %d", - __func__, gpio_num, tx_channel, rx_channel); - - owb_status status = _init(info, gpio_num, tx_channel, rx_channel); - if(status != OWB_STATUS_OK) - { - ESP_LOGE(TAG, "_init() failed with status %d", status); + // otain a 'bytes' encoder (an RMT built-in used for sending variable bit patterns) + const rmt_bytes_encoder_config_t rmt_bytes_encoder_config = { + .bit0 = OWB_RMT_SYMBOL_0BIT, + .bit1 = OWB_RMT_SYMBOL_1BIT, + .flags = { + .msb_first = 0 // onewire bus on-the-wire bit order is lsb first + } + }; + if (rmt_new_bytes_encoder(&rmt_bytes_encoder_config, &info->bytes_encoder_handle) != ESP_OK) { + ESP_LOGE(TAG, "err requesting bytes encoder"); + goto exit_delete_copy_encoder; } + + // ----- success ------ + info->gpio = gpio_num; + info->bus.driver = &rmt_driver_functions; // route driver API calls to the functions in this file + ESP_LOGI(TAG, "%s: OK", __func__); return &(info->bus); + + // ----- error: unwind allocated resources ----- +exit_delete_copy_encoder: + ESP_ERROR_CHECK(rmt_del_encoder(info->copy_encoder_handle)); +exit_disable_tx_channel: + ESP_ERROR_CHECK(rmt_disable (info->tx_channel_handle)); +exit_delete_tx_channel: + ESP_ERROR_CHECK(rmt_del_channel (info->tx_channel_handle)); +exit_disable_rx_channel: + ESP_ERROR_CHECK(rmt_disable (info->rx_channel_handle)); +exit_release_rx_buffer: + free (info->rx_buffer); +exit_delete_rx_queue: + vQueueDelete (info->rx_queue); +exit_delete_rx_channel: + ESP_ERROR_CHECK(rmt_del_channel (info->rx_channel_handle)); +exit_err: + ESP_LOGE(TAG, "%s: failed", __func__); + return NULL; }