7 Commits

Author SHA1 Message Date
Tony 449a3a801a Add KNX DALI Gateway Module and Message Queue Implementation
- Introduced KnxDaliModule class for handling DALI message queuing, commissioning, and KNX group-object dispatch.
- Implemented Message and MessageQueue classes for managing message operations.
- Removed obsolete OpenKNX IDF component files and CMake configurations.
- Updated submodule reference for KNX.

Signed-off-by: Tony <tonylu@tony-cloud.com>
2026-05-15 12:34:13 +08:00
Tony 3f15cd7f3f fix(gateway): update DALI query response timeout and activity wait parameters
Signed-off-by: Tony <tonylu@tony-cloud.com>
2026-05-15 10:33:22 +08:00
Tony f005d2bc09 feat(gateway): update BLE connection parameters and enhance DALI timeout configurations
Signed-off-by: Tony <tonylu@tony-cloud.com>
2026-05-15 08:42:20 +08:00
Tony 70ae1ae6cf feat(dali): enhance DALI timing configurations and add new timeout parameters
Signed-off-by: Tony <tonylu@tony-cloud.com>
2026-05-15 03:17:35 +08:00
Tony f2ffb45ca6 feat(gateway): implement LegacyRawPayload function for DALI and USB components
Signed-off-by: Tony <tonylu@tony-cloud.com>
2026-05-15 02:35:37 +08:00
Tony 0b2d00472e Enhance DALI Component Configuration and Functionality
- Updated README.md to include new configuration options for native timing values, TX/RX polarity, power-down polling, and logging levels.
- Introduced new default values for query response timeout and double-send delay in dali.c.
- Implemented a function to drain stale RX frames from the queue to improve query handling.
- Enhanced DALI HAL implementation in dali_hal_idf5.c with additional configuration options for timer resolution and bus power check intervals.
- Added logging capabilities to track bus states and message transmissions in the DALI HAL.
- Improved error handling and message response mechanisms in dali_domain.cpp and gateway_usb_setup.cpp for better communication reliability.
- Refactored GPIO handling to support configurable TX/RX active states in dali_hal.h.
- Introduced legacy query response handling for backward compatibility in the DALI domain.

Signed-off-by: Tony <tonylu@tony-cloud.com>
2026-05-15 01:26:13 +08:00
Tony 4553ed32e7 feat(gateway): add support for KNX TP UART 9-bit mode and enhance UART pin configuration
Signed-off-by: Tony <tonylu@tony-cloud.com>
2026-05-14 22:39:14 +08:00
57 changed files with 6629 additions and 1105 deletions
+1 -1
View File
@@ -34,7 +34,7 @@ The native rewrite now wires a shared `gateway_core` bootstrap component, a mult
KNX Data Secure and KNXnet/IP Secure support are controlled by `GATEWAY_KNX_DATA_SECURE_SUPPORTED` and `GATEWAY_KNX_IP_SECURE_SUPPORTED`. The current KNXnet/IP Secure flag reserves and reports secure service capability, while runtime secure-session transport is still reported as not implemented until that path is wired. The gateway derives its KNX serial identity from the ESP base MAC, and the development factory setup key is deterministically derived from that KNX serial so the same board keeps the same FDSK across NVS erases.
The KNXnet/IP tunnel can start from the built-in default configuration before any ETS download. KNX TP-UART is enabled only when `GATEWAY_KNX_TP_UART_PORT` is `0`, `1`, or `2`; set that UART port to `-1` for IP-only operation. UART TX/RX GPIO values of `-1` mean use the ESP-IDF default IO routing for that UART, not disabled. Non-UART GPIO options use `-1` as disabled, including the KNX programming button, KNX programming LED, setup AP button, Wi-Fi reset button, and status LED.
The KNXnet/IP tunnel can start from the built-in default configuration before any ETS download. KNX TP-UART is enabled only when `GATEWAY_KNX_TP_UART_PORT` is `0`, `1`, or `2`; set that UART port to `-1` for IP-only operation. UART TX/RX GPIO values of `-1` mean use the ESP-IDF target default pins for that UART, not disabled. `GATEWAY_KNX_TP_UART_9BIT_MODE` enables the NCN5120/OpenKNX-style 9-bit host frame on the wire, represented on ESP-IDF as 8 data bits plus even parity. Non-UART GPIO options use `-1` as disabled, including the KNX programming button, KNX programming LED, setup AP button, Wi-Fi reset button, and status LED.
When no KNX bridge config or ETS application data has been downloaded, the KNXnet/IP router starts in commissioning mode: OpenKNX receives tunnel programming traffic from ETS, while DALI group routing and REG1-Dali function-property actions stay inactive until ETS reports a configured application.
+1
View File
@@ -6,6 +6,7 @@ endif()
set(EXTRA_COMPONENT_DIRS
"${CMAKE_CURRENT_LIST_DIR}/../../components"
"${CMAKE_CURRENT_LIST_DIR}/../../knx"
"${CMAKE_CURRENT_LIST_DIR}/../../../dali_cpp"
)
+10
View File
@@ -772,6 +772,16 @@ config GATEWAY_KNX_TP_BAUDRATE
range 1200 921600
default 19200
config GATEWAY_KNX_TP_UART_9BIT_MODE
bool "KNX TP UART 9-bit mode"
depends on GATEWAY_KNX_BRIDGE_SUPPORTED
default y
help
Enable the NCN5120/OpenKNX-style 9-bit UART frame on the wire. ESP-IDF
exposes this as 8 data bits plus even parity, matching the TP-UART host
mode commonly described as 19200 baud 9-bit UART. Disable only for
hardware wired for 8N1 host UART mode.
config GATEWAY_BRIDGE_KNX_TASK_STACK_SIZE
int "KNX/IP bridge task stack bytes"
depends on GATEWAY_KNX_BRIDGE_SUPPORTED
+5
View File
@@ -886,6 +886,11 @@ extern "C" void app_main(void) {
default_knx.tp_uart.tx_pin = CONFIG_GATEWAY_KNX_TP_TX_PIN;
default_knx.tp_uart.rx_pin = CONFIG_GATEWAY_KNX_TP_RX_PIN;
default_knx.tp_uart.baudrate = static_cast<uint32_t>(CONFIG_GATEWAY_KNX_TP_BAUDRATE);
#ifdef CONFIG_GATEWAY_KNX_TP_UART_9BIT_MODE
default_knx.tp_uart.nine_bit_mode = true;
#else
default_knx.tp_uart.nine_bit_mode = false;
#endif
bridge_config.default_knx_config = default_knx;
}
bridge_config.knx_task_stack_size =
+80 -59
View File
@@ -603,15 +603,13 @@ CONFIG_GATEWAY_CHANNEL_COUNT=1
#
CONFIG_GATEWAY_CHANNEL1_GW_ID=3
# CONFIG_GATEWAY_CHANNEL1_PHY_DISABLED is not set
# CONFIG_GATEWAY_CHANNEL1_PHY_NATIVE is not set
CONFIG_GATEWAY_CHANNEL1_PHY_UART1=y
CONFIG_GATEWAY_CHANNEL1_PHY_NATIVE=y
# CONFIG_GATEWAY_CHANNEL1_PHY_UART1 is not set
# CONFIG_GATEWAY_CHANNEL1_PHY_UART2 is not set
CONFIG_GATEWAY_CHANNEL1_SERIAL_TX_PIN=1
CONFIG_GATEWAY_CHANNEL1_SERIAL_RX_PIN=2
CONFIG_GATEWAY_CHANNEL1_SERIAL_BAUDRATE=9600
CONFIG_GATEWAY_CHANNEL1_SERIAL_RX_BUFFER=512
CONFIG_GATEWAY_CHANNEL1_SERIAL_TX_BUFFER=512
CONFIG_GATEWAY_CHANNEL1_SERIAL_QUERY_TIMEOUT_MS=100
CONFIG_GATEWAY_CHANNEL1_NATIVE_BUS_ID=0
CONFIG_GATEWAY_CHANNEL1_NATIVE_TX_PIN=2
CONFIG_GATEWAY_CHANNEL1_NATIVE_RX_PIN=1
CONFIG_GATEWAY_CHANNEL1_NATIVE_BAUDRATE=1200
# end of Gateway Channel 1
#
@@ -624,11 +622,8 @@ CONFIG_GATEWAY_CHANNEL1_SERIAL_QUERY_TIMEOUT_MS=100
#
CONFIG_GATEWAY_CACHE_SUPPORTED=y
CONFIG_GATEWAY_CACHE_START_ENABLED=y
CONFIG_GATEWAY_CACHE_RECONCILIATION_ENABLED=y
# CONFIG_GATEWAY_CACHE_FULL_STATE_MIRROR is not set
CONFIG_GATEWAY_CACHE_FLUSH_INTERVAL_MS=5000
CONFIG_GATEWAY_CACHE_OUTSIDE_BUS_FIRST=y
# CONFIG_GATEWAY_CACHE_LOCAL_GATEWAY_FIRST is not set
# CONFIG_GATEWAY_CACHE_RECONCILIATION_ENABLED is not set
CONFIG_GATEWAY_CACHE_FLUSH_INTERVAL_MS=60000
# end of Gateway Cache
# CONFIG_GATEWAY_ENABLE_DALI_BUS is not set
@@ -696,6 +691,7 @@ CONFIG_GATEWAY_KNX_TP_UART_PORT=0
CONFIG_GATEWAY_KNX_TP_TX_PIN=-1
CONFIG_GATEWAY_KNX_TP_RX_PIN=-1
CONFIG_GATEWAY_KNX_TP_BAUDRATE=19200
CONFIG_GATEWAY_KNX_TP_UART_9BIT_MODE=y
CONFIG_GATEWAY_BRIDGE_KNX_TASK_STACK_SIZE=12288
CONFIG_GATEWAY_BRIDGE_KNX_TASK_PRIORITY=5
CONFIG_GATEWAY_CLOUD_BRIDGE_SUPPORTED=y
@@ -795,12 +791,12 @@ CONFIG_BT_CONTROLLER_ENABLED=y
#
# General
#
CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_INTERNAL=y
# CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_EXTERNAL is not set
# CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_INTERNAL is not set
CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_EXTERNAL=y
# CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_DEFAULT is not set
CONFIG_BT_NIMBLE_PINNED_TO_CORE=0
CONFIG_BT_NIMBLE_PINNED_TO_CORE_0=y
# CONFIG_BT_NIMBLE_PINNED_TO_CORE_1 is not set
CONFIG_BT_NIMBLE_PINNED_TO_CORE=1
# CONFIG_BT_NIMBLE_PINNED_TO_CORE_0 is not set
CONFIG_BT_NIMBLE_PINNED_TO_CORE_1=y
CONFIG_BT_NIMBLE_HOST_TASK_STACK_SIZE=4096
CONFIG_BT_NIMBLE_LEGACY_VHCI_ENABLE=y
# end of General
@@ -842,7 +838,7 @@ CONFIG_BT_NIMBLE_MAX_CONN_REATTEMPT=3
CONFIG_BT_NIMBLE_HS_PVCY=y
# CONFIG_BT_NIMBLE_HOST_ALLOW_CONNECT_WITH_SCAN is not set
# CONFIG_BT_NIMBLE_HOST_QUEUE_CONG_CHECK is not set
CONFIG_BT_NIMBLE_MAX_CONNECTIONS=3
CONFIG_BT_NIMBLE_MAX_CONNECTIONS=4
CONFIG_BT_NIMBLE_MAX_CCCDS=8
CONFIG_BT_NIMBLE_CRYPTO_STACK_MBEDTLS=y
CONFIG_BT_NIMBLE_HS_STOP_TIMEOUT_MS=2000
@@ -1005,10 +1001,10 @@ CONFIG_BT_NIMBLE_HCI_UART_CTS_PIN=23
# CONFIG_BT_NIMBLE_MEM_DEBUG is not set
# CONFIG_BT_NIMBLE_LOG_LEVEL_NONE is not set
# CONFIG_BT_NIMBLE_LOG_LEVEL_ERROR is not set
# CONFIG_BT_NIMBLE_LOG_LEVEL_WARNING is not set
CONFIG_BT_NIMBLE_LOG_LEVEL_INFO=y
CONFIG_BT_NIMBLE_LOG_LEVEL_WARNING=y
# CONFIG_BT_NIMBLE_LOG_LEVEL_INFO is not set
# CONFIG_BT_NIMBLE_LOG_LEVEL_DEBUG is not set
CONFIG_BT_NIMBLE_LOG_LEVEL=1
CONFIG_BT_NIMBLE_LOG_LEVEL=2
CONFIG_BT_NIMBLE_PRINT_ERR_NAME=y
# CONFIG_BT_NIMBLE_DEBUG is not set
# CONFIG_BT_NIMBLE_TEST_THROUGHPUT_TEST is not set
@@ -1037,9 +1033,9 @@ CONFIG_BT_CTRL_MODE_EFF=1
CONFIG_BT_CTRL_BLE_MAX_ACT=6
CONFIG_BT_CTRL_BLE_MAX_ACT_EFF=6
CONFIG_BT_CTRL_BLE_STATIC_ACL_TX_BUF_NB=0
CONFIG_BT_CTRL_PINNED_TO_CORE_0=y
# CONFIG_BT_CTRL_PINNED_TO_CORE_1 is not set
CONFIG_BT_CTRL_PINNED_TO_CORE=0
# CONFIG_BT_CTRL_PINNED_TO_CORE_0 is not set
CONFIG_BT_CTRL_PINNED_TO_CORE_1=y
CONFIG_BT_CTRL_PINNED_TO_CORE=1
CONFIG_BT_CTRL_HCI_MODE_VHCI=y
# CONFIG_BT_CTRL_HCI_MODE_UART_H4 is not set
CONFIG_BT_CTRL_HCI_TL=1
@@ -1134,8 +1130,8 @@ CONFIG_BT_CTRL_BLE_ADV=y
# Common Options
#
CONFIG_BT_ALARM_MAX_NUM=50
CONFIG_BT_SMP_CRYPTO_STACK_TINYCRYPT=y
# CONFIG_BT_SMP_CRYPTO_STACK_MBEDTLS is not set
# CONFIG_BT_SMP_CRYPTO_STACK_TINYCRYPT is not set
CONFIG_BT_SMP_CRYPTO_STACK_MBEDTLS=y
#
# BLE Log
@@ -1302,15 +1298,15 @@ CONFIG_ESP_ERR_TO_NAME_LOOKUP=y
#
# ESP-Driver:GPIO Configurations
#
# CONFIG_GPIO_CTRL_FUNC_IN_IRAM is not set
CONFIG_GPIO_CTRL_FUNC_IN_IRAM=y
# end of ESP-Driver:GPIO Configurations
#
# ESP-Driver:GPTimer Configurations
#
CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y
# CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is not set
# CONFIG_GPTIMER_ISR_CACHE_SAFE is not set
CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM=y
CONFIG_GPTIMER_ISR_CACHE_SAFE=y
CONFIG_GPTIMER_OBJ_CACHE_SAFE=y
# CONFIG_GPTIMER_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:GPTimer Configurations
@@ -1746,9 +1742,9 @@ CONFIG_ESP_ROM_PRINT_IN_IRAM=y
# ESP System Settings
#
# CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_80 is not set
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160=y
# CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240 is not set
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=160
# CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160 is not set
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240=y
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=240
#
# Cache config
@@ -1794,7 +1790,7 @@ CONFIG_ESP_SYSTEM_IN_IRAM=y
CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT=y
# CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT is not set
# CONFIG_ESP_SYSTEM_PANIC_GDBSTUB is not set
CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS=0
CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS=2
CONFIG_ESP_SYSTEM_RTC_FAST_MEM_AS_HEAP_DEPCHECK=y
CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP=y
@@ -1874,9 +1870,9 @@ CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=32
CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER=y
CONFIG_ESP_WIFI_TX_BUFFER_TYPE=1
CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM=32
CONFIG_ESP_WIFI_STATIC_RX_MGMT_BUFFER=y
# CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUFFER is not set
CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUF=0
# CONFIG_ESP_WIFI_STATIC_RX_MGMT_BUFFER is not set
CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUFFER=y
CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUF=1
CONFIG_ESP_WIFI_RX_MGMT_BUF_NUM_DEF=5
# CONFIG_ESP_WIFI_CSI_ENABLED is not set
CONFIG_ESP_WIFI_AMPDU_TX_ENABLED=y
@@ -1884,8 +1880,8 @@ CONFIG_ESP_WIFI_TX_BA_WIN=6
CONFIG_ESP_WIFI_AMPDU_RX_ENABLED=y
CONFIG_ESP_WIFI_RX_BA_WIN=6
CONFIG_ESP_WIFI_NVS_ENABLED=y
CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_0=y
# CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_1 is not set
# CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_0 is not set
CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_1=y
CONFIG_ESP_WIFI_SOFTAP_BEACON_MAX_LEN=752
CONFIG_ESP_WIFI_MGMT_SBUF_NUM=32
CONFIG_ESP_WIFI_IRAM_OPT=y
@@ -2002,12 +1998,12 @@ CONFIG_FATFS_DONT_TRUST_LAST_ALLOC=0
#
# CONFIG_FREERTOS_SMP is not set
# CONFIG_FREERTOS_UNICORE is not set
CONFIG_FREERTOS_HZ=100
CONFIG_FREERTOS_HZ=1000
# CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE is not set
# CONFIG_FREERTOS_CHECK_STACKOVERFLOW_PTRVAL is not set
CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY=y
CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS=1
CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=1536
CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=2048
# CONFIG_FREERTOS_USE_IDLE_HOOK is not set
# CONFIG_FREERTOS_USE_TICK_HOOK is not set
CONFIG_FREERTOS_MAX_TASK_NAME_LEN=16
@@ -2772,13 +2768,36 @@ CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y
#
CONFIG_DALI_PHY_COUNT=16
CONFIG_DALI_DEFAULT_BAUDRATE=1200
CONFIG_DALI_API_QUEUE_LEN=10
CONFIG_DALI_TX_QUEUE_LEN=1
CONFIG_DALI_TIMER_RESOLUTION_HZ=3636363
CONFIG_DALI_CUSTOM_HALF_BIT_TIME_X100_US=0
CONFIG_DALI_TX_STOP_CONDITION_US=0
CONFIG_DALI_RX_STOP_CONDITION_US=0
CONFIG_DALI_QUERY_RESPONSE_TIMEOUT_MS=25
CONFIG_DALI_DOUBLE_SEND_DELAY_MS=15
CONFIG_DALI_FORWARD_ACTIVITY_WAIT_MS=15
CONFIG_DALI_FORWARD_AFTER_BACKWARD_WAIT_MS=5
CONFIG_DALI_FORWARD_MAX_WAIT_MS=50
CONFIG_DALI_BACKWARD_IDLE_TIMEOUT_MS=10
CONFIG_DALI_BUS_POWER_CHECK_INTERVAL_MS=500
CONFIG_DALI_BUS_ABNORMAL_REPORT_INTERVAL_MS=3000
# CONFIG_DALI_LOG_LEVEL_NONE is not set
# CONFIG_DALI_LOG_LEVEL_ERROR is not set
# CONFIG_DALI_LOG_LEVEL_WARN is not set
# CONFIG_DALI_LOG_LEVEL_INFO is not set
CONFIG_DALI_LOG_LEVEL_DEBUG=y
# CONFIG_DALI_LOG_LEVEL_VERBOSE is not set
CONFIG_DALI_LOG_LEVEL=4
CONFIG_DALI_TX_ACTIVE_LOW=y
# CONFIG_DALI_TX_ACTIVE_HIGH is not set
CONFIG_DALI_RX_ACTIVE_LOW=y
# CONFIG_DALI_RX_ACTIVE_HIGH is not set
CONFIG_DALI_API_QUEUE_LEN=64
CONFIG_DALI_TX_QUEUE_LEN=4
CONFIG_DALI_TX_REPLY_QUEUE_LEN=4
CONFIG_DALI_RX_QUEUE_LEN=50
CONFIG_DALI_DEBUG_QUEUE_LEN=100
# CONFIG_DALI_ENABLE_DEBUG_TASK is not set
CONFIG_DALI_DALI_TASK_STACK_SIZE=2048
CONFIG_DALI_ENABLE_DEBUG_TASK=y
CONFIG_DALI_DALI_TASK_STACK_SIZE=8192
CONFIG_DALI_DALI_TASK_PRIORITY=2
CONFIG_DALI_DEBUG_TASK_STACK_SIZE=2048
CONFIG_DALI_DEBUG_TASK_PRIORITY=1
@@ -2800,10 +2819,12 @@ CONFIG_MQTT_TRANSPORT_SSL=y
CONFIG_MQTT_TRANSPORT_WEBSOCKET=y
CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE=y
# CONFIG_MQTT_MSG_ID_INCREMENTAL is not set
# CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED is not set
CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED=y
# CONFIG_MQTT_REPORT_DELETED_MESSAGES is not set
# CONFIG_MQTT_USE_CUSTOM_CONFIG is not set
# CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED is not set
CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED=y
# CONFIG_MQTT_USE_CORE_0 is not set
CONFIG_MQTT_USE_CORE_1=y
# CONFIG_MQTT_CUSTOM_OUTBOX is not set
# end of ESP-MQTT Configurations
# end of Component config
@@ -2847,12 +2868,12 @@ CONFIG_ESP32_APPTRACE_DEST_NONE=y
CONFIG_ESP32_APPTRACE_LOCK_ENABLE=y
# CONFIG_BLUEDROID_ENABLED is not set
CONFIG_NIMBLE_ENABLED=y
CONFIG_NIMBLE_MEM_ALLOC_MODE_INTERNAL=y
# CONFIG_NIMBLE_MEM_ALLOC_MODE_EXTERNAL is not set
# CONFIG_NIMBLE_MEM_ALLOC_MODE_INTERNAL is not set
CONFIG_NIMBLE_MEM_ALLOC_MODE_EXTERNAL=y
# CONFIG_NIMBLE_MEM_ALLOC_MODE_DEFAULT is not set
CONFIG_NIMBLE_PINNED_TO_CORE=0
CONFIG_NIMBLE_PINNED_TO_CORE_0=y
# CONFIG_NIMBLE_PINNED_TO_CORE_1 is not set
CONFIG_NIMBLE_PINNED_TO_CORE=1
# CONFIG_NIMBLE_PINNED_TO_CORE_0 is not set
CONFIG_NIMBLE_PINNED_TO_CORE_1=y
CONFIG_NIMBLE_TASK_STACK_SIZE=4096
CONFIG_BT_NIMBLE_TASK_STACK_SIZE=4096
CONFIG_NIMBLE_ROLE_CENTRAL=y
@@ -2866,7 +2887,7 @@ CONFIG_BT_NIMBLE_SM_SC_LVL=0
# CONFIG_NIMBLE_NVS_PERSIST is not set
CONFIG_NIMBLE_MAX_BONDS=3
CONFIG_NIMBLE_RPA_TIMEOUT=900
CONFIG_NIMBLE_MAX_CONNECTIONS=3
CONFIG_NIMBLE_MAX_CONNECTIONS=4
CONFIG_NIMBLE_MAX_CCCDS=8
CONFIG_NIMBLE_CRYPTO_STACK_MBEDTLS=y
# CONFIG_NIMBLE_HS_FLOW_CTRL is not set
@@ -2889,7 +2910,7 @@ CONFIG_SW_COEXIST_ENABLE=y
CONFIG_ESP32_WIFI_SW_COEXIST_ENABLE=y
CONFIG_ESP_WIFI_SW_COEXIST_ENABLE=y
# CONFIG_CAM_CTLR_DVP_CAM_ISR_IRAM_SAFE is not set
# CONFIG_GPTIMER_ISR_IRAM_SAFE is not set
CONFIG_GPTIMER_ISR_IRAM_SAFE=y
# CONFIG_MCPWM_ISR_IRAM_SAFE is not set
# CONFIG_EVENT_LOOP_PROFILING is not set
CONFIG_POST_EVENTS_FROM_ISR=y
@@ -2936,9 +2957,9 @@ CONFIG_ESP32S3_SPIRAM_SUPPORT=y
CONFIG_DEFAULT_PSRAM_CLK_IO=30
CONFIG_DEFAULT_PSRAM_CS_IO=26
# CONFIG_ESP32S3_DEFAULT_CPU_FREQ_80 is not set
CONFIG_ESP32S3_DEFAULT_CPU_FREQ_160=y
# CONFIG_ESP32S3_DEFAULT_CPU_FREQ_240 is not set
CONFIG_ESP32S3_DEFAULT_CPU_FREQ_MHZ=160
# CONFIG_ESP32S3_DEFAULT_CPU_FREQ_160 is not set
CONFIG_ESP32S3_DEFAULT_CPU_FREQ_240=y
CONFIG_ESP32S3_DEFAULT_CPU_FREQ_MHZ=240
CONFIG_SYSTEM_EVENT_QUEUE_SIZE=32
CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE=2304
CONFIG_MAIN_TASK_STACK_SIZE=8192
@@ -2973,8 +2994,8 @@ CONFIG_ESP32_WIFI_TX_BA_WIN=6
CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y
CONFIG_ESP32_WIFI_RX_BA_WIN=6
CONFIG_ESP32_WIFI_NVS_ENABLED=y
CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_0=y
# CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_1 is not set
# CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_0 is not set
CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_1=y
CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN=752
CONFIG_ESP32_WIFI_MGMT_SBUF_NUM=32
CONFIG_ESP32_WIFI_IRAM_OPT=y
File diff suppressed because it is too large Load Diff
+70 -57
View File
@@ -596,38 +596,25 @@ CONFIG_PARTITION_TABLE_MD5=y
#
# Gateway App
#
CONFIG_GATEWAY_CHANNEL_COUNT=2
CONFIG_GATEWAY_CHANNEL_COUNT=1
#
# Gateway Channel 1
#
CONFIG_GATEWAY_CHANNEL1_GW_ID=3
# CONFIG_GATEWAY_CHANNEL1_PHY_DISABLED is not set
# CONFIG_GATEWAY_CHANNEL1_PHY_NATIVE is not set
CONFIG_GATEWAY_CHANNEL1_PHY_UART1=y
CONFIG_GATEWAY_CHANNEL1_PHY_NATIVE=y
# CONFIG_GATEWAY_CHANNEL1_PHY_UART1 is not set
# CONFIG_GATEWAY_CHANNEL1_PHY_UART2 is not set
CONFIG_GATEWAY_CHANNEL1_SERIAL_TX_PIN=1
CONFIG_GATEWAY_CHANNEL1_SERIAL_RX_PIN=2
CONFIG_GATEWAY_CHANNEL1_SERIAL_BAUDRATE=9600
CONFIG_GATEWAY_CHANNEL1_SERIAL_RX_BUFFER=512
CONFIG_GATEWAY_CHANNEL1_SERIAL_TX_BUFFER=512
CONFIG_GATEWAY_CHANNEL1_SERIAL_QUERY_TIMEOUT_MS=100
CONFIG_GATEWAY_CHANNEL1_NATIVE_BUS_ID=0
CONFIG_GATEWAY_CHANNEL1_NATIVE_TX_PIN=2
CONFIG_GATEWAY_CHANNEL1_NATIVE_RX_PIN=1
CONFIG_GATEWAY_CHANNEL1_NATIVE_BAUDRATE=1200
# end of Gateway Channel 1
#
# Gateway Channel 2
#
CONFIG_GATEWAY_CHANNEL2_GW_ID=4
# CONFIG_GATEWAY_CHANNEL2_PHY_DISABLED is not set
# CONFIG_GATEWAY_CHANNEL2_PHY_NATIVE is not set
# CONFIG_GATEWAY_CHANNEL2_PHY_UART1 is not set
CONFIG_GATEWAY_CHANNEL2_PHY_UART2=y
CONFIG_GATEWAY_CHANNEL2_SERIAL_TX_PIN=6
CONFIG_GATEWAY_CHANNEL2_SERIAL_RX_PIN=7
CONFIG_GATEWAY_CHANNEL2_SERIAL_BAUDRATE=9600
CONFIG_GATEWAY_CHANNEL2_SERIAL_RX_BUFFER=512
CONFIG_GATEWAY_CHANNEL2_SERIAL_TX_BUFFER=512
CONFIG_GATEWAY_CHANNEL2_SERIAL_QUERY_TIMEOUT_MS=100
# end of Gateway Channel 2
#
@@ -637,7 +624,7 @@ CONFIG_GATEWAY_CACHE_SUPPORTED=y
CONFIG_GATEWAY_CACHE_START_ENABLED=y
CONFIG_GATEWAY_CACHE_RECONCILIATION_ENABLED=y
# CONFIG_GATEWAY_CACHE_FULL_STATE_MIRROR is not set
CONFIG_GATEWAY_CACHE_FLUSH_INTERVAL_MS=5000
CONFIG_GATEWAY_CACHE_FLUSH_INTERVAL_MS=60000
CONFIG_GATEWAY_CACHE_OUTSIDE_BUS_FIRST=y
# CONFIG_GATEWAY_CACHE_LOCAL_GATEWAY_FIRST is not set
# end of Gateway Cache
@@ -707,7 +694,8 @@ CONFIG_GATEWAY_KNX_TP_UART_PORT=0
CONFIG_GATEWAY_KNX_TP_TX_PIN=-1
CONFIG_GATEWAY_KNX_TP_RX_PIN=-1
CONFIG_GATEWAY_KNX_TP_BAUDRATE=19200
CONFIG_GATEWAY_BRIDGE_KNX_TASK_STACK_SIZE=8192
CONFIG_GATEWAY_KNX_TP_UART_9BIT_MODE=y
CONFIG_GATEWAY_BRIDGE_KNX_TASK_STACK_SIZE=12288
CONFIG_GATEWAY_BRIDGE_KNX_TASK_PRIORITY=5
CONFIG_GATEWAY_CLOUD_BRIDGE_SUPPORTED=y
# CONFIG_GATEWAY_START_CLOUD_BRIDGE_ENABLED is not set
@@ -806,12 +794,12 @@ CONFIG_BT_CONTROLLER_ENABLED=y
#
# General
#
CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_INTERNAL=y
# CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_EXTERNAL is not set
# CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_INTERNAL is not set
CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_EXTERNAL=y
# CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_DEFAULT is not set
CONFIG_BT_NIMBLE_PINNED_TO_CORE=0
CONFIG_BT_NIMBLE_PINNED_TO_CORE_0=y
# CONFIG_BT_NIMBLE_PINNED_TO_CORE_1 is not set
CONFIG_BT_NIMBLE_PINNED_TO_CORE=1
# CONFIG_BT_NIMBLE_PINNED_TO_CORE_0 is not set
CONFIG_BT_NIMBLE_PINNED_TO_CORE_1=y
CONFIG_BT_NIMBLE_HOST_TASK_STACK_SIZE=4096
CONFIG_BT_NIMBLE_LEGACY_VHCI_ENABLE=y
# end of General
@@ -853,7 +841,7 @@ CONFIG_BT_NIMBLE_MAX_CONN_REATTEMPT=3
CONFIG_BT_NIMBLE_HS_PVCY=y
# CONFIG_BT_NIMBLE_HOST_ALLOW_CONNECT_WITH_SCAN is not set
# CONFIG_BT_NIMBLE_HOST_QUEUE_CONG_CHECK is not set
CONFIG_BT_NIMBLE_MAX_CONNECTIONS=3
CONFIG_BT_NIMBLE_MAX_CONNECTIONS=4
CONFIG_BT_NIMBLE_MAX_CCCDS=8
CONFIG_BT_NIMBLE_CRYPTO_STACK_MBEDTLS=y
CONFIG_BT_NIMBLE_HS_STOP_TIMEOUT_MS=2000
@@ -1016,10 +1004,10 @@ CONFIG_BT_NIMBLE_HCI_UART_CTS_PIN=23
# CONFIG_BT_NIMBLE_MEM_DEBUG is not set
# CONFIG_BT_NIMBLE_LOG_LEVEL_NONE is not set
# CONFIG_BT_NIMBLE_LOG_LEVEL_ERROR is not set
# CONFIG_BT_NIMBLE_LOG_LEVEL_WARNING is not set
CONFIG_BT_NIMBLE_LOG_LEVEL_INFO=y
CONFIG_BT_NIMBLE_LOG_LEVEL_WARNING=y
# CONFIG_BT_NIMBLE_LOG_LEVEL_INFO is not set
# CONFIG_BT_NIMBLE_LOG_LEVEL_DEBUG is not set
CONFIG_BT_NIMBLE_LOG_LEVEL=1
CONFIG_BT_NIMBLE_LOG_LEVEL=2
CONFIG_BT_NIMBLE_PRINT_ERR_NAME=y
# CONFIG_BT_NIMBLE_DEBUG is not set
# CONFIG_BT_NIMBLE_TEST_THROUGHPUT_TEST is not set
@@ -1048,9 +1036,9 @@ CONFIG_BT_CTRL_MODE_EFF=1
CONFIG_BT_CTRL_BLE_MAX_ACT=6
CONFIG_BT_CTRL_BLE_MAX_ACT_EFF=6
CONFIG_BT_CTRL_BLE_STATIC_ACL_TX_BUF_NB=0
CONFIG_BT_CTRL_PINNED_TO_CORE_0=y
# CONFIG_BT_CTRL_PINNED_TO_CORE_1 is not set
CONFIG_BT_CTRL_PINNED_TO_CORE=0
# CONFIG_BT_CTRL_PINNED_TO_CORE_0 is not set
CONFIG_BT_CTRL_PINNED_TO_CORE_1=y
CONFIG_BT_CTRL_PINNED_TO_CORE=1
CONFIG_BT_CTRL_HCI_MODE_VHCI=y
# CONFIG_BT_CTRL_HCI_MODE_UART_H4 is not set
CONFIG_BT_CTRL_HCI_TL=1
@@ -1145,8 +1133,8 @@ CONFIG_BT_CTRL_BLE_ADV=y
# Common Options
#
CONFIG_BT_ALARM_MAX_NUM=50
CONFIG_BT_SMP_CRYPTO_STACK_TINYCRYPT=y
# CONFIG_BT_SMP_CRYPTO_STACK_MBEDTLS is not set
# CONFIG_BT_SMP_CRYPTO_STACK_TINYCRYPT is not set
CONFIG_BT_SMP_CRYPTO_STACK_MBEDTLS=y
#
# BLE Log
@@ -1313,15 +1301,15 @@ CONFIG_ESP_ERR_TO_NAME_LOOKUP=y
#
# ESP-Driver:GPIO Configurations
#
# CONFIG_GPIO_CTRL_FUNC_IN_IRAM is not set
CONFIG_GPIO_CTRL_FUNC_IN_IRAM=y
# end of ESP-Driver:GPIO Configurations
#
# ESP-Driver:GPTimer Configurations
#
CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y
# CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is not set
# CONFIG_GPTIMER_ISR_CACHE_SAFE is not set
CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM=y
CONFIG_GPTIMER_ISR_CACHE_SAFE=y
CONFIG_GPTIMER_OBJ_CACHE_SAFE=y
# CONFIG_GPTIMER_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:GPTimer Configurations
@@ -1757,9 +1745,9 @@ CONFIG_ESP_ROM_PRINT_IN_IRAM=y
# ESP System Settings
#
# CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_80 is not set
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160=y
# CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240 is not set
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=160
# CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160 is not set
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240=y
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=240
#
# Cache config
@@ -1805,7 +1793,7 @@ CONFIG_ESP_SYSTEM_IN_IRAM=y
CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT=y
# CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT is not set
# CONFIG_ESP_SYSTEM_PANIC_GDBSTUB is not set
CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS=0
CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS=2
CONFIG_ESP_SYSTEM_RTC_FAST_MEM_AS_HEAP_DEPCHECK=y
CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP=y
@@ -1818,7 +1806,7 @@ CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_LOCK=y
CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE=32
CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=2304
CONFIG_ESP_MAIN_TASK_STACK_SIZE=3584
CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192
CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0=y
# CONFIG_ESP_MAIN_TASK_AFFINITY_CPU1 is not set
# CONFIG_ESP_MAIN_TASK_AFFINITY_NO_AFFINITY is not set
@@ -1885,9 +1873,9 @@ CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=32
CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER=y
CONFIG_ESP_WIFI_TX_BUFFER_TYPE=1
CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM=32
CONFIG_ESP_WIFI_STATIC_RX_MGMT_BUFFER=y
# CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUFFER is not set
CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUF=0
# CONFIG_ESP_WIFI_STATIC_RX_MGMT_BUFFER is not set
CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUFFER=y
CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUF=1
CONFIG_ESP_WIFI_RX_MGMT_BUF_NUM_DEF=5
# CONFIG_ESP_WIFI_CSI_ENABLED is not set
CONFIG_ESP_WIFI_AMPDU_TX_ENABLED=y
@@ -1895,8 +1883,8 @@ CONFIG_ESP_WIFI_TX_BA_WIN=6
CONFIG_ESP_WIFI_AMPDU_RX_ENABLED=y
CONFIG_ESP_WIFI_RX_BA_WIN=6
CONFIG_ESP_WIFI_NVS_ENABLED=y
CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_0=y
# CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_1 is not set
# CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_0 is not set
CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_1=y
CONFIG_ESP_WIFI_SOFTAP_BEACON_MAX_LEN=752
CONFIG_ESP_WIFI_MGMT_SBUF_NUM=32
CONFIG_ESP_WIFI_IRAM_OPT=y
@@ -2013,12 +2001,12 @@ CONFIG_FATFS_DONT_TRUST_LAST_ALLOC=0
#
# CONFIG_FREERTOS_SMP is not set
# CONFIG_FREERTOS_UNICORE is not set
CONFIG_FREERTOS_HZ=100
CONFIG_FREERTOS_HZ=1000
# CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE is not set
# CONFIG_FREERTOS_CHECK_STACKOVERFLOW_PTRVAL is not set
CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY=y
CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS=1
CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=1536
CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=2048
# CONFIG_FREERTOS_USE_IDLE_HOOK is not set
# CONFIG_FREERTOS_USE_TICK_HOOK is not set
CONFIG_FREERTOS_MAX_TASK_NAME_LEN=16
@@ -2783,13 +2771,36 @@ CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y
#
CONFIG_DALI_PHY_COUNT=16
CONFIG_DALI_DEFAULT_BAUDRATE=1200
CONFIG_DALI_API_QUEUE_LEN=10
CONFIG_DALI_TX_QUEUE_LEN=1
CONFIG_DALI_TIMER_RESOLUTION_HZ=3636363
CONFIG_DALI_CUSTOM_HALF_BIT_TIME_X100_US=0
CONFIG_DALI_TX_STOP_CONDITION_US=0
CONFIG_DALI_RX_STOP_CONDITION_US=0
CONFIG_DALI_QUERY_RESPONSE_TIMEOUT_MS=25
CONFIG_DALI_DOUBLE_SEND_DELAY_MS=15
CONFIG_DALI_FORWARD_ACTIVITY_WAIT_MS=15
CONFIG_DALI_FORWARD_AFTER_BACKWARD_WAIT_MS=5
CONFIG_DALI_FORWARD_MAX_WAIT_MS=50
CONFIG_DALI_BACKWARD_IDLE_TIMEOUT_MS=10
CONFIG_DALI_BUS_POWER_CHECK_INTERVAL_MS=500
CONFIG_DALI_BUS_ABNORMAL_REPORT_INTERVAL_MS=3000
# CONFIG_DALI_LOG_LEVEL_NONE is not set
# CONFIG_DALI_LOG_LEVEL_ERROR is not set
# CONFIG_DALI_LOG_LEVEL_WARN is not set
# CONFIG_DALI_LOG_LEVEL_INFO is not set
CONFIG_DALI_LOG_LEVEL_DEBUG=y
# CONFIG_DALI_LOG_LEVEL_VERBOSE is not set
CONFIG_DALI_LOG_LEVEL=4
CONFIG_DALI_TX_ACTIVE_LOW=y
# CONFIG_DALI_TX_ACTIVE_HIGH is not set
CONFIG_DALI_RX_ACTIVE_LOW=y
# CONFIG_DALI_RX_ACTIVE_HIGH is not set
CONFIG_DALI_API_QUEUE_LEN=64
CONFIG_DALI_TX_QUEUE_LEN=4
CONFIG_DALI_TX_REPLY_QUEUE_LEN=4
CONFIG_DALI_RX_QUEUE_LEN=50
CONFIG_DALI_DEBUG_QUEUE_LEN=100
# CONFIG_DALI_ENABLE_DEBUG_TASK is not set
CONFIG_DALI_DALI_TASK_STACK_SIZE=2048
CONFIG_DALI_ENABLE_DEBUG_TASK=y
CONFIG_DALI_DALI_TASK_STACK_SIZE=8192
CONFIG_DALI_DALI_TASK_PRIORITY=2
CONFIG_DALI_DEBUG_TASK_STACK_SIZE=2048
CONFIG_DALI_DEBUG_TASK_PRIORITY=1
@@ -2811,10 +2822,12 @@ CONFIG_MQTT_TRANSPORT_SSL=y
CONFIG_MQTT_TRANSPORT_WEBSOCKET=y
CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE=y
# CONFIG_MQTT_MSG_ID_INCREMENTAL is not set
# CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED is not set
CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED=y
# CONFIG_MQTT_REPORT_DELETED_MESSAGES is not set
# CONFIG_MQTT_USE_CUSTOM_CONFIG is not set
# CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED is not set
CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED=y
# CONFIG_MQTT_USE_CORE_0 is not set
CONFIG_MQTT_USE_CORE_1=y
# CONFIG_MQTT_CUSTOM_OUTBOX is not set
# end of ESP-MQTT Configurations
# end of Component config
+169 -1
View File
@@ -14,6 +14,174 @@ config DALI_DEFAULT_BAUDRATE
help
Default baudrate used during initialization.
config DALI_TIMER_RESOLUTION_HZ
int "Native DALI timer resolution Hz"
range 1000000 8000000
default 3000000
help
GPTimer resolution for native DALI Manchester timing. The default 3 MHz
allows a 1200 bps half-bit period of 416.67 us to be represented as
1250 timer ticks.
config DALI_CUSTOM_HALF_BIT_TIME_X100_US
int "Custom native DALI half-bit time x100 us"
range 0 500000
default 0
help
Development override for the native DALI half-bit period, expressed in
1/100 us. Set to 0 to derive the value from the configured baudrate.
Standard 1200 bps DALI is 41667, meaning 416.67 us.
config DALI_TX_STOP_CONDITION_US
int "Custom TX stop condition us"
range 0 10000
default 0
help
Development override for the native TX stop-condition wait. Set to 0 to
use the scaled standard timing.
config DALI_RX_STOP_CONDITION_US
int "Custom RX stop condition us"
range 0 10000
default 0
help
Development override for the native RX stop-condition wait. Set to 0 to
use the scaled standard timing.
config DALI_QUERY_RESPONSE_TIMEOUT_MS
int "DALI query response timeout ms"
range 10 100
default 25
help
Time to wait for a complete backward frame after a forward query has
finished transmitting. DALI backward frames start 5.5-10.5 ms after the
forward frame and last about 9.95 ms, so 25 ms leaves margin without the
legacy 50 ms no-response delay.
config DALI_DOUBLE_SEND_DELAY_MS
int "Double-send delay ms"
range 0 100
default 10
help
Delay between the two frames sent by dali_send_double(), measured after
the first frame has completed. Exposed for development tuning.
config DALI_FORWARD_ACTIVITY_WAIT_MS
int "Forward-frame wait after bus activity ms"
range 0 1000
default 25
help
Minimum delay before sending a 2- to 4-byte forward frame after normal
bus activity. This is the native queue anti-collision wait.
config DALI_FORWARD_AFTER_BACKWARD_WAIT_MS
int "Forward-frame wait after backward frame ms"
range 0 1000
default 5
help
Minimum delay before sending a 2- to 4-byte forward frame after the last
valid 1-byte backward frame received by the native bus.
config DALI_FORWARD_MAX_WAIT_MS
int "Forward-frame maximum queue wait ms"
range 0 5000
default 50
help
Maximum time the native queue waits for a forward-frame send window. If
no valid send window is reached before this timeout, the frame is
dropped with an error status.
config DALI_BACKWARD_IDLE_TIMEOUT_MS
int "Backward-frame idle wait timeout ms"
range 0 1000
default 9
help
Time a 1-byte backward frame waits for an idle bus before being sent
anyway. Backward frame sends are not echo-verified because collisions
during addressing responses are valid DALI behavior.
config DALI_BUS_POWER_CHECK_INTERVAL_MS
int "Bus power-down check interval ms"
range 10 5000
default 100
help
Interval used to resample the RX pin while the native DALI bus is marked
power-down. This lets the HAL recover when the bus was already powered
before gateway startup and no RX edge is generated.
config DALI_BUS_ABNORMAL_REPORT_INTERVAL_MS
int "Legacy bus abnormal report interval ms"
range 0 60000
default 1000
help
Interval for publishing the legacy two-byte FF FD bus-abnormal raw frame
while the native DALI bus is power-down. Set to 0 to disable the report.
choice DALI_LOG_LEVEL_CHOICE
prompt "DALI log level"
default DALI_LOG_LEVEL_WARN
help
Runtime log level applied to the native DALI HAL ESP-IDF log tag.
config DALI_LOG_LEVEL_NONE
bool "No output"
config DALI_LOG_LEVEL_ERROR
bool "Error"
config DALI_LOG_LEVEL_WARN
bool "Warning"
config DALI_LOG_LEVEL_INFO
bool "Info"
config DALI_LOG_LEVEL_DEBUG
bool "Debug"
config DALI_LOG_LEVEL_VERBOSE
bool "Verbose"
endchoice
config DALI_LOG_LEVEL
int
default 0 if DALI_LOG_LEVEL_NONE
default 1 if DALI_LOG_LEVEL_ERROR
default 2 if DALI_LOG_LEVEL_WARN
default 3 if DALI_LOG_LEVEL_INFO
default 4 if DALI_LOG_LEVEL_DEBUG
default 5 if DALI_LOG_LEVEL_VERBOSE
choice DALI_TX_ACTIVE_LEVEL
prompt "DALI TX pin active level"
default DALI_TX_ACTIVE_LOW
help
Select the physical GPIO level that drives the DALI bus active. The
native gateway default is TX active low.
config DALI_TX_ACTIVE_LOW
bool "Active low"
config DALI_TX_ACTIVE_HIGH
bool "Active high"
endchoice
choice DALI_RX_ACTIVE_LEVEL
prompt "DALI RX pin active level"
default DALI_RX_ACTIVE_HIGH
help
Select the physical GPIO level read when the DALI bus is active. The
native gateway default is RX active high.
config DALI_RX_ACTIVE_LOW
bool "Active low"
config DALI_RX_ACTIVE_HIGH
bool "Active high"
endchoice
config DALI_API_QUEUE_LEN
int "Global API queue length"
range 1 64
@@ -48,7 +216,7 @@ config DALI_ENABLE_DEBUG_TASK
config DALI_DALI_TASK_STACK_SIZE
int "DALI task stack size"
range 1024 8192
default 2048
default 4096
config DALI_DALI_TASK_PRIORITY
int "DALI task priority"
+24
View File
@@ -41,10 +41,34 @@ void app_main(void) {
Use `menuconfig` under `DALI Component` to configure:
- Bus count and default baudrate.
- Native timing values for development, including timer resolution, half-bit period,
TX/RX stop conditions, query response timeout, double-send delay, and TX queue
arbitration waits.
- TX/RX active polarity. The native gateway default is TX active low and RX active high.
- Native bus power-down polling and legacy `FF FD` bus-abnormal raw-frame reporting intervals.
- Native DALI HAL log level for the `dali_hal` ESP-IDF log tag.
- Queue sizes.
- Task stack sizes and priorities.
- Optional debug task.
The native bus monitor uses `CONFIG_DALI_BUS_POWER_CHECK_INTERVAL_MS` to resample RX while
power-down and `CONFIG_DALI_BUS_ABNORMAL_REPORT_INTERVAL_MS` to publish legacy `FF FD`
raw frames while down. The report interval defaults to 1000 ms; set it to 0 to disable the
compatibility report.
Native timing defaults target standard 1200 bps DALI: a 416.67 us half-bit period is
generated by the default 3 MHz timer as 1250 ticks. `CONFIG_DALI_CUSTOM_HALF_BIT_TIME_X100_US`
can override the half-bit period for development; keep it at 0 for baudrate-derived timing.
Query no-response timeout defaults to 25 ms, which covers the 5.5-10.5 ms backward-frame
start window plus the approximately 9.95 ms backward frame duration.
Native TX queue arbitration uses frame length as the frame type signal. Two- to four-byte
forward frames wait up to `CONFIG_DALI_FORWARD_MAX_WAIT_MS` for a valid send window,
using `CONFIG_DALI_FORWARD_ACTIVITY_WAIT_MS` after normal bus activity and
`CONFIG_DALI_FORWARD_AFTER_BACKWARD_WAIT_MS` after a valid backward frame. One-byte
backward frames wait up to `CONFIG_DALI_BACKWARD_IDLE_TIMEOUT_MS` for idle, then are
sent without echo verification because addressing-phase collisions are valid.
## API Note
The global TX response queue symbol was renamed:
+28 -7
View File
@@ -6,6 +6,14 @@
#include <memory.h> // for memset
#include "freertos/semphr.h"
#ifndef CONFIG_DALI_QUERY_RESPONSE_TIMEOUT_MS
#define CONFIG_DALI_QUERY_RESPONSE_TIMEOUT_MS 25
#endif
#ifndef CONFIG_DALI_DOUBLE_SEND_DELAY_MS
#define CONFIG_DALI_DOUBLE_SEND_DELAY_MS 10
#endif
static SemaphoreHandle_t s_dali_core_lock;
static SemaphoreHandle_t dali_core_mutex(void)
@@ -31,6 +39,20 @@ static inline void dali_core_unlock(void)
}
}
static UBaseType_t drain_rx_queue(QueueHandle_t rx_q)
{
if (rx_q == NULL) {
return 0;
}
Dali_msg_t stale = {0};
UBaseType_t drained = 0;
while (xQueueReceive(rx_q, &stale, 0) == pdTRUE) {
drained++;
}
return drained;
}
Dali_msg_t dali_msg_new_generic(uint8_t bit_length, uint8_t address, uint8_t cmd1, uint8_t cmd2, uint8_t cmd3) {
Dali_msg_t dali_msg;
dali_msg.id = 0;
@@ -90,7 +112,7 @@ void dali_send_double(Dali_msg_t *dali_msg) {
dali_send_locked(dali_msg);
// TODO check status
dali_msg->id++; // increment message ID
dali_delay_ms(10); // delay 13ms 101.8.1.2: 13.5 - 75ms
dali_delay_ms(CONFIG_DALI_DOUBLE_SEND_DELAY_MS);
dali_send_locked(dali_msg);
// TODO check status
dali_core_unlock();
@@ -110,17 +132,16 @@ int dali_query(Dali_msg_t *tx_msg, Dali_msg_t *rx_msg) {
return -1;
}
// TODO check empty queue
if(xQueueReceive(rx_q, rx_msg, 0) == pdTRUE) {
printf("Queue not empty\n");
return -1;
dali_core_lock();
UBaseType_t drained = drain_rx_queue(rx_q);
if (drained > 0) {
printf("dali_query: dropped %u stale RX frame(s)\n", (unsigned)drained);
}
// printf("check A tx=%d tm=%d[ms] st=%d len=%d d0=0x%X\n", ret, tx_msg->type, tx_msg->status, tx_msg->length, tx_msg->data[0]);
dali_core_lock();
dali_send_locked(tx_msg);
// receive message from DALI task
ret = xQueueReceive(rx_q, rx_msg, pdMS_TO_TICKS(50));
ret = xQueueReceive(rx_q, rx_msg, pdMS_TO_TICKS(CONFIG_DALI_QUERY_RESPONSE_TIMEOUT_MS));
dali_core_unlock();
// printf("B rx=%d tm=%d[ms] st=%d len=%d d0=0x%X\n", ret, rx_msg->type, rx_msg->status, rx_msg->length, rx_msg->data[0]);
return ret;
+621 -52
View File
@@ -4,6 +4,15 @@
//ESP-IDF HAL
#ifdef CONFIG_IDF_TARGET
#include "sdkconfig.h"
#ifndef CONFIG_DALI_LOG_LEVEL
#define CONFIG_DALI_LOG_LEVEL 2
#endif
#ifndef LOG_LOCAL_LEVEL
#define LOG_LOCAL_LEVEL CONFIG_DALI_LOG_LEVEL
#endif
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
@@ -39,7 +48,7 @@
#endif
#ifndef CONFIG_DALI_DALI_TASK_STACK_SIZE
#define CONFIG_DALI_DALI_TASK_STACK_SIZE 2048
#define CONFIG_DALI_DALI_TASK_STACK_SIZE 4096
#endif
#ifndef CONFIG_DALI_DALI_TASK_PRIORITY
@@ -54,14 +63,57 @@
#define CONFIG_DALI_DEBUG_TASK_PRIORITY 1
#endif
#ifndef CONFIG_DALI_TIMER_RESOLUTION_HZ
#define CONFIG_DALI_TIMER_RESOLUTION_HZ 3000000
#endif
#ifndef CONFIG_DALI_CUSTOM_HALF_BIT_TIME_X100_US
#define CONFIG_DALI_CUSTOM_HALF_BIT_TIME_X100_US 0
#endif
#ifndef CONFIG_DALI_TX_STOP_CONDITION_US
#define CONFIG_DALI_TX_STOP_CONDITION_US 0
#endif
#ifndef CONFIG_DALI_RX_STOP_CONDITION_US
#define CONFIG_DALI_RX_STOP_CONDITION_US 0
#endif
#ifndef CONFIG_DALI_BUS_POWER_CHECK_INTERVAL_MS
#define CONFIG_DALI_BUS_POWER_CHECK_INTERVAL_MS 100
#endif
#ifndef CONFIG_DALI_BUS_ABNORMAL_REPORT_INTERVAL_MS
#define CONFIG_DALI_BUS_ABNORMAL_REPORT_INTERVAL_MS 1000
#endif
#ifndef CONFIG_DALI_FORWARD_ACTIVITY_WAIT_MS
#define CONFIG_DALI_FORWARD_ACTIVITY_WAIT_MS 25
#endif
#ifndef CONFIG_DALI_FORWARD_AFTER_BACKWARD_WAIT_MS
#define CONFIG_DALI_FORWARD_AFTER_BACKWARD_WAIT_MS 5
#endif
#ifndef CONFIG_DALI_FORWARD_MAX_WAIT_MS
#define CONFIG_DALI_FORWARD_MAX_WAIT_MS 50
#endif
#ifndef CONFIG_DALI_BACKWARD_IDLE_TIMEOUT_MS
#define CONFIG_DALI_BACKWARD_IDLE_TIMEOUT_MS 9
#endif
#define WITHIN_RANGE(x, min, max) ((x) > (min) && (x) < (max))
#define MAX_DELTA_RELOAD_TIME 600000000 // 600s - max u32: 4,294,967,295~4,294s
#define DALI_BAUDRATE_MIN 400U
#define DALI_BAUDRATE_MAX 2400U
#define DALI_BUS_POWER_CHECK_INTERVAL_US ((uint64_t)CONFIG_DALI_BUS_POWER_CHECK_INTERVAL_MS * 1000ULL)
#define DALI_BUS_ABNORMAL_REPORT_INTERVAL_US ((uint64_t)CONFIG_DALI_BUS_ABNORMAL_REPORT_INTERVAL_MS * 1000ULL)
typedef struct {
uint32_t hb;
uint32_t timer_alarm_ticks;
uint32_t rx_hb_min;
uint32_t rx_hb_max;
uint32_t rx_2hb_min;
@@ -76,6 +128,11 @@ typedef struct {
static const char *TAG = "dali_hal";
static inline void apply_dali_log_level(void)
{
esp_log_level_set(TAG, (esp_log_level_t)CONFIG_DALI_LOG_LEVEL);
}
typedef struct {
uint8_t bus_id;
uint8_t tx_pin;
@@ -91,8 +148,17 @@ typedef struct {
uint32_t rx_tx_delta;
uint32_t rx_pulse_width;
uint8_t rx_level;
uint8_t tx_level;
uint64_t bus_level_check_time;
uint64_t bus_abnormal_report_time;
Dali_msg_t tx_data;
bool bus_activity_seen;
uint64_t rx_last_frame_time;
uint8_t rx_last_frame_length;
uint8_t rx_last_frame_status;
volatile bool force_backward_tx;
Dali_msg_t rx_data;
uint8_t tx_half_bit_counter;
@@ -137,17 +203,31 @@ static inline void dali_hal_unlock(void)
}
}
static uint32_t dali_half_bit_from_baud(uint32_t baudrate)
static uint32_t dali_half_bit_x100_from_baud(uint32_t baudrate)
{
if (baudrate < DALI_BAUDRATE_MIN || baudrate > DALI_BAUDRATE_MAX) {
return 0;
}
uint64_t hb = 500000ULL + (baudrate / 2U); // round to nearest
hb /= baudrate;
if (hb == 0 || hb > 2000000ULL) { // should never happen with checked bounds
uint64_t hb_x100 = 50000000ULL + (baudrate / 2U); // round to nearest 0.01 us
hb_x100 /= baudrate;
if (hb_x100 == 0 || hb_x100 > 200000000ULL) { // should never happen with checked bounds
return 0;
}
return (uint32_t)hb;
return (uint32_t)hb_x100;
}
static uint32_t half_bit_us_from_x100(uint32_t hb_x100)
{
return (hb_x100 + 50U) / 100U;
}
static uint32_t timer_alarm_ticks_from_x100(uint32_t hb_x100)
{
uint64_t ticks = ((uint64_t)CONFIG_DALI_TIMER_RESOLUTION_HZ * hb_x100 + 50000000ULL) / 100000000ULL;
if (ticks == 0 || ticks > UINT32_MAX) {
return 0;
}
return (uint32_t)ticks;
}
static inline uint32_t scale_time_by_hb(uint32_t base_us, uint32_t hb_us)
@@ -155,25 +235,40 @@ static inline uint32_t scale_time_by_hb(uint32_t base_us, uint32_t hb_us)
return (uint32_t)(((uint64_t)base_us * hb_us + (DALI_TIME_HB / 2U)) / DALI_TIME_HB);
}
static inline uint32_t configured_or_scaled_time(uint32_t configured_us, uint32_t base_us,
uint32_t hb_us)
{
return configured_us > 0 ? configured_us : scale_time_by_hb(base_us, hb_us);
}
static esp_err_t update_timing_locked(uint32_t baudrate)
{
uint32_t hb = dali_half_bit_from_baud(baudrate);
if (hb == 0) {
ESP_LOGE(TAG, "invalid baudrate: %u", baudrate);
uint32_t hb_x100 = CONFIG_DALI_CUSTOM_HALF_BIT_TIME_X100_US;
if (hb_x100 == 0) {
hb_x100 = dali_half_bit_x100_from_baud(baudrate);
}
uint32_t hb = half_bit_us_from_x100(hb_x100);
uint32_t timer_alarm_ticks = timer_alarm_ticks_from_x100(hb_x100);
if (hb == 0 || timer_alarm_ticks == 0) {
ESP_LOGE(TAG, "invalid native timing: baudrate=%u hbX100Us=%u timerHz=%u",
baudrate, hb_x100, CONFIG_DALI_TIMER_RESOLUTION_HZ);
return ESP_ERR_INVALID_ARG;
}
dali_timing_t new_timing = {
.hb = hb,
.timer_alarm_ticks = timer_alarm_ticks,
.rx_hb_min = scale_time_by_hb(DALI_RX_HB_MIN, hb),
.rx_hb_max = scale_time_by_hb(DALI_RX_HB_MAX, hb),
.rx_2hb_min = scale_time_by_hb(DALI_RX_2HB_MIN, hb),
.rx_2hb_max = scale_time_by_hb(DALI_RX_2HB_MAX, hb),
.rx_stop_cond = scale_time_by_hb(DALI_RX_STOP_COND, hb),
.rx_stop_cond = configured_or_scaled_time(CONFIG_DALI_RX_STOP_CONDITION_US,
DALI_RX_STOP_COND, hb),
.time_bus_down = scale_time_by_hb(DALI_TIME_BUS_DOWN, hb),
.time_break_min = scale_time_by_hb(DALI_TIME_BREAK_MIN, hb),
.time_recovery_min = scale_time_by_hb(DALI_TIME_RECOVERY_MIN, hb),
.tx_stop_cond = scale_time_by_hb(DALI_TX_STOP_COND, hb),
.tx_stop_cond = configured_or_scaled_time(CONFIG_DALI_TX_STOP_CONDITION_US,
DALI_TX_STOP_COND, hb),
.collision_txrx_delta = scale_time_by_hb(DALI_COLLISION_TXRX_DELTA, hb),
};
@@ -199,7 +294,7 @@ static esp_err_t apply_timer_alarm_locked(void)
return ESP_OK;
}
gptimer_alarm_config_t timer_alarm_config = {
.alarm_count = s_timing.hb,
.alarm_count = s_timing.timer_alarm_ticks,
.reload_count = 0,
.flags = {
.auto_reload_on_alarm = true,
@@ -235,22 +330,330 @@ static bool s_debug_task_created = false;
#endif
static bool s_dali_task_created = false;
#define DALI_SET_BUS_HIGH(bus) gpio_set_level((bus)->tx_pin, DALI_TX_HIGH) // set bus level
#define DALI_SET_BUS_LOW(bus) gpio_set_level((bus)->tx_pin, DALI_TX_LOW) // set bus level
#define DALI_SET_BUS_LEVEL(bus, x) gpio_set_level((bus)->tx_pin, ((x)==DALI_TX_HIGH)) // set bus level
#define DALI_SET_BUS_HIGH(bus) do { gpio_set_level((bus)->tx_pin, DALI_TX_HIGH); (bus)->tx_level = 1; } while (0)
#define DALI_SET_BUS_LOW(bus) do { gpio_set_level((bus)->tx_pin, DALI_TX_LOW); (bus)->tx_level = 0; } while (0)
#define DALI_SET_BUS_LEVEL(bus, x) do { \
uint8_t level = (x) ? 1 : 0; \
gpio_set_level((bus)->tx_pin, level ? DALI_TX_HIGH : DALI_TX_LOW); \
(bus)->tx_level = level; \
} while (0)
// !!! read from RX pin, we need real bus level, not logic level of TX pin
// return: 0 - bus level low, active state
// 1 - bus level high, idle state
#define DALI_GET_BUS_LEVEL(bus) (gpio_get_level((bus)->rx_pin) == (DALI_RX_HIGH)) // get bus level
// return: 0 - tx pin drive bus low, active state
// 1 - tx pin drive bus high, idle state
#define DALI_GET_TX_LEVEL(bus) (gpio_get_level((bus)->tx_pin) == (DALI_TX_HIGH)) // get TX pin level
// return: 0 - TX drives bus low, active state
// 1 - TX releases/drives bus high, idle state
#define DALI_GET_TX_LEVEL(bus) ((bus)->tx_level)
static inline bool bus_valid(uint8_t bus_id) {
return bus_id < DALI_PHY_COUNT && s_bus[bus_id].inited;
}
static const char *bus_state_name(dali_bus_state_t state)
{
switch (state) {
case DALI_BUS_UNKNOWN: return "unknown";
case DALI_BUS_POWER_DOWN: return "power_down";
case DALI_BUS_ERROR: return "error";
case DALI_BUS_READY: return "ready";
case DALI_BUS_TRANSMITTING: return "transmitting";
case DALI_BUS_RECEIVING: return "receiving";
case DALI_BUS_TIME_BREAK: return "time_break";
case DALI_BUS_RECOVERY: return "recovery";
default: return "invalid";
}
}
static const char *tx_state_name(dali_tx_state_t state)
{
switch (state) {
case TX_STATE_ERROR: return "error";
case TX_STATE_COLLISION: return "collision";
case TX_STATE_IDLE: return "idle";
case TX_STATE_START: return "start";
case TX_STATE_DATA: return "data";
case TX_STATE_STOP: return "stop";
default: return "invalid";
}
}
static const char *rx_state_name(dali_rx_state_t state)
{
switch (state) {
case RX_STATE_ERROR: return "error";
case RX_STATE_IDLE: return "idle";
case RX_STATE_START: return "start";
case RX_STATE_DATA: return "data";
case RX_STATE_STOP: return "stop";
case RX_STATE_END: return "end";
default: return "invalid";
}
}
static uint32_t tx_completion_timeout_ms(const Dali_msg_t *msg)
{
uint32_t hb = s_timing_ready ? s_timing.hb : DALI_TIME_HB;
uint32_t stop_us = s_timing_ready ? s_timing.tx_stop_cond : DALI_TX_STOP_COND;
uint32_t bits = msg ? msg->length : DALI_MAX_BITS;
if (bits == 0 || bits > DALI_MAX_BITS) {
bits = DALI_MAX_BITS;
}
uint64_t frame_us = ((uint64_t)(2U + bits * 2U) * hb) + stop_us;
uint32_t frame_ms = (uint32_t)((frame_us + 999U) / 1000U);
uint32_t timeout_ms = frame_ms + 20U;
if (timeout_ms < 20U) {
timeout_ms = 20U;
}
if (timeout_ms > 500U) {
timeout_ms = 500U;
}
return timeout_ms;
}
static inline bool IRAM_ATTR is_backward_tx_msg(const Dali_msg_t *msg)
{
return msg != NULL && msg->length == 8;
}
static bool is_forward_tx_msg(const Dali_msg_t *msg)
{
return msg != NULL && msg->length >= 16 && msg->length <= 32 && (msg->length % 8) == 0;
}
static UBaseType_t queue_waiting(QueueHandle_t queue);
static uint64_t bus_last_activity_time_us(const dali_bus_ctx_t *bus)
{
if (bus == NULL || !bus->bus_activity_seen) {
return 0;
}
return bus->rx_last_edge_time > bus->tx_last_edge_time ? bus->rx_last_edge_time
: bus->tx_last_edge_time;
}
static bool bus_idle_for_tx(const dali_bus_ctx_t *bus)
{
return bus != NULL && bus->bus_state == DALI_BUS_READY && bus->tx_state == TX_STATE_IDLE &&
bus->rx_state == RX_STATE_IDLE && bus->rx_level == 1 && queue_waiting(bus->tx_queue) == 0;
}
static bool last_activity_was_backward_frame(const dali_bus_ctx_t *bus, uint64_t last_activity)
{
return bus != NULL && bus->rx_last_frame_status == DALI_FRAME_OK &&
bus->rx_last_frame_length == 8 && bus->rx_last_frame_time != 0 &&
bus->rx_last_frame_time >= last_activity;
}
static TickType_t tx_wait_poll_ticks(void)
{
TickType_t ticks = pdMS_TO_TICKS(1);
return ticks == 0 ? 1 : ticks;
}
static bool wait_for_forward_tx_window(dali_bus_ctx_t *bus, const Dali_msg_t *msg)
{
if (bus == NULL || !is_forward_tx_msg(msg)) {
return true;
}
const uint64_t started = esp_timer_get_time();
const uint64_t max_wait_us = (uint64_t)CONFIG_DALI_FORWARD_MAX_WAIT_MS * 1000ULL;
const TickType_t poll_ticks = tx_wait_poll_ticks();
while (true) {
if (bus->bus_state == DALI_BUS_POWER_DOWN) {
return false;
}
const uint64_t now = esp_timer_get_time();
if (bus_idle_for_tx(bus)) {
const uint64_t last_activity = bus_last_activity_time_us(bus);
if (last_activity == 0) {
return true;
}
const uint32_t wait_ms = last_activity_was_backward_frame(bus, last_activity)
? CONFIG_DALI_FORWARD_AFTER_BACKWARD_WAIT_MS
: CONFIG_DALI_FORWARD_ACTIVITY_WAIT_MS;
if (wait_ms == 0 || (now - last_activity) >= ((uint64_t)wait_ms * 1000ULL)) {
return true;
}
}
if (max_wait_us == 0 || (now - started) >= max_wait_us) {
return false;
}
vTaskDelay(poll_ticks);
}
}
static bool wait_for_backward_tx_window(dali_bus_ctx_t *bus, const Dali_msg_t *msg,
bool *force_start)
{
if (force_start != NULL) {
*force_start = false;
}
if (bus == NULL || !is_backward_tx_msg(msg)) {
return true;
}
const uint64_t started = esp_timer_get_time();
const uint64_t timeout_us = (uint64_t)CONFIG_DALI_BACKWARD_IDLE_TIMEOUT_MS * 1000ULL;
const TickType_t poll_ticks = tx_wait_poll_ticks();
while (true) {
if (bus->bus_state == DALI_BUS_POWER_DOWN) {
return false;
}
if (bus_idle_for_tx(bus)) {
return true;
}
const uint64_t now = esp_timer_get_time();
if (timeout_us == 0 || (now - started) >= timeout_us) {
if (force_start != NULL) {
*force_start = true;
}
return true;
}
vTaskDelay(poll_ticks);
}
}
static UBaseType_t queue_waiting(QueueHandle_t queue)
{
return queue ? uxQueueMessagesWaiting(queue) : 0;
}
static void log_tx_message(const char *prefix, const dali_bus_ctx_t *bus,
const Dali_msg_t *msg, uint32_t timeout_ms)
{
if (bus == NULL || msg == NULL) {
return;
}
ESP_LOGW(TAG,
"%s bus=%u timeoutMs=%lu busState=%s txState=%s rxState=%s "
"txQ=%u replyQ=%u status=%u len=%u data=%02x %02x %02x %02x",
prefix, bus->bus_id, (unsigned long)timeout_ms,
bus_state_name(bus->bus_state), tx_state_name(bus->tx_state),
rx_state_name(bus->rx_state), (unsigned)queue_waiting(bus->tx_queue),
(unsigned)queue_waiting(bus->tx_reply_queue), msg->status, msg->length,
msg->data[0], msg->data[1], msg->data[2], msg->data[3]);
}
static void drain_tx_reply_queue(dali_bus_ctx_t *bus)
{
if (bus == NULL || bus->tx_reply_queue == NULL) {
return;
}
Dali_msg_t stale = {0};
UBaseType_t drained = 0;
while (xQueueReceive(bus->tx_reply_queue, &stale, 0) == pdTRUE) {
drained++;
}
if (drained > 0) {
ESP_LOGW(TAG,
"bus=%u dropped %u stale TX completion(s) status=%u len=%u data=%02x %02x %02x %02x",
bus->bus_id, (unsigned)drained, stale.status, stale.length, stale.data[0],
stale.data[1], stale.data[2], stale.data[3]);
}
}
static void recover_tx_timeout(dali_bus_ctx_t *bus)
{
if (bus == NULL) {
return;
}
if (bus->tx_queue) {
xQueueReset(bus->tx_queue);
}
if (bus->tx_reply_queue) {
xQueueReset(bus->tx_reply_queue);
}
bus->tx_data.status = DALI_FRAME_ERROR;
bus->tx_state = TX_STATE_IDLE;
bus->rx_state = RX_STATE_IDLE;
bus->tx_half_bit_counter = 0;
bus->tx_data_bit_counter = 0;
bus->rx_half_bit_counter = 0;
bus->rx_data_bit_counter = 0;
if (bus->bus_state == DALI_BUS_TRANSMITTING || bus->bus_state == DALI_BUS_TIME_BREAK ||
bus->bus_state == DALI_BUS_RECOVERY) {
bus->tx_last_edge_time = esp_timer_get_time();
DALI_SET_BUS_HIGH(bus);
bus->bus_state = DALI_BUS_READY;
}
ESP_LOGW(TAG, "bus=%u native TX queue recovered busState=%s txState=%s rxState=%s",
bus->bus_id, bus_state_name(bus->bus_state), tx_state_name(bus->tx_state),
rx_state_name(bus->rx_state));
}
static inline bool IRAM_ATTR interval_elapsed_us(uint64_t time_now, uint64_t last_time,
uint64_t interval_us)
{
return interval_us > 0 && (time_now - last_time) >= interval_us;
}
static void IRAM_ATTR publish_bus_abnormal_from_isr(dali_bus_ctx_t *bus, BaseType_t *yield)
{
if (bus == NULL || dali_raw_receive_queue == NULL || DALI_BUS_ABNORMAL_REPORT_INTERVAL_US == 0) {
return;
}
Dali_msg_t abnormal = {0};
abnormal.id = bus->bus_id;
abnormal.type = DALI_MSG_FORWARD;
abnormal.status = DALI_FRAME_OK;
abnormal.length = 16;
abnormal.data[0] = 0xFF;
abnormal.data[1] = 0xFD;
if (xQueueSendToBackFromISR(dali_raw_receive_queue, &abnormal, yield) != pdTRUE) {
Dali_msg_t dropped = {0};
xQueueReceiveFromISR(dali_raw_receive_queue, &dropped, yield);
xQueueSendToBackFromISR(dali_raw_receive_queue, &abnormal, yield);
}
}
static void IRAM_ATTR maybe_report_bus_abnormal_from_isr(dali_bus_ctx_t *bus, uint64_t time_now,
BaseType_t *yield)
{
if (bus == NULL || DALI_BUS_ABNORMAL_REPORT_INTERVAL_US == 0) {
return;
}
if (!interval_elapsed_us(time_now, bus->bus_abnormal_report_time,
DALI_BUS_ABNORMAL_REPORT_INTERVAL_US)) {
return;
}
publish_bus_abnormal_from_isr(bus, yield);
bus->bus_abnormal_report_time = time_now;
}
static void IRAM_ATTR poll_power_down_bus_from_isr(dali_bus_ctx_t *bus, uint64_t time_now,
BaseType_t *yield)
{
if (bus == NULL || bus->bus_state != DALI_BUS_POWER_DOWN) {
return;
}
if (interval_elapsed_us(time_now, bus->bus_level_check_time,
DALI_BUS_POWER_CHECK_INTERVAL_US)) {
const uint8_t current_level = DALI_GET_BUS_LEVEL(bus);
bus->bus_level_check_time = time_now;
if (current_level != bus->rx_level) {
bus->rx_level = current_level;
bus->rx_last_edge_time = time_now;
}
}
maybe_report_bus_abnormal_from_isr(bus, time_now, yield);
}
static inline void publish_rx_frame_from_isr(Dali_msg_t *msg, QueueHandle_t queue, BaseType_t *yield)
{
if (msg == NULL) {
@@ -264,6 +667,48 @@ static inline void publish_rx_frame_from_isr(Dali_msg_t *msg, QueueHandle_t queu
}
}
static inline void IRAM_ATTR note_rx_frame_from_isr(dali_bus_ctx_t *bus)
{
if (bus == NULL) {
return;
}
bus->rx_last_frame_time = bus->rx_last_edge_time;
bus->rx_last_frame_length = bus->rx_data.length;
bus->rx_last_frame_status = bus->rx_data.status;
}
static void IRAM_ATTR complete_tx_from_isr(dali_bus_ctx_t *bus, BaseType_t *yield)
{
if (bus == NULL) {
return;
}
bus->tx_data.status = DALI_FRAME_OK;
if (!is_backward_tx_msg(&bus->tx_data) && bus->tx_reply_queue) {
if (xQueueSendToBackFromISR(bus->tx_reply_queue, &bus->tx_data, yield) != pdTRUE) {
Dali_msg_t dropped = {0};
xQueueReceiveFromISR(bus->tx_reply_queue, &dropped, yield);
xQueueSendToBackFromISR(bus->tx_reply_queue, &bus->tx_data, yield);
}
}
bus->tx_state = TX_STATE_IDLE;
}
static void IRAM_ATTR start_tx_collision_recovery_from_isr(dali_bus_ctx_t *bus,
uint64_t time_now)
{
if (bus == NULL) {
return;
}
bus->rx_last_edge_time = time_now;
bus->tx_last_edge_time = time_now;
DALI_SET_BUS_LOW(bus);
bus->bus_state = DALI_BUS_TIME_BREAK;
bus->tx_data.status = DALI_FRAME_COLLISION;
}
// GPIO ISR handler
// define rx_gpio_isr_handler on any edge
static void IRAM_ATTR rx_gpio_isr_handler(void* arg)
@@ -273,6 +718,7 @@ static void IRAM_ATTR rx_gpio_isr_handler(void* arg)
return;
}
BaseType_t yield = false;
uint64_t rx_current_edge_time = esp_timer_get_time(); // get time in us
uint8_t rx_previous_level = bus->rx_level;
@@ -280,6 +726,7 @@ static void IRAM_ATTR rx_gpio_isr_handler(void* arg)
// rx_level = 1 if and only if DALI bus is really high, idle
bus->rx_level = DALI_GET_BUS_LEVEL(bus); // get level of RX pin - not depend on hw: 0 - low, 1 - high
bus->bus_activity_seen = true;
bus->rx_pulse_width = rx_current_edge_time - bus->rx_last_edge_time; // time from last edge
bus->rx_tx_delta = rx_current_edge_time - bus->tx_last_edge_time; // time from last edge
@@ -287,8 +734,16 @@ static void IRAM_ATTR rx_gpio_isr_handler(void* arg)
// always save time of last edge
bus->rx_last_edge_time = rx_current_edge_time; // get time in us
if(bus->bus_state == DALI_BUS_READY && bus->rx_level == 0) // found start bit
bool tx_stop_released = bus->bus_state == DALI_BUS_TRANSMITTING &&
bus->tx_state == TX_STATE_STOP &&
DALI_GET_TX_LEVEL(bus) == 1;
if((bus->bus_state == DALI_BUS_READY || tx_stop_released) && bus->rx_level == 0) // found start bit
{
if (tx_stop_released) {
complete_tx_from_isr(bus, &yield);
}
// within range for backward frame
uint32_t time_ms = bus->rx_pulse_width / 1000; // 1ms = 1000us
if(time_ms>255) bus->rx_data.type = 255;
@@ -378,12 +833,14 @@ static void IRAM_ATTR rx_gpio_isr_handler(void* arg)
// if collision detected: we are too late after bit was transmitted
else if (bus->bus_state == DALI_BUS_TRANSMITTING && bus->rx_tx_delta > s_timing.collision_txrx_delta)
else if (bus->bus_state == DALI_BUS_TRANSMITTING && bus->tx_state != TX_STATE_STOP &&
!is_backward_tx_msg(&bus->tx_data) &&
bus->rx_tx_delta > s_timing.collision_txrx_delta)
{
// we need now to start collision recovery with time break: 101.9.2.4
bus->tx_last_edge_time = esp_timer_get_time(); // get time in us
DALI_SET_BUS_LOW(bus); // force TX low - active state, inform about collision, this also generate new GPIO ISR
bus->tx_last_edge_time = esp_timer_get_time(); // get time in us
bus->bus_state = DALI_BUS_TIME_BREAK; // we are in time break state
bus->tx_data.status = DALI_FRAME_COLLISION; // collision detected
}
@@ -399,7 +856,11 @@ static void IRAM_ATTR rx_gpio_isr_handler(void* arg)
dbg.rx_pulse_width = bus->rx_pulse_width;
dbg.rx_tx_delta = bus->rx_tx_delta;
dbg.bus_id = bus->bus_id;
xQueueSendToBackFromISR(rx_dbg_queue, &dbg, NULL); // send data to queue
xQueueSendToBackFromISR(rx_dbg_queue, &dbg, &yield); // send data to queue
}
if (yield) {
portYIELD_FROM_ISR();
}
}
@@ -423,6 +884,18 @@ static bool IRAM_ATTR handle_bus_timer(dali_bus_ctx_t *bus, uint64_t time_now)
bus->tx_last_edge_time = time_now - MAX_DELTA_RELOAD_TIME/2; // half of max time
}
poll_power_down_bus_from_isr(bus, time_now, &yield);
rx_delta = time_now - bus->rx_last_edge_time;
tx_delta = time_now - bus->tx_last_edge_time;
if (bus->bus_state == DALI_BUS_TRANSMITTING && bus->tx_state == TX_STATE_STOP &&
DALI_GET_TX_LEVEL(bus) == 1 &&
(bus->rx_state == RX_STATE_START || bus->rx_state == RX_STATE_DATA ||
bus->rx_state == RX_STATE_STOP)) {
complete_tx_from_isr(bus, &yield);
bus->bus_state = DALI_BUS_RECEIVING;
}
// recovery from different error states: UNKNOWN, ERROR, POWER_DOWN
if(bus->bus_state <= DALI_BUS_ERROR)
{ // 101.8.2.4 - startup BUS after 2.4ms
@@ -434,8 +907,13 @@ static bool IRAM_ATTR handle_bus_timer(dali_bus_ctx_t *bus, uint64_t time_now)
// if bus power down - if bus is low for more then 45ms
if(bus->rx_level==0 && rx_delta > s_timing.time_bus_down)
{ // power lost
bool entered_power_down = bus->bus_state != DALI_BUS_POWER_DOWN;
bus->bus_state = DALI_BUS_POWER_DOWN; // bus is power down - recovery see previous if
DALI_SET_BUS_HIGH(bus); // make sure TX is high
if (entered_power_down) {
bus->bus_level_check_time = time_now;
bus->bus_abnormal_report_time = time_now;
}
}
// recovery from collision detection
@@ -444,9 +922,9 @@ static bool IRAM_ATTR handle_bus_timer(dali_bus_ctx_t *bus, uint64_t time_now)
// BUS: ACTIVE, LOW - BUS is busy, let caller to restart transmission
if(bus->bus_state == DALI_BUS_TIME_BREAK && rx_delta > s_timing.time_break_min)
{
bus->tx_last_edge_time = esp_timer_get_time(); // get time in us
DALI_SET_BUS_HIGH(bus); // TX high - idle state - generate ISR on RX pin
bus->tx_last_edge_time = esp_timer_get_time(); // get time in us
// read bus state
if(DALI_GET_BUS_LEVEL(bus) == 0) // other device is keeping bus low
{
@@ -467,33 +945,58 @@ static bool IRAM_ATTR handle_bus_timer(dali_bus_ctx_t *bus, uint64_t time_now)
}
// start transmitting
else if(bus->bus_state == DALI_BUS_READY && bus->tx_state == TX_STATE_IDLE && bus->tx_queue && xQueueReceiveFromISR(bus->tx_queue, &bus->tx_data, NULL) == pdTRUE)
else if(bus->tx_state == TX_STATE_IDLE && bus->tx_queue)
{
bus->tx_data.status = DALI_FRAME_ERROR; // error status - will be set ok on success
bus->bus_state = DALI_BUS_TRANSMITTING; // bus is transmitting
bus->tx_state = TX_STATE_START; // start transmitting
bus->tx_half_bit_counter = 0;
bus->tx_data_bit_counter = 0; // actually sent bits count
DALI_SET_BUS_LOW(bus); // start bit first half
bus->tx_last_edge_time = esp_timer_get_time(); // get time in us
Dali_msg_t pending = {0};
bool can_start = bus->bus_state == DALI_BUS_READY;
bool force_backward = false;
if (!can_start && bus->force_backward_tx &&
xQueuePeekFromISR(bus->tx_queue, &pending) == pdTRUE) {
if (is_backward_tx_msg(&pending) && bus->bus_state != DALI_BUS_POWER_DOWN) {
can_start = true;
force_backward = true;
} else {
bus->force_backward_tx = false;
}
}
if (can_start && xQueueReceiveFromISR(bus->tx_queue, &bus->tx_data, &yield) == pdTRUE) {
bus->force_backward_tx = false;
if (force_backward) {
bus->rx_state = RX_STATE_IDLE;
}
bus->tx_data.status = DALI_FRAME_ERROR; // error status - will be set ok on success
bus->bus_activity_seen = true;
bus->bus_state = DALI_BUS_TRANSMITTING; // bus is transmitting
bus->tx_state = TX_STATE_START; // start transmitting
bus->tx_half_bit_counter = 0;
bus->tx_data_bit_counter = 0; // actually sent bits count
bus->tx_last_edge_time = esp_timer_get_time(); // get time in us
DALI_SET_BUS_LOW(bus); // start bit first half
}
}
else if(bus->bus_state == DALI_BUS_TRANSMITTING)
{
uint8_t bus_level = DALI_GET_BUS_LEVEL(bus);
if(bus->tx_state != TX_STATE_STOP && !is_backward_tx_msg(&bus->tx_data) &&
tx_delta > s_timing.collision_txrx_delta &&
bus_level != DALI_GET_TX_LEVEL(bus)) {
bus->rx_level = bus_level;
bus->rx_tx_delta = tx_delta;
start_tx_collision_recovery_from_isr(bus, time_now);
}
// transmit data
if(bus->tx_state == TX_STATE_START) {
else if(bus->tx_state == TX_STATE_START) {
bus->tx_state = TX_STATE_DATA; // start transmitting data
bus->tx_half_bit_counter++;
DALI_SET_BUS_HIGH(bus); // start bit second half
bus->tx_last_edge_time = esp_timer_get_time(); // get time in us
DALI_SET_BUS_HIGH(bus); // start bit second half
}
else if(bus->tx_state == TX_STATE_DATA) {
bool value = (bus->tx_data.data[bus->tx_data_bit_counter/8] >> ( 7 - (bus->tx_data_bit_counter % 8) )) & 0x01;
value ^= bus->tx_half_bit_counter & 0x01; // xor=invert value for odd half bit 1:0->1 and 0:1->0
bus->tx_last_edge_time = esp_timer_get_time(); // get time in us
DALI_SET_BUS_LEVEL(bus, value);
bus->tx_last_edge_time = esp_timer_get_time(); // get time in us
bus->tx_half_bit_counter++; // increment half bit counter before next test
if(bus->tx_half_bit_counter & 0x01) { // next bit
bus->tx_data_bit_counter++;
@@ -506,15 +1009,11 @@ static bool IRAM_ATTR handle_bus_timer(dali_bus_ctx_t *bus, uint64_t time_now)
// here we check TX (NOT RX) bit state
if(DALI_GET_TX_LEVEL(bus) == 0) // really ok - otherwise we will keep bus low forever
{
DALI_SET_BUS_HIGH(bus);
bus->tx_last_edge_time = esp_timer_get_time(); // get time in us
DALI_SET_BUS_HIGH(bus);
}
else if(tx_delta > s_timing.tx_stop_cond) {
bus->tx_data.status = DALI_FRAME_OK; // frame is OK
if (bus->tx_reply_queue) {
xQueueSendToBackFromISR(bus->tx_reply_queue, &bus->tx_data, &yield); // send data to queue
}
bus->tx_state = TX_STATE_IDLE; // final state with transmitted data
complete_tx_from_isr(bus, &yield);
bus->bus_state = DALI_BUS_READY; // bus is ready
}
}
@@ -522,7 +1021,7 @@ static bool IRAM_ATTR handle_bus_timer(dali_bus_ctx_t *bus, uint64_t time_now)
else if(bus->bus_state == DALI_BUS_READY && bus->tx_state > TX_STATE_IDLE)
{
// we are not transmitting but we have data - reply to queue and let error state in tx_data.status
if (bus->tx_reply_queue) {
if (bus->tx_reply_queue && !is_backward_tx_msg(&bus->tx_data)) {
xQueueSendToBackFromISR(bus->tx_reply_queue, &bus->tx_data, &yield); // send data to queue
}
bus->tx_state = TX_STATE_IDLE; // clear state
@@ -538,6 +1037,7 @@ static bool IRAM_ATTR handle_bus_timer(dali_bus_ctx_t *bus, uint64_t time_now)
// rx_data.status = DALI_FRAME_ERROR; // should be set inside ISR
bus->rx_data.length = bus->rx_data_bit_counter; // set length of data
// rx_data.data[0] = 0xAA; // debug
note_rx_frame_from_isr(bus);
publish_rx_frame_from_isr(&bus->rx_data, bus->rx_queue, &yield); // send data to queue
}
}
@@ -549,9 +1049,14 @@ static bool IRAM_ATTR handle_bus_timer(dali_bus_ctx_t *bus, uint64_t time_now)
bus->rx_data.status = DALI_FRAME_OK; // frame is OK
bus->rx_data.length = bus->rx_data_bit_counter; // set length of data
// rx_data.data[0] = 0xBB; // debug
note_rx_frame_from_isr(bus);
publish_rx_frame_from_isr(&bus->rx_data, bus->rx_queue, &yield); // send data to queue
}
}
else if(bus->rx_state == RX_STATE_START && rx_delta > s_timing.rx_hb_max) {
bus->rx_state = RX_STATE_ERROR;
bus->rx_data.status = DALI_FRAME_TIME_VIOLATION;
}
}
return yield;
}
@@ -588,7 +1093,7 @@ static void debug_task(void *pvParameters)
else v = '0' + dbg.level;
}
else v=' ';
printf("bus[%u] rx: [%2d] pw=%lu v=%u rtd=%lu [%c]",
ESP_LOGD(TAG, "bus[%u] rx: [%2d] pw=%lu v=%u rtd=%lu [%c]",
dbg.bus_id, i++, dbg.rx_pulse_width, dbg.level, dbg.rx_tx_delta, v);
if(dbg.rx_pulse_width < 1000) {
if(dbg.rx_pulse_width > 550) HB+=2;
@@ -659,7 +1164,7 @@ static esp_err_t ensure_timer_started(void)
.flags = {
.intr_shared = true,
},
.resolution_hz = 1 * 1000 * 1000, // 1MHz, 1 tick = 1us
.resolution_hz = CONFIG_DALI_TIMER_RESOLUTION_HZ,
};
err = gptimer_new_timer(&timer_config, &gptimer);
if (err != ESP_OK) {
@@ -726,6 +1231,9 @@ static esp_err_t init_bus(uint8_t bus_id, uint8_t tx_pin, uint8_t rx_pin)
bus->bus_id = bus_id;
bus->tx_pin = tx_pin;
bus->rx_pin = rx_pin;
bus->tx_level = 1;
gpio_set_level(bus->tx_pin, DALI_TX_HIGH);
gpio_config_t io_conf;
@@ -771,6 +1279,13 @@ static esp_err_t init_bus(uint8_t bus_id, uint8_t tx_pin, uint8_t rx_pin)
bus->rx_last_edge_time = esp_timer_get_time(); // get time in us - startup time
bus->rx_level = DALI_GET_BUS_LEVEL(bus); // get level of RX pin
bus->tx_last_edge_time = bus->rx_last_edge_time;
bus->bus_level_check_time = bus->rx_last_edge_time;
bus->bus_abnormal_report_time = 0;
bus->bus_activity_seen = false;
bus->rx_last_frame_time = 0;
bus->rx_last_frame_length = 0;
bus->rx_last_frame_status = DALI_FRAME_UNKNOWN;
bus->force_backward_tx = false;
err = ensure_isr_service();
if (err != ESP_OK) {
@@ -805,17 +1320,69 @@ static int dali_tx_bus(dali_bus_ctx_t *bus, Dali_msg_t *dali_msg)
if (bus == NULL || !bus->inited) {
return ESP_FAIL;
}
if(xQueueSendToBack(bus->tx_queue, dali_msg, pdMS_TO_TICKS(50)) == pdFALSE) {
xQueueReset(bus->tx_queue); // clear queue
printf("dali_tx: Queue full\n");
if (bus->tx_queue == NULL || bus->tx_reply_queue == NULL || dali_msg == NULL) {
return ESP_FAIL;
}
if(xQueueReceive(bus->tx_reply_queue, dali_msg, pdMS_TO_TICKS(50)) == pdFALSE) {
xQueueReset(bus->tx_reply_queue); // clear queue
printf("dali_tx: No reply\n");
const uint32_t timeout_ms = tx_completion_timeout_ms(dali_msg);
const TickType_t timeout_ticks = pdMS_TO_TICKS(timeout_ms);
drain_tx_reply_queue(bus);
if (bus->bus_state == DALI_BUS_POWER_DOWN) {
dali_msg->status = DALI_FRAME_ERROR;
log_tx_message("native TX skipped, bus power down", bus, dali_msg, timeout_ms);
return ESP_FAIL;
}
return ESP_OK;
ESP_LOGD(TAG, "bus=%u queue TX len=%u data=%02x %02x %02x %02x timeoutMs=%lu",
bus->bus_id, dali_msg->length, dali_msg->data[0], dali_msg->data[1],
dali_msg->data[2], dali_msg->data[3], (unsigned long)timeout_ms);
if (is_forward_tx_msg(dali_msg) && !wait_for_forward_tx_window(bus, dali_msg)) {
dali_msg->status = DALI_FRAME_ERROR;
log_tx_message("native TX wait timeout", bus, dali_msg,
CONFIG_DALI_FORWARD_MAX_WAIT_MS);
return ESP_FAIL;
}
bool force_backward = false;
if (is_backward_tx_msg(dali_msg) &&
!wait_for_backward_tx_window(bus, dali_msg, &force_backward)) {
dali_msg->status = DALI_FRAME_ERROR;
log_tx_message("native backward TX wait timeout", bus, dali_msg,
CONFIG_DALI_BACKWARD_IDLE_TIMEOUT_MS);
return ESP_FAIL;
}
bus->force_backward_tx = force_backward;
if(xQueueSendToBack(bus->tx_queue, dali_msg, 0) == pdFALSE) {
bus->force_backward_tx = false;
log_tx_message("native TX queue full", bus, dali_msg, timeout_ms);
if (bus->tx_state == TX_STATE_IDLE) {
xQueueReset(bus->tx_queue);
}
return ESP_FAIL;
}
if (is_backward_tx_msg(dali_msg)) {
dali_msg->status = DALI_FRAME_OK;
return ESP_OK;
}
if(xQueueReceive(bus->tx_reply_queue, dali_msg, timeout_ticks) == pdFALSE) {
if (bus->tx_state == TX_STATE_IDLE && queue_waiting(bus->tx_queue) == 0) {
*dali_msg = bus->tx_data;
log_tx_message("native TX completion queue missed", bus, dali_msg, timeout_ms);
return dali_msg->status == DALI_FRAME_OK ? ESP_OK : ESP_FAIL;
}
log_tx_message("native TX completion timeout", bus, dali_msg, timeout_ms);
recover_tx_timeout(bus);
return ESP_FAIL;
}
ESP_LOGD(TAG, "bus=%u TX complete status=%u len=%u data=%02x %02x %02x %02x",
bus->bus_id, dali_msg->status, dali_msg->length, dali_msg->data[0],
dali_msg->data[1], dali_msg->data[2], dali_msg->data[3]);
return dali_msg->status == DALI_FRAME_OK ? ESP_OK : ESP_FAIL;
}
// dali_task - should run at highest priority
@@ -843,6 +1410,7 @@ void dali_task(void *pvParameters)
esp_err_t dali_hal_init(uint8_t dali_id, uint8_t tx_pin, uint8_t rx_pin)
{
dali_hal_lock();
apply_dali_log_level();
esp_err_t err = ensure_timing_ready_locked();
if (err == ESP_OK) {
@@ -873,6 +1441,7 @@ esp_err_t dali_hal_init(uint8_t dali_id, uint8_t tx_pin, uint8_t rx_pin)
esp_err_t dali_hal_set_baudrate(uint32_t baudrate)
{
dali_hal_lock();
apply_dali_log_level();
bool resume_timer = s_timer_started && gptimer;
if (resume_timer) {
+8
View File
@@ -3,6 +3,10 @@
#include <stdint.h>
#include "dali_hal.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
Addressing: 102.7.2.1
0AAA AAAx - short address AAAAAA 0-63
@@ -77,5 +81,9 @@ void dali_set_search_addr24(uint32_t addr24);
uint32_t dali_binary_search();
void dali_change_short_address(int addr1, int addr2);
#ifdef __cplusplus
}
#endif
+24 -7
View File
@@ -8,6 +8,10 @@
#include "freertos/task.h"
#include "freertos/queue.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef CONFIG_DALI_PHY_COUNT
#define DALI_PHY_COUNT CONFIG_DALI_PHY_COUNT
#else
@@ -182,13 +186,22 @@ typedef struct Dali_msg Dali_msg_t;
// define HW DALI for gpio functions
#ifndef DALI_HW_PINS
// define HW DALI for gpio functions
// - what we should write to pin to get HIGH/LOW
#define DALI_TX_HIGH 1 // idle state
#define DALI_TX_LOW 0 // active state
// - what we should read from pin to get HIGH/LOW
#define DALI_RX_HIGH 1 // idle state
#define DALI_RX_LOW 0 // active state
// Physical GPIO levels for logical DALI idle/high and active/low bus states.
#ifdef CONFIG_DALI_TX_ACTIVE_HIGH
#define DALI_TX_HIGH 0 // idle state
#define DALI_TX_LOW 1 // active state
#else
#define DALI_TX_HIGH 1 // idle state
#define DALI_TX_LOW 0 // active state
#endif
#ifdef CONFIG_DALI_RX_ACTIVE_LOW
#define DALI_RX_HIGH 1 // idle state
#define DALI_RX_LOW 0 // active state
#else
#define DALI_RX_HIGH 0 // idle state
#define DALI_RX_LOW 1 // active state
#endif
#endif
// LED onboard - debug
@@ -228,3 +241,7 @@ esp_err_t dali_hal_get_bus_info(uint8_t bus_id, dali_hal_bus_info_t *info);
QueueHandle_t dali_hal_raw_receive_queue(void);
void dali_task(void *pvParameters);
#ifdef __cplusplus
}
#endif
+114 -21
View File
@@ -1,22 +1,82 @@
#include "dali_domain.hpp"
#define LOG_LOCAL_LEVEL CONFIG_DALI_LOG_LEVEL
#include "esp_log.h"
#include "dali.h"
#include "dali_hal.h"
#include "dali.hpp"
#include "driver/uart.h"
#include "esp_log.h"
#include "freertos/queue.h"
#include <algorithm>
#include <utility>
#ifndef CONFIG_DALI_QUERY_RESPONSE_TIMEOUT_MS
#define CONFIG_DALI_QUERY_RESPONSE_TIMEOUT_MS 25
#endif
static const char *TAG = "dali_domain";
namespace gateway {
namespace {
constexpr const char* kTag = "dali_domain";
constexpr size_t kSerialRxPacketMaxBytes = 8;
constexpr UBaseType_t kSerialRxQueueDepth = 8;
constexpr uint32_t kHardwareQueryRawPostSuppressMs = 10;
portMUX_TYPE s_query_raw_suppress_lock = portMUX_INITIALIZER_UNLOCKED;
uint8_t s_query_raw_suppress_inflight[DALI_PHY_COUNT] = {};
TickType_t s_query_raw_suppress_post_until[DALI_PHY_COUNT] = {};
void BeginHardwareQueryRawSuppress(uint8_t bus_id) {
if (bus_id >= DALI_PHY_COUNT) {
return;
}
portENTER_CRITICAL(&s_query_raw_suppress_lock);
if (s_query_raw_suppress_inflight[bus_id] < UINT8_MAX) {
++s_query_raw_suppress_inflight[bus_id];
}
s_query_raw_suppress_post_until[bus_id] = 0;
portEXIT_CRITICAL(&s_query_raw_suppress_lock);
}
bool TakeHardwareQueryRawSuppress(uint8_t bus_id) {
if (bus_id >= DALI_PHY_COUNT) {
return false;
}
bool suppress = false;
const TickType_t now = xTaskGetTickCount();
portENTER_CRITICAL(&s_query_raw_suppress_lock);
const TickType_t post_until = s_query_raw_suppress_post_until[bus_id];
if (s_query_raw_suppress_inflight[bus_id] > 0) {
suppress = true;
} else if (post_until != 0 && now <= post_until) {
suppress = true;
} else if (post_until != 0) {
s_query_raw_suppress_post_until[bus_id] = 0;
}
portEXIT_CRITICAL(&s_query_raw_suppress_lock);
return suppress;
}
void ClearHardwareQueryRawSuppress(uint8_t bus_id) {
if (bus_id >= DALI_PHY_COUNT) {
return;
}
const TickType_t post_until = xTaskGetTickCount() +
pdMS_TO_TICKS(kHardwareQueryRawPostSuppressMs);
portENTER_CRITICAL(&s_query_raw_suppress_lock);
if (s_query_raw_suppress_inflight[bus_id] > 0) {
--s_query_raw_suppress_inflight[bus_id];
}
if (s_query_raw_suppress_inflight[bus_id] == 0) {
s_query_raw_suppress_post_until[bus_id] = post_until;
}
portEXIT_CRITICAL(&s_query_raw_suppress_lock);
}
DaliDomainSnapshot MakeSnapshot(uint8_t gateway_id, int address, const char* kind) {
DaliDomainSnapshot snapshot;
@@ -64,6 +124,10 @@ struct SerialRxPacket {
uint8_t data[kSerialRxPacketMaxBytes]{};
};
std::vector<uint8_t> LegacyQueryResponse(uint8_t status, uint8_t value = 0x00) {
return {status, value};
}
bool SendHardwareFrame(uint8_t bus_id, const uint8_t* data, size_t len) {
if (data == nullptr || len != 3) {
return false;
@@ -78,9 +142,11 @@ bool SendHardwareFrame(uint8_t bus_id, const uint8_t* data, size_t len) {
switch (data[0]) {
case 0x10:
ESP_LOGD(TAG, "sending hardware frame for bus=%u data=%02x %02x", bus_id, data[1], data[2]);
dali_send(&tx);
return true;
case 0x11:
ESP_LOGD(TAG, "sending extended frame for bus=%u data=%02x %02x", bus_id, data[1], data[2]);
dali_send_double(&tx);
return true;
default:
@@ -89,13 +155,16 @@ bool SendHardwareFrame(uint8_t bus_id, const uint8_t* data, size_t len) {
}
std::vector<uint8_t> TransactHardwareFrame(uint8_t bus_id, const uint8_t* data, size_t len) {
if (data == nullptr || len != 3) {
if (data == nullptr) {
return {};
}
if (len != 3) {
return len > 0 && data[0] == 0x12 ? LegacyQueryResponse(0xFD) : std::vector<uint8_t>{};
}
switch (data[0]) {
case 0x00:
return {0xFF};
ESP_LOGD(TAG, "received reset for bus=%u", bus_id);
case 0x01:
return {1};
case 0x10:
@@ -103,13 +172,25 @@ std::vector<uint8_t> TransactHardwareFrame(uint8_t bus_id, const uint8_t* data,
return SendHardwareFrame(bus_id, data, len) ? std::vector<uint8_t>{0xFF}
: std::vector<uint8_t>{0xFD};
case 0x12: {
ESP_LOGD(TAG, "received hardware query frame for bus=%u data=%02x %02x", bus_id, data[1],
data[2]);
Dali_msg_t tx = dali_msg_new(data[1], data[2]);
tx.id = bus_id;
Dali_msg_t rx = {};
BeginHardwareQueryRawSuppress(bus_id);
if (dali_query(&tx, &rx) == pdTRUE) {
ClearHardwareQueryRawSuppress(bus_id);
if (rx.status != DALI_FRAME_OK || rx.length != 8) {
ESP_LOGW(TAG, "hardware query response for bus=%u has invalid status or length", bus_id);
return LegacyQueryResponse(0xFD);
}
ESP_LOGD(TAG, "got hardware query response for bus=%u status=%u len=%u data=%02x %02x "
"%02x %02x",
bus_id, rx.status, rx.length, rx.data[0], rx.data[1], rx.data[2], rx.data[3]);
return {0xFF, rx.data[0]};
}
return {0xFE};
ClearHardwareQueryRawSuppress(bus_id);
return LegacyQueryResponse(0xFE);
}
default:
return {};
@@ -151,13 +232,19 @@ std::vector<uint8_t> ReadSerialFrame(QueueHandle_t queue, size_t len, uint32_t t
std::vector<uint8_t> TransactSerialFrame(int uart_port, QueueHandle_t queue,
uint32_t query_timeout_ms, const uint8_t* data,
size_t len) {
if (data == nullptr || len == 0) {
return LegacyQueryResponse(0xFD);
}
if (data[0] == 0x12 && len != 3) {
return LegacyQueryResponse(0xFD);
}
if (data != nullptr && len > 0 && data[0] == 0x12) {
DrainSerialQueue(queue);
}
if (!WriteSerialFrame(uart_port, data, len)) {
return {0xFD};
return LegacyQueryResponse(0xFD);
}
if (data == nullptr || len == 0 || data[0] != 0x12) {
if (data[0] != 0x12) {
return {0xFF};
}
@@ -173,10 +260,10 @@ std::vector<uint8_t> TransactSerialFrame(int uart_port, QueueHandle_t queue,
auto response = PacketToVector(packet, 2);
if (!response.empty() &&
(response[0] == 0xFF || response[0] == 0xFE || response[0] == 0xFD)) {
return response;
return LegacyQueryResponse(response[0], response.size() > 1 ? response[1] : 0x00);
}
}
return {0xFE};
return LegacyQueryResponse(0xFE);
}
} // namespace
@@ -225,14 +312,14 @@ bool DaliDomainService::bindTransport(const DaliChannelConfig& config, DaliTrans
esp_err_t DaliDomainService::bindHardwareBus(const DaliHardwareBusConfig& config) {
esp_err_t err = dali_hal_set_baudrate(config.baudrate);
if (err != ESP_OK) {
ESP_LOGE(kTag, "failed to set baudrate=%lu: %s", static_cast<unsigned long>(config.baudrate),
ESP_LOGE(TAG, "failed to set baudrate=%lu: %s", static_cast<unsigned long>(config.baudrate),
esp_err_to_name(err));
return err;
}
err = dali_hal_init(config.bus_id, config.tx_pin, config.rx_pin);
if (err != ESP_OK) {
ESP_LOGE(kTag, "failed to init bus=%u tx=%u rx=%u: %s", config.bus_id, config.tx_pin,
ESP_LOGE(TAG, "failed to init bus=%u tx=%u rx=%u: %s", config.bus_id, config.tx_pin,
config.rx_pin, esp_err_to_name(err));
return err;
}
@@ -258,9 +345,9 @@ esp_err_t DaliDomainService::bindHardwareBus(const DaliHardwareBusConfig& config
}
err = startRawFrameTask();
if (err != ESP_OK) {
ESP_LOGW(kTag, "failed to start raw frame task: %s", esp_err_to_name(err));
ESP_LOGW(TAG, "failed to start raw frame task: %s", esp_err_to_name(err));
}
ESP_LOGI(kTag, "bound channel=%u gateway=%u hardware bus=%u tx=%u rx=%u baudrate=%lu",
ESP_LOGI(TAG, "bound channel=%u gateway=%u hardware bus=%u tx=%u rx=%u baudrate=%lu",
config.channel_index, config.gateway_id, config.bus_id, config.tx_pin, config.rx_pin,
static_cast<unsigned long>(config.baudrate));
return ESP_OK;
@@ -271,7 +358,7 @@ esp_err_t DaliDomainService::bindSerialBus(const DaliSerialBusConfig& config) {
return ESP_ERR_INVALID_ARG;
}
if (hasSerialPort(config.uart_port)) {
ESP_LOGE(kTag, "uart%d is already assigned to another DALI channel", config.uart_port);
ESP_LOGE(TAG, "uart%d is already assigned to another DALI channel", config.uart_port);
return ESP_ERR_INVALID_STATE;
}
@@ -287,27 +374,27 @@ esp_err_t DaliDomainService::bindSerialBus(const DaliSerialBusConfig& config) {
auto uart = static_cast<uart_port_t>(config.uart_port);
esp_err_t err = uart_param_config(uart, &uart_config);
if (err != ESP_OK) {
ESP_LOGE(kTag, "failed to configure uart%d: %s", config.uart_port, esp_err_to_name(err));
ESP_LOGE(TAG, "failed to configure uart%d: %s", config.uart_port, esp_err_to_name(err));
return err;
}
err = uart_set_pin(uart, config.tx_pin < 0 ? UART_PIN_NO_CHANGE : config.tx_pin,
config.rx_pin < 0 ? UART_PIN_NO_CHANGE : config.rx_pin,
UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
if (err != ESP_OK) {
ESP_LOGE(kTag, "failed to set uart%d pins tx=%d rx=%d: %s", config.uart_port,
ESP_LOGE(TAG, "failed to set uart%d pins tx=%d rx=%d: %s", config.uart_port,
config.tx_pin, config.rx_pin, esp_err_to_name(err));
return err;
}
err = uart_driver_install(uart, config.rx_buffer_size, config.tx_buffer_size, 0, nullptr, 0);
if (err != ESP_OK && err != ESP_ERR_INVALID_STATE) {
ESP_LOGE(kTag, "failed to install uart%d driver: %s", config.uart_port, esp_err_to_name(err));
ESP_LOGE(TAG, "failed to install uart%d driver: %s", config.uart_port, esp_err_to_name(err));
return err;
}
uart_flush_input(uart);
QueueHandle_t serial_rx_queue = xQueueCreate(kSerialRxQueueDepth, sizeof(SerialRxPacket));
if (serial_rx_queue == nullptr) {
ESP_LOGE(kTag, "failed to create uart%d RX queue", config.uart_port);
ESP_LOGE(TAG, "failed to create uart%d RX queue", config.uart_port);
return ESP_ERR_NO_MEM;
}
@@ -337,12 +424,12 @@ esp_err_t DaliDomainService::bindSerialBus(const DaliSerialBusConfig& config) {
channel->serial_rx_queue = serial_rx_queue;
err = startSerialRxTask(*channel);
if (err != ESP_OK) {
ESP_LOGE(kTag, "failed to start uart%d RX task: %s", config.uart_port,
ESP_LOGE(TAG, "failed to start uart%d RX task: %s", config.uart_port,
esp_err_to_name(err));
return err;
}
}
ESP_LOGI(kTag, "bound channel=%u gateway=%u serial uart%d tx=%d rx=%d baudrate=%lu",
ESP_LOGI(TAG, "bound channel=%u gateway=%u serial uart%d tx=%d rx=%d baudrate=%lu",
config.channel_index, config.gateway_id, config.uart_port, config.tx_pin, config.rx_pin,
static_cast<unsigned long>(config.baudrate));
return ESP_OK;
@@ -1216,7 +1303,7 @@ void DaliDomainService::rawFrameTaskLoop() {
Dali_msg_t message = {};
while (true) {
if (queue == nullptr) {
vTaskDelay(pdMS_TO_TICKS(100));
vTaskDelay(pdMS_TO_TICKS(10));
queue = dali_hal_raw_receive_queue();
continue;
}
@@ -1234,6 +1321,12 @@ void DaliDomainService::rawFrameTaskLoop() {
if (byte_count > DALI_MAX_BYTES) {
byte_count = DALI_MAX_BYTES;
}
if (byte_count == 1 && TakeHardwareQueryRawSuppress(message.id)) {
continue;
}
if (byte_count != 1 && byte_count != 2 && byte_count != 3) {
continue;
}
DaliRawFrame frame;
frame.channel_index = channel->config.channel_index;
frame.gateway_id = channel->config.gateway_id;
+20 -1
View File
@@ -141,6 +141,13 @@ void RegisterGatt(struct ble_gatt_register_ctxt* ctxt, void* arg) {
}
}
std::vector<uint8_t> LegacyRawPayload(const std::vector<uint8_t>& data) {
if (data.size() == 1) {
return {0xBE, data[0]};
}
return data;
}
const struct ble_gatt_svc_def kGattServices[] = {
{
.type = BLE_GATT_SVC_TYPE_PRIMARY,
@@ -377,7 +384,7 @@ void GatewayBleBridge::handleDaliRawFrame(const DaliRawFrame& frame) {
if (!enabled_ || conn_handle_ == kInvalidConnectionHandle || frame.data.empty()) {
return;
}
notifyCharacteristic(frame.channel_index, frame.data);
notifyCharacteristic(frame.channel_index, LegacyRawPayload(frame.data));
}
void GatewayBleBridge::handleRawWrite(size_t channel_index, const std::vector<uint8_t>& payload) {
@@ -448,6 +455,18 @@ int GatewayBleBridge::handleGapEvent(struct ble_gap_event* event) {
notify_enabled_.fill(false);
last_notify_payload_.clear();
last_notify_at_us_ = 0;
struct ble_gap_upd_params params = {
.itvl_min = 15,
.itvl_max = 15,
.latency = 3,
.supervision_timeout = 1000,
.min_ce_len = 0,
.max_ce_len = 0,
};
int rc = ble_gap_update_params(event->connect.conn_handle, &params);
if (rc != 0) {
ESP_LOGW(kTag, "ble_gap_update_params rc=%d", rc);
}
ESP_LOGI(kTag, "BLE client connected handle=%u", conn_handle_);
} else if (enabled_) {
startAdvertising();
+4 -2
View File
@@ -7,14 +7,16 @@ set(GATEWAY_BRIDGE_REQUIRES
gateway_cache
gateway_knx
gateway_modbus
knx
log
lwip
nvs_flash
openknx_idf
)
idf_component_register(
SRCS "src/gateway_bridge.cpp"
SRCS
"src/gateway_bridge.cpp"
"src/security_storage.cpp"
INCLUDE_DIRS "include"
REQUIRES ${GATEWAY_BRIDGE_REQUIRES}
PRIV_REQUIRES gateway_bacnet
@@ -15,7 +15,7 @@
#include "gateway_knx.hpp"
#include "gateway_modbus.hpp"
#include "gateway_provisioning.hpp"
#include "openknx_idf/security_storage.h"
#include "security_storage.h"
#include "cJSON.h"
#include "driver/uart.h"
@@ -2062,12 +2062,14 @@ struct GatewayBridgeService::ChannelRuntime {
const bool commissioning_only = !knx_config.has_value();
ESP_LOGI(kTag,
"gateway=%u KNX/IP start config namespace=%s storedConfig=%d udp=%u tunnel=%d "
"multicast=%d multicastGroup=%s mainGroup=%u tpUart=%d tx=%d rx=%d individual=0x%04x",
"multicast=%d multicastGroup=%s mainGroup=%u tpUart=%d tx=%d rx=%d nineBit=%d "
"individual=0x%04x",
channel.gateway_id, openKnxNamespace().c_str(), !commissioning_only,
static_cast<unsigned>(runtime_config.udp_port), runtime_config.tunnel_enabled,
runtime_config.multicast_enabled, runtime_config.multicast_address.c_str(),
static_cast<unsigned>(runtime_config.main_group), runtime_config.tp_uart.uart_port,
runtime_config.tp_uart.tx_pin, runtime_config.tp_uart.rx_pin,
runtime_config.tp_uart.nine_bit_mode,
runtime_config.individual_address);
knx->setConfig(runtime_config);
knx_router->setConfig(runtime_config);
@@ -2304,6 +2306,7 @@ struct GatewayBridgeService::ChannelRuntime {
cJSON_AddNumberToObject(serial_json, "txPin", effective_knx->tp_uart.tx_pin);
cJSON_AddNumberToObject(serial_json, "rxPin", effective_knx->tp_uart.rx_pin);
cJSON_AddNumberToObject(serial_json, "baudrate", effective_knx->tp_uart.baudrate);
cJSON_AddBoolToObject(serial_json, "nineBitMode", effective_knx->tp_uart.nine_bit_mode);
cJSON_AddItemToObject(knx_json, "tpUart", serial_json);
}
}
@@ -1,4 +1,4 @@
#include "openknx_idf/security_storage.h"
#include "security_storage.h"
#include "esp_log.h"
#include "esp_mac.h"
+5 -2
View File
@@ -1,7 +1,10 @@
idf_component_register(
SRCS "src/gateway_knx.cpp"
SRCS
"src/gateway_knx.cpp"
"src/ets_device_runtime.cpp"
"src/ets_memory_loader.cpp"
INCLUDE_DIRS "include"
REQUIRES dali_cpp esp_driver_gpio esp_driver_uart esp_hw_support esp_netif freertos log lwip openknx_idf
REQUIRES dali_cpp esp_driver_gpio esp_driver_uart esp_hw_support esp_netif freertos log lwip knx
)
set_property(TARGET ${COMPONENT_LIB} PROPERTY CXX_STANDARD 17)
@@ -1,7 +1,7 @@
#pragma once
#include "openknx_idf/esp_idf_platform.h"
#include "openknx_idf/ets_memory_loader.h"
#include "esp_idf_platform.h"
#include "ets_memory_loader.h"
#include "knx/bau07B0.h"
#include "knx/cemi_frame.h"
@@ -39,6 +39,7 @@ struct GatewayKnxTpUartConfig {
size_t rx_buffer_size{1024};
size_t tx_buffer_size{1024};
uint32_t read_timeout_ms{20};
bool nine_bit_mode{true};
};
enum class GatewayKnxMappingMode : uint8_t {
@@ -348,6 +349,8 @@ class GatewayKnxTpIpRouter {
int tcp_sock_{-1};
int active_tcp_sock_{-1};
int tp_uart_port_{-1};
int tp_uart_tx_pin_{-1};
int tp_uart_rx_pin_{-1};
std::vector<uint32_t> multicast_joined_interfaces_;
TickType_t network_refresh_tick_{0};
std::array<TcpClient, kMaxTcpClients> tcp_clients_{};
@@ -0,0 +1,61 @@
#pragma once
// Internal header shared between gateway_knx.cpp and gateway_knx_router.cpp.
#include "driver/uart.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "soc/uart_periph.h"
#include <cstdint>
#include <string>
namespace gateway {
namespace knx_internal {
constexpr const char* kTag = "gateway_knx";
// RAII semaphore guard.
class SemaphoreGuard {
public:
explicit SemaphoreGuard(SemaphoreHandle_t semaphore) : semaphore_(semaphore) {
if (semaphore_ != nullptr) {
xSemaphoreTake(semaphore_, portMAX_DELAY);
locked_ = true;
}
}
~SemaphoreGuard() {
if (locked_) {
xSemaphoreGive(semaphore_);
}
}
private:
SemaphoreHandle_t semaphore_{nullptr};
bool locked_{false};
};
// Resolve a UART IO pin from config or SoC defaults.
inline bool ResolveUartIoPin(uart_port_t uart_port, int configured_pin,
uint32_t pin_index, int* resolved_pin) {
if (resolved_pin == nullptr) return false;
if (configured_pin >= 0) {
*resolved_pin = configured_pin;
return true;
}
if (uart_port < 0 || uart_port >= SOC_UART_NUM ||
pin_index >= SOC_UART_PINS_COUNT) {
*resolved_pin = UART_PIN_NO_CHANGE;
return false;
}
const int default_pin =
uart_periph_signal[uart_port].pins[pin_index].default_gpio;
if (default_pin < 0) {
*resolved_pin = UART_PIN_NO_CHANGE;
return false;
}
*resolved_pin = default_pin;
return true;
}
} // namespace knx_internal
} // namespace gateway
@@ -1,4 +1,4 @@
#include "openknx_idf/ets_device_runtime.h"
#include "ets_device_runtime.h"
#include "knx/cemi_server.h"
#include "knx/secure_application_layer.h"
@@ -80,6 +80,7 @@ EtsDeviceRuntime::EtsDeviceRuntime(std::string nvs_namespace,
? tunnel_client_address
: DefaultTunnelClientAddress(
device_.deviceObject().individualAddress()));
server->deviceAddressPropertiesTargetClient(false);
server->tunnelFrameCallback(&EtsDeviceRuntime::EmitTunnelFrame, this);
}
device_.functionPropertyCallback(&EtsDeviceRuntime::HandleFunctionPropertyCommand);
@@ -1,6 +1,6 @@
#include "openknx_idf/ets_memory_loader.h"
#include "ets_memory_loader.h"
#include "openknx_idf/esp_idf_platform.h"
#include "esp_idf_platform.h"
#include "knx/bau07B0.h"
#include "knx/property.h"
+77 -13
View File
@@ -8,7 +8,8 @@
#include "esp_log.h"
#include "lwip/inet.h"
#include "lwip/sockets.h"
#include "openknx_idf/ets_device_runtime.h"
#include "ets_device_runtime.h"
#include "soc/uart_periph.h"
#include <algorithm>
#include <array>
@@ -173,6 +174,38 @@ std::string ErrnoDetail(const std::string& message, int err) {
return std::string(message) + ": errno=" + std::to_string(err) + " (" + std::strerror(err) + ")";
}
bool ResolveUartIoPin(uart_port_t uart_port, int configured_pin, uint32_t pin_index,
int* resolved_pin) {
if (resolved_pin == nullptr) {
return false;
}
if (configured_pin >= 0) {
*resolved_pin = configured_pin;
return true;
}
if (uart_port < 0 || uart_port >= SOC_UART_NUM || pin_index >= SOC_UART_PINS_COUNT) {
*resolved_pin = UART_PIN_NO_CHANGE;
return false;
}
const int default_pin = uart_periph_signal[uart_port].pins[pin_index].default_gpio;
if (default_pin < 0) {
*resolved_pin = UART_PIN_NO_CHANGE;
return false;
}
*resolved_pin = default_pin;
return true;
}
std::string UartPinDescription(int configured_pin, int resolved_pin) {
if (configured_pin >= 0) {
return std::to_string(configured_pin);
}
if (resolved_pin >= 0) {
return std::to_string(resolved_pin) + " (default from -1)";
}
return "unrouted (-1 with no target default)";
}
std::string Ipv4String(uint32_t network_address) {
const uint32_t address = ntohl(network_address);
char buffer[16]{};
@@ -909,6 +942,9 @@ std::optional<GatewayKnxConfig> GatewayKnxConfigFromValue(const DaliValue* value
config.tp_uart.read_timeout_ms = static_cast<uint32_t>(std::max(
1, ObjectIntAny(serial, {"readTimeoutMs", "read_timeout_ms"})
.value_or(static_cast<int>(config.tp_uart.read_timeout_ms))));
config.tp_uart.nine_bit_mode = ObjectBoolAny(
serial, {"nineBitMode", "nine_bit_mode", "use9BitMode", "use_9_bit_mode"})
.value_or(config.tp_uart.nine_bit_mode);
}
return config;
}
@@ -939,6 +975,7 @@ DaliValue GatewayKnxConfigToValue(const GatewayKnxConfig& config) {
serial["rxBufferSize"] = static_cast<int>(config.tp_uart.rx_buffer_size);
serial["txBufferSize"] = static_cast<int>(config.tp_uart.tx_buffer_size);
serial["readTimeoutMs"] = static_cast<int>(config.tp_uart.read_timeout_ms);
serial["nineBitMode"] = config.tp_uart.nine_bit_mode;
out["tpUart"] = std::move(serial);
DaliValue::Array ets_associations;
ets_associations.reserve(config.ets_associations.size());
@@ -1911,13 +1948,24 @@ esp_err_t GatewayKnxTpIpRouter::start(uint32_t task_stack_size, UBaseType_t task
}
stop_requested_ = false;
last_error_.clear();
int log_tp_uart_tx_pin = -1;
int log_tp_uart_rx_pin = -1;
if (config_.tp_uart.uart_port >= 0 && config_.tp_uart.uart_port < SOC_UART_NUM) {
const uart_port_t log_uart_port = static_cast<uart_port_t>(config_.tp_uart.uart_port);
ResolveUartIoPin(log_uart_port, config_.tp_uart.tx_pin, SOC_UART_TX_PIN_IDX,
&log_tp_uart_tx_pin);
ResolveUartIoPin(log_uart_port, config_.tp_uart.rx_pin, SOC_UART_RX_PIN_IDX,
&log_tp_uart_rx_pin);
}
ESP_LOGI(kTag,
"starting KNXnet/IP router namespace=%s udp=%u tunnel=%d multicast=%d group=%s "
"tpUart=%d tx=%d rx=%d commissioningOnly=%d",
"tpUart=%d tx=%s rx=%s nineBit=%d commissioningOnly=%d",
openknx_namespace_.c_str(), static_cast<unsigned>(config_.udp_port),
config_.tunnel_enabled, config_.multicast_enabled,
config_.multicast_address.c_str(), config_.tp_uart.uart_port,
config_.tp_uart.tx_pin, config_.tp_uart.rx_pin, commissioning_only_);
UartPinDescription(config_.tp_uart.tx_pin, log_tp_uart_tx_pin).c_str(),
UartPinDescription(config_.tp_uart.rx_pin, log_tp_uart_rx_pin).c_str(),
config_.tp_uart.nine_bit_mode, commissioning_only_);
if (!configureSocket()) {
return ESP_FAIL;
}
@@ -2447,11 +2495,24 @@ bool GatewayKnxTpIpRouter::configureTpUart() {
uart_config_t uart_config{};
uart_config.baud_rate = static_cast<int>(serial.baudrate);
uart_config.data_bits = UART_DATA_8_BITS;
uart_config.parity = UART_PARITY_EVEN;
uart_config.parity = serial.nine_bit_mode ? UART_PARITY_EVEN : UART_PARITY_DISABLE;
uart_config.stop_bits = UART_STOP_BITS_1;
uart_config.flow_ctrl = UART_HW_FLOWCTRL_DISABLE;
uart_config.source_clk = UART_SCLK_DEFAULT;
const uart_port_t uart_port = static_cast<uart_port_t>(serial.uart_port);
int tx_pin = UART_PIN_NO_CHANGE;
int rx_pin = UART_PIN_NO_CHANGE;
const bool tx_pin_ok = ResolveUartIoPin(uart_port, serial.tx_pin, SOC_UART_TX_PIN_IDX, &tx_pin);
const bool rx_pin_ok = ResolveUartIoPin(uart_port, serial.rx_pin, SOC_UART_RX_PIN_IDX, &rx_pin);
if (!tx_pin_ok || !rx_pin_ok) {
last_error_ = "KNX TP-UART UART" + std::to_string(serial.uart_port) +
" has no ESP-IDF default " + (!tx_pin_ok ? std::string("TX") : std::string("")) +
(!tx_pin_ok && !rx_pin_ok ? "/" : "") +
(!rx_pin_ok ? std::string("RX") : std::string("")) +
" pin; configure explicit txPin/rxPin values";
ESP_LOGE(kTag, "%s", last_error_.c_str());
return false;
}
esp_err_t err = uart_param_config(uart_port, &uart_config);
if (err != ESP_OK) {
last_error_ = EspErrDetail("failed to configure KNX TP-UART parameters on UART" +
@@ -2460,14 +2521,12 @@ bool GatewayKnxTpIpRouter::configureTpUart() {
ESP_LOGE(kTag, "%s", last_error_.c_str());
return false;
}
err = uart_set_pin(uart_port, serial.tx_pin < 0 ? UART_PIN_NO_CHANGE : serial.tx_pin,
serial.rx_pin < 0 ? UART_PIN_NO_CHANGE : serial.rx_pin,
UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
err = uart_set_pin(uart_port, tx_pin, rx_pin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
if (err != ESP_OK) {
last_error_ = EspErrDetail("failed to configure KNX TP-UART pins uart=" +
std::to_string(serial.uart_port) + " tx=" +
std::to_string(serial.tx_pin) + " rx=" +
std::to_string(serial.rx_pin),
UartPinDescription(serial.tx_pin, tx_pin) + " rx=" +
UartPinDescription(serial.rx_pin, rx_pin),
err);
ESP_LOGE(kTag, "%s", last_error_.c_str());
return false;
@@ -2482,6 +2541,8 @@ bool GatewayKnxTpIpRouter::configureTpUart() {
return false;
}
tp_uart_port_ = serial.uart_port;
tp_uart_tx_pin_ = tx_pin;
tp_uart_rx_pin_ = rx_pin;
if (!initializeTpUart()) {
if (ets_device_ != nullptr && !ets_device_->configured()) {
ESP_LOGW(kTag,
@@ -2496,8 +2557,11 @@ bool GatewayKnxTpIpRouter::configureTpUart() {
ESP_LOGE(kTag, "%s", last_error_.c_str());
return false;
}
ESP_LOGI(kTag, "KNX TP-UART online uart=%d tx=%d rx=%d baud=%u", serial.uart_port,
serial.tx_pin, serial.rx_pin, static_cast<unsigned>(serial.baudrate));
ESP_LOGI(kTag, "KNX TP-UART online uart=%d tx=%s rx=%s baud=%u nineBit=%d",
serial.uart_port,
UartPinDescription(serial.tx_pin, tp_uart_tx_pin_).c_str(),
UartPinDescription(serial.rx_pin, tp_uart_rx_pin_).c_str(),
static_cast<unsigned>(serial.baudrate), serial.nine_bit_mode);
return true;
}
@@ -2600,8 +2664,8 @@ bool GatewayKnxTpIpRouter::initializeTpUart() {
last_error_ = (saw_reset ? "timed out waiting for KNX TP-UART state indication"
: "timed out waiting for KNX TP-UART reset indication") +
std::string(" uart=") + std::to_string(config_.tp_uart.uart_port) +
" tx=" + std::to_string(config_.tp_uart.tx_pin) +
" rx=" + std::to_string(config_.tp_uart.rx_pin) +
" tx=" + UartPinDescription(config_.tp_uart.tx_pin, tp_uart_tx_pin_) +
" rx=" + UartPinDescription(config_.tp_uart.rx_pin, tp_uart_rx_pin_) +
" timeoutMs=1500";
return false;
}
@@ -12,6 +12,13 @@ namespace gateway {
namespace {
constexpr const char* kTag = "gateway_usb";
constexpr size_t kCommandFrameMinLen = 7;
std::vector<uint8_t> LegacyRawPayload(const std::vector<uint8_t>& data) {
if (data.size() == 1) {
return {0xBE, data[0]};
}
return data;
}
}
GatewayUsbSetupBridge::GatewayUsbSetupBridge(GatewayController& controller,
@@ -82,6 +89,19 @@ void GatewayUsbSetupBridge::handleBytes(const uint8_t* data, size_t len) {
}
const uint8_t gateway_id = setupGatewayId();
if (data[0] == 0x12) {
const auto response = dali_domain_.transactBridgeFrame(gateway_id, data, len);
if (!response.empty()) {
const int written = usb_serial_jtag_write_bytes(response.data(), response.size(),
pdMS_TO_TICKS(config_.write_timeout_ms));
if (written < 0 || static_cast<size_t>(written) != response.size()) {
ESP_LOGW(kTag, "failed to write USB raw query response channel=%u len=%u",
config_.channel_index, static_cast<unsigned>(response.size()));
}
}
return;
}
if (!dali_domain_.writeBridgeFrame(gateway_id, data, len)) {
ESP_LOGW(kTag, "failed to write USB raw setup frame channel=%u len=%u", config_.channel_index,
static_cast<unsigned>(len));
@@ -93,11 +113,12 @@ void GatewayUsbSetupBridge::handleRawFrame(const DaliRawFrame& frame) {
return;
}
const int written = usb_serial_jtag_write_bytes(frame.data.data(), frame.data.size(),
const auto payload = LegacyRawPayload(frame.data);
const int written = usb_serial_jtag_write_bytes(payload.data(), payload.size(),
pdMS_TO_TICKS(config_.write_timeout_ms));
if (written < 0 || static_cast<size_t>(written) != frame.data.size()) {
if (written < 0 || static_cast<size_t>(written) != payload.size()) {
ESP_LOGW(kTag, "failed to forward USB raw setup frame channel=%u len=%u", frame.channel_index,
static_cast<unsigned>(frame.data.size()));
static_cast<unsigned>(payload.size()));
}
}
+24
View File
@@ -0,0 +1,24 @@
idf_component_register(
SRCS
"src/knx_dali_gw.cpp"
"src/knx_dali_module.cpp"
"src/knx_dali_channel.cpp"
"src/hcl_curve.cpp"
"src/color_helper.cpp"
"src/dali_helper.cpp"
"src/message_queue.cpp"
"src/dali_gateway_bridge.cpp"
INCLUDE_DIRS
"include"
"src"
REQUIRES
dali_cpp
dali_domain
esp_timer
freertos
knx
log
nvs_flash
)
set_property(TARGET ${COMPONENT_LIB} PROPERTY CXX_STANDARD 17)
@@ -0,0 +1,127 @@
#pragma once
// =============================================================================
// dali_gateway_bridge.h — Thin adapter mapping legacy DALI operations to
// dali_domain / dali_cpp API.
// =============================================================================
#include "dali_domain.hpp"
#include <cstdint>
#include <optional>
#include <vector>
namespace gateway {
namespace knx_dali_gw {
// DALI target types matching the legacy DaliModule target model.
enum class DaliTargetKind : uint8_t {
kShortAddress = 0,
kGroup = 1,
kBroadcast = 2,
};
struct DaliTarget {
DaliTargetKind kind{DaliTargetKind::kShortAddress};
int address{0}; // short address 0-63, group 0-15, or ignored for broadcast
};
// Encodes a DaliTarget into a raw DALI address byte.
uint8_t EncodeDaliRawAddr(DaliTarget target);
// Decodes a raw DALI address byte into a DaliTarget for a given short address.
DaliTarget DecodeDaliRawAddr(uint8_t raw_addr, int default_short_address = -1);
// Lightweight bridge over DaliDomainService for the KNX-DALI gateway.
// All operations go through a single DALI channel (gateway_id).
class DaliGatewayBridge {
public:
explicit DaliGatewayBridge(DaliDomainService& dali, uint8_t gateway_id = 0);
// ---- Basic send / query ----
bool sendRaw(DaliTarget target, uint8_t command) const;
bool sendExtRaw(DaliTarget target, uint8_t command) const;
std::optional<uint8_t> queryRaw(DaliTarget target, uint8_t command) const;
// ---- Brightness (arc power level) ----
bool setArc(DaliTarget target, uint8_t arc) const;
std::optional<uint8_t> queryActualLevel(int short_address) const;
// ---- On / Off / Step / Recall ----
bool on(DaliTarget target) const;
bool off(DaliTarget target) const;
bool stepUp(DaliTarget target) const;
bool stepDown(DaliTarget target) const;
bool recallMax(DaliTarget target) const;
bool recallMin(DaliTarget target) const;
bool goToScene(DaliTarget target, uint8_t scene) const;
// ---- Queries ----
std::optional<uint8_t> queryStatus(int short_address) const;
std::optional<uint8_t> queryDeviceType(int short_address) const;
std::optional<uint8_t> queryMinLevel(int short_address) const;
std::optional<uint8_t> queryMaxLevel(int short_address) const;
std::optional<uint8_t> queryPowerOnLevel(int short_address) const;
std::optional<uint8_t> querySystemFailureLevel(int short_address) const;
std::optional<uint8_t> queryFadeTimeRate(int short_address) const;
std::optional<uint8_t> queryFadeTime(int short_address) const;
std::optional<uint16_t> queryGroups(int short_address) const;
std::optional<uint8_t> querySceneLevel(int short_address, uint8_t scene) const;
// ---- DT8 colour ----
bool setColourTemperature(int short_address, int kelvin) const;
bool setColourRGB(int short_address, uint8_t r, uint8_t g, uint8_t b) const;
std::optional<DaliDomainSnapshot> dt8StatusSnapshot(int short_address) const;
std::optional<DaliDomainSnapshot> dt8SceneColorReport(int short_address, int scene) const;
// ---- Scenes & groups (write operations) ----
bool setDtr(uint8_t value) const;
bool setDtrAsScene(DaliTarget target, uint8_t scene) const;
bool addToGroup(DaliTarget target, uint8_t group) const;
bool removeFromGroup(DaliTarget target, uint8_t group) const;
bool removeFromScene(DaliTarget target, uint8_t scene) const;
bool setSceneLevel(DaliTarget target, uint8_t scene, uint8_t level) const;
// ---- Commissioning ----
bool initialise(DaliTarget target) const;
bool randomise() const;
bool searchAddrH(uint8_t high) const;
bool searchAddrM(uint8_t middle) const;
bool searchAddrL(uint8_t low) const;
bool compare() const;
bool withdraw() const;
bool terminate() const;
bool programShort(DaliTarget target, uint8_t short_address) const;
bool verifyShort(DaliTarget target) const;
std::optional<uint8_t> queryShort(DaliTarget target) const;
// High-level addressing.
bool allocateAllAddr(int start_address = 0) const;
void stopAllocAddr() const;
bool resetAndAllocAddr(int start_address = 0, bool remove_addr_first = false,
bool close_light = false) const;
// ---- Bus control ----
bool resetBus() const;
private:
DaliDomainService& dali_;
uint8_t gateway_id_;
};
// Convert DALI arc power level (0-254) to percentage (0.0-100.0).
double ArcToPercent(uint8_t arc);
// Convert percentage (0.0-100.0) to DALI arc power level (0-254).
uint8_t PercentToArc(double percent);
} // namespace knx_dali_gw
} // namespace gateway
@@ -0,0 +1,55 @@
#pragma once
// =============================================================================
// knx_dali_gw — KNX-to-DALI Gateway Component (ESP-IDF)
// =============================================================================
#include "esp_idf_platform.h"
#include "dali_domain.hpp"
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
// Forward declarations.
class Bau07B0;
namespace gateway {
namespace knx_dali_gw {
struct KnxDaliGatewayConfig {
std::string nvs_namespace{"knx_dali_gw"};
uint16_t fallback_individual_address{0xfffe};
int dali_channel{0};
};
class KnxDaliGateway {
public:
explicit KnxDaliGateway(const KnxDaliGatewayConfig& config);
~KnxDaliGateway();
KnxDaliGateway(const KnxDaliGateway&) = delete;
KnxDaliGateway& operator=(const KnxDaliGateway&) = delete;
bool init();
void loop();
Bau07B0& knxDevice();
const Bau07B0& knxDevice() const;
void setNetworkInterface(esp_netif_t* netif);
bool handleTunnelFrame(const uint8_t* data, size_t len);
bool handleBusFrame(const uint8_t* data, size_t len);
bool emitGroupValue(uint16_t group_object_number, const uint8_t* data,
size_t len);
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace knx_dali_gw
} // namespace gateway
+66
View File
@@ -0,0 +1,66 @@
#pragma once
// Minimal stub for knxprod.h — generated KNX product definitions.
// The full file (1796 bytes of parameters, 1439 group objects) will be
// adapted in Phase 3 to use the gateway/knx API directly.
// Product identity
#define MAIN_OpenKnxId 0xA4
#define MAIN_ApplicationNumber 1
#define MAIN_ApplicationVersion 5
#define MAIN_OrderNumber "REG1-Dali"
#define MAIN_ParameterSize 1796
#define MAIN_MaxKoNumber 1439
// Parameter type enums (subset)
enum PT_DeviceType : uint8_t {
PT_deviceType_Deaktiviert = 0,
PT_deviceType_DT0 = 1,
PT_deviceType_DT1 = 2,
PT_deviceType_DT6 = 3,
PT_deviceType_DT8 = 4,
};
enum PT_ColorType : uint8_t {
PT_colorType_HSV = 0,
PT_colorType_RGB = 1,
PT_colorType_TW = 2,
PT_colorType_XYY = 3,
};
enum PT_ColorSpace : uint8_t {
PT_colorSpace_rgb = 0,
PT_colorSpace_xy = 1,
};
// Placeholder macros — will be replaced with direct Bau07B0 access in Phase 3.
#define ParamAPP_daynight(channelIndex) (0)
#define ParamAPP_funcBtn(channelIndex) (0)
#define ParamAPP_funcBtnLong(channelIndex) (0)
#define ParamAPP_funcBtnDbl(channelIndex) (0)
#define ParamADR_deviceType(channelIndex) (PT_DeviceType::PT_deviceType_Deaktiviert)
#define ParamADR_type(channelIndex) (0)
#define ParamADR_min(channelIndex) (0)
#define ParamADR_max(channelIndex) (254)
#define ParamADR_stairtime(channelIndex) (0)
#define ParamADR_onDay(channelIndex) (0)
#define ParamADR_onNight(channelIndex) (0)
#define ParamADR_error(channelIndex) (0)
#define ParamADR_queryTime(channelIndex) (0)
#define ParamADR_colorType(channelIndex) (PT_ColorType::PT_colorType_TW)
#define ParamADR_colorSpace(channelIndex) (PT_ColorSpace::PT_colorSpace_rgb)
#define ParamGRP_deviceType(channelIndex) (PT_DeviceType::PT_deviceType_Deaktiviert)
#define ParamGRP_type(channelIndex) (0)
#define ParamGRP_colorType(channelIndex) (PT_ColorType::PT_colorType_TW)
#define ParamHCL_type(channelIndex) (0)
// Group object offset placeholders
#define ADR_KoOffset 0
#define GRP_KoOffset 0
#define HCL_KoOffset 0
#define ADR_KoBlockSize 0
#define GRP_KoBlockSize 0
#define HCL_KoBlockSize 0
+10
View File
@@ -0,0 +1,10 @@
#pragma once
#include <cstdint>
struct Ballast {
uint8_t high{0};
uint8_t middle{0};
uint8_t low{0};
uint8_t address{255};
};
+138
View File
@@ -0,0 +1,138 @@
#include "color_helper.h"
uint16_t ColorHelper::getKelvinFromSun(uint16_t minCurr, uint16_t minDiff, uint16_t minK, uint16_t maxK)
{
float xAchse = (minCurr * 3.14159) / minDiff;
float yAchse = sin(xAchse);
return (maxK - minK) * yAchse + minK;
}
void ColorHelper::rgbToXY(uint8_t in_r, uint8_t in_g, uint8_t in_b, uint16_t& x, uint16_t& y)
{
float r = in_r / 255.0;
float g = in_g / 255.0;
float b = in_b / 255.0;
r = (r > 0.04045) ? pow((r + 0.055) / (1.0 + 0.055), 2.4) : (r / 12.92);
g = (g > 0.04045) ? pow((g + 0.055) / (1.0 + 0.055), 2.4) : (g / 12.92);
b = (b > 0.04045) ? pow((b + 0.055) / (1.0 + 0.055), 2.4) : (b / 12.92);
float X = r * 0.4124 + g * 0.3576 + b * 0.1805;
float Y = r * 0.2126 + g * 0.7152 + b * 0.0722;
float Z = r * 0.0193 + g * 0.1192 + b * 0.9505;
float cx = X / (X + Y + Z);
float cy = Y / (X + Y + Z);
x = getBytes(cx);
y = getBytes(cy);
y = y + 1;
y = y - 1;
}
void ColorHelper::hsvToRGB(uint8_t in_h, uint8_t in_s, uint8_t in_v, uint8_t& r, uint8_t& g, uint8_t& b)
{
float h = in_h / 255.0;
float s = in_s / 255.0;
float v = in_v / 255.0;
double rt = 0;
double gt = 0;
double bt = 0;
int i = int(h * 6);
double f = h * 6 - i;
double p = v * (1 - s);
double q = v * (1 - f * s);
double t = v * (1 - (1 - f) * s);
switch(i % 6){
case 0: rt = v, gt = t, bt = p; break;
case 1: rt = q, gt = v, bt = p; break;
case 2: rt = p, gt = v, bt = t; break;
case 3: rt = p, gt = q, bt = v; break;
case 4: rt = t, gt = p, bt = v; break;
case 5: rt = v, gt = p, bt = q; break;
}
r = rt * 255;
g = gt * 255;
b = bt * 255;
}
void ColorHelper::kelvinToRGB(uint16_t kelvin, uint8_t& r, uint8_t& g, uint8_t& b)
{
auto temp = kelvin / 100;
if (temp <= 66)
{
r = 255;
g = 99.4708025861 * log(temp) - 161.1195681661;
if (temp <= 19)
b = 0;
else
b = 138.5177312231 * log(temp - 10) - 305.0447927307;
}
else
{
r = 329.698727446 * pow(temp - 60, -0.1332047592);
g = 288.1221695283 * pow(temp - 60, -0.0755148492);
b = 255;
}
}
void ColorHelper::xyyToRGB(uint16_t ix, uint16_t iy, uint8_t iz, uint8_t& r, uint8_t& g, uint8_t& b)
{
float _x = getFloat(ix);
float _y = getFloat(iy);
//let z = 1.0 - x - y;
//return this.colorFromXYZ((Y / y) * x, Y, (Y / y) * z);
float y = iz / 255.0f;
float x = _x * (y / _y);
float z = ((1.0 - _x - _y) * y) / _y;
float rt = x * 3.2404f + y * -1.5371f + z * -0.4985f;
float gt = x * -0.9693f + y * 1.8760f + z * 0.0416f;
float bt = x * 0.0556f + y * -0.2040f + z * 1.05723f;
rt = adjust(rt);
gt = adjust(gt);
bt = adjust(bt);
r = std::max(std::min(rt, 255.0f), 0.0f);
g = std::max(std::min(gt, 255.0f), 0.0f);
b = std::max(std::min(bt, 255.0f), 0.0f);
}
uint16_t ColorHelper::getBytes(float input)
{
return std::max(std::min(round(input * 65536.0), 65534.0), 0.0);
}
float ColorHelper::getFloat(uint16_t input)
{
float output = input / 65536.0f;
return std::max(std::min(output, 0.0f), 1.0f);
}
double ColorHelper::hue2rgb(double p, double q, double t)
{
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6.0) return p + (q - p) * 6 * t;
if (t < 1 / 2.0) return q;
if (t < 2 / 3.0) return p + (q - p) * (2 / 3.0 - t) * 6;
return p;
}
float ColorHelper::adjust(float input)
{
if (input > 0.0031308) {
return (1.055f * pow(input, (1.0f / 2.4f)) - 0.055f) * 255.0;
}
return 12.92f * input;
}
+23
View File
@@ -0,0 +1,23 @@
#pragma once
#include <cstdint>
#include <cmath>
#include <algorithm>
//extended lib from https://github.com/ratkins/RGBConverter
//WTFPL license
class ColorHelper
{
public:
static void rgbToXY(uint8_t r, uint8_t g, uint8_t b, uint16_t& x, uint16_t& y);
static void hsvToRGB(uint8_t h, uint8_t s, uint8_t v, uint8_t& r, uint8_t& g, uint8_t& b);
static void kelvinToRGB(uint16_t kelvin, uint8_t& r, uint8_t& g, uint8_t& b);
static void xyyToRGB(uint16_t x, uint16_t y, uint8_t z, uint8_t& r, uint8_t& g, uint8_t& b);
static uint16_t getKelvinFromSun(uint16_t minCurr, uint16_t minDiff, uint16_t minK, uint16_t maxK);
private:
static uint16_t getBytes(float input);
static float getFloat(uint16_t input);
static double hue2rgb(double p, double q, double t);
static float adjust(float input);
};
@@ -0,0 +1,323 @@
#include "dali_gateway_bridge.h"
#include "dali_define.hpp"
#include "dali_comm.hpp"
#include <algorithm>
#include <cmath>
namespace gateway {
namespace knx_dali_gw {
namespace {
constexpr double kArcMax = 254.0;
constexpr double kLogFactor = 3.0;
// DALI address encoding helpers (mirroring lib/dali/comm.dart).
// Short address 0-63 → (addr << 1) | 0x01 for commands.
constexpr uint8_t kShortAddrCmdBase = 0x01;
constexpr uint8_t kShortAddrArcBase = 0x00;
constexpr uint8_t kGroupAddrBase = 0x80;
constexpr uint8_t kBroadcastCmd = 0xFE;
constexpr uint8_t kBroadcastArc = 0xFF;
uint8_t makeShortCmdAddr(int addr) {
return static_cast<uint8_t>((addr << 1) | kShortAddrCmdBase);
}
uint8_t makeShortArcAddr(int addr) {
return static_cast<uint8_t>((addr << 1) | kShortAddrArcBase);
}
uint8_t makeGroupCmdAddr(int group) {
return static_cast<uint8_t>(kGroupAddrBase | (group << 1) | 0x01);
}
uint8_t makeBroadcastCmdAddr() { return kBroadcastCmd; }
uint8_t makeBroadcastArcAddr() { return kBroadcastArc; }
bool isBroadcastAddr(uint8_t raw) { return raw == kBroadcastCmd || raw == kBroadcastArc; }
bool isGroupAddr(uint8_t raw) { return (raw & 0x80) != 0 && !isBroadcastAddr(raw); }
int extractGroupAddr(uint8_t raw) { return (raw >> 1) & 0x0F; }
int extractShortAddr(uint8_t raw) { return (raw >> 1) & 0x3F; }
uint8_t encodeDaliRawAddr(DaliTarget target) {
switch (target.kind) {
case DaliTargetKind::kShortAddress:
return makeShortCmdAddr(target.address);
case DaliTargetKind::kGroup:
return makeGroupCmdAddr(target.address);
case DaliTargetKind::kBroadcast:
default:
return makeBroadcastCmdAddr();
}
}
} // namespace
// =============================================================================
// DaliTarget ↔ raw address encoding (public API)
// =============================================================================
uint8_t EncodeDaliRawAddr(DaliTarget target) {
return encodeDaliRawAddr(target);
}
DaliTarget DecodeDaliRawAddr(uint8_t raw_addr, int default_short_address) {
if (isBroadcastAddr(raw_addr)) {
return {DaliTargetKind::kBroadcast, 0};
}
if (isGroupAddr(raw_addr)) {
return {DaliTargetKind::kGroup, extractGroupAddr(raw_addr)};
}
int sa = extractShortAddr(raw_addr);
if (sa < 0 && default_short_address >= 0) {
sa = default_short_address;
}
return {DaliTargetKind::kShortAddress, sa};
}
// =============================================================================
// Arc power ↔ percentage conversion
// =============================================================================
double ArcToPercent(uint8_t arc) {
if (arc == 0) return 0.0;
return 100.0 * std::pow(static_cast<double>(arc) / kArcMax, kLogFactor);
}
uint8_t PercentToArc(double percent) {
if (percent <= 0.0) return 0;
if (percent >= 100.0) return 254;
return static_cast<uint8_t>(
std::round(kArcMax * std::pow(percent / 100.0, 1.0 / kLogFactor)));
}
// =============================================================================
// DaliGatewayBridge
// =============================================================================
DaliGatewayBridge::DaliGatewayBridge(DaliDomainService& dali, uint8_t gateway_id)
: dali_(dali), gateway_id_(gateway_id) {}
bool DaliGatewayBridge::sendRaw(DaliTarget target, uint8_t command) const {
return dali_.sendRaw(gateway_id_, encodeDaliRawAddr(target), command);
}
bool DaliGatewayBridge::sendExtRaw(DaliTarget target, uint8_t command) const {
return dali_.sendExtRaw(gateway_id_, encodeDaliRawAddr(target), command);
}
std::optional<uint8_t> DaliGatewayBridge::queryRaw(DaliTarget target, uint8_t command) const {
return dali_.queryRaw(gateway_id_, encodeDaliRawAddr(target), command);
}
bool DaliGatewayBridge::setArc(DaliTarget target, uint8_t arc) const {
return sendRaw(target, arc);
}
std::optional<uint8_t> DaliGatewayBridge::queryActualLevel(int short_address) const {
return dali_.queryRaw(gateway_id_, makeShortCmdAddr(short_address),
DALI_CMD_QUERY_ACTUAL_LEVEL);
}
bool DaliGatewayBridge::on(DaliTarget target) const {
return sendRaw(target, DALI_CMD_RECALL_MAX);
}
bool DaliGatewayBridge::off(DaliTarget target) const {
return sendRaw(target, DALI_CMD_OFF);
}
bool DaliGatewayBridge::stepUp(DaliTarget target) const {
return sendRaw(target, DALI_CMD_RECALL_MAX);
}
bool DaliGatewayBridge::stepDown(DaliTarget target) const {
return sendRaw(target, DALI_CMD_OFF);
}
bool DaliGatewayBridge::recallMax(DaliTarget target) const {
return sendRaw(target, DALI_CMD_RECALL_MAX);
}
bool DaliGatewayBridge::recallMin(DaliTarget target) const {
return sendRaw(target, DALI_CMD_RECALL_MIN);
}
bool DaliGatewayBridge::goToScene(DaliTarget target, uint8_t scene) const {
return sendRaw(target, DALI_CMD_GO_TO_SCENE(scene & 0x0F));
}
std::optional<uint8_t> DaliGatewayBridge::queryStatus(int short_address) const {
return dali_.queryRaw(gateway_id_, makeShortCmdAddr(short_address),
DALI_CMD_QUERY_STATUS);
}
std::optional<uint8_t> DaliGatewayBridge::queryDeviceType(int short_address) const {
return dali_.queryRaw(gateway_id_, makeShortCmdAddr(short_address),
DALI_CMD_QUERY_DEVICE_TYPE);
}
std::optional<uint8_t> DaliGatewayBridge::queryMinLevel(int short_address) const {
return dali_.queryRaw(gateway_id_, makeShortCmdAddr(short_address),
DALI_CMD_QUERY_MIN_LEVEL);
}
std::optional<uint8_t> DaliGatewayBridge::queryMaxLevel(int short_address) const {
return dali_.queryRaw(gateway_id_, makeShortCmdAddr(short_address),
DALI_CMD_QUERY_MAX_LEVEL);
}
std::optional<uint8_t> DaliGatewayBridge::queryPowerOnLevel(int short_address) const {
return dali_.queryRaw(gateway_id_, makeShortCmdAddr(short_address),
DALI_CMD_QUERY_POWER_ON_LEVEL);
}
std::optional<uint8_t> DaliGatewayBridge::querySystemFailureLevel(int short_address) const {
return dali_.queryRaw(gateway_id_, makeShortCmdAddr(short_address),
DALI_CMD_QUERY_SYSTEM_FAILURE_LEVEL);
}
std::optional<uint8_t> DaliGatewayBridge::queryFadeTimeRate(int short_address) const {
return dali_.queryRaw(gateway_id_, makeShortCmdAddr(short_address),
DALI_CMD_QUERY_FADE_TIME_FADE_RATE);
}
std::optional<uint8_t> DaliGatewayBridge::queryFadeTime(int short_address) const {
return dali_.queryRaw(gateway_id_, makeShortCmdAddr(short_address),
DALI_CMD_QUERY_EXTENDED_FADE_TIME);
}
std::optional<uint16_t> DaliGatewayBridge::queryGroups(int short_address) const {
return dali_.queryGroupMask(gateway_id_, short_address);
}
std::optional<uint8_t> DaliGatewayBridge::querySceneLevel(int short_address,
uint8_t scene) const {
return dali_.querySceneLevel(gateway_id_, short_address, scene & 0x0F);
}
// ---- DT8 ----
bool DaliGatewayBridge::setColourTemperature(int short_address, int kelvin) const {
return dali_.setColTemp(gateway_id_, short_address, kelvin);
}
bool DaliGatewayBridge::setColourRGB(int short_address, uint8_t r, uint8_t g,
uint8_t b) const {
return dali_.setColourRGB(gateway_id_, short_address, r, g, b);
}
std::optional<DaliDomainSnapshot> DaliGatewayBridge::dt8StatusSnapshot(
int short_address) const {
return dali_.dt8StatusSnapshot(gateway_id_, short_address);
}
std::optional<DaliDomainSnapshot> DaliGatewayBridge::dt8SceneColorReport(
int short_address, int scene) const {
return dali_.dt8SceneColorReport(gateway_id_, short_address, scene);
}
// ---- Scenes & groups ----
bool DaliGatewayBridge::setDtr(uint8_t value) const {
return dali_.sendRaw(gateway_id_, makeBroadcastCmdAddr(),
DALI_CMD_SPECIAL_SET_DTR0) &&
dali_.sendRaw(gateway_id_, makeBroadcastCmdAddr(), value);
}
bool DaliGatewayBridge::setDtrAsScene(DaliTarget target, uint8_t scene) const {
return sendRaw(target, DALI_CMD_SET_SCENE(scene & 0x0F));
}
bool DaliGatewayBridge::addToGroup(DaliTarget target, uint8_t group) const {
return sendRaw(target, DALI_CMD_ADD_TO_GROUP(group & 0x0F));
}
bool DaliGatewayBridge::removeFromGroup(DaliTarget target, uint8_t group) const {
return sendRaw(target, DALI_CMD_REMOVE_FROM_GROUP(group & 0x0F));
}
bool DaliGatewayBridge::removeFromScene(DaliTarget target, uint8_t scene) const {
return sendRaw(target, DALI_CMD_REMOVE_SCENE(scene & 0x0F));
}
bool DaliGatewayBridge::setSceneLevel(DaliTarget target, uint8_t scene,
uint8_t level) const {
return setDtr(level) && setDtrAsScene(target, scene);
}
// ---- Commissioning ----
bool DaliGatewayBridge::initialise(DaliTarget target) const {
return sendRaw(target, DALI_CMD_SPECIAL_INITIALIZE);
}
bool DaliGatewayBridge::randomise() const {
return sendRaw({DaliTargetKind::kBroadcast, 0}, DALI_CMD_SPECIAL_RANDOMIZE);
}
bool DaliGatewayBridge::searchAddrH(uint8_t high) const {
return dali_.sendRaw(gateway_id_, makeBroadcastCmdAddr(),
DALI_CMD_SPECIAL_SEARCHADDRH) &&
dali_.sendRaw(gateway_id_, makeBroadcastCmdAddr(), high);
}
bool DaliGatewayBridge::searchAddrM(uint8_t middle) const {
return dali_.sendRaw(gateway_id_, makeBroadcastCmdAddr(),
DALI_CMD_SPECIAL_SEARCHADDRM) &&
dali_.sendRaw(gateway_id_, makeBroadcastCmdAddr(), middle);
}
bool DaliGatewayBridge::searchAddrL(uint8_t low) const {
return dali_.sendRaw(gateway_id_, makeBroadcastCmdAddr(),
DALI_CMD_SPECIAL_SEARCHADDRL) &&
dali_.sendRaw(gateway_id_, makeBroadcastCmdAddr(), low);
}
bool DaliGatewayBridge::compare() const {
return sendRaw({DaliTargetKind::kBroadcast, 0}, DALI_CMD_SPECIAL_COMPARE);
}
bool DaliGatewayBridge::withdraw() const {
return sendRaw({DaliTargetKind::kBroadcast, 0}, DALI_CMD_SPECIAL_WITHDRAW);
}
bool DaliGatewayBridge::terminate() const {
return sendRaw({DaliTargetKind::kBroadcast, 0}, DALI_CMD_SPECIAL_TERMINATE);
}
bool DaliGatewayBridge::programShort(DaliTarget target, uint8_t short_address) const {
const uint8_t raw = (short_address << 1) | 0x01;
return dali_.sendRaw(gateway_id_, encodeDaliRawAddr(target),
DALI_CMD_SPECIAL_PROGRAM_SHORT_ADDRESS) &&
dali_.sendRaw(gateway_id_, encodeDaliRawAddr(target), raw);
}
bool DaliGatewayBridge::verifyShort(DaliTarget target) const {
return sendRaw(target, DALI_CMD_SPECIAL_VERIFY_SHORT_ADDRESS);
}
std::optional<uint8_t> DaliGatewayBridge::queryShort(DaliTarget target) const {
return dali_.queryRaw(gateway_id_, encodeDaliRawAddr(target),
DALI_CMD_SPECIAL_QUERY_SHORT_ADDRESS);
}
bool DaliGatewayBridge::allocateAllAddr(int start_address) const {
return dali_.allocateAllAddr(gateway_id_, start_address);
}
void DaliGatewayBridge::stopAllocAddr() const {
dali_.stopAllocAddr(gateway_id_);
}
bool DaliGatewayBridge::resetAndAllocAddr(int start_address, bool remove_addr_first,
bool close_light) const {
return dali_.resetAndAllocAddr(gateway_id_, start_address, remove_addr_first, close_light);
}
bool DaliGatewayBridge::resetBus() const {
return dali_.resetBus(gateway_id_);
}
} // namespace knx_dali_gw
} // namespace gateway
@@ -0,0 +1,40 @@
#include "dali_helper.h"
uint8_t DaliHelper::percentToArc(uint8_t value)
{
if(value == 0)
{
return 0;
}
//Todo also include _max
uint8_t arc = roundToInt(((253/3.0)*(std::log10(value)+1)) + 1);
return arc;
}
uint8_t DaliHelper::arcToPercent(uint8_t value)
{
if(value == 0)
{
return 0;
}
//Todo also include _max
double arc = std::pow(10, ((value-1) / (253/3.0)) - 1);
return roundToInt(arc);
}
float DaliHelper::arcToPercentFloat(uint8_t value)
{
if(value == 0)
{
return 0;
}
//Todo also include _max
float arc = std::pow(10, ((value-1) / (253/3.0)) - 1);
return arc;
}
uint8_t DaliHelper::roundToInt(double input)
{
double temp = input + 0.5;
return (uint8_t)temp;
}
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include <cstdint>
#include <cmath>
class DaliHelper
{
public:
static uint8_t percentToArc(uint8_t value);
static uint8_t arcToPercent(uint8_t value);
static float arcToPercentFloat(uint8_t value);
static uint8_t roundToInt(double input);
};
+15
View File
@@ -0,0 +1,15 @@
#include "hcl_curve.h"
#include "esp_timer.h"
namespace gateway {
namespace knx_dali_gw {
void HclCurve::setup(uint8_t index) { index_ = index; }
void HclCurve::loop() {
// HCL curve logic — simplified for now.
// Full port from HclCurve.cpp in subsequent iteration.
}
} // namespace knx_dali_gw
} // namespace gateway
+23
View File
@@ -0,0 +1,23 @@
#pragma once
#include <cstdint>
namespace gateway {
namespace knx_dali_gw {
class HclCurve {
public:
void setup(uint8_t index);
void loop();
private:
uint8_t index_{0};
bool is_configured_{false};
uint8_t type_{0};
uint64_t last_check_{0};
uint8_t last_day_{0};
uint8_t last_minute_{0};
};
} // namespace knx_dali_gw
} // namespace gateway
@@ -0,0 +1,184 @@
#include "knx_dali_channel.h"
#include "dali_define.hpp"
#include "knxprod.h"
#include "dali_helper.h"
#include "esp_log.h"
#include "esp_timer.h"
namespace gateway {
namespace knx_dali_gw {
KnxDaliChannel::KnxDaliChannel() = default;
KnxDaliChannel::~KnxDaliChannel() = default;
void KnxDaliChannel::init(uint8_t channel_index, bool is_group, DaliGatewayBridge& bridge) {
index_ = channel_index;
is_group_ = is_group;
dali_ = &bridge;
}
void KnxDaliChannel::setup() {
if (dali_ == nullptr) return;
// Query initial state
DaliTarget target = is_group_ ? DaliTarget{DaliTargetKind::kGroup, static_cast<int>(index_)}
: DaliTarget{DaliTargetKind::kShortAddress, static_cast<int>(index_)};
(void)target; // Will be used in full port
}
void KnxDaliChannel::loop() {
if (dali_ == nullptr) return;
loopDimming();
loopStaircase();
loopQueryLevel();
}
void KnxDaliChannel::processInputKo(GroupObject& ko) {
uint16_t asap = ko.asap();
int slot = static_cast<int>(asap) - (is_group_ ? GRP_KoOffset : ADR_KoOffset) - index_ * (is_group_ ? GRP_KoBlockSize : ADR_KoBlockSize);
// TODO: Full slot-to-handler mapping from DaliChannel.cpp
// For now, delegate to basic handlers
switch (slot) {
case 0: koHandleSwitch(ko); break;
// ... more slots
default: break;
}
}
// ---- Dimming ----
void KnxDaliChannel::loopDimming() {
if (dimm_direction_ == DimmDirection::kNone) return;
uint64_t now = esp_timer_get_time() / 1000ULL;
if (now - dimm_last_ < dimm_interval_) return;
dimm_last_ = now;
DaliTarget target = is_group_ ? DaliTarget{DaliTargetKind::kGroup, static_cast<int>(index_)}
: DaliTarget{DaliTargetKind::kShortAddress, static_cast<int>(index_)};
if (dimm_direction_ == DimmDirection::kUp) {
if (current_step_ < max_) current_step_++;
dali_->setArc(target, current_step_);
} else {
if (current_step_ > min_) current_step_--;
dali_->setArc(target, current_step_);
}
}
// ---- Staircase ----
void KnxDaliChannel::loopStaircase() {
if (interval_ == 0 || !current_state_) return;
uint64_t now = esp_timer_get_time() / 1000ULL;
if (now - start_time_ >= interval_ * 1000ULL) {
current_state_ = false;
interval_ = 0;
DaliTarget target = is_group_ ? DaliTarget{DaliTargetKind::kGroup, static_cast<int>(index_)}
: DaliTarget{DaliTargetKind::kShortAddress, static_cast<int>(index_)};
dali_->off(target);
}
}
// ---- Query Level ----
void KnxDaliChannel::loopQueryLevel() {
// Periodic status query — simplified for now
}
// ---- Switch State ----
void KnxDaliChannel::setSwitchState(bool value, bool is_switch_command) {
if (current_is_locked_) return;
current_state_ = value;
DaliTarget target = is_group_ ? DaliTarget{DaliTargetKind::kGroup, static_cast<int>(index_)}
: DaliTarget{DaliTargetKind::kShortAddress, static_cast<int>(index_)};
if (value) {
dali_->on(target);
} else {
dali_->off(target);
}
if (value) {
start_time_ = esp_timer_get_time() / 1000ULL;
}
}
// ---- Configuration setters ----
void KnxDaliChannel::setOnValue(uint8_t value) {
on_day_ = value;
on_night_ = value / 2;
}
void KnxDaliChannel::setGroups(uint16_t groups) { groups_ = groups; }
void KnxDaliChannel::setGroupState(uint8_t group, bool state) {
if (state) groups_ |= (1 << group); else groups_ &= ~(1 << group);
}
void KnxDaliChannel::setGroupState(uint8_t group, uint8_t) {}
void KnxDaliChannel::setMinMax(uint8_t min, uint8_t max) { min_ = min; max_ = max; }
void KnxDaliChannel::setMinArc(uint8_t min) { min_ = min; }
void KnxDaliChannel::setHcl(uint8_t curve, uint16_t temp, uint8_t) {
hcl_curve_ = curve;
hcl_current_temp_ = temp;
}
// ---- Dimm State ----
void KnxDaliChannel::setDimmState(uint8_t value, bool, bool) {
current_step_ = value;
}
// ---- Color ----
void KnxDaliChannel::sendColor() {
if (dali_ == nullptr) return;
dali_->setColourRGB(static_cast<int>(index_), current_color_[0],
current_color_[1], current_color_[2]);
}
// ---- KO Handlers ----
void KnxDaliChannel::koHandleSwitch(GroupObject& ko) {
bool on = static_cast<bool>(ko.value());
setSwitchState(on);
}
void KnxDaliChannel::koHandleDimmRel(GroupObject& ko) {
int step = static_cast<int>(static_cast<float>(ko.value()));
if (step > 0) {
dimm_direction_ = DimmDirection::kUp;
dimm_step_ = static_cast<uint8_t>(step);
} else if (step < 0) {
dimm_direction_ = DimmDirection::kDown;
dimm_step_ = static_cast<uint8_t>(-step);
} else {
dimm_direction_ = DimmDirection::kNone;
}
dimm_last_ = esp_timer_get_time() / 1000ULL;
}
void KnxDaliChannel::koHandleDimmAbs(GroupObject& ko) {
uint8_t value = static_cast<uint8_t>(static_cast<float>(ko.value()) * 255.0f / 100.0f);
setDimmState(value);
dimm_direction_ = DimmDirection::kNone;
DaliTarget target = is_group_ ? DaliTarget{DaliTargetKind::kGroup, static_cast<int>(index_)}
: DaliTarget{DaliTargetKind::kShortAddress, static_cast<int>(index_)};
dali_->setArc(target, value);
}
void KnxDaliChannel::koHandleLock(GroupObject& ko) {
bool lock = static_cast<bool>(ko.value());
current_is_locked_ = lock;
}
void KnxDaliChannel::koHandleColor(GroupObject& ko) {
KNXValue val = ko.value();
if (true) {
// RGB packed in float or raw bytes
// Simplified: store and send
sendColor();
}
}
} // namespace knx_dali_gw
} // namespace gateway
@@ -0,0 +1,91 @@
#pragma once
// =============================================================================
// KnxDaliChannel — Per-address / per-group DALI channel (ported from DaliChannel)
// =============================================================================
#include "dali_gateway_bridge.h"
#include "knx/group_object.h"
#include <cstdint>
namespace gateway {
namespace knx_dali_gw {
class KnxDaliChannel {
public:
KnxDaliChannel();
~KnxDaliChannel();
void init(uint8_t channel_index, bool is_group, DaliGatewayBridge& bridge);
void setup();
void loop();
void processInputKo(GroupObject& ko);
// --- Configuration ---
void setOnValue(uint8_t value);
void setGroups(uint16_t groups);
void setGroupState(uint8_t group, bool state);
void setGroupState(uint8_t group, uint8_t value);
void setMinMax(uint8_t min, uint8_t max);
void setMinArc(uint8_t min);
void setHcl(uint8_t curve, uint16_t temp, uint8_t bri);
uint8_t getMin() const { return min_; }
uint8_t getMax() const { return max_; }
uint16_t getGroups() const { return groups_; }
bool isNight{false};
private:
enum class DimmDirection { kDown, kUp, kNone };
void loopDimming();
void loopStaircase();
void loopQueryLevel();
void sendColor();
void setSwitchState(bool value, bool is_switch_command = true);
void setDimmState(uint8_t value, bool is_dimm_command = true, bool is_last = false);
void koHandleSwitch(GroupObject& ko);
void koHandleDimmRel(GroupObject& ko);
void koHandleDimmAbs(GroupObject& ko);
void koHandleLock(GroupObject& ko);
void koHandleColor(GroupObject& ko);
DaliGatewayBridge* dali_{nullptr};
uint8_t index_{0};
bool is_group_{false};
// Dimming
DimmDirection dimm_direction_{DimmDirection::kNone};
uint8_t dimm_step_{0};
uint64_t dimm_last_{0};
uint8_t dimm_interval_{100};
// Staircase
uint64_t start_time_{0};
uint32_t interval_{0};
// Limits
uint8_t min_{0};
uint8_t max_{254};
uint8_t on_day_{100};
uint8_t on_night_{10};
// State
bool current_state_{false};
uint8_t current_step_{0};
bool current_is_locked_{false};
uint8_t current_color_[4]{};
// HCL
uint8_t hcl_curve_{255};
uint16_t hcl_current_temp_{0};
// Groups
uint16_t groups_{0};
};
} // namespace knx_dali_gw
} // namespace gateway
+106
View File
@@ -0,0 +1,106 @@
#include "knx_dali_gw.hpp"
#include "knx/bau07B0.h"
#include "esp_log.h"
namespace gateway {
namespace knx_dali_gw {
namespace {
constexpr const char* kTag = "knx_dali_gw";
} // namespace
// =============================================================================
// KnxDaliGateway::Impl
// =============================================================================
struct KnxDaliGateway::Impl {
KnxDaliGatewayConfig config;
gateway::openknx::EspIdfPlatform platform;
Bau07B0 device;
bool initialized{false};
explicit Impl(const KnxDaliGatewayConfig& cfg)
: config(cfg),
platform(nullptr, cfg.nvs_namespace.c_str()),
device(platform) {}
bool init() {
if (initialized) return true;
device.deviceObject().manufacturerId(0x00a4);
device.deviceObject().bauNumber(platform.uniqueSerialNumber());
const uint8_t order_number[10] = {'R', 'E', 'G', '1', '-', 'D', 'a', 'l', 'i', 0};
device.deviceObject().orderNumber(order_number);
const uint8_t program_version[5] = {0x00, 0xa4, 0x00, 0x01, 0x05};
device.parameters().property(PID_PROG_VERSION)->write(program_version);
device.readMemory();
if (!device.configured()) {
ESP_LOGW(kTag, "KNX device is not configured (blank ETS memory). "
"Individual address: 0x%04X (fallback).",
config.fallback_individual_address);
}
device.enabled(true);
initialized = true;
ESP_LOGI(kTag, "KNX-DALI gateway initialized");
return true;
}
void loop() {
if (!initialized) return;
device.loop();
}
void setNetworkInterface(esp_netif_t* netif) {
platform.networkInterface(netif);
}
};
// =============================================================================
// Public API
// =============================================================================
KnxDaliGateway::KnxDaliGateway(const KnxDaliGatewayConfig& config)
: impl_(std::make_unique<Impl>(config)) {}
KnxDaliGateway::~KnxDaliGateway() = default;
bool KnxDaliGateway::init() { return impl_->init(); }
void KnxDaliGateway::loop() { impl_->loop(); }
Bau07B0& KnxDaliGateway::knxDevice() { return impl_->device; }
const Bau07B0& KnxDaliGateway::knxDevice() const { return impl_->device; }
void KnxDaliGateway::setNetworkInterface(esp_netif_t* netif) {
impl_->setNetworkInterface(netif);
}
bool KnxDaliGateway::handleTunnelFrame(const uint8_t* data, size_t len) {
// TODO: Implement cEMI tunnel frame handling.
(void)data; (void)len;
return false;
}
bool KnxDaliGateway::handleBusFrame(const uint8_t* data, size_t len) {
// TODO: Implement bus frame handling.
(void)data; (void)len;
return false;
}
bool KnxDaliGateway::emitGroupValue(uint16_t group_object_number,
const uint8_t* data, size_t len) {
(void)group_object_number; (void)data; (void)len;
// TODO(Phase 3): Implement with proper KNXValue conversion.
return false;
}
} // namespace knx_dali_gw
} // namespace gateway
@@ -0,0 +1,679 @@
#include "knx_dali_module.h"
#include "knx/bau07B0.h"
#include "knx/group_object.h"
#include "dali_define.hpp"
#include "esp_log.h"
#include "esp_timer.h"
#include <algorithm>
#include <cstdio>
#include <cstring>
namespace gateway {
namespace knx_dali_gw {
namespace {
constexpr const char* kLogTag = "knx_dali_module";
constexpr uint8_t kDaliBroadcastAddr = 0xFE;
} // namespace
// =============================================================================
// Constructor / Destructor
// =============================================================================
KnxDaliModule::KnxDaliModule() {
std::memset(addresses_, 0, sizeof(addresses_));
std::memset(ballasts_, 0, sizeof(ballasts_));
}
KnxDaliModule::~KnxDaliModule() = default;
// =============================================================================
// Setup
// =============================================================================
void KnxDaliModule::setup(Bau07B0& device, DaliGatewayBridge& bridge) {
device_ = &device;
dali_ = &bridge;
for (int i = 0; i < 64; i++) {
channels_[i].init(i, false, bridge);
}
for (int i = 0; i < 16; i++) {
groups_[i].init(i, true, bridge);
}
for (int i = 0; i < 3; i++) {
curves_[i].setup(static_cast<uint8_t>(i));
}
}
// =============================================================================
// Main Loop
// =============================================================================
void KnxDaliModule::loop(bool configured) {
if (!configured || device_ == nullptr) return;
loopMessages();
loopAddressing();
loopAssigning();
loopBusState();
loopInitData();
loopGroupState();
for (auto& ch : channels_) ch.loop();
for (auto& grp : groups_) grp.loop();
for (auto& curve : curves_) curve.loop();
}
// =============================================================================
// Message Queue Execution
// =============================================================================
void KnxDaliModule::loopMessages() {
if (dali_ == nullptr) return;
Message msg;
while (queue_.pop(msg)) {
DaliTarget target;
switch (msg.addrtype) {
case 0: target = {DaliTargetKind::kShortAddress, static_cast<int>(msg.para1)}; break;
case 1: target = {DaliTargetKind::kGroup, static_cast<int>(msg.para1)}; break;
default: target = {DaliTargetKind::kBroadcast, 0}; break;
}
switch (msg.type) {
case MessageType::Arc:
dali_->setArc(target, msg.data);
break;
case MessageType::Cmd:
dali_->sendRaw(target, msg.data);
break;
case MessageType::SpecialCmd:
dali_->sendRaw(target, msg.data);
break;
case MessageType::Query:
if (auto resp = dali_->queryRaw(target, msg.data)) {
queue_.setResponse(msg.id, *resp);
} else {
queue_.setResponse(msg.id, -1);
}
break;
}
}
}
// =============================================================================
// Addressing State Machine
// =============================================================================
void KnxDaliModule::loopAddressing() {
if (adr_state_ == AddressingState::kOff || dali_ == nullptr) return;
switch (adr_state_) {
case AddressingState::kOff:
break;
case AddressingState::kInit:
adr_found_ = 0;
adr_iterations_ = 0;
ESP_LOGI(kLogTag, "Addressing: init (only_new=%d, randomize=%d, delete_all=%d)",
adr_only_new_, adr_randomize_, adr_delete_all_);
dali_->sendRaw({DaliTargetKind::kBroadcast, 0}, DALI_CMD_SPECIAL_INITIALIZE);
adr_state_ = AddressingState::kInit2;
break;
case AddressingState::kInit2:
dali_->sendRaw({DaliTargetKind::kBroadcast, 0}, DALI_CMD_SPECIAL_INITIALIZE);
if (adr_delete_all_) {
adr_state_ = AddressingState::kWriteDtr;
} else if (adr_randomize_) {
adr_state_ = AddressingState::kRandom;
} else {
adr_state_ = AddressingState::kStartSearch;
}
break;
case AddressingState::kWriteDtr:
dali_->setDtr(255);
adr_state_ = AddressingState::kRemoveShort;
break;
case AddressingState::kRemoveShort: {
dali_->sendRaw({DaliTargetKind::kBroadcast, 0}, DALI_CMD_STORE_DTR_AS_SHORT_ADDRESS);
adr_state_ = AddressingState::kRemoveShort2;
break;
}
case AddressingState::kRemoveShort2:
dali_->sendRaw({DaliTargetKind::kBroadcast, 0}, DALI_CMD_STORE_DTR_AS_SHORT_ADDRESS);
if (adr_randomize_) {
adr_state_ = AddressingState::kRandom;
} else {
adr_state_ = AddressingState::kStartSearch;
}
break;
case AddressingState::kRandom:
dali_->randomise();
adr_state_ = AddressingState::kRandom2;
break;
case AddressingState::kRandom2:
dali_->randomise();
adr_state_ = AddressingState::kRandomWait;
break;
case AddressingState::kRandomWait:
vTaskDelay(pdMS_TO_TICKS(100));
adr_state_ = AddressingState::kStartSearch;
break;
case AddressingState::kStartSearch:
adr_search_ = 0xFFFFFF;
adr_state_ = AddressingState::kSearchHigh;
break;
case AddressingState::kSearchHigh:
dali_->searchAddrH(static_cast<uint8_t>((adr_search_ >> 16) & 0xFF));
adr_state_ = AddressingState::kSearchMid;
break;
case AddressingState::kSearchMid:
dali_->searchAddrM(static_cast<uint8_t>((adr_search_ >> 8) & 0xFF));
adr_state_ = AddressingState::kSearchLow;
break;
case AddressingState::kSearchLow:
dali_->searchAddrL(static_cast<uint8_t>(adr_search_ & 0xFF));
adr_state_ = AddressingState::kCompare;
break;
case AddressingState::kCompare: {
dali_->compare();
adr_state_ = AddressingState::kCheckFound;
break;
}
case AddressingState::kCheckFound: {
// Binary search: query short address to check if a device responded.
auto resp = dali_->queryShort({DaliTargetKind::kBroadcast, 0});
bool found = resp.has_value() && *resp != 0xFF;
if (adr_iterations_ < 24) {
int64_t delta = static_cast<int64_t>(1) << (23 - adr_iterations_);
if (found) {
adr_search_ += delta;
} else {
adr_search_ -= delta;
}
adr_iterations_++;
adr_state_ = AddressingState::kSearchHigh;
} else {
if (found) {
adr_state_ = AddressingState::kGetShort;
} else {
// Check one address higher
adr_search_++;
if (adr_search_ > 0xFFFFFF) {
adr_state_ = AddressingState::kTerminate;
} else {
adr_iterations_ = 0;
adr_state_ = AddressingState::kSearchHigh;
}
}
}
break;
}
case AddressingState::kGetShort: {
auto short_addr = dali_->queryShort({DaliTargetKind::kBroadcast, 0});
if (short_addr.has_value()) {
ballasts_[adr_found_].address = *short_addr;
ballasts_[adr_found_].high = static_cast<uint8_t>((adr_search_ >> 16) & 0xFF);
ballasts_[adr_found_].middle = static_cast<uint8_t>((adr_search_ >> 8) & 0xFF);
ballasts_[adr_found_].low = static_cast<uint8_t>(adr_search_ & 0xFF);
if (*short_addr == 0xFF) {
// Unaddressed — assign a free short address
int free_addr = -1;
for (int i = 0; i < 64; i++) {
if (!addresses_[i]) { free_addr = i; break; }
}
if (free_addr >= 0) {
adr_new_ = static_cast<uint8_t>(free_addr);
adr_state_ = AddressingState::kProgramShort;
} else {
adr_state_ = AddressingState::kWithdraw;
}
} else {
addresses_[*short_addr] = true;
adr_found_++;
adr_state_ = AddressingState::kWithdraw;
}
}
break;
}
case AddressingState::kProgramShort:
dali_->programShort({DaliTargetKind::kBroadcast, 0}, adr_new_);
adr_state_ = AddressingState::kVerifyShort;
break;
case AddressingState::kVerifyShort:
dali_->verifyShort({DaliTargetKind::kBroadcast, 0});
adr_state_ = AddressingState::kVerifyShortResponse;
break;
case AddressingState::kVerifyShortResponse: {
auto verify = dali_->queryShort({DaliTargetKind::kBroadcast, 0});
if (verify.has_value() && *verify == adr_new_) {
addresses_[adr_new_] = true;
adr_found_++;
ESP_LOGI(kLogTag, "Addressed device %d", adr_new_);
}
adr_state_ = AddressingState::kWithdraw;
break;
}
case AddressingState::kWithdraw:
dali_->withdraw();
adr_state_ = AddressingState::kStartSearch;
break;
case AddressingState::kTerminate:
dali_->terminate();
ESP_LOGI(kLogTag, "Addressing complete: %d devices found", adr_found_);
adr_state_ = AddressingState::kOff;
break;
default:
break;
}
}
// =============================================================================
// Assigning State Machine
// =============================================================================
void KnxDaliModule::loopAssigning() {
if (ass_state_ == AssigningState::kOff || dali_ == nullptr) return;
switch (ass_state_) {
case AssigningState::kOff:
break;
case AssigningState::kInit:
dali_->sendRaw({DaliTargetKind::kBroadcast, 0}, DALI_CMD_SPECIAL_INITIALIZE);
ass_state_ = AssigningState::kInit2;
break;
case AssigningState::kInit2:
dali_->sendRaw({DaliTargetKind::kBroadcast, 0}, DALI_CMD_SPECIAL_INITIALIZE);
ass_state_ = AssigningState::kQuery;
break;
case AssigningState::kQuery: {
auto level = dali_->queryActualLevel(adr_new_);
ass_state_ = AssigningState::kCheckQuery;
break;
}
case AssigningState::kCheckQuery:
// If the target address already has a device, stop
ass_state_ = AssigningState::kStartSearch;
break;
case AssigningState::kStartSearch:
adr_iterations_ = 0;
ass_state_ = AssigningState::kSearchHigh;
break;
case AssigningState::kSearchHigh:
dali_->searchAddrH(static_cast<uint8_t>((adr_search_ >> 16) & 0xFF));
ass_state_ = AssigningState::kSearchMid;
break;
case AssigningState::kSearchMid:
dali_->searchAddrM(static_cast<uint8_t>((adr_search_ >> 8) & 0xFF));
ass_state_ = AssigningState::kSearchLow;
break;
case AssigningState::kSearchLow:
dali_->searchAddrL(static_cast<uint8_t>(adr_search_ & 0xFF));
ass_state_ = AssigningState::kCompare;
break;
case AssigningState::kCompare:
dali_->compare();
ass_state_ = AssigningState::kCheckFound;
break;
case AssigningState::kCheckFound:
if (!adr_assign_) {
adr_assign_ = true;
ass_state_ = AssigningState::kWithdraw;
} else {
auto resp = dali_->queryShort({DaliTargetKind::kBroadcast, 0});
if (resp.has_value() && *resp != 0xFF) {
ass_state_ = AssigningState::kProgramShort;
} else {
ass_state_ = AssigningState::kTerminate;
}
}
break;
case AssigningState::kWithdraw:
dali_->withdraw();
adr_assign_ = true;
ass_state_ = AssigningState::kSearchHigh;
break;
case AssigningState::kProgramShort:
dali_->programShort({DaliTargetKind::kBroadcast, 0}, adr_new_);
ass_state_ = AssigningState::kVerifyShort;
break;
case AssigningState::kVerifyShort:
dali_->verifyShort({DaliTargetKind::kBroadcast, 0});
ass_state_ = AssigningState::kVerifyShortResponse;
break;
case AssigningState::kVerifyShortResponse: {
auto verify = dali_->queryShort({DaliTargetKind::kBroadcast, 0});
if (verify.has_value() && *verify == adr_new_) {
addresses_[adr_new_] = true;
ESP_LOGI(kLogTag, "Assigned short address %d", adr_new_);
}
ass_state_ = AssigningState::kTerminate;
break;
}
case AssigningState::kTerminate:
dali_->terminate();
ass_state_ = AssigningState::kOff;
break;
}
}
// =============================================================================
// Bus State / Init Data
// =============================================================================
void KnxDaliModule::loopBusState() {
if (dali_ == nullptr) return;
dali_bus_state_ = true; // Simplified: assume bus is always OK
}
void KnxDaliModule::loopInitData() {
if (got_init_data_ || device_ == nullptr || !device_->configured()) return;
// Read initial device data from all channels
for (int i = 0; i < 64; i++) {
if (!addresses_[i]) continue;
channels_[i].setup();
}
got_init_data_ = true;
}
void KnxDaliModule::loopGroupState() {
if (last_changed_group_ == 255) return;
uint8_t group_idx = last_changed_group_ & 0x0F;
bool is_group = (last_changed_group_ & 0x80) != 0;
if (is_group && group_idx < 16) {
groups_[group_idx].setGroupState(group_idx, last_changed_value_);
} else if (!is_group && group_idx < 64) {
channels_[group_idx].setGroupState(group_idx, last_changed_value_);
}
last_changed_group_ = 255;
}
// =============================================================================
// processInputKo — KNX group write dispatch
// =============================================================================
void KnxDaliModule::processInputKo(GroupObject& ko) {
if (device_ == nullptr) return;
if (adr_state_ != AddressingState::kOff) return;
if (current_lock_state_) return;
uint16_t asap = ko.asap();
ESP_LOGD(kLogTag, "processInputKo asap=%d", asap);
// Channel KOs (64 channels x N group objects each)
int adr_relative = static_cast<int>(asap) - ADR_KoOffset;
if (adr_relative >= 0 && adr_relative < ADR_KoBlockSize * 64) {
int ch = adr_relative / ADR_KoBlockSize;
if (ch < 64) {
channels_[ch].processInputKo(ko);
return;
}
}
// Group KOs (16 groups x N group objects each)
int grp_relative = static_cast<int>(asap) - GRP_KoOffset;
if (grp_relative >= 0 && grp_relative < GRP_KoBlockSize * 16) {
int grp_idx = grp_relative / GRP_KoBlockSize;
int slot = grp_relative % GRP_KoBlockSize;
if (grp_idx < 16) {
groups_[grp_idx].processInputKo(ko);
// Track group state changes
if (slot == 0) { // switch state
last_changed_group_ = 0x80 | static_cast<uint8_t>(grp_idx);
}
return;
}
}
// HCL KOs
int hcl_relative = static_cast<int>(asap) - HCL_KoOffset;
if (hcl_relative >= 0 && hcl_relative < HCL_KoBlockSize * 3) {
int curve_idx = hcl_relative / HCL_KoBlockSize;
if (curve_idx < 3) {
// HCL: apply Kelvin to all channels and groups
KNXValue val = ko.value();
if (true) {
uint16_t kelvin = static_cast<uint16_t>(static_cast<float>(val));
for (int i = 0; i < 64; i++) {
channels_[i].setHcl(static_cast<uint8_t>(curve_idx), kelvin, 255);
}
for (int i = 0; i < 16; i++) {
groups_[i].setHcl(static_cast<uint8_t>(curve_idx), kelvin, 255);
}
}
return;
}
}
}
// =============================================================================
// Function Property Handlers (stubs — full port in subsequent iteration)
// =============================================================================
bool KnxDaliModule::processFunctionProperty(uint8_t object_index, uint8_t property_id,
uint8_t length, uint8_t* data,
uint8_t* result_data, uint8_t& result_length) {
// Only handle object 160, property 1 (REG1 DALI function properties)
if (object_index != 160 || property_id != 1 || length == 0 || data == nullptr) {
return false;
}
switch (data[0]) {
case 2: funcHandleType(data, result_data, result_length); return true;
case 3: funcHandleScan(data, result_data, result_length); return true;
case 4: funcHandleAssign(data, result_data, result_length); return true;
case 10: funcHandleEvgWrite(data, result_data, result_length); return true;
case 11: funcHandleEvgRead(data, result_data, result_length); return true;
case 12: funcHandleSetScene(data, result_data, result_length); return true;
case 13: funcHandleGetScene(data, result_data, result_length); return true;
case 14: funcHandleIdentify(data, result_data, result_length); return true;
default: return false;
}
}
bool KnxDaliModule::processFunctionPropertyState(uint8_t object_index, uint8_t property_id,
uint8_t length, uint8_t* data,
uint8_t* result_data, uint8_t& result_length) {
if (object_index != 160 || property_id != 1 || length == 0 || data == nullptr) {
return false;
}
switch (data[0]) {
case 3:
case 5: stateHandleScanAndAddress(data, result_data, result_length); return true;
case 4: stateHandleAssign(data, result_data, result_length); return true;
case 7: stateHandleFoundEVGs(data, result_data, result_length); return true;
default: return false;
}
}
// =============================================================================
// Function Property Implementations (simplified stubs)
// =============================================================================
void KnxDaliModule::funcHandleType(uint8_t*, uint8_t* result_data, uint8_t& result_length) {
// Query device type(s) for the selected short address
result_data[0] = 0; // working
result_length = 1;
}
void KnxDaliModule::funcHandleScan(uint8_t* data, uint8_t* result_data, uint8_t& result_length) {
if (data == nullptr) return;
adr_only_new_ = (data[1] & 0x01) != 0;
adr_randomize_ = (data[1] & 0x02) != 0;
adr_delete_all_ = (data[1] & 0x04) != 0;
adr_state_ = AddressingState::kInit;
result_data[0] = 0; // working
result_length = 1;
}
void KnxDaliModule::funcHandleAssign(uint8_t* data, uint8_t* result_data, uint8_t& result_length) {
if (data == nullptr) return;
adr_search_ = (static_cast<uint64_t>(data[1]) << 16) |
(static_cast<uint64_t>(data[2]) << 8) | data[3];
adr_new_ = data[4];
if (adr_new_ == 99) adr_new_ = 255; // "remove short address"
ass_state_ = AssigningState::kInit;
result_data[0] = 0;
result_length = 1;
}
void KnxDaliModule::funcHandleEvgWrite(uint8_t*, uint8_t*, uint8_t&) {}
void KnxDaliModule::funcHandleEvgRead(uint8_t*, uint8_t*, uint8_t&) {}
void KnxDaliModule::funcHandleSetScene(uint8_t*, uint8_t*, uint8_t&) {}
void KnxDaliModule::funcHandleGetScene(uint8_t*, uint8_t*, uint8_t&) {}
void KnxDaliModule::funcHandleIdentify(uint8_t*, uint8_t*, uint8_t&) {}
void KnxDaliModule::stateHandleType(uint8_t*, uint8_t*, uint8_t&) {}
void KnxDaliModule::stateHandleAssign(uint8_t*, uint8_t*, uint8_t&) {}
void KnxDaliModule::stateHandleScanAndAddress(uint8_t*, uint8_t*, uint8_t&) {}
void KnxDaliModule::stateHandleFoundEVGs(uint8_t*, uint8_t*, uint8_t&) {}
// =============================================================================
// Public state accessors
// =============================================================================
bool KnxDaliModule::isAddressingActive() const {
return adr_state_ != AddressingState::kOff || ass_state_ != AssigningState::kOff;
}
bool KnxDaliModule::isLocked() const { return current_lock_state_; }
void KnxDaliModule::setLocked(bool locked) { current_lock_state_ = locked; }
bool KnxDaliModule::isNight() const { return is_night_; }
void KnxDaliModule::setNight(bool night) { is_night_ = night; }
uint8_t KnxDaliModule::lastChangedGroup() const { return last_changed_group_; }
uint8_t KnxDaliModule::lastChangedValue() const { return last_changed_value_; }
KnxDaliChannel& KnxDaliModule::channel(int index) { return channels_[index]; }
KnxDaliChannel& KnxDaliModule::group(int index) { return groups_[index]; }
HclCurve& KnxDaliModule::curve(int index) { return curves_[index]; }
// =============================================================================
// DALI Send Helpers
// =============================================================================
uint8_t KnxDaliModule::sendMsg(MessageType type, uint8_t addr, uint8_t val,
uint8_t addr_type, bool wait) {
Message* msg = new Message();
msg->type = type;
msg->data = val;
msg->addrtype = addr_type;
msg->para1 = addr;
return queue_.push(msg);
}
uint8_t KnxDaliModule::sendCmd(uint8_t addr, uint8_t value, uint8_t addr_type, bool wait) {
return sendMsg(MessageType::Cmd, addr, value, addr_type, wait);
}
uint8_t KnxDaliModule::sendSpecialCmd(uint8_t command, uint8_t value, bool wait) {
return sendMsg(MessageType::SpecialCmd, command, value, 2, wait);
}
uint8_t KnxDaliModule::sendArc(uint8_t addr, uint8_t value, uint8_t addr_type) {
return sendMsg(MessageType::Arc, addr, value, addr_type, false);
}
int16_t KnxDaliModule::getInfo(uint8_t address, int command, uint8_t additional) {
(void)additional;
uint8_t msg_id = sendMsg(MessageType::Query, address, static_cast<uint8_t>(command), 0, true);
// Wait for response
for (int i = 0; i < 300; i++) {
vTaskDelay(pdMS_TO_TICKS(1));
int16_t resp = queue_.getResponse(msg_id);
if (resp != -200) return resp;
}
return -1;
}
// =============================================================================
// KO Handlers
// =============================================================================
void KnxDaliModule::koHandleSwitch(GroupObject& ko) {
KNXValue val = ko.value();
bool on = static_cast<bool>(val);
if (dali_ != nullptr) {
if (on) {
dali_->on({DaliTargetKind::kBroadcast, 0});
} else {
dali_->off({DaliTargetKind::kBroadcast, 0});
}
}
}
void KnxDaliModule::koHandleDimm(GroupObject& ko) {
KNXValue val = ko.value();
uint8_t percent = static_cast<uint8_t>(static_cast<float>(val) * 255.0f / 100.0f);
uint8_t arc = PercentToArc(static_cast<double>(percent) * 100.0 / 255.0);
if (dali_ != nullptr) {
dali_->setArc({DaliTargetKind::kBroadcast, 0}, arc);
}
}
void KnxDaliModule::koHandleDayNight(GroupObject& ko) {
is_night_ = static_cast<bool>(ko.value());
for (int i = 0; i < 64; i++) channels_[i].isNight = is_night_;
for (int i = 0; i < 16; i++) groups_[i].isNight = is_night_;
}
void KnxDaliModule::koHandleOnValue(GroupObject& ko) {
uint8_t on_value = static_cast<uint8_t>(static_cast<float>(ko.value()) * 255.0f / 100.0f);
for (int i = 0; i < 64; i++) channels_[i].setOnValue(on_value);
for (int i = 0; i < 16; i++) groups_[i].setOnValue(on_value);
}
void KnxDaliModule::koHandleScene(GroupObject& ko) {
uint8_t scene = static_cast<uint8_t>(ko.value());
if (dali_ != nullptr) {
dali_->goToScene({DaliTargetKind::kBroadcast, 0}, scene);
}
}
} // namespace knx_dali_gw
} // namespace gateway
@@ -0,0 +1,166 @@
#pragma once
// =============================================================================
// KnxDaliModule — Core DALI gateway module (ported from DaliModule)
// =============================================================================
// Handles:
// - DALI message queuing and execution
// - DALI commissioning (addressing + assigning state machines)
// - KNX group-object dispatch (processInputKo)
// - KNX function-property commands (ETS programming)
// - Broadcast switch/dim/scene handling
#include "dali_gateway_bridge.h"
#include "knx_dali_channel.h"
#include "hcl_curve.h"
#include "message_queue.h"
#include "ballast.hpp"
#include "knxprod.h"
#include "knx/group_object.h"
#include <cstdint>
#include <functional>
#include <string>
#include <vector>
// Forward declarations
class Bau07B0;
namespace gateway {
namespace knx_dali_gw {
class KnxDaliModule {
public:
enum class AddressingState {
kOff, kInit, kInit2, kWriteDtr, kRemoveShort, kRemoveShort2,
kRandom, kRandom2, kRandomWait, kStartSearch, kSearchHigh,
kSearchMid, kSearchLow, kCompare, kGetShort, kCheckFound,
kProgramShort, kVerifyShort, kVerifyShortResponse, kWithdraw,
kTerminate, kSearchShort, kCheckSearchShort
};
enum class AssigningState {
kOff, kInit, kInit2, kQuery, kCheckQuery, kStartSearch,
kSearchHigh, kSearchMid, kSearchLow, kCompare, kCheckFound,
kWithdraw, kProgramShort, kVerifyShort, kVerifyShortResponse,
kTerminate
};
KnxDaliModule();
~KnxDaliModule();
// ---- Lifecycle ----
void setup(Bau07B0& device, DaliGatewayBridge& bridge);
void loop(bool configured);
// ---- KNX input ----
void processInputKo(GroupObject& ko);
// ---- Function properties (ETS programming) ----
bool processFunctionProperty(uint8_t object_index, uint8_t property_id,
uint8_t length, uint8_t* data,
uint8_t* result_data, uint8_t& result_length);
bool processFunctionPropertyState(uint8_t object_index, uint8_t property_id,
uint8_t length, uint8_t* data,
uint8_t* result_data, uint8_t& result_length);
// ---- Public state ----
bool isAddressingActive() const;
bool isLocked() const;
void setLocked(bool locked);
bool isNight() const;
void setNight(bool night);
uint8_t lastChangedGroup() const;
uint8_t lastChangedValue() const;
// ---- Channel / group access ----
KnxDaliChannel& channel(int index);
KnxDaliChannel& group(int index);
HclCurve& curve(int index);
private:
// ---- DALI helpers ----
uint8_t sendMsg(MessageType type, uint8_t addr, uint8_t value,
uint8_t addr_type = 0, bool wait = false);
uint8_t sendCmd(uint8_t addr, uint8_t value, uint8_t addr_type = 0,
bool wait = false);
uint8_t sendSpecialCmd(uint8_t command, uint8_t value = 0, bool wait = false);
uint8_t sendArc(uint8_t addr, uint8_t value, uint8_t addr_type);
int16_t getInfo(uint8_t address, int command, uint8_t additional = 0);
// ---- KNX KO handlers ----
void koHandleSwitch(GroupObject& ko);
void koHandleDimm(GroupObject& ko);
void koHandleDayNight(GroupObject& ko);
void koHandleOnValue(GroupObject& ko);
void koHandleScene(GroupObject& ko);
// ---- Function property handlers ----
void funcHandleType(uint8_t* data, uint8_t* result_data, uint8_t& result_length);
void funcHandleScan(uint8_t* data, uint8_t* result_data, uint8_t& result_length);
void funcHandleAssign(uint8_t* data, uint8_t* result_data, uint8_t& result_length);
void funcHandleEvgWrite(uint8_t* data, uint8_t* result_data, uint8_t& result_length);
void funcHandleEvgRead(uint8_t* data, uint8_t* result_data, uint8_t& result_length);
void funcHandleSetScene(uint8_t* data, uint8_t* result_data, uint8_t& result_length);
void funcHandleGetScene(uint8_t* data, uint8_t* result_data, uint8_t& result_length);
void funcHandleIdentify(uint8_t* data, uint8_t* result_data, uint8_t& result_length);
// ---- State handlers ----
void stateHandleType(uint8_t* data, uint8_t* result_data, uint8_t& result_length);
void stateHandleAssign(uint8_t* data, uint8_t* result_data, uint8_t& result_length);
void stateHandleScanAndAddress(uint8_t* data, uint8_t* result_data,
uint8_t& result_length);
void stateHandleFoundEVGs(uint8_t* data, uint8_t* result_data,
uint8_t& result_length);
// ---- Loops ----
void loopMessages();
void loopAddressing();
void loopAssigning();
void loopBusState();
void loopInitData();
void loopGroupState();
// ---- State ----
Bau07B0* device_{nullptr};
DaliGatewayBridge* dali_{nullptr};
// Addressing / commissioning
AddressingState adr_state_{AddressingState::kOff};
AssigningState ass_state_{AssigningState::kOff};
Ballast ballasts_[64];
bool addresses_[64]{};
int adr_found_{0};
uint8_t adr_new_{0};
uint8_t last_bus_state_{2};
uint8_t adr_iterations_{0};
uint64_t adr_search_{0};
bool adr_assign_{false};
bool adr_only_new_{false};
bool adr_randomize_{false};
bool adr_delete_all_{false};
// Group state
uint8_t last_changed_group_{255};
uint8_t last_changed_value_{0};
// Bus
bool got_init_data_{false};
bool dali_bus_state_{true};
bool dali_bus_state_to_set_{true};
uint64_t dali_state_last_{1};
// Lock / night
bool current_lock_state_{false};
bool is_night_{false};
// Channels / groups / curves
KnxDaliChannel channels_[64];
KnxDaliChannel groups_[16];
HclCurve curves_[3];
MessageQueue queue_;
};
} // namespace knx_dali_gw
} // namespace gateway
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#include <cstdint>
enum class MessageType {
Arc,
Cmd,
SpecialCmd,
Query
};
struct Message {
Message *next{nullptr};
uint8_t data{0};
MessageType type{MessageType::Arc};
uint8_t para1{0};
uint8_t addrtype{0};
uint8_t para2{0};
bool wait{false};
uint8_t id{0};
};
@@ -0,0 +1,74 @@
#include "message_queue.h"
#include "esp_timer.h"
uint8_t MessageQueue::push(Message *msg)
{
while(isLocked) ;
isLocked = true;
msg->next = nullptr;
if(tail == nullptr)
{
head = msg;
tail = msg;
isLocked = false;
return msg->id;
}
tail->next = msg;
tail = msg;
isLocked = false;
return msg->id;
}
bool MessageQueue::pop(Message &msg)
{
unsigned long started = esp_timer_get_time() / 1000ULL;
while(isLocked && ((esp_timer_get_time() / 1000ULL) - started < 3000)) ;
if(isLocked || head == nullptr) return false;
isLocked = true;
msg.addrtype = head->addrtype;
msg.data = head->data;
msg.id = head->id;
msg.para1 = head->para1;
msg.para2 = head->para2;
msg.type = head->type;
msg.wait = head->wait;
Message *temp = head;
if(head->next == nullptr)
{
head = nullptr;
tail = nullptr;
} else {
head = head->next;
}
delete temp;
isLocked = false;
return true;
}
uint8_t MessageQueue::getNextId()
{
currentId++;
if(currentId == 0) currentId++;
responses[currentId] = -200;
return currentId;
}
void MessageQueue::setResponse(uint8_t id, int16_t value)
{
responses[id] = value;
}
int16_t MessageQueue::getResponse(uint8_t id)
{
return responses[id];
}
@@ -0,0 +1,21 @@
#pragma once
#include <cstdint>
#include "message.hpp"
class MessageQueue
{
public:
uint8_t push(Message *msg);
bool pop(Message &msg);
uint8_t getNextId();
void setResponse(uint8_t id, int16_t value);
int16_t getResponse(uint8_t id);
private:
Message *head;
Message *tail;
uint8_t currentId = 0;
int16_t responses[256];
bool isLocked = false;
};
-78
View File
@@ -1,78 +0,0 @@
set(OPENKNX_ROOT "${CMAKE_CURRENT_LIST_DIR}/../../knx")
set(TPUART_ROOT "${CMAKE_CURRENT_LIST_DIR}/../../tpuart")
if(NOT EXISTS "${OPENKNX_ROOT}/src/knx/platform.h")
message(FATAL_ERROR "OpenKNX submodule is missing at ${OPENKNX_ROOT}")
endif()
if(NOT EXISTS "${TPUART_ROOT}/src/TPUart/DataLinkLayer.h")
message(FATAL_ERROR "TPUart submodule is missing at ${TPUART_ROOT}")
endif()
file(GLOB OPENKNX_SRCS
"${OPENKNX_ROOT}/src/knx/*.cpp"
)
if(CONFIG_GATEWAY_KNX_DATA_SECURE_SUPPORTED)
list(APPEND OPENKNX_SRCS
"${OPENKNX_ROOT}/src/knx/aes.c"
)
endif()
set(TPUART_SRCS
"${TPUART_ROOT}/src/TPUart/DataLinkLayer.cpp"
"${TPUART_ROOT}/src/TPUart/Receiver.cpp"
"${TPUART_ROOT}/src/TPUart/RepetitionFilter.cpp"
"${TPUART_ROOT}/src/TPUart/RingBuffer.cpp"
"${TPUART_ROOT}/src/TPUart/SearchBuffer.cpp"
"${TPUART_ROOT}/src/TPUart/Statistics.cpp"
"${TPUART_ROOT}/src/TPUart/SystemState.cpp"
"${TPUART_ROOT}/src/TPUart/Transmitter.cpp"
"${TPUART_ROOT}/src/TPUart.cpp"
)
idf_component_register(
SRCS
"src/arduino_compat.cpp"
"src/esp_idf_platform.cpp"
"src/ets_device_runtime.cpp"
"src/ets_memory_loader.cpp"
"src/security_storage.cpp"
"src/tpuart_uart_interface.cpp"
${OPENKNX_SRCS}
${TPUART_SRCS}
INCLUDE_DIRS
"include"
"${OPENKNX_ROOT}/src"
"${TPUART_ROOT}/src"
REQUIRES
esp_driver_gpio
esp_driver_uart
esp_netif
esp_system
esp_timer
esp_wifi
freertos
log
lwip
mbedtls
nvs_flash
)
target_compile_definitions(${COMPONENT_LIB} PUBLIC
MASK_VERSION=0x07B0
KNX_FLASH_SIZE=4096
KNX_NO_AUTOMATIC_GLOBAL_INSTANCE
KNX_NO_SPI
USE_CEMI_SERVER
)
if(CONFIG_GATEWAY_KNX_DATA_SECURE_SUPPORTED)
target_compile_definitions(${COMPONENT_LIB} PUBLIC USE_DATASECURE)
endif()
target_compile_options(${COMPONENT_LIB} PRIVATE
-Wno-unused-parameter
)
set_property(TARGET ${COMPONENT_LIB} PROPERTY CXX_STANDARD 17)
-59
View File
@@ -1,59 +0,0 @@
#pragma once
#include <stdint.h>
#ifndef DEC
#define DEC 10
#endif
#ifndef HEX
#define HEX 16
#endif
#ifndef INPUT
#define INPUT 0x0
#endif
#ifndef OUTPUT
#define OUTPUT 0x1
#endif
#ifndef INPUT_PULLUP
#define INPUT_PULLUP 0x2
#endif
#ifndef INPUT_PULLDOWN
#define INPUT_PULLDOWN 0x3
#endif
#ifndef LOW
#define LOW 0x0
#endif
#ifndef HIGH
#define HIGH 0x1
#endif
#ifndef CHANGE
#define CHANGE 2
#endif
#ifndef FALLING
#define FALLING 3
#endif
#ifndef RISING
#define RISING 4
#endif
using uint = unsigned int;
uint32_t millis();
uint32_t micros();
void delay(uint32_t millis);
void delayMicroseconds(unsigned int howLong);
void pinMode(uint32_t pin, uint32_t mode);
void digitalWrite(uint32_t pin, uint32_t value);
uint32_t digitalRead(uint32_t pin);
typedef void (*voidFuncPtr)(void);
void attachInterrupt(uint32_t pin, voidFuncPtr callback, uint32_t mode);
@@ -1,66 +0,0 @@
#pragma once
#include "knx/platform.h"
#include "esp_netif.h"
#include "lwip/sockets.h"
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
namespace gateway::openknx {
class EspIdfPlatform : public Platform {
public:
using OutboundCemiFrameCallback = bool (*)(CemiFrame& frame, void* context);
explicit EspIdfPlatform(TPUart::Interface::Abstract* interface = nullptr,
const char* nvs_namespace = "openknx");
~EspIdfPlatform() override;
void outboundCemiFrameCallback(OutboundCemiFrameCallback callback, void* context);
bool handleOutboundCemiFrame(CemiFrame& frame) override;
void networkInterface(esp_netif_t* netif);
esp_netif_t* networkInterface() const;
uint32_t currentIpAddress() override;
uint32_t currentSubnetMask() override;
uint32_t currentDefaultGateway() override;
void macAddress(uint8_t* data) override;
uint32_t uniqueSerialNumber() override;
void restart() override;
void fatalError() override;
void setupMultiCast(uint32_t addr, uint16_t port) override;
void closeMultiCast() override;
bool sendBytesMultiCast(uint8_t* buffer, uint16_t len) override;
int readBytesMultiCast(uint8_t* buffer, uint16_t maxLen) override;
int readBytesMultiCast(uint8_t* buffer, uint16_t maxLen, uint32_t& src_addr,
uint16_t& src_port) override;
bool sendBytesUniCast(uint32_t addr, uint16_t port, uint8_t* buffer,
uint16_t len) override;
uint8_t* getEepromBuffer(uint32_t size) override;
void commitToEeprom() override;
private:
esp_netif_t* effectiveNetif() const;
void loadEeprom(size_t size);
esp_netif_t* netif_{nullptr};
int udp_sock_{-1};
sockaddr_in multicast_remote_{};
sockaddr_in last_remote_{};
bool has_last_remote_{false};
std::vector<uint8_t> eeprom_;
std::string nvs_namespace_;
bool eeprom_loaded_{false};
OutboundCemiFrameCallback outbound_cemi_frame_callback_{nullptr};
void* outbound_cemi_frame_context_{nullptr};
};
} // namespace gateway::openknx
@@ -1,16 +0,0 @@
#pragma once
#include "openknx_idf/ets_memory_loader.h"
#include "openknx_idf/ets_device_runtime.h"
#include "openknx_idf/esp_idf_platform.h"
#include "openknx_idf/security_storage.h"
#include "openknx_idf/tpuart_uart_interface.h"
#include "knx/bau07B0.h"
#include "knx_facade.h"
namespace gateway::openknx {
using DaliGatewayDevice = KnxFacade<EspIdfPlatform, Bau07B0>;
} // namespace gateway::openknx
@@ -1,41 +0,0 @@
#pragma once
#include "TPUart/Interface/Abstract.h"
#include "driver/uart.h"
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <functional>
namespace gateway::openknx {
class TpuartUartInterface : public TPUart::Interface::Abstract {
public:
TpuartUartInterface(uart_port_t uart_port, int tx_pin, int rx_pin,
size_t rx_buffer_size = 512, size_t tx_buffer_size = 512);
~TpuartUartInterface();
void begin(int baud) override;
void end() override;
bool available() override;
bool availableForWrite() override;
bool write(char value) override;
int read() override;
bool overflow() override;
void flush() override;
bool hasCallback() override;
void registerCallback(std::function<bool()> callback) override;
private:
uart_port_t uart_port_;
int tx_pin_;
int rx_pin_;
size_t rx_buffer_size_;
size_t tx_buffer_size_;
std::atomic_bool overflow_{false};
std::function<bool()> callback_;
};
} // namespace gateway::openknx
@@ -1,180 +0,0 @@
#include "Arduino.h"
#include "driver/gpio.h"
#include "esp_err.h"
#include "esp_rom_sys.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <array>
#include <cstdio>
namespace {
std::array<voidFuncPtr, GPIO_NUM_MAX> g_gpio_callbacks{};
bool g_isr_service_installed = false;
void IRAM_ATTR gpioIsrThunk(void* arg) {
const auto pin = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(arg));
if (pin < g_gpio_callbacks.size() && g_gpio_callbacks[pin] != nullptr) {
g_gpio_callbacks[pin]();
}
}
gpio_int_type_t toGpioInterrupt(uint32_t mode) {
switch (mode) {
case RISING:
return GPIO_INTR_POSEDGE;
case FALLING:
return GPIO_INTR_NEGEDGE;
case CHANGE:
return GPIO_INTR_ANYEDGE;
default:
return GPIO_INTR_DISABLE;
}
}
void printUnsigned(unsigned long long value, int base) {
if (base == HEX) {
std::printf("%llX", value);
} else {
std::printf("%llu", value);
}
}
void printSigned(long long value, int base) {
if (base == HEX) {
std::printf("%llX", static_cast<unsigned long long>(value));
} else {
std::printf("%lld", value);
}
}
} // namespace
uint32_t millis() { return static_cast<uint32_t>(esp_timer_get_time() / 1000ULL); }
uint32_t micros() { return static_cast<uint32_t>(esp_timer_get_time()); }
void delay(uint32_t millis) { vTaskDelay(pdMS_TO_TICKS(millis)); }
void delayMicroseconds(unsigned int howLong) { esp_rom_delay_us(howLong); }
void pinMode(uint32_t pin, uint32_t mode) {
if (pin >= GPIO_NUM_MAX) {
return;
}
gpio_config_t config{};
config.pin_bit_mask = 1ULL << pin;
config.mode = mode == OUTPUT ? GPIO_MODE_OUTPUT : GPIO_MODE_INPUT;
config.pull_up_en = mode == INPUT_PULLUP ? GPIO_PULLUP_ENABLE : GPIO_PULLUP_DISABLE;
config.pull_down_en = mode == INPUT_PULLDOWN ? GPIO_PULLDOWN_ENABLE : GPIO_PULLDOWN_DISABLE;
config.intr_type = GPIO_INTR_DISABLE;
gpio_config(&config);
}
void digitalWrite(uint32_t pin, uint32_t value) {
if (pin < GPIO_NUM_MAX) {
gpio_set_level(static_cast<gpio_num_t>(pin), value == LOW ? 0 : 1);
}
}
uint32_t digitalRead(uint32_t pin) {
if (pin >= GPIO_NUM_MAX) {
return LOW;
}
return gpio_get_level(static_cast<gpio_num_t>(pin)) == 0 ? LOW : HIGH;
}
void attachInterrupt(uint32_t pin, voidFuncPtr callback, uint32_t mode) {
if (pin >= GPIO_NUM_MAX) {
return;
}
if (!g_isr_service_installed) {
const esp_err_t err = gpio_install_isr_service(ESP_INTR_FLAG_IRAM);
g_isr_service_installed = err == ESP_OK || err == ESP_ERR_INVALID_STATE;
}
if (!g_isr_service_installed) {
return;
}
gpio_set_intr_type(static_cast<gpio_num_t>(pin), toGpioInterrupt(mode));
gpio_isr_handler_remove(static_cast<gpio_num_t>(pin));
g_gpio_callbacks[pin] = callback;
if (callback != nullptr) {
gpio_isr_handler_add(static_cast<gpio_num_t>(pin), gpioIsrThunk,
reinterpret_cast<void*>(static_cast<uintptr_t>(pin)));
}
}
void print(const char value[]) { std::printf("%s", value == nullptr ? "" : value); }
void print(char value) { std::printf("%c", value); }
void print(unsigned char value, int base) { printUnsigned(value, base); }
void print(int value, int base) { printSigned(value, base); }
void print(unsigned int value, int base) { printUnsigned(value, base); }
void print(long value, int base) { printSigned(value, base); }
void print(unsigned long value, int base) { printUnsigned(value, base); }
void print(long long value, int base) { printSigned(value, base); }
void print(unsigned long long value, int base) { printUnsigned(value, base); }
void print(double value) { std::printf("%f", value); }
void println(const char value[]) {
print(value);
std::printf("\n");
}
void println(char value) {
print(value);
std::printf("\n");
}
void println(unsigned char value, int base) {
print(value, base);
std::printf("\n");
}
void println(int value, int base) {
print(value, base);
std::printf("\n");
}
void println(unsigned int value, int base) {
print(value, base);
std::printf("\n");
}
void println(long value, int base) {
print(value, base);
std::printf("\n");
}
void println(unsigned long value, int base) {
print(value, base);
std::printf("\n");
}
void println(long long value, int base) {
print(value, base);
std::printf("\n");
}
void println(unsigned long long value, int base) {
print(value, base);
std::printf("\n");
}
void println(double value) {
print(value);
std::printf("\n");
}
void println(void) { std::printf("\n"); }
@@ -1,316 +0,0 @@
#include "openknx_idf/esp_idf_platform.h"
#include "esp_log.h"
#include "esp_mac.h"
#include "esp_system.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "lwip/inet.h"
#include "nvs.h"
#include "nvs_flash.h"
#include <algorithm>
#include <cerrno>
#include <cstring>
#include <unistd.h>
namespace gateway::openknx {
namespace {
constexpr const char* kTag = "openknx_idf";
constexpr const char* kEepromKey = "eeprom";
bool readBaseMac(uint8_t* data) {
if (data == nullptr) {
return false;
}
if (esp_efuse_mac_get_default(data) == ESP_OK) {
return true;
}
return esp_read_mac(data, ESP_MAC_WIFI_STA) == ESP_OK;
}
esp_netif_t* findDefaultNetif() {
constexpr const char* kPreferredIfKeys[] = {"ETH_DEF", "WIFI_STA_DEF", "WIFI_AP_DEF"};
for (const char* key : kPreferredIfKeys) {
auto* netif = esp_netif_get_handle_from_ifkey(key);
if (netif == nullptr || !esp_netif_is_netif_up(netif)) {
continue;
}
esp_netif_ip_info_t ip_info{};
if (esp_netif_get_ip_info(netif, &ip_info) == ESP_OK && ip_info.ip.addr != 0) {
return netif;
}
}
for (const char* key : kPreferredIfKeys) {
if (auto* netif = esp_netif_get_handle_from_ifkey(key)) {
return netif;
}
}
return nullptr;
}
bool ensureNvsReady() {
const esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
if (nvs_flash_erase() != ESP_OK) {
return false;
}
return nvs_flash_init() == ESP_OK;
}
return err == ESP_OK || err == ESP_ERR_INVALID_STATE;
}
} // namespace
EspIdfPlatform::EspIdfPlatform(TPUart::Interface::Abstract* interface,
const char* nvs_namespace)
: nvs_namespace_(nvs_namespace == nullptr ? "openknx" : nvs_namespace) {
this->interface(interface);
}
EspIdfPlatform::~EspIdfPlatform() { closeMultiCast(); }
void EspIdfPlatform::outboundCemiFrameCallback(OutboundCemiFrameCallback callback,
void* context) {
outbound_cemi_frame_callback_ = callback;
outbound_cemi_frame_context_ = context;
}
bool EspIdfPlatform::handleOutboundCemiFrame(CemiFrame& frame) {
if (outbound_cemi_frame_callback_ == nullptr) {
return false;
}
return outbound_cemi_frame_callback_(frame, outbound_cemi_frame_context_);
}
void EspIdfPlatform::networkInterface(esp_netif_t* netif) { netif_ = netif; }
esp_netif_t* EspIdfPlatform::networkInterface() const { return netif_; }
esp_netif_t* EspIdfPlatform::effectiveNetif() const {
return netif_ == nullptr ? findDefaultNetif() : netif_;
}
uint32_t EspIdfPlatform::currentIpAddress() {
esp_netif_ip_info_t ip_info{};
esp_netif_t* netif = effectiveNetif();
if (netif == nullptr || esp_netif_get_ip_info(netif, &ip_info) != ESP_OK) {
return 0;
}
return ip_info.ip.addr;
}
uint32_t EspIdfPlatform::currentSubnetMask() {
esp_netif_ip_info_t ip_info{};
esp_netif_t* netif = effectiveNetif();
if (netif == nullptr || esp_netif_get_ip_info(netif, &ip_info) != ESP_OK) {
return 0;
}
return ip_info.netmask.addr;
}
uint32_t EspIdfPlatform::currentDefaultGateway() {
esp_netif_ip_info_t ip_info{};
esp_netif_t* netif = effectiveNetif();
if (netif == nullptr || esp_netif_get_ip_info(netif, &ip_info) != ESP_OK) {
return 0;
}
return ip_info.gw.addr;
}
void EspIdfPlatform::macAddress(uint8_t* data) {
if (data == nullptr) {
return;
}
if (!readBaseMac(data)) {
std::memset(data, 0, 6);
}
}
uint32_t EspIdfPlatform::uniqueSerialNumber() {
uint8_t mac[6]{};
macAddress(mac);
return (static_cast<uint32_t>(mac[2]) << 24) | (static_cast<uint32_t>(mac[3]) << 16) |
(static_cast<uint32_t>(mac[4]) << 8) | mac[5];
}
void EspIdfPlatform::restart() { esp_restart(); }
void EspIdfPlatform::fatalError() {
ESP_LOGE(kTag, "OpenKNX fatal error");
while (true) {
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void EspIdfPlatform::setupMultiCast(uint32_t addr, uint16_t port) {
closeMultiCast();
udp_sock_ = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (udp_sock_ < 0) {
ESP_LOGE(kTag, "failed to create UDP socket: errno=%d", errno);
return;
}
int reuse = 1;
setsockopt(udp_sock_, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
sockaddr_in bind_addr{};
bind_addr.sin_family = AF_INET;
const uint32_t local_address = currentIpAddress();
bind_addr.sin_addr.s_addr = local_address == 0 ? htonl(INADDR_ANY) : local_address;
bind_addr.sin_port = htons(port);
if (bind(udp_sock_, reinterpret_cast<sockaddr*>(&bind_addr), sizeof(bind_addr)) < 0) {
ESP_LOGE(kTag, "failed to bind UDP socket: errno=%d", errno);
closeMultiCast();
return;
}
timeval timeout{};
timeout.tv_sec = 0;
timeout.tv_usec = 1000;
setsockopt(udp_sock_, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
ip_mreq mreq{};
mreq.imr_multiaddr.s_addr = htonl(addr);
mreq.imr_interface.s_addr = local_address == 0 ? htonl(INADDR_ANY) : local_address;
if (setsockopt(udp_sock_, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
ESP_LOGW(kTag, "failed to join KNX multicast group: errno=%d", errno);
}
if (local_address != 0) {
in_addr multicast_interface{};
multicast_interface.s_addr = local_address;
if (setsockopt(udp_sock_, IPPROTO_IP, IP_MULTICAST_IF, &multicast_interface,
sizeof(multicast_interface)) < 0) {
ESP_LOGW(kTag, "failed to select KNX multicast interface: errno=%d", errno);
}
}
uint8_t loop = 0;
setsockopt(udp_sock_, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
multicast_remote_ = {};
multicast_remote_.sin_family = AF_INET;
multicast_remote_.sin_addr.s_addr = htonl(addr);
multicast_remote_.sin_port = htons(port);
}
void EspIdfPlatform::closeMultiCast() {
if (udp_sock_ >= 0) {
shutdown(udp_sock_, SHUT_RDWR);
close(udp_sock_);
udp_sock_ = -1;
}
has_last_remote_ = false;
}
bool EspIdfPlatform::sendBytesMultiCast(uint8_t* buffer, uint16_t len) {
if (udp_sock_ < 0 || buffer == nullptr || len == 0) {
return false;
}
const int sent = sendto(udp_sock_, buffer, len, 0, reinterpret_cast<sockaddr*>(&multicast_remote_),
sizeof(multicast_remote_));
return sent == len;
}
int EspIdfPlatform::readBytesMultiCast(uint8_t* buffer, uint16_t maxLen) {
uint32_t src_addr = 0;
uint16_t src_port = 0;
return readBytesMultiCast(buffer, maxLen, src_addr, src_port);
}
int EspIdfPlatform::readBytesMultiCast(uint8_t* buffer, uint16_t maxLen, uint32_t& src_addr,
uint16_t& src_port) {
if (udp_sock_ < 0 || buffer == nullptr || maxLen == 0) {
return 0;
}
sockaddr_in remote{};
socklen_t remote_len = sizeof(remote);
const int len = recvfrom(udp_sock_, buffer, maxLen, 0, reinterpret_cast<sockaddr*>(&remote),
&remote_len);
if (len <= 0) {
return 0;
}
last_remote_ = remote;
has_last_remote_ = true;
src_addr = ntohl(remote.sin_addr.s_addr);
src_port = ntohs(remote.sin_port);
return len;
}
bool EspIdfPlatform::sendBytesUniCast(uint32_t addr, uint16_t port, uint8_t* buffer,
uint16_t len) {
if (udp_sock_ < 0 || buffer == nullptr || len == 0) {
return false;
}
sockaddr_in remote{};
if (addr == 0 && port == 0 && has_last_remote_) {
remote = last_remote_;
} else {
remote.sin_family = AF_INET;
remote.sin_addr.s_addr = htonl(addr);
remote.sin_port = htons(port);
}
const int sent = sendto(udp_sock_, buffer, len, 0, reinterpret_cast<sockaddr*>(&remote),
sizeof(remote));
return sent == len;
}
void EspIdfPlatform::loadEeprom(size_t size) {
if (eeprom_loaded_ && eeprom_.size() == size) {
return;
}
eeprom_.assign(size, 0xff);
eeprom_loaded_ = true;
if (!ensureNvsReady()) {
ESP_LOGW(kTag, "NVS is not ready for OpenKNX EEPROM load");
return;
}
nvs_handle_t handle = 0;
if (nvs_open(nvs_namespace_.c_str(), NVS_READONLY, &handle) != ESP_OK) {
return;
}
size_t stored_size = 0;
if (nvs_get_blob(handle, kEepromKey, nullptr, &stored_size) == ESP_OK && stored_size > 0) {
std::vector<uint8_t> stored(stored_size);
if (nvs_get_blob(handle, kEepromKey, stored.data(), &stored_size) == ESP_OK) {
std::memcpy(eeprom_.data(), stored.data(), std::min(eeprom_.size(), stored.size()));
}
}
nvs_close(handle);
}
uint8_t* EspIdfPlatform::getEepromBuffer(uint32_t size) {
loadEeprom(size);
return eeprom_.data();
}
void EspIdfPlatform::commitToEeprom() {
if (eeprom_.empty()) {
return;
}
if (!ensureNvsReady()) {
ESP_LOGW(kTag, "NVS is not ready for OpenKNX EEPROM commit");
return;
}
nvs_handle_t handle = 0;
esp_err_t err = nvs_open(nvs_namespace_.c_str(), NVS_READWRITE, &handle);
if (err != ESP_OK) {
ESP_LOGW(kTag, "failed to open OpenKNX NVS namespace: %s", esp_err_to_name(err));
return;
}
err = nvs_set_blob(handle, kEepromKey, eeprom_.data(), eeprom_.size());
if (err == ESP_OK) {
err = nvs_commit(handle);
}
if (err != ESP_OK) {
ESP_LOGW(kTag, "failed to commit OpenKNX EEPROM: %s", esp_err_to_name(err));
}
nvs_close(handle);
}
} // namespace gateway::openknx
@@ -1,114 +0,0 @@
#include "openknx_idf/tpuart_uart_interface.h"
#include "esp_log.h"
#include <utility>
namespace gateway::openknx {
namespace {
constexpr const char* kTag = "openknx_tpuart";
} // namespace
TpuartUartInterface::TpuartUartInterface(uart_port_t uart_port, int tx_pin, int rx_pin,
size_t rx_buffer_size, size_t tx_buffer_size)
: uart_port_(uart_port),
tx_pin_(tx_pin),
rx_pin_(rx_pin),
rx_buffer_size_(rx_buffer_size),
tx_buffer_size_(tx_buffer_size) {}
TpuartUartInterface::~TpuartUartInterface() { end(); }
void TpuartUartInterface::begin(int baud) {
if (_running) {
end();
}
uart_config_t config{};
config.baud_rate = baud;
config.data_bits = UART_DATA_8_BITS;
config.parity = UART_PARITY_EVEN;
config.stop_bits = UART_STOP_BITS_1;
config.flow_ctrl = UART_HW_FLOWCTRL_DISABLE;
config.source_clk = UART_SCLK_DEFAULT;
esp_err_t err = uart_param_config(uart_port_, &config);
if (err != ESP_OK) {
ESP_LOGE(kTag, "failed to configure UART%d: %s", uart_port_, esp_err_to_name(err));
return;
}
err = uart_set_pin(uart_port_, tx_pin_ < 0 ? UART_PIN_NO_CHANGE : tx_pin_,
rx_pin_ < 0 ? UART_PIN_NO_CHANGE : rx_pin_, UART_PIN_NO_CHANGE,
UART_PIN_NO_CHANGE);
if (err != ESP_OK) {
ESP_LOGE(kTag, "failed to route UART%d pins: %s", uart_port_, esp_err_to_name(err));
return;
}
err = uart_driver_install(uart_port_, rx_buffer_size_, tx_buffer_size_, 0, nullptr, 0);
if (err != ESP_OK) {
ESP_LOGE(kTag, "failed to install UART%d driver: %s", uart_port_, esp_err_to_name(err));
return;
}
uart_set_rx_full_threshold(uart_port_, 1);
_running = true;
}
void TpuartUartInterface::end() {
if (!_running) {
return;
}
_running = false;
uart_driver_delete(uart_port_);
}
bool TpuartUartInterface::available() {
if (!_running) {
return false;
}
size_t len = 0;
return uart_get_buffered_data_len(uart_port_, &len) == ESP_OK && len > 0;
}
bool TpuartUartInterface::availableForWrite() {
if (!_running) {
return false;
}
size_t len = 0;
return uart_get_tx_buffer_free_size(uart_port_, &len) == ESP_OK && len > 0;
}
bool TpuartUartInterface::write(char value) {
if (!_running) {
return false;
}
return uart_write_bytes(uart_port_, &value, 1) == 1;
}
int TpuartUartInterface::read() {
if (!_running) {
return -1;
}
uint8_t value = 0;
return uart_read_bytes(uart_port_, &value, 1, 0) == 1 ? value : -1;
}
bool TpuartUartInterface::overflow() { return overflow_.exchange(false); }
void TpuartUartInterface::flush() {
if (_running) {
uart_flush(uart_port_);
}
}
bool TpuartUartInterface::hasCallback() { return false; }
void TpuartUartInterface::registerCallback(std::function<bool()> callback) {
callback_ = std::move(callback);
}
} // namespace gateway::openknx
+1 -1
Submodule knx updated: 5d7d6e573b...dcf565dc03