Finish ESP IDF native support with sample project kn-demo-diy-idf but not pass real test.

This commit is contained in:
VietDzung 2025-07-02 13:29:50 +07:00
parent 1be9a2b3f8
commit cb58f2e73d
14 changed files with 2374 additions and 9 deletions

View File

@ -0,0 +1,23 @@
cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
# require for knx components
add_definitions(
-Wno-unknown-pragmas
-DMASK_VERSION=0x07B0
-DKNX_NO_AUTOMATIC_GLOBAL_INSTANCE
-DKNX_FLASH_SIZE=4096
-DKNX_NO_PRINT
-Wno-stringop-truncation ## remove warning strncpy((char *)sta_wifi_config.sta.ssid, config_values.ssid, sizeof(sta_wifi_config.sta.ssid)); in tuya.h
)
project(knx-demo-diy-idf)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# idf_component_register(
# SRCS "main.c"
# INCLUDE_DIRS ".." "../../src"
# REQUIRES freertos nvs_flash esp_wifi esp_system
# )

View File

@ -0,0 +1,29 @@
# KNX Demo DIY (ESP-IDF 5.x Native)
This is a native ESP-IDF 5.x example project for KNX, based on the Arduino `knx-demo-diy` example but using the new `Esp32IdfPlatform` for direct ESP-IDF support.
## Features
- Uses the native ESP-IDF APIs (no Arduino layer)
- Demonstrates KNX stack integration on ESP32
- Based on the logic of the Arduino `knx-demo-diy.ino` example
## How to Build
1. Install [ESP-IDF 5.x](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/get-started/)
2. Open a terminal in this directory (`examples/knx-demo-diy-idf`)
3. Run:
```sh
idf.py set-target esp32
idf.py build
idf.py -p /dev/ttyUSB0 flash monitor
```
(Replace `/dev/ttyUSB0` with your ESP32 serial port)
## Project Structure
- `main.c` — Main application file (C++ code, but named .c for ESP-IDF compatibility)
- `CMakeLists.txt` — ESP-IDF build configuration
## Notes
- This project uses the new `Esp32IdfPlatform` class for native ESP-IDF support.
- You may need to adapt pin numbers and KNX configuration for your hardware.
- The logic is adapted from the Arduino `knx-demo-diy.ino` example.

View File

@ -0,0 +1,11 @@
# Define the directory containing your source files
set(SOURCE_DIR "../../../../src")
set(SOURCE_DIR_1 "../../../../src/knx")
# Use file(GLOB) to find all .cpp files in the 'src' directory
file(GLOB SOURCE_FILES "${SOURCE_DIR}/*.cpp")
file(GLOB SOURCE_FILES_1 "${SOURCE_DIR_1}/*.cpp")
idf_component_register(SRCS ${SOURCE_FILES} ${SOURCE_FILES_1}
INCLUDE_DIRS "../../../../src" "../../../../src/knx"
REQUIRES esp_netif driver esp_timer esp_wifi freertos nvs_flash esp_system)

View File

@ -0,0 +1,12 @@
idf_component_register(
SRCS "main.cpp"
INCLUDE_DIRS "."
REQUIRES
knx
esp_timer
nvs_flash
esp_wifi
esp_event
esp_netif
mdns
)

View File

@ -0,0 +1,2 @@
dependencies:
espressif/mdns: ^1.8.2

View File

@ -0,0 +1,161 @@
#include "esp32_idf_platform.h"
#include "knx_facade.h"
#include "knx/bau07B0.h"
#include "knx/group_object.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "esp_log.h"
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <cstring>
#include <stdlib.h>
#include <limits.h>
#define WIFI_SSID "your_ssid"
#define WIFI_PASS "your_password"
#define MASK_VERSION 0x07B0
static const char *TAG = "knx-demo";
// --- KNX Group Object Shortcuts ---
#define goCurrent knx.getGroupObject(1)
#define goMax knx.getGroupObject(2)
#define goMin knx.getGroupObject(3)
#define goReset knx.getGroupObject(4)
// --- Global Variables ---
float currentValue = 0;
float maxValue = 0;
float minValue = RAND_MAX;
int64_t lastsend = 0;
// --- KNX Stack Instance (migrated pattern) ---
Esp32IdfPlatform knxPlatform(UART_NUM_1); // Use UART_NUM_1, change if needed
Bau07B0 knxBau(knxPlatform);
KnxFacade<Esp32IdfPlatform, Bau07B0> knx(knxBau);
// --- WiFi event handler ---
static esp_netif_t* s_wifi_netif = nullptr;
static void wifi_event_handler(void* arg, esp_event_base_t event_base,
int32_t event_id, void* event_data) {
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
esp_wifi_connect();
ESP_LOGI(TAG, "Retrying connection to the WiFi AP");
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
ESP_LOGI(TAG, "Got IP: " IPSTR, IP2STR(&event->ip_info.ip));
if (s_wifi_netif) {
knxPlatform.setNetif(s_wifi_netif);
}
}
}
// --- Button ISR (simulate with a function call or GPIO interrupt in real use) ---
void myButtonPressed() {
static int64_t lastpressed = 0;
int64_t now = esp_timer_get_time() / 1000; // ms
if (now - lastpressed > 200) {
knx.toggleProgMode();
lastpressed = now;
}
}
// --- KNX Reset Callback ---
void resetCallback(GroupObject& go) {
if (go.value()) {
maxValue = 0;
minValue = 10000;
}
}
// --- Simulate temperature measurement ---
void measureTemp() {
int64_t now = esp_timer_get_time() / 1000; // ms
if ((now - lastsend) < 2000)
return;
lastsend = now;
int r = rand();
currentValue = (r * 1.0) / (RAND_MAX * 1.0);
currentValue *= 100 * 100;
goCurrent.value(currentValue);
if (currentValue > maxValue) {
maxValue = currentValue;
goMax.value(maxValue);
}
if (currentValue < minValue) {
minValue = currentValue;
goMin.value(minValue);
}
}
extern "C" void app_main(void) {
// Initialize NVS
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
// Initialize TCP/IP and WiFi
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
s_wifi_netif = esp_netif_create_default_wifi_sta();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL, NULL));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL, NULL));
wifi_config_t wifi_config = {};
strcpy((char*)wifi_config.sta.ssid, WIFI_SSID);
strcpy((char*)wifi_config.sta.password, WIFI_PASS);
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
ESP_LOGI(TAG, "WiFi initialization finished.");
// Set UART pins (example: RX=16, TX=17)
knxPlatform.knxUartPins(16, 17);
knxPlatform.setupUart();
// Set button ISR
knx.setButtonISRFunction(myButtonPressed);
// Read KNX memory (address table, etc.)
knx.readMemory();
// Register group object callbacks and types if configured
if (knx.configured()) {
goReset.callback(resetCallback);
goReset.dataPointType(DPT_Trigger);
goCurrent.dataPointType(DPT_Value_Temp);
goMin.dataPointType(DPT_Value_Temp);
goMax.dataPointType(DPT_Value_Temp);
ESP_LOGI(TAG, "Timeout: %d", knx.paramByte(0));
ESP_LOGI(TAG, "Cyclic send: %d", knx.paramByte(1));
ESP_LOGI(TAG, "Min/Max send: %d", knx.paramByte(2));
ESP_LOGI(TAG, "Send on change: %d", knx.paramByte(3));
ESP_LOGI(TAG, "Alignment: %d", knx.paramByte(4));
}
// Start KNX stack
knx.start();
// Main loop
while (1) {
knx.loop();
if (knx.configured()) {
measureTemp();
}
vTaskDelay(pdMS_TO_TICKS(10));
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,5 @@
#ifdef ARDUINO
#include "arduino_platform.h" #include "arduino_platform.h"
#include "knx/bits.h" #include "knx/bits.h"
@ -309,3 +311,5 @@ void println(void)
ArduinoPlatform::SerialDebug->println(); ArduinoPlatform::SerialDebug->println();
} }
#endif // KNX_NO_PRINT #endif // KNX_NO_PRINT
#endif // ARDUINO

View File

@ -1,5 +1,7 @@
#pragma once #pragma once
#ifdef ARDUINO
#include "knx/platform.h" #include "knx/platform.h"
#include "Arduino.h" #include "Arduino.h"
@ -42,3 +44,4 @@ class ArduinoPlatform : public Platform
protected: protected:
HardwareSerial* _knxSerial; HardwareSerial* _knxSerial;
}; };
#endif // ARDUINO

View File

@ -1,13 +1,13 @@
#ifdef ESP_PLATFORM #ifdef ESP_PLATFORM
// esp_idf_platform.cpp // esp32_idf_platform.cpp
#include "esp_efuse.h" #include <esp_system.h>
#include <esp_mac.h>
#include "esp32_idf_platform.h" #include "esp32_idf_platform.h"
#include "esp_log.h" #include "esp_log.h"
#include "knx/bits.h" #include "knx/bits.h"
#include "nvs.h" #include "nvs.h"
#include <esp_timer.h>
// Define a logging tag for this file
static const char* KTAG = "Esp32IdfPlatform";
Esp32IdfPlatform::Esp32IdfPlatform(uart_port_t uart_num) Esp32IdfPlatform::Esp32IdfPlatform(uart_port_t uart_num)
: _uart_num(uart_num) : _uart_num(uart_num)
@ -391,7 +391,14 @@ void Esp32IdfPlatform::commitToEeprom()
} }
else else
{ {
ESP_LOGI(KTAG, "Committed %d bytes to NVS.", _eeprom_size); ESP_LOGI(KTAG, "Committed %" PRIu32 " bytes to NVS.", _eeprom_size);
} }
} }
uint32_t millis()
{
// esp_timer_get_time() returns microseconds, so we divide by 1000 for milliseconds.
// Cast to uint32_t to match the Arduino function signature.
return (uint32_t)(esp_timer_get_time() / 1000);
}
#endif #endif

View File

@ -43,6 +43,7 @@
#include <esp_timer.h> #include <esp_timer.h>
#include <esp_log.h> #include <esp_log.h>
#include <esp_netif.h> #include <esp_netif.h>
#include <lwip/inet.h>
#include <nvs_flash.h> #include <nvs_flash.h>
#include <driver/uart.h> #include <driver/uart.h>
// ESP-IDF: Use FreeRTOS and ESP-IDF APIs for timing, GPIO, etc. // ESP-IDF: Use FreeRTOS and ESP-IDF APIs for timing, GPIO, etc.
@ -50,9 +51,16 @@
#include <freertos/task.h> #include <freertos/task.h>
#include <driver/gpio.h> #include <driver/gpio.h>
// Define Arduino-like macros if needed for compatibility // Define Arduino-like macros if needed for compatibility
#define lowByte(val) ((val)&255)
#define highByte(val) (((val) >> ((sizeof(val) - 1) << 3)) & 255)
#define bitRead(val, bitno) (((val) >> (bitno)) & 1)
#define DEC 10
#define HEX 16
#define LOW 0 #define LOW 0
#define HIGH 1 #define HIGH 1
// Implement or map Arduino-like functions if needed // Implement or map Arduino-like functions if needed
uint32_t millis();
#else // Non-Arduino platforms #else // Non-Arduino platforms
#define lowByte(val) ((val)&255) #define lowByte(val) ((val)&255)
#define highByte(val) (((val) >> ((sizeof(val) - 1) << 3)) & 255) #define highByte(val) (((val) >> ((sizeof(val) - 1) << 3)) & 255)

View File

@ -279,20 +279,34 @@ template <class P, class B> class KnxFacade : private SaveRestore
void start() void start()
{ {
if (_progLedOffCallback == 0 || _progLedOnCallback == 0) if (_progLedOffCallback == 0 || _progLedOnCallback == 0){
#if defined(ESP_PLATFORM)
gpio_reset_pin((gpio_num_t)ledPin());
gpio_set_direction((gpio_num_t)ledPin(), GPIO_MODE_OUTPUT);
#else
pinMode(ledPin(), OUTPUT); pinMode(ledPin(), OUTPUT);
#endif // ESP_PLATFORM
}
progLedOff(); progLedOff();
if (_progButtonISRFuncPtr && _buttonPin >= 0) if (_progButtonISRFuncPtr && _buttonPin >= 0)
{ {
#if defined(ESP_PLATFORM)
// TODO: add support for buttonPin() in ESP_PLATFORM
gpio_reset_pin((gpio_num_t)buttonPin());
gpio_set_direction((gpio_num_t)buttonPin(), GPIO_MODE_INPUT);
gpio_pullup_en((gpio_num_t)buttonPin());
#else
pinMode(buttonPin(), INPUT_PULLUP); pinMode(buttonPin(), INPUT_PULLUP);
// Workaround for https://github.com/arduino/ArduinoCore-samd/issues/587 // Workaround for https://github.com/arduino/ArduinoCore-samd/issues/587
#if (ARDUINO_API_VERSION >= 10200) #if (ARDUINO_API_VERSION >= 10200)
attachInterrupt(_buttonPin, _progButtonISRFuncPtr, (PinStatus)CHANGE); attachInterrupt(_buttonPin, _progButtonISRFuncPtr, (PinStatus)CHANGE);
#else #else
attachInterrupt(_buttonPin, _progButtonISRFuncPtr, CHANGE); attachInterrupt(_buttonPin, _progButtonISRFuncPtr, CHANGE);
#endif #endif // ARDUINO_API_VERSION
#endif // ESP_PLATFORM
} }
enabled(true); enabled(true);
@ -470,16 +484,27 @@ template <class P, class B> class KnxFacade : private SaveRestore
void progLedOn() void progLedOn()
{ {
if (_progLedOnCallback == 0) if (_progLedOnCallback == 0){
#if defined(ESP_PLATFORM)
gpio_set_level((gpio_num_t)ledPin(), _ledPinActiveOn);
#else
digitalWrite(ledPin(), _ledPinActiveOn); digitalWrite(ledPin(), _ledPinActiveOn);
#endif // ESP_PLATFORM
}
else else
_progLedOnCallback(); _progLedOnCallback();
} }
void progLedOff() void progLedOff()
{ {
if (_progLedOffCallback == 0) if (_progLedOffCallback == 0){
#if defined(ESP_PLATFORM)
gpio_set_level((gpio_num_t)ledPin(), 1 - _ledPinActiveOn);
#else
digitalWrite(ledPin(), HIGH - _ledPinActiveOn); digitalWrite(ledPin(), HIGH - _ledPinActiveOn);
#endif // ESP_PLATFORM
}
else else
_progLedOffCallback(); _progLedOffCallback();
} }

View File

@ -1,3 +1,4 @@
#ifdef ARDUINO
#pragma once #pragma once
#include "arduino_platform.h" #include "arduino_platform.h"
@ -153,3 +154,4 @@ class RP2040ArduinoPlatform : public ArduinoPlatform
}; };
#endif #endif
#endif // ARDUINO

View File

@ -1,3 +1,4 @@
#ifdef ARDUINO
#include "arduino_platform.h" #include "arduino_platform.h"
#include "Arduino.h" #include "Arduino.h"
@ -53,3 +54,4 @@ class SamdPlatform : public ArduinoPlatform
}; };
#endif #endif
#endif // ARDUINO