Compare commits

...
7 Commits
Author SHA1 Message Date
aZholtikov 384360d2a4 wip: 2026-11-01 09:07:02 +03:00
aZholtikov 036b856a93 wip: 2026-11-01 07:59:36 +03:00
aZholtikov 0daf4de19f wip: 2026-10-31 09:25:15 +03:00
aZholtikov 30bbbc9303 wip: 2026-10-31 09:18:55 +03:00
aZholtikov 253a2168ae wip: 2026-10-31 09:11:59 +03:00
aZholtikov 98fb08cd6f wip: 2026-10-31 08:34:51 +03:00
aZholtikov 81a2eb04ac wip: 2026-10-25 10:23:30 +03:00
8 changed files with 1256 additions and 1 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
.DS_Store
.vscode
Executable
+1
View File
@@ -0,0 +1 @@
idf_component_register(SRCS "zh_nrf24_gateway.c" INCLUDE_DIRS "include" REQUIRES esp_driver_spi esp_driver_gpio esp_event nvs_flash zh_nrf24_config)
Executable
+73
View File
@@ -0,0 +1,73 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Regular → Executable
+75 -1
View File
@@ -1,2 +1,76 @@
# zh_rf_gateway
#include "zh_nrf24_gateway.h"
#define GATEWAY_CHANNEL 120
#define GATEWAY_ADDRESS 0xDDEEFF
void zh_nrf24_gateway_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data);
void app_main(void)
{
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND)
{
ESP_ERROR_CHECK(nvs_flash_erase());
ESP_ERROR_CHECK(nvs_flash_init());
}
esp_event_loop_create_default();
esp_event_handler_instance_register(ZH_NRF24_GATEWAY_EVENTS, ESP_EVENT_ANY_ID, &zh_nrf24_gateway_event_handler, NULL, NULL);
zh_nrf_gateway_config_t config = {
.spi_host = SPI2_HOST,
.pin_sck = 18,
.pin_miso = 19,
.pin_mosi = 23,
.pin_csn = 17,
.pin_ce = 16,
.pin_irq = 4,
.channel = GATEWAY_CHANNEL,
.address = GATEWAY_ADDRESS,
.spi_clock_hz = 0,
};
zh_nrf_gateway_init(&config);
zh_nrf_gateway_start();
}
void zh_nrf24_gateway_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
switch (event_id)
{
case ZH_NRF_GATEWAY_EVENT_SENSOR_DATA:
zh_nrf24_sensor_transmitted_data_t *sensor_data = (zh_nrf24_sensor_transmitted_data_t *)event_data;
printf("Data received - id=%d type=%s battery=%.2fV ", sensor_data->id, zh_get_nrf24_sensor_type_name((zh_nrf24_sensor_type_t)sensor_data->type), sensor_data->battery / 100.0);
switch (sensor_data->type)
{
case ZH_NRF24_SENSOR_TOUCH_SWITCH:
printf("button pressed\n");
break;
case ZH_NRF24_SENSOR_WATER_LEAKAGE:
printf("status=%s\n", sensor_data->value_1 == ZH_NRF24_SENSOR_STATUS_ALARM ? "ALARM" : "DRY");
break;
case ZH_NRF24_SENSOR_OPEN_CLOSE:
printf("status=%s\n", sensor_data->value_1 == ZH_NRF24_SENSOR_STATUS_OPEN ? "OPEN" : "CLOSE");
break;
case ZH_NRF24_SENSOR_PLANT_HUMIDITY:
printf("soil moisture=%.1f%%\n", sensor_data->value_1 / 10.0);
break;
case ZH_NRF24_SENSOR_BMP280:
printf("temperature=%.1fC, atmospheric pressure=%.1fmmHg\n", sensor_data->value_1 / 10.0, sensor_data->value_2 / 10.0);
break;
case ZH_NRF24_SENSOR_BME280:
printf("humidity=%.1f%%, temperature=%.1fC, atmospheric pressure=%.1fmmHg\n", sensor_data->value_1 / 10.0, sensor_data->value_2 / 10.0, sensor_data->value_3 / 10.0);
break;
default:
break;
}
break;
case ZH_NRF_GATEWAY_EVENT_SENSOR_PAIRED:
zh_nrf_gateway_binding_t *pairing_data = (zh_nrf_gateway_binding_t *)event_data;
printf("Sensor paired - id=%d type=%s\n", pairing_data->id, zh_get_nrf24_sensor_type_name((zh_nrf24_sensor_type_t)pairing_data->type));
break;
case ZH_NRF_GATEWAY_EVENT_SENSOR_REGISTERED:
zh_nrf_gateway_binding_t *registering_data = (zh_nrf_gateway_binding_t *)event_data;
printf("Sensor registered - id=%d type=%s\n", registering_data->id, zh_get_nrf24_sensor_type_name((zh_nrf24_sensor_type_t)registering_data->type));
break;
default:
break;
}
}
+11
View File
@@ -0,0 +1,11 @@
description: In progress
url: https://github.com/aZholtikov/zh_sim_race_button_box
version: "1.0.0"
license: "Apache-2.0"
maintainers:
- "Alexey Zholtikov <alexey.zholtikov@yandex.ru>"
dependencies:
idf: ">=5.0"
zh_nrf24_config:
git: "https://github.com/aZholtikov/zh_nrf24_config.git"
version: "dev"
+164
View File
@@ -0,0 +1,164 @@
/**
* @file zh_nrf24_gateway.h
*
* nRF24L01+ gateway for ESP-IDF.
*
* Receives RF sensor telemetry and posts it as events on the default
* ESP event loop. Pairing is fully internal: the gateway allocates
* per-type device IDs, persists the binding table in NVS and sends
* ACK packets.
*
* Events emitted:
* - ZH_NRF_GATEWAY_EVENT_SENSOR_DATA — sensor telemetry
* - ZH_NRF_GATEWAY_EVENT_SENSOR_PAIRED — pairing completed (gateway
* assigned a new id and the ACK was delivered)
* - ZH_NRF_GATEWAY_EVENT_SENSOR_REGISTERED — data packet arrived from a
* {id, type} that was missing from the binding table; it was added
* on the fly (covers gateway replacement / NVS wipe without re-pairing)
*
* Binding table semantics:
* - each binding is a pair {id, type};
* - the same id may be reused across different types;
* - on pairing, the gateway allocates the smallest free id in 1..254
* for the requested type;
* - deleting a binding makes its id available to the next pairing
* request of the same type.
*/
#pragma once
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "esp_rom_sys.h"
#include "nvs_flash.h"
#include "nvs.h"
#include "esp_err.h"
#include "esp_event.h"
#include "driver/spi_master.h"
#include "zh_nrf24_config.h"
#ifdef __cplusplus
extern "C"
{
#endif
extern TaskHandle_t zh_nrf24_gateway;
typedef struct
{
spi_host_device_t spi_host; /*!< SPI host (SPI2_HOST / SPI3_HOST) */
int pin_sck; /*!< SCK GPIO */
int pin_miso; /*!< MISO GPIO */
int pin_mosi; /*!< MOSI GPIO */
int pin_csn; /*!< CSN GPIO (chip select, active low) */
int pin_ce; /*!< CE GPIO (chip enable, active high) */
int pin_irq; /*!< IRQ GPIO (open-drain, active low) */
uint8_t channel; /*!< RF channel (0..125) */
uint32_t address; /*!< 24-bit pipe address, transmitted as LE bytes */
uint32_t spi_clock_hz; /*!< SPI clock, 0 → default 4 MHz */
} zh_nrf24_gateway_init_config_t;
typedef enum
{
ZH_NRF_GATEWAY_EVENT_SENSOR_DATA,
ZH_NRF_GATEWAY_EVENT_SENSOR_PAIRED,
ZH_NRF_GATEWAY_EVENT_SENSOR_REGISTERED,
} zh_nrf24_gateway_event_t;
ESP_EVENT_DECLARE_BASE(ZH_NRF24_GATEWAY_EVENTS);
/** A single {id, type} binding. */
typedef struct
{
uint8_t id; /**< 1..254, 0xFF = unassigned */
uint8_t type; /**< zh_nrf24_sensor_type_t */
} zh_nrf_gateway_binding_t;
/**
* @brief Initialize the gateway.
*
* Configures SPI, the IRQ GPIO with falling-edge interrupt, the nRF24L01+
* transceiver (DPL enabled, RX mode) and prepares NVS and the default
* event loop if they are not already initialized.
*
* @param[in] config Gateway configuration (must not be NULL)
*
* @return ESP_OK on success, or an ESP-IDF error code
*/
esp_err_t zh_nrf_gateway_init(const zh_nrf24_gateway_init_config_t *config);
/**
* @brief Start the receiver task.
*
* The task blocks on the IRQ semaphore (or polls the FIFO as a fallback
* once per second) and dispatches received packets.
*
* @return ESP_OK on success
*/
esp_err_t zh_nrf_gateway_start(void);
/* ===================== BINDING TABLE API ===================== */
/**
* @brief Copy current bindings into @p buf.
*
* Thread-safe. Returns number of entries copied (≤ max_count and ≤
* current table size).
*/
size_t zh_nrf_gateway_bindings_get(zh_nrf_gateway_binding_t *buf, size_t max_count);
/** @brief Current number of bindings in the table. */
size_t zh_nrf_gateway_bindings_count(void);
/**
* @brief Check whether a {id, type} binding exists.
*
* @return true if the binding is present in the table
*/
bool zh_nrf_gateway_binding_exists(uint8_t id, uint8_t type);
/**
* @brief Auto-register {id, type} if not present.
*
* Validates both fields, then adds the pair to the table and persists
* to NVS if it is not already there. The id is taken from the packet
* as-is (unlike pairing, which assigns a new id).
*
* @return 1 binding was newly added
* @return 0 binding already existed
* @return negative ESP error (invalid arg, NVS failure, etc.)
*/
int zh_nrf_gateway_binding_auto_register(uint8_t id, uint8_t type);
/**
* @brief Delete a {id, type} binding.
*
* Composite key: both @p id AND @p type must match. If only one matches,
* nothing is deleted and ESP_ERR_NOT_FOUND is returned.
*
* @return ESP_OK / ESP_ERR_NOT_FOUND / ESP_ERR_INVALID_ARG / ESP_ERR_INVALID_STATE / NVS error
*/
esp_err_t zh_nrf_gateway_binding_delete(uint8_t id, uint8_t type);
/** Delete every binding whose id equals @p id (any type). Returns count, or -err. */
int zh_nrf_gateway_bindings_delete_by_id(uint8_t id);
/** Delete every binding whose type equals @p type (any id). Returns count, or -err. */
int zh_nrf_gateway_bindings_delete_by_type(uint8_t type);
/** Remove all bindings (persisted). */
esp_err_t zh_nrf_gateway_binding_clear_all(void);
#ifdef __cplusplus
}
#endif
Executable
View File
Whitespace-only changes.
+930
View File
@@ -0,0 +1,930 @@
#include "zh_nrf24_gateway.h"
// #include <stdio.h>
// #include <string.h>
// #include "freertos/FreeRTOS.h"
// #include "freertos/task.h"
// #include "freertos/semphr.h"
// #include "driver/spi_master.h"
// #include "driver/gpio.h"
// #include "esp_log.h"
// #include "esp_rom_sys.h"
// #include "nvs_flash.h"
// #include "nvs.h"
ESP_EVENT_DEFINE_BASE(ZH_NRF24_GATEWAY_EVENTS);
static const char *TAG = "NRF_GW";
#define ZH_NRF_GATEWAY_MAX_BINDINGS 254
/* ================== nRF24 КОМАНДЫ / РЕГИСТРЫ ================== */
#define NRF_CMD_R_REGISTER 0x00
#define NRF_CMD_W_REGISTER 0x20
#define NRF_CMD_R_RX_PAYLOAD 0x61
#define NRF_CMD_W_TX_PAYLOAD 0xA0
#define NRF_CMD_FLUSH_TX 0xE1
#define NRF_CMD_FLUSH_RX 0xE2
#define NRF_CMD_NOP 0xFF
#define NRF_CMD_ACTIVATE 0x50
#define NRF_CMD_R_RX_PL_WID 0x60
#define NRF_REG_CONFIG 0x00
#define NRF_REG_EN_AA 0x01
#define NRF_REG_EN_RXADDR 0x02
#define NRF_REG_SETUP_AW 0x03
#define NRF_REG_SETUP_RETR 0x04
#define NRF_REG_RF_CH 0x05
#define NRF_REG_RF_SETUP 0x06
#define NRF_REG_STATUS 0x07
#define NRF_REG_RX_ADDR_P0 0x0A
#define NRF_REG_TX_ADDR 0x10
#define NRF_REG_FIFO_STATUS 0x17
#define NRF_REG_DYNPD 0x1C
#define NRF_REG_FEATURE 0x1D
#define NRF_CONFIG_MASK_RX_DR 0x40
#define NRF_CONFIG_MASK_TX_DS 0x20
#define NRF_CONFIG_MASK_MAX_RT 0x10
#define NRF_CONFIG_EN_CRC 0x08
#define NRF_CONFIG_PWR_UP 0x02
#define NRF_CONFIG_PRIM_RX 0x01
#define NRF_CONFIG_ALL_MASKED (NRF_CONFIG_MASK_RX_DR | NRF_CONFIG_MASK_TX_DS | NRF_CONFIG_MASK_MAX_RT | NRF_CONFIG_EN_CRC)
#define NRF_CONFIG_RX_UNMASKED (NRF_CONFIG_EN_CRC | NRF_CONFIG_PWR_UP | NRF_CONFIG_PRIM_RX)
#define NRF_STATUS_RX_DR 0x40
#define NRF_STATUS_TX_DS 0x20
#define NRF_STATUS_MAX_RT 0x10
#define NRF_FIFO_RX_EMPTY 0x01
#define NRF_FEATURE_EN_DPL 0x04
#define NRF_DYNPD_DPL_P0 0x01
/* ================== NVS ================== */
#define NVS_NAMESPACE "zh_gw"
#define NVS_KEY_BINDINGS "bindings"
#define BINDING_ID_MIN 1
#define BINDING_ID_MAX 254
/* ================== СОСТОЯНИЕ КОМПОНЕНТА ================== */
typedef struct __attribute__((packed))
{
uint16_t count;
zh_nrf_gateway_binding_t items[ZH_NRF_GATEWAY_MAX_BINDINGS];
} bindings_blob_t;
static struct
{
zh_nrf24_gateway_init_config_t cfg;
spi_device_handle_t spi;
SemaphoreHandle_t irq_sem;
SemaphoreHandle_t bindings_mutex;
TaskHandle_t task;
bindings_blob_t bindings;
bool initialized;
} s_ctx = {0};
/* ============================================================
* SPI / nRF24 HELPERS
* ============================================================ */
static void nrf_csn_low(void) { gpio_set_level(s_ctx.cfg.pin_csn, 0); }
static void nrf_csn_high(void) { gpio_set_level(s_ctx.cfg.pin_csn, 1); }
static void nrf_ce_low(void) { gpio_set_level(s_ctx.cfg.pin_ce, 0); }
static void nrf_ce_high(void) { gpio_set_level(s_ctx.cfg.pin_ce, 1); }
static uint8_t nrf_read_register(uint8_t reg)
{
uint8_t tx[2] = {NRF_CMD_R_REGISTER | (reg & 0x1F), 0xFF};
uint8_t rx[2] = {0};
spi_transaction_t t = {.length = 16, .tx_buffer = tx, .rx_buffer = rx};
nrf_csn_low();
ESP_ERROR_CHECK(spi_device_transmit(s_ctx.spi, &t));
nrf_csn_high();
return rx[1];
}
static void nrf_write_register(uint8_t reg, uint8_t val)
{
uint8_t tx[2] = {NRF_CMD_W_REGISTER | (reg & 0x1F), val};
spi_transaction_t t = {.length = 16, .tx_buffer = tx};
nrf_csn_low();
ESP_ERROR_CHECK(spi_device_transmit(s_ctx.spi, &t));
nrf_csn_high();
}
static void nrf_write_buffer(uint8_t reg, const uint8_t *buf, uint8_t len)
{
uint8_t tx[32 + 1];
tx[0] = NRF_CMD_W_REGISTER | (reg & 0x1F);
memcpy(&tx[1], buf, len);
spi_transaction_t t = {.length = (len + 1) * 8, .tx_buffer = tx};
nrf_csn_low();
ESP_ERROR_CHECK(spi_device_transmit(s_ctx.spi, &t));
nrf_csn_high();
}
static uint8_t nrf_send_command(uint8_t cmd)
{
uint8_t tx[1] = {cmd};
uint8_t rx[1] = {0};
spi_transaction_t t = {.length = 8, .tx_buffer = tx, .rx_buffer = rx};
nrf_csn_low();
ESP_ERROR_CHECK(spi_device_transmit(s_ctx.spi, &t));
nrf_csn_high();
return rx[0];
}
static void nrf_read_payload(uint8_t *buf, uint8_t len)
{
uint8_t cmd = NRF_CMD_R_RX_PAYLOAD;
nrf_csn_low();
spi_transaction_t t_cmd = {.length = 8, .tx_buffer = &cmd};
ESP_ERROR_CHECK(spi_device_transmit(s_ctx.spi, &t_cmd));
spi_transaction_t t_data = {.length = len * 8, .rx_buffer = buf};
ESP_ERROR_CHECK(spi_device_transmit(s_ctx.spi, &t_data));
nrf_csn_high();
}
static uint8_t nrf_read_payload_width(void)
{
uint8_t tx[2] = {NRF_CMD_R_RX_PL_WID, 0xFF};
uint8_t rx[2] = {0};
spi_transaction_t t = {.length = 16, .tx_buffer = tx, .rx_buffer = rx};
nrf_csn_low();
ESP_ERROR_CHECK(spi_device_transmit(s_ctx.spi, &t));
nrf_csn_high();
return rx[1];
}
static void nrf_activate(void)
{
uint8_t tx[2] = {NRF_CMD_ACTIVATE, 0x73};
spi_transaction_t t = {.length = 16, .tx_buffer = tx};
nrf_csn_low();
ESP_ERROR_CHECK(spi_device_transmit(s_ctx.spi, &t));
nrf_csn_high();
}
/* ============================================================
* IRQ (GPIO ISR)
* ============================================================ */
static void IRAM_ATTR nrf_irq_isr(void *arg)
{
BaseType_t woken = pdFALSE;
xSemaphoreGiveFromISR(s_ctx.irq_sem, &woken);
if (woken)
portYIELD_FROM_ISR();
}
static esp_err_t nrf_irq_init(void)
{
s_ctx.irq_sem = xSemaphoreCreateBinary();
if (!s_ctx.irq_sem)
return ESP_ERR_NO_MEM;
gpio_config_t io_conf = {
.pin_bit_mask = (1ULL << s_ctx.cfg.pin_irq),
.mode = GPIO_MODE_INPUT,
.pull_up_en = GPIO_PULLUP_ENABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_NEGEDGE,
};
esp_err_t err = gpio_config(&io_conf);
if (err != ESP_OK)
return err;
err = gpio_install_isr_service(0);
if (err != ESP_OK && err != ESP_ERR_INVALID_STATE)
return err;
return gpio_isr_handler_add(s_ctx.cfg.pin_irq, nrf_irq_isr, NULL);
}
/* ============================================================
* NVS BINDING TABLE (internal)
* ============================================================ */
static esp_err_t bindings_load(void)
{
nvs_handle_t h;
esp_err_t err = nvs_open(NVS_NAMESPACE, NVS_READONLY, &h);
if (err != ESP_OK)
{
memset(&s_ctx.bindings, 0, sizeof(s_ctx.bindings));
return ESP_OK;
}
size_t size = sizeof(s_ctx.bindings);
err = nvs_get_blob(h, NVS_KEY_BINDINGS, &s_ctx.bindings, &size);
nvs_close(h);
if (err == ESP_ERR_NVS_NOT_FOUND)
{
memset(&s_ctx.bindings, 0, sizeof(s_ctx.bindings));
ESP_LOGI(TAG, "Bindings: empty (first run)");
return ESP_OK;
}
if (err != ESP_OK)
{
memset(&s_ctx.bindings, 0, sizeof(s_ctx.bindings));
return err;
}
if (s_ctx.bindings.count > ZH_NRF_GATEWAY_MAX_BINDINGS)
{
ESP_LOGW(TAG, "Bindings: corrupt count %u, resetting", s_ctx.bindings.count);
memset(&s_ctx.bindings, 0, sizeof(s_ctx.bindings));
return ESP_OK;
}
ESP_LOGI(TAG, "Bindings: loaded %u entries", s_ctx.bindings.count);
return ESP_OK;
}
static esp_err_t bindings_save(void)
{
nvs_handle_t h;
esp_err_t err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &h);
if (err != ESP_OK)
return err;
size_t size = sizeof(s_ctx.bindings.count) +
s_ctx.bindings.count * sizeof(zh_nrf_gateway_binding_t);
err = nvs_set_blob(h, NVS_KEY_BINDINGS, &s_ctx.bindings, size);
if (err == ESP_OK)
err = nvs_commit(h);
nvs_close(h);
return err;
}
/* Caller must hold bindings_mutex. */
static bool bindings_exists_locked(uint8_t id, uint8_t type)
{
for (uint16_t i = 0; i < s_ctx.bindings.count; i++)
{
if (s_ctx.bindings.items[i].id == id &&
s_ctx.bindings.items[i].type == type)
{
return true;
}
}
return false;
}
/* Caller must hold bindings_mutex. */
static uint8_t bindings_alloc_id(uint8_t type)
{
for (uint16_t id = BINDING_ID_MIN; id <= BINDING_ID_MAX; id++)
{
if (!bindings_exists_locked((uint8_t)id, type))
{
return (uint8_t)id;
}
}
return 0;
}
/* Caller must hold bindings_mutex. */
static esp_err_t bindings_add(uint8_t id, uint8_t type)
{
if (s_ctx.bindings.count >= ZH_NRF_GATEWAY_MAX_BINDINGS)
{
return ESP_ERR_NO_MEM;
}
s_ctx.bindings.items[s_ctx.bindings.count].id = id;
s_ctx.bindings.items[s_ctx.bindings.count].type = type;
s_ctx.bindings.count++;
return bindings_save();
}
/* Caller must hold bindings_mutex. */
static esp_err_t bindings_delete(uint8_t id, uint8_t type)
{
for (uint16_t i = 0; i < s_ctx.bindings.count; i++)
{
if (s_ctx.bindings.items[i].id == id &&
s_ctx.bindings.items[i].type == type)
{
memmove(&s_ctx.bindings.items[i],
&s_ctx.bindings.items[i + 1],
(s_ctx.bindings.count - i - 1) * sizeof(zh_nrf_gateway_binding_t));
s_ctx.bindings.count--;
return bindings_save();
}
}
return ESP_ERR_NOT_FOUND;
}
/* ============================================================
* BINDING TABLE PUBLIC API
* ============================================================ */
size_t zh_nrf_gateway_bindings_get(zh_nrf_gateway_binding_t *buf, size_t max_count)
{
if (!buf || max_count == 0 || !s_ctx.bindings_mutex)
return 0;
xSemaphoreTake(s_ctx.bindings_mutex, portMAX_DELAY);
size_t n = s_ctx.bindings.count < max_count ? s_ctx.bindings.count : max_count;
memcpy(buf, s_ctx.bindings.items, n * sizeof(zh_nrf_gateway_binding_t));
xSemaphoreGive(s_ctx.bindings_mutex);
return n;
}
size_t zh_nrf_gateway_bindings_count(void)
{
if (!s_ctx.bindings_mutex)
return 0;
xSemaphoreTake(s_ctx.bindings_mutex, portMAX_DELAY);
size_t n = s_ctx.bindings.count;
xSemaphoreGive(s_ctx.bindings_mutex);
return n;
}
bool zh_nrf_gateway_binding_exists(uint8_t id, uint8_t type)
{
if (!s_ctx.initialized || !s_ctx.bindings_mutex)
return false;
xSemaphoreTake(s_ctx.bindings_mutex, portMAX_DELAY);
bool found = bindings_exists_locked(id, type);
xSemaphoreGive(s_ctx.bindings_mutex);
return found;
}
int zh_nrf_gateway_binding_auto_register(uint8_t id, uint8_t type)
{
if (!s_ctx.initialized || !s_ctx.bindings_mutex)
return -ESP_ERR_INVALID_STATE;
if (id < BINDING_ID_MIN || id > BINDING_ID_MAX)
return -ESP_ERR_INVALID_ARG;
if (zh_get_nrf24_sensor_payload_size(type) == 0)
return -ESP_ERR_INVALID_ARG;
xSemaphoreTake(s_ctx.bindings_mutex, portMAX_DELAY);
int result = 0;
if (!bindings_exists_locked(id, type))
{
esp_err_t err = bindings_add(id, type);
if (err == ESP_OK)
{
result = 1;
}
else
{
if (s_ctx.bindings.count > 0 &&
s_ctx.bindings.items[s_ctx.bindings.count - 1].id == id &&
s_ctx.bindings.items[s_ctx.bindings.count - 1].type == type)
{
s_ctx.bindings.count--;
}
result = -(int)err;
}
}
xSemaphoreGive(s_ctx.bindings_mutex);
return result;
}
esp_err_t zh_nrf_gateway_binding_delete(uint8_t id, uint8_t type)
{
if (!s_ctx.initialized)
return ESP_ERR_INVALID_STATE;
if (id == 0 || id == 0xFF)
return ESP_ERR_INVALID_ARG;
if (zh_get_nrf24_sensor_payload_size(type) == 0)
return ESP_ERR_INVALID_ARG;
xSemaphoreTake(s_ctx.bindings_mutex, portMAX_DELAY);
esp_err_t err = bindings_delete(id, type);
xSemaphoreGive(s_ctx.bindings_mutex);
if (err == ESP_OK)
{
ESP_LOGI(TAG, "Binding deleted: id=%u type=%u (%s)",
id, type, zh_get_nrf24_sensor_type_name((zh_nrf24_sensor_type_t)type));
}
else if (err == ESP_ERR_NOT_FOUND)
{
ESP_LOGW(TAG, "Binding not found: id=%u type=%u (%s)",
id, type, zh_get_nrf24_sensor_type_name((zh_nrf24_sensor_type_t)type));
}
else
{
ESP_LOGE(TAG, "Binding delete failed (id=%u type=%u): %s",
id, type, esp_err_to_name(err));
}
return err;
}
int zh_nrf_gateway_bindings_delete_by_id(uint8_t id)
{
if (!s_ctx.initialized)
return -ESP_ERR_INVALID_STATE;
if (id == 0 || id == 0xFF)
return -ESP_ERR_INVALID_ARG;
xSemaphoreTake(s_ctx.bindings_mutex, portMAX_DELAY);
int deleted = 0;
for (uint16_t i = 0; i < s_ctx.bindings.count;)
{
if (s_ctx.bindings.items[i].id == id)
{
memmove(&s_ctx.bindings.items[i],
&s_ctx.bindings.items[i + 1],
(s_ctx.bindings.count - i - 1) * sizeof(zh_nrf_gateway_binding_t));
s_ctx.bindings.count--;
deleted++;
}
else
{
i++;
}
}
esp_err_t err = (deleted > 0) ? bindings_save() : ESP_OK;
xSemaphoreGive(s_ctx.bindings_mutex);
if (err != ESP_OK)
return -(int)err;
if (deleted > 0)
ESP_LOGI(TAG, "Deleted %d binding(s) with id=%u", deleted, id);
else
ESP_LOGW(TAG, "No bindings with id=%u", id);
return deleted;
}
int zh_nrf_gateway_bindings_delete_by_type(uint8_t type)
{
if (!s_ctx.initialized)
return -ESP_ERR_INVALID_STATE;
if (zh_get_nrf24_sensor_payload_size(type) == 0)
return -ESP_ERR_INVALID_ARG;
xSemaphoreTake(s_ctx.bindings_mutex, portMAX_DELAY);
int deleted = 0;
for (uint16_t i = 0; i < s_ctx.bindings.count;)
{
if (s_ctx.bindings.items[i].type == type)
{
memmove(&s_ctx.bindings.items[i],
&s_ctx.bindings.items[i + 1],
(s_ctx.bindings.count - i - 1) * sizeof(zh_nrf_gateway_binding_t));
s_ctx.bindings.count--;
deleted++;
}
else
{
i++;
}
}
esp_err_t err = (deleted > 0) ? bindings_save() : ESP_OK;
xSemaphoreGive(s_ctx.bindings_mutex);
if (err != ESP_OK)
return -(int)err;
if (deleted > 0)
{
ESP_LOGI(TAG, "Deleted %d binding(s) of type=%u (%s)",
deleted, type, zh_get_nrf24_sensor_type_name((zh_nrf24_sensor_type_t)type));
}
else
{
ESP_LOGW(TAG, "No bindings of type=%u (%s)",
type, zh_get_nrf24_sensor_type_name((zh_nrf24_sensor_type_t)type));
}
return deleted;
}
esp_err_t zh_nrf_gateway_binding_clear_all(void)
{
if (!s_ctx.initialized)
return ESP_ERR_INVALID_STATE;
xSemaphoreTake(s_ctx.bindings_mutex, portMAX_DELAY);
s_ctx.bindings.count = 0;
esp_err_t err = bindings_save();
xSemaphoreGive(s_ctx.bindings_mutex);
if (err == ESP_OK)
ESP_LOGI(TAG, "All bindings cleared");
return err;
}
/* ============================================================
* PAIRING ACK
* ============================================================ */
static bool send_pairing_ack(uint8_t req_type, uint16_t token, uint8_t new_id)
{
uint8_t pkt[ZH_NRF24_PAIRING_PACKET_SIZE] = {
req_type,
ZH_NRF24_PAIRING_ACK_MAGIC,
(uint8_t)(token >> 8),
(uint8_t)(token & 0xFF),
new_id};
nrf_ce_low();
nrf_write_register(NRF_REG_CONFIG, NRF_CONFIG_ALL_MASKED | NRF_CONFIG_PWR_UP);
vTaskDelay(pdMS_TO_TICKS(2));
nrf_write_register(NRF_REG_STATUS, NRF_STATUS_TX_DS | NRF_STATUS_MAX_RT);
nrf_send_command(NRF_CMD_FLUSH_TX);
uint8_t tx[1 + ZH_NRF24_PAIRING_PACKET_SIZE];
tx[0] = NRF_CMD_W_TX_PAYLOAD;
memcpy(&tx[1], pkt, ZH_NRF24_PAIRING_PACKET_SIZE);
spi_transaction_t t = {
.length = (1 + ZH_NRF24_PAIRING_PACKET_SIZE) * 8,
.tx_buffer = tx,
};
nrf_csn_low();
ESP_ERROR_CHECK(spi_device_transmit(s_ctx.spi, &t));
nrf_csn_high();
nrf_ce_high();
esp_rom_delay_us(20);
nrf_ce_low();
uint8_t status = 0;
for (int i = 0; i < 100; i++)
{
status = nrf_send_command(NRF_CMD_NOP);
if (status & (NRF_STATUS_TX_DS | NRF_STATUS_MAX_RT))
break;
vTaskDelay(pdMS_TO_TICKS(1));
}
bool ok = (status & NRF_STATUS_TX_DS) != 0;
nrf_write_register(NRF_REG_STATUS, NRF_STATUS_TX_DS | NRF_STATUS_MAX_RT);
nrf_send_command(NRF_CMD_FLUSH_TX);
nrf_write_register(NRF_REG_CONFIG, NRF_CONFIG_RX_UNMASKED);
vTaskDelay(pdMS_TO_TICKS(5));
nrf_ce_high();
vTaskDelay(pdMS_TO_TICKS(1));
return ok;
}
/* ============================================================
* ОБРАБОТКА ПАКЕТОВ
* ============================================================ */
static void handle_pairing_request(const uint8_t *data)
{
uint8_t req_type = data[0];
uint16_t token = ((uint16_t)data[2] << 8) | data[3];
ESP_LOGI(TAG, "Pairing request: type=%u (%s), token=0x%04X",
req_type,
zh_get_nrf24_sensor_type_name((zh_nrf24_sensor_type_t)req_type),
token);
xSemaphoreTake(s_ctx.bindings_mutex, portMAX_DELAY);
uint8_t new_id = bindings_alloc_id(req_type);
if (new_id == 0)
{
xSemaphoreGive(s_ctx.bindings_mutex);
ESP_LOGW(TAG, "Pairing: no free id for type %u (all %d used)",
req_type, BINDING_ID_MAX);
return;
}
esp_err_t err = bindings_add(new_id, req_type);
if (err != ESP_OK)
{
if (s_ctx.bindings.count > 0 &&
s_ctx.bindings.items[s_ctx.bindings.count - 1].id == new_id &&
s_ctx.bindings.items[s_ctx.bindings.count - 1].type == req_type)
{
s_ctx.bindings.count--;
}
xSemaphoreGive(s_ctx.bindings_mutex);
ESP_LOGE(TAG, "Pairing: NVS save failed (%s), aborting", esp_err_to_name(err));
return;
}
xSemaphoreGive(s_ctx.bindings_mutex);
ESP_LOGI(TAG, "Pairing: allocated id=%u for type=%u", new_id, req_type);
if (!send_pairing_ack(req_type, token, new_id))
{
ESP_LOGW(TAG, "Pairing: ACK not delivered, removing binding id=%u type=%u",
new_id, req_type);
xSemaphoreTake(s_ctx.bindings_mutex, portMAX_DELAY);
bindings_delete(new_id, req_type);
xSemaphoreGive(s_ctx.bindings_mutex);
return;
}
ESP_LOGI(TAG, "Pairing complete: id=%u type=%u", new_id, req_type);
zh_nrf_gateway_binding_t paired = {
.id = new_id,
.type = req_type,
};
esp_err_t post_err = esp_event_post(ZH_NRF24_GATEWAY_EVENTS,
ZH_NRF_GATEWAY_EVENT_SENSOR_PAIRED,
&paired, sizeof(paired),
pdMS_TO_TICKS(100));
if (post_err != ESP_OK)
{
ESP_LOGW(TAG, "esp_event_post(paired) failed: %s", esp_err_to_name(post_err));
}
}
static void handle_sensor_data(const uint8_t *buf, uint8_t len)
{
if (len < ZH_NRF24_DATA_HEADER_SIZE)
{
ESP_LOGW(TAG, "Too short data packet (%u)", len);
return;
}
zh_nrf24_sensor_transmitted_data_t d = {0};
d.id = zh_nrf24_sensor_read_i16_le_at(buf, 0);
d.type = zh_nrf24_sensor_read_i16_le_at(buf, 2);
d.battery = zh_nrf24_sensor_read_i16_le_at(buf, 4);
uint8_t expected = zh_get_nrf24_sensor_payload_size(d.type);
if (expected == 0)
{
ESP_LOGW(TAG, "Unknown sensor type %d, dropping", d.type);
return;
}
if (len != expected)
{
ESP_LOGW(TAG, "Length %u != expected %u for type %d",
len, expected, d.type);
}
/* ----- Auto-register unknown {id, type} ----- */
if (d.id >= BINDING_ID_MIN && d.id <= BINDING_ID_MAX)
{
int r = zh_nrf_gateway_binding_auto_register((uint8_t)d.id,
(uint8_t)d.type);
if (r == 1)
{
ESP_LOGI(TAG, "Auto-registered sensor: id=%d type=%d (%s)",
d.id, d.type,
zh_get_nrf24_sensor_type_name((zh_nrf24_sensor_type_t)d.type));
zh_nrf_gateway_binding_t b = {
.id = (uint8_t)d.id,
.type = (uint8_t)d.type,
};
esp_err_t perr = esp_event_post(ZH_NRF24_GATEWAY_EVENTS,
ZH_NRF_GATEWAY_EVENT_SENSOR_REGISTERED,
&b, sizeof(b),
pdMS_TO_TICKS(100));
if (perr != ESP_OK)
{
ESP_LOGW(TAG, "esp_event_post(registered) failed: %s",
esp_err_to_name(perr));
}
}
else if (r < 0)
{
ESP_LOGW(TAG, "Auto-register failed for id=%d type=%d: %s",
d.id, d.type, esp_err_to_name((esp_err_t)(-r)));
}
}
else
{
ESP_LOGW(TAG, "Sensor id %d out of range [%d..%d], skipping auto-register",
d.id, BINDING_ID_MIN, BINDING_ID_MAX);
}
/* ----- Parse type-specific fields ----- */
switch (d.type)
{
case ZH_NRF24_SENSOR_TOUCH_SWITCH:
break;
case ZH_NRF24_SENSOR_WATER_LEAKAGE:
case ZH_NRF24_SENSOR_OPEN_CLOSE:
case ZH_NRF24_SENSOR_PLANT_HUMIDITY:
if (len >= ZH_NRF24_DATA_HEADER_SIZE + ZH_NRF24_DATA_FIELD_SIZE)
d.value_1 = zh_nrf24_sensor_read_i16_le_at(buf, 6);
break;
case ZH_NRF24_SENSOR_BMP280:
if (len >= ZH_NRF24_DATA_HEADER_SIZE + 2 * ZH_NRF24_DATA_FIELD_SIZE)
{
d.value_1 = zh_nrf24_sensor_read_i16_le_at(buf, 6);
d.value_2 = zh_nrf24_sensor_read_i16_le_at(buf, 8);
}
break;
case ZH_NRF24_SENSOR_BME280:
if (len >= ZH_NRF24_DATA_HEADER_SIZE + 3 * ZH_NRF24_DATA_FIELD_SIZE)
{
d.value_1 = zh_nrf24_sensor_read_i16_le_at(buf, 6);
d.value_2 = zh_nrf24_sensor_read_i16_le_at(buf, 8);
d.value_3 = zh_nrf24_sensor_read_i16_le_at(buf, 10);
}
break;
case ZH_NRF24_SENSOR_BME680:
if (len >= ZH_NRF24_DATA_HEADER_SIZE + 4 * ZH_NRF24_DATA_FIELD_SIZE)
{
d.value_1 = zh_nrf24_sensor_read_i16_le_at(buf, 6);
d.value_2 = zh_nrf24_sensor_read_i16_le_at(buf, 8);
d.value_3 = zh_nrf24_sensor_read_i16_le_at(buf, 10);
d.value_4 = zh_nrf24_sensor_read_i16_le_at(buf, 12);
}
break;
default:
break;
}
/* ----- Post SENSOR_DATA ----- */
esp_err_t err = esp_event_post(ZH_NRF24_GATEWAY_EVENTS,
ZH_NRF_GATEWAY_EVENT_SENSOR_DATA,
&d, sizeof(d), pdMS_TO_TICKS(100));
if (err != ESP_OK)
{
ESP_LOGW(TAG, "esp_event_post(data) failed: %s", esp_err_to_name(err));
}
}
static bool process_one_packet(void)
{
uint8_t fifo = nrf_read_register(NRF_REG_FIFO_STATUS);
if (fifo & NRF_FIFO_RX_EMPTY)
return false;
uint8_t width = nrf_read_payload_width();
if (width > ZH_NRF24_MAX_PAYLOAD_SIZE)
{
ESP_LOGW(TAG, "Corrupt payload width %u, FLUSH_RX", width);
nrf_send_command(NRF_CMD_FLUSH_RX);
nrf_write_register(NRF_REG_STATUS, NRF_STATUS_RX_DR);
return true;
}
uint8_t buf[ZH_NRF24_MAX_PAYLOAD_SIZE] = {0};
nrf_read_payload(buf, width);
nrf_write_register(NRF_REG_STATUS, NRF_STATUS_RX_DR);
if (width == ZH_NRF24_PAIRING_PACKET_SIZE && buf[1] == ZH_NRF24_PAIRING_REQ_MAGIC)
{
handle_pairing_request(buf);
}
else
{
handle_sensor_data(buf, width);
}
return true;
}
static void process_all_pending(void)
{
while (process_one_packet())
{
}
}
static void gateway_task(void *arg)
{
while (1)
{
if (xSemaphoreTake(s_ctx.irq_sem, pdMS_TO_TICKS(1000)) == pdTRUE)
{
process_all_pending();
}
else
{
process_all_pending();
}
}
}
/* ============================================================
* PUBLIC API
* ============================================================ */
esp_err_t zh_nrf_gateway_init(const zh_nrf24_gateway_init_config_t *config)
{
if (!config)
return ESP_ERR_INVALID_ARG;
if (s_ctx.initialized)
return ESP_ERR_INVALID_STATE;
s_ctx.cfg = *config;
if (s_ctx.cfg.spi_clock_hz == 0)
s_ctx.cfg.spi_clock_hz = 4 * 1000 * 1000;
if (s_ctx.cfg.channel > 125)
s_ctx.cfg.channel = 120;
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND)
{
ESP_LOGW(TAG, "NVS flash needs erase, erasing");
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
if (err != ESP_OK)
return err;
s_ctx.bindings_mutex = xSemaphoreCreateMutex();
if (!s_ctx.bindings_mutex)
return ESP_ERR_NO_MEM;
err = bindings_load();
if (err != ESP_OK)
{
ESP_LOGW(TAG, "Bindings load failed (%s), starting empty", esp_err_to_name(err));
memset(&s_ctx.bindings, 0, sizeof(s_ctx.bindings));
}
err = esp_event_loop_create_default();
if (err != ESP_OK && err != ESP_ERR_INVALID_STATE)
return err;
spi_bus_config_t buscfg = {
.miso_io_num = s_ctx.cfg.pin_miso,
.mosi_io_num = s_ctx.cfg.pin_mosi,
.sclk_io_num = s_ctx.cfg.pin_sck,
.quadwp_io_num = -1,
.quadhd_io_num = -1,
.max_transfer_sz = ZH_NRF24_MAX_PAYLOAD_SIZE,
};
err = spi_bus_initialize(s_ctx.cfg.spi_host, &buscfg, SPI_DMA_CH_AUTO);
if (err != ESP_OK)
return err;
spi_device_interface_config_t devcfg = {
.clock_speed_hz = (int)s_ctx.cfg.spi_clock_hz,
.mode = 0,
.spics_io_num = s_ctx.cfg.pin_csn,
.queue_size = 1,
};
err = spi_bus_add_device(s_ctx.cfg.spi_host, &devcfg, &s_ctx.spi);
if (err != ESP_OK)
return err;
gpio_config_t ce_conf = {
.pin_bit_mask = (1ULL << s_ctx.cfg.pin_ce),
.mode = GPIO_MODE_OUTPUT,
};
err = gpio_config(&ce_conf);
if (err != ESP_OK)
return err;
nrf_ce_low();
vTaskDelay(pdMS_TO_TICKS(100));
nrf_write_register(NRF_REG_CONFIG, 0x00);
nrf_write_register(NRF_REG_EN_AA, 0x01);
nrf_write_register(NRF_REG_EN_RXADDR, 0x01);
nrf_write_register(NRF_REG_SETUP_AW, 0x01); /* 3-byte address */
nrf_write_register(NRF_REG_SETUP_RETR, 0xFF);
nrf_write_register(NRF_REG_RF_CH, s_ctx.cfg.channel);
nrf_write_register(NRF_REG_RF_SETUP, 0x26); /* 250 kbps, 0 dBm */
uint8_t addr_bytes[3] = {
(uint8_t)(s_ctx.cfg.address >> 0),
(uint8_t)(s_ctx.cfg.address >> 8),
(uint8_t)(s_ctx.cfg.address >> 16),
};
nrf_write_buffer(NRF_REG_TX_ADDR, addr_bytes, 3);
nrf_write_buffer(NRF_REG_RX_ADDR_P0, addr_bytes, 3);
nrf_write_register(NRF_REG_STATUS,
NRF_STATUS_RX_DR | NRF_STATUS_TX_DS | NRF_STATUS_MAX_RT);
/* Enable Dynamic Payload Length */
nrf_activate();
nrf_write_register(NRF_REG_FEATURE, NRF_FEATURE_EN_DPL);
nrf_write_register(NRF_REG_DYNPD, NRF_DYNPD_DPL_P0);
/* Enter RX */
nrf_write_register(NRF_REG_CONFIG, NRF_CONFIG_RX_UNMASKED);
vTaskDelay(pdMS_TO_TICKS(5));
nrf_ce_high();
vTaskDelay(pdMS_TO_TICKS(1));
err = nrf_irq_init();
if (err != ESP_OK)
return err;
xSemaphoreTake(s_ctx.irq_sem, 0);
s_ctx.initialized = true;
ESP_LOGI(TAG, "Initialized: ch=%u addr=0x%06X, %u bindings in NVS",
s_ctx.cfg.channel, (unsigned)(s_ctx.cfg.address & 0xFFFFFF),
s_ctx.bindings.count);
return ESP_OK;
}
esp_err_t zh_nrf_gateway_start(void)
{
if (!s_ctx.initialized)
return ESP_ERR_INVALID_STATE;
if (s_ctx.task)
return ESP_OK;
BaseType_t r = xTaskCreatePinnedToCore(gateway_task, "nrf_gateway",
4096, NULL, 5,
&s_ctx.task, tskNO_AFFINITY);
if (r != pdPASS)
{
s_ctx.task = NULL;
return ESP_ERR_NO_MEM;
}
ESP_LOGI(TAG, "Receiver task started");
return ESP_OK;
}