From fbbbf7a7321915b871dbfd5365a831272d892aa7 Mon Sep 17 00:00:00 2001 From: 1998-felix Date: Wed, 23 Aug 2023 13:49:41 +0300 Subject: [PATCH 01/15] Add esp32 mqtt capability Signed-off-by: 1998-felix --- targets/esp32/mqtt/.gitignore | 6 ++ targets/esp32/mqtt/CMakeLists.txt | 3 + targets/esp32/mqtt/include/cnetwork.h | 21 +++++ targets/esp32/mqtt/include/config.h | 11 +++ targets/esp32/mqtt/platformio.ini | 14 +++ targets/esp32/mqtt/src/CMakeLists.txt | 4 + targets/esp32/mqtt/src/cnetwork.c | 69 ++++++++++++++ targets/esp32/mqtt/src/main.c | 131 ++++++++++++++++++++++++++ 8 files changed, 259 insertions(+) create mode 100644 targets/esp32/mqtt/.gitignore create mode 100644 targets/esp32/mqtt/CMakeLists.txt create mode 100644 targets/esp32/mqtt/include/cnetwork.h create mode 100644 targets/esp32/mqtt/include/config.h create mode 100644 targets/esp32/mqtt/platformio.ini create mode 100644 targets/esp32/mqtt/src/CMakeLists.txt create mode 100644 targets/esp32/mqtt/src/cnetwork.c create mode 100644 targets/esp32/mqtt/src/main.c diff --git a/targets/esp32/mqtt/.gitignore b/targets/esp32/mqtt/.gitignore new file mode 100644 index 0000000..c493534 --- /dev/null +++ b/targets/esp32/mqtt/.gitignore @@ -0,0 +1,6 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch +sdkconfig.esp32-c3-devkitc-02 diff --git a/targets/esp32/mqtt/CMakeLists.txt b/targets/esp32/mqtt/CMakeLists.txt new file mode 100644 index 0000000..fb788a0 --- /dev/null +++ b/targets/esp32/mqtt/CMakeLists.txt @@ -0,0 +1,3 @@ +cmake_minimum_required(VERSION 3.16.0) +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(mqt) diff --git a/targets/esp32/mqtt/include/cnetwork.h b/targets/esp32/mqtt/include/cnetwork.h new file mode 100644 index 0000000..7b2470c --- /dev/null +++ b/targets/esp32/mqtt/include/cnetwork.h @@ -0,0 +1,21 @@ +#ifndef C_NETWORK_H +#define C_NETWORK_H + +#include +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "esp_mac.h" +#include "esp_wifi.h" +#include "esp_event.h" +#include "esp_log.h" +#include "nvs_flash.h" + +#include "lwip/err.h" +#include "lwip/sys.h" + +static void wifi_event_handler(void *arg, esp_event_base_t event_base, + int32_t event_id, void *event_data); + +void wifi_init_softap(void); + +#endif \ No newline at end of file diff --git a/targets/esp32/mqtt/include/config.h b/targets/esp32/mqtt/include/config.h new file mode 100644 index 0000000..3437fce --- /dev/null +++ b/targets/esp32/mqtt/include/config.h @@ -0,0 +1,11 @@ +#ifndef CONFIG_H +#define CONFIG_H + +const char *mfThingId = " "; +const char *mfThingPass = " "; +const char *mfChannelId = " "; +char mfTopic[150]; + +const char *server = " "; + +#endif diff --git a/targets/esp32/mqtt/platformio.ini b/targets/esp32/mqtt/platformio.ini new file mode 100644 index 0000000..c4d17d9 --- /dev/null +++ b/targets/esp32/mqtt/platformio.ini @@ -0,0 +1,14 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:esp32-c3-devkitc-02] +platform = espressif32 +board = esp32-c3-devkitc-02 +framework = espidf diff --git a/targets/esp32/mqtt/src/CMakeLists.txt b/targets/esp32/mqtt/src/CMakeLists.txt new file mode 100644 index 0000000..af2cb2f --- /dev/null +++ b/targets/esp32/mqtt/src/CMakeLists.txt @@ -0,0 +1,4 @@ + +FILE(GLOB_RECURSE app_sources ${CMAKE_SOURCE_DIR}/src/*.*) + +idf_component_register(SRCS ${app_sources}) diff --git a/targets/esp32/mqtt/src/cnetwork.c b/targets/esp32/mqtt/src/cnetwork.c new file mode 100644 index 0000000..0d7198e --- /dev/null +++ b/targets/esp32/mqtt/src/cnetwork.c @@ -0,0 +1,69 @@ +/***** +Implements a network interface fpr the esp. +Current interface is wifi. +**/ + +#include "cnetwork.h" + +#define ESP_WIFI_SSID " " // Enter the wifi ssid +#define ESP_WIFI_PASS " " // Enter the wifi password + +static const char *TAG = "wifi softAP"; // tag for esp logging + +// Wifi event handler +static void wifi_event_handler(void *arg, esp_event_base_t event_base, + int32_t event_id, void *event_data) +{ + if (event_id == WIFI_EVENT_AP_STACONNECTED) + { + wifi_event_ap_staconnected_t *event = (wifi_event_ap_staconnected_t *)event_data; + ESP_LOGI(TAG, "station " MACSTR " join, AID=%d", + MAC2STR(event->mac), event->aid); + } + else if (event_id == WIFI_EVENT_AP_STADISCONNECTED) + { + wifi_event_ap_stadisconnected_t *event = (wifi_event_ap_stadisconnected_t *)event_data; + ESP_LOGI(TAG, "station " MACSTR " leave, AID=%d", + MAC2STR(event->mac), event->aid); + } +} + +// Wi-fi initial +void wifi_init_softap(void) +{ + ESP_ERROR_CHECK(esp_netif_init()); + ESP_ERROR_CHECK(esp_event_loop_create_default()); + esp_netif_create_default_wifi_ap(); + + 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)); + + wifi_config_t wifi_config = { + .ap = { + .ssid = ESP_WIFI_SSID, + .ssid_len = strlen(ESP_WIFI_SSID), + .password = ESP_WIFI_PASS, + .authmode = WIFI_AUTH_WPA2_PSK, + .pmf_cfg = { + .required = true, + }, + }, + }; + if (strlen(ESP_WIFI_PASS) == 0) + { + wifi_config.ap.authmode = WIFI_AUTH_OPEN; + } + + ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP)); + ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &wifi_config)); + ESP_ERROR_CHECK(esp_wifi_start()); + + ESP_LOGI(TAG, "wifi_init_softap finished. SSID:%s password:%s", + ESP_WIFI_SSID, ESP_WIFI_PASS); // Success log +} diff --git a/targets/esp32/mqtt/src/main.c b/targets/esp32/mqtt/src/main.c new file mode 100644 index 0000000..160693b --- /dev/null +++ b/targets/esp32/mqtt/src/main.c @@ -0,0 +1,131 @@ +#include +#include +#include +#include +#include "esp_wifi.h" +#include "esp_system.h" +#include "nvs_flash.h" +#include "esp_event.h" +#include "esp_netif.h" + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/semphr.h" +#include "freertos/queue.h" + +#include "lwip/sockets.h" +#include "lwip/dns.h" +#include "lwip/netdb.h" + +#include "esp_log.h" +#include "mqtt_client.h" +#include "cnetwork.h" +#include "config.h" + +#define CLIENT_ID "ESP32" + +static const char *TAG = "MQTT_MAINFLUX"; + +static void log_error_if_nonzero(const char *message, int error_code) +{ + if (error_code != 0) + { + ESP_LOGE(TAG, "Last error %s: 0x%x", message, error_code); + } +} +void create_mainflux_channel(void) +{ + const char *_preId = "channels/"; + const char *_postId = "/messages"; + strcpy(mfTopic, _preId); + strcat(mfTopic, mfChannelId); + strcat(mfTopic, _postId); +} + +static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) +{ + ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%" PRIi32 "", base, event_id); + esp_mqtt_event_handle_t event = event_data; + esp_mqtt_client_handle_t client = event->client; + int msg_id; + create_mainflux_channel(); + switch ((esp_mqtt_event_id_t)event_id) + { + case MQTT_EVENT_CONNECTED: + ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED"); + msg_id = esp_mqtt_client_publish(client, mfTopic, "'{'message':'hello mainflux'}", 0, 0, 0); + ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id); + + msg_id = esp_mqtt_client_subscribe(client, mfTopic, 0); + ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id); + break; + case MQTT_EVENT_DISCONNECTED: + ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED"); + break; + case MQTT_EVENT_SUBSCRIBED: + ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id); + msg_id = esp_mqtt_client_publish(client, mfTopic, "'{'message':'hello mainflux'}", 0, 0, 0); + ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id); + break; + case MQTT_EVENT_UNSUBSCRIBED: + ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id); + break; + case MQTT_EVENT_PUBLISHED: + ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id); + break; + case MQTT_EVENT_DATA: + ESP_LOGI(TAG, "MQTT_EVENT_DATA"); + printf("TOPIC=%.*s\r\n", event->topic_len, event->topic); + printf("DATA=%.*s\r\n", event->data_len, event->data); + break; + case MQTT_EVENT_ERROR: + ESP_LOGI(TAG, "MQTT_EVENT_ERROR"); + if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT) + { + log_error_if_nonzero("reported from esp-tls", event->error_handle->esp_tls_last_esp_err); + log_error_if_nonzero("reported from tls stack", event->error_handle->esp_tls_stack_err); + log_error_if_nonzero("captured as transport's socket errno", event->error_handle->esp_transport_sock_errno); + ESP_LOGI(TAG, "Last errno string (%s)", strerror(event->error_handle->esp_transport_sock_errno)); + } + break; + default: + ESP_LOGI(TAG, "Other event id:%d", event->event_id); + break; + } +} + +static void mqtt_app_start(void) +{ + esp_mqtt_client_config_t mqtt_cfg = { + .broker.address.uri = server, + .credentials.client_id = CLIENT_ID, + .credentials.username = mfThingId, + .credentials.authentication.password = mfThingPass, + }; + esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg); + esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL); + esp_mqtt_client_start(client); +} + +// main app called by rtos +void app_main(void) +{ + // Defualt start up logs for ESP -IDF + ESP_LOGI(TAG, "[APP] Startup.."); + ESP_LOGI(TAG, "[APP] Free memory: %" PRIu32 " bytes", esp_get_free_heap_size()); + ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version()); + // set log level + esp_log_level_set("*", ESP_LOG_INFO); + esp_log_level_set("mqtt_client", ESP_LOG_VERBOSE); + esp_log_level_set("TRANSPORT_BASE", ESP_LOG_VERBOSE); + esp_log_level_set("esp-tls", ESP_LOG_VERBOSE); + esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE); + esp_log_level_set("outbox", ESP_LOG_VERBOSE); + // Handle error on start up + ESP_ERROR_CHECK(nvs_flash_init()); + ESP_ERROR_CHECK(esp_netif_init()); + ESP_ERROR_CHECK(esp_event_loop_create_default()); + // Run main application + wifi_init_softap(); + mqtt_app_start(); +} From ab2d35274032b2a60d9975a32de63b071c6da625 Mon Sep 17 00:00:00 2001 From: 1998-felix Date: Thu, 24 Aug 2023 12:38:42 +0300 Subject: [PATCH 02/15] Add stm32 capability Signed-off-by: 1998-felix --- targets/stm32/mqtt/.gitignore | 2 + targets/stm32/mqtt/Makefile | 17 ++++ targets/stm32/mqtt/README.md | 24 +++++ targets/stm32/mqtt/include/MQTTClientapp.h | 27 +++++ targets/stm32/mqtt/include/MQTTInterface.h | 36 +++++++ targets/stm32/mqtt/include/config.h | 11 ++ targets/stm32/mqtt/platformio.ini | 28 ++++++ targets/stm32/mqtt/src/MQTTClientapp.c | 104 +++++++++++++++++++ targets/stm32/mqtt/src/MQTTInterface.c | 111 +++++++++++++++++++++ 9 files changed, 360 insertions(+) create mode 100644 targets/stm32/mqtt/.gitignore create mode 100644 targets/stm32/mqtt/Makefile create mode 100644 targets/stm32/mqtt/README.md create mode 100644 targets/stm32/mqtt/include/MQTTClientapp.h create mode 100644 targets/stm32/mqtt/include/MQTTInterface.h create mode 100644 targets/stm32/mqtt/include/config.h create mode 100644 targets/stm32/mqtt/platformio.ini create mode 100644 targets/stm32/mqtt/src/MQTTClientapp.c create mode 100644 targets/stm32/mqtt/src/MQTTInterface.c diff --git a/targets/stm32/mqtt/.gitignore b/targets/stm32/mqtt/.gitignore new file mode 100644 index 0000000..b9f3806 --- /dev/null +++ b/targets/stm32/mqtt/.gitignore @@ -0,0 +1,2 @@ +.pio +.vscode diff --git a/targets/stm32/mqtt/Makefile b/targets/stm32/mqtt/Makefile new file mode 100644 index 0000000..a911c7c --- /dev/null +++ b/targets/stm32/mqtt/Makefile @@ -0,0 +1,17 @@ +all: + platformio -f run + +upload: + platformio -f run --target upload + +clean: + platformio -f run --target clean + +program: + platformio -f run --target program + +uploadfs: + platformio -f run --target uploadfs + +update: + platformio -f update \ No newline at end of file diff --git a/targets/stm32/mqtt/README.md b/targets/stm32/mqtt/README.md new file mode 100644 index 0000000..b507e69 --- /dev/null +++ b/targets/stm32/mqtt/README.md @@ -0,0 +1,24 @@ +# MQTTS- stm32 target +## Requirements +1. Mainflux broker details including: hostname, ThingID, Thing Credentials and Channel ID +2. [PlatformIO](https://platformio.org/) +3. [dfu-util](https://dfu-util.sourceforge.net/) +4. [STM32CubeIDE](https://www.st.com/en/development-tools/stm32cubeide.html) + +## Configure +1. Use the STM32CUbeIDE to generate the specific files for your target. Please ensure to add the [Lwip]() and [Paho embedded c]()libraries as third party libraries. Then copy the files to this section +Edit the platform.ini file for the specific target. +2. Edit the [config file](include/config.h) with your broker and network details. + +## Build +The project can be built by utilising the make file within the target directory + +```bash +make +``` +## Flash +Platform io generate a build directory with the fimware.bin within it. Use the make command to flash to board +```bash +make upload +``` + diff --git a/targets/stm32/mqtt/include/MQTTClientapp.h b/targets/stm32/mqtt/include/MQTTClientapp.h new file mode 100644 index 0000000..71945c9 --- /dev/null +++ b/targets/stm32/mqtt/include/MQTTClientapp.h @@ -0,0 +1,27 @@ + +#ifndef MQTT_CLIENT_APP_H_ +#define MQTT_CLIENT_APP_H_ + +#include "MQTTClient.h" +#include "MQTTInterface.h" +#include "cmsis_os.h" +#include "config.h" + +#include + +#define MQTT_PORT 1883 +#define MQTT_BUFSIZE 1024 + +Network net; +MQTTClient mqttClient; + +uint8_t sndBuffer[MQTT_BUFSIZE]; +uint8_t rcvBuffer[MQTT_BUFSIZE]; +uint8_t msgBuffer[MQTT_BUFSIZE]; + +void mqttClientSubTask(void const *argument); +void mqttClientPubTask(void const *argument); +int mqttConnectBroker(void); +void mqttMessageArrived(MessageData* msg); + +#endif diff --git a/targets/stm32/mqtt/include/MQTTInterface.h b/targets/stm32/mqtt/include/MQTTInterface.h new file mode 100644 index 0000000..887117e --- /dev/null +++ b/targets/stm32/mqtt/include/MQTTInterface.h @@ -0,0 +1,36 @@ +#ifndef _MQTTInterface_H +#define _MQTTInterface_H + +typedef struct Timer Timer; + +struct Timer +{ + unsigned long systick_period; + unsigned long end_time; +}; + +typedef struct Network Network; + +struct Network +{ + struct netconn *conn; + struct netbuf *buf; + int offset; + int (*mqttread)(Network *, unsigned char *, int, int); + int (*mqttwrite)(Network *, unsigned char *, int, int); + void (*disconnect)(Network *); +}; + +void initTimer(Timer *); +char timerIsExpired(Timer *); +void timerCountDownMS(Timer *, unsigned int); +void timerCountDown(Timer *, unsigned int); +int timerLeftMS(Timer *); + +int netRead(Network *, unsigned char *, int, int); +int netWrite(Network *, unsigned char *, int, int); +void netDisconnect(Network *); +void newNetwork(Network *); +int connectNetwork(Network *, char *, int); + +#endif diff --git a/targets/stm32/mqtt/include/config.h b/targets/stm32/mqtt/include/config.h new file mode 100644 index 0000000..3437fce --- /dev/null +++ b/targets/stm32/mqtt/include/config.h @@ -0,0 +1,11 @@ +#ifndef CONFIG_H +#define CONFIG_H + +const char *mfThingId = " "; +const char *mfThingPass = " "; +const char *mfChannelId = " "; +char mfTopic[150]; + +const char *server = " "; + +#endif diff --git a/targets/stm32/mqtt/platformio.ini b/targets/stm32/mqtt/platformio.ini new file mode 100644 index 0000000..a4aa44d --- /dev/null +++ b/targets/stm32/mqtt/platformio.ini @@ -0,0 +1,28 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:nucleo_f429zi] +platform = ststm32 +board = nucleo_f429zi +framework = stm32cube +monitor_speed=115200 +lib_deps= + https://git.savannah.nongnu.org/git/lwip.git + https://github.com/eclipse/paho.mqtt.embedded-c.git + +upload_protocol = dfu +build_flags = + -D ENABLE_USB_SERIAL + -D USBCON + -D USBD_VID=0x0483 + -D USBD_PID=0x5740 + -D PIO_FRAMEWORK_ARDUINO_ENABLE_CDC + + -D HAL_PCD_MODULE_ENABLED \ No newline at end of file diff --git a/targets/stm32/mqtt/src/MQTTClientapp.c b/targets/stm32/mqtt/src/MQTTClientapp.c new file mode 100644 index 0000000..a1e84b8 --- /dev/null +++ b/targets/stm32/mqtt/src/MQTTClientapp.c @@ -0,0 +1,104 @@ +#include "main.h" +#include "MQTTClientapp.h" + +void createMainfluxChannel(void) +{ + const char *_preId = "channels/"; + const char *_postId = "/messages"; + strcpy(mfTopic, _preId); + strcat(mfTopic, mfChannelId); + strcat(mfTopic, _postId); +} + +void mqttClientSubTask(void const *argument) +{ + while (1) + { + if (!mqttClient.isconnected) + { + MQTTDisconnect(&mqttClient); + mqttConnectBroker(); + osDelay(1000); + } + else + { + MQTTYield(&mqttClient, 1000); + osDelay(100); + } + } +} + +void mqttClientPubTask(void const *argument) +{ + const char *str = "{'message':'hello'}"; + MQTTMessage message; + + while (1) + { + if (mqttClient.isconnected) + { + message.payload = (void *)str; + message.payloadlen = strlen(str); + + MQTTPublish(&mqttClient, mfTopic, &message); + } + osDelay(1000); + } +} + +int mqttConnectBroker() +{ + int ret; + + net_clear(); + ret = net_init(&net); + if (ret != MQTT_SUCCESS) + { + printf("net_init failed.\n"); + return -1; + } + + ret = net_connect(&net, server, MQTT_PORT); + if (ret != MQTT_SUCCESS) + { + printf("net_connect failed.\n"); + return -1; + } + + MQTTClientInit(&mqttClient, &net, 1000, sndBuffer, sizeof(sndBuffer), rcvBuffer, sizeof(rcvBuffer)); + createMainfluxChannel(); + + MQTTPacket_connectData data = MQTTPacket_connectData_initializer; + data.willFlag = 0; + data.MQTTVersion = 3; + data.clientID.cstring = "STM32F4"; + data.username.cstring = mfThingId; + data.password.cstring = mfThingPass; + data.keepAliveInterval = 60; + data.cleansession = 1; + + ret = MQTTConnect(&mqttClient, &data); + if (ret != MQTT_SUCCESS) + { + printf("MQTTConnect failed.\n"); + return ret; + } + + ret = MQTTSubscribe(&mqttClient, mfChannelId, QOS0, mqttMessageArrived); + if (ret != MQTT_SUCCESS) + { + printf("MQTT Subscribe failed.\n"); + return ret; + } + + return MQTT_SUCCESS; +} + +void mqttMessageArrived(MessageData *msg) +{ + MQTTMessage *message = msg->message; + memset(msgBuffer, 0, sizeof(msgBuffer)); + memcpy(msgBuffer, message->payload, message->payloadlen); + + printf("MQTT MSG[%d]:%s\n", (int)message->payloadlen, msgBuffer); +} \ No newline at end of file diff --git a/targets/stm32/mqtt/src/MQTTInterface.c b/targets/stm32/mqtt/src/MQTTInterface.c new file mode 100644 index 0000000..2ff714a --- /dev/null +++ b/targets/stm32/mqtt/src/MQTTInterface.c @@ -0,0 +1,111 @@ +#include + +#include "lwip.h" +#include "lwip/api.h" +#include "lwip/sockets.h" +#include "stm32f4xx_hal.h" +#include "MQTTInterface.h" + + +#define MQTT_PORT 1883 + +uint32_t MilliTimer; + +char timerIsExpired(Timer *timer) { + long left = timer->end_time - MilliTimer; + return (left < 0); +} + +void timerCountDownMS(Timer *timer, unsigned int timeout) { + timer->end_time = MilliTimer + timeout; +} + +void timerCountDown(Timer *timer, unsigned int timeout) { + timer->end_time = MilliTimer + (timeout * 1000); +} + +int timerLeftMS(Timer *timer) { + long left = timer->end_time - MilliTimer; + return (left < 0) ? 0 : left; +} + +void initTimer(Timer *timer) { + timer->end_time = 0; +} + +void newNetwork(Network *n) { + n->conn = NULL; + n->buf = NULL; + n->offset = 0; + n->mqttread = netRead; + n->mqttwrite = netWrite; + n->disconnect = netDisconnect; +} + +int connectNetwork(Network *n, char *ip, int port) { + err_t err; + + n->conn = netconn_new(NETCONN_TCP); + if (n->conn != NULL) { + err = netconn_connect(n->conn, &ip, port); + + if (err != ERR_OK) { + netconn_delete(n->conn); + return -1; + } + } + + return 0; +} + +int netRead(Network *n, unsigned char *buffer, int len, int timeout_ms) { + int rc; + struct netbuf *inbuf; + int offset = 0; + int bytes = 0; + + while(bytes < len) { + if(n->buf != NULL) { + inbuf = n->buf; + offset = n->offset; + rc = ERR_OK; + } else { + rc = netconn_recv(n->conn, &inbuf); + offset = 0; + } + + if(rc != ERR_OK) { + if(rc != ERR_TIMEOUT) { + bytes = -1; + } + break; + } else { + int nblen = netbuf_len(inbuf) - offset; + if((bytes+nblen) > len) { + netbuf_copy_partial(inbuf, buffer+bytes, len-bytes,offset); + n->buf = inbuf; + n->offset = offset + len - bytes; + bytes = len; + } else { + netbuf_copy_partial(inbuf, buffer+bytes, nblen, offset); + bytes += nblen; + netbuf_delete(inbuf); + n->buf = NULL; + n->offset = 0; + } + } + } + return bytes; +} + +int netWrite(Network *n, unsigned char *buffer, int len, int timeout_ms) { + int rc = netconn_write(n->conn, buffer, len, NETCONN_NOCOPY); + if(rc != ERR_OK) return -1; + return len; +} + +void netDisconnect(Network *n) { + netconn_close(n->conn); + netconn_delete(n->conn); + n->conn = NULL; +} \ No newline at end of file From 1f6ea759a5e01cb60e182d86e5a54ef9a64c7904 Mon Sep 17 00:00:00 2001 From: 1998-felix Date: Thu, 24 Aug 2023 14:30:56 +0300 Subject: [PATCH 03/15] Add README.nd Signed-off-by: 1998-felix --- targets/esp32/mqtt/Makefile | 18 ++++++++++++++++++ targets/esp32/mqtt/README.md | 22 ++++++++++++++++++++++ targets/esp32/mqtt/src/cnetwork.c | 4 ++-- targets/esp32/mqtt/src/main.c | 4 ++-- 4 files changed, 44 insertions(+), 4 deletions(-) create mode 100644 targets/esp32/mqtt/Makefile create mode 100644 targets/esp32/mqtt/README.md diff --git a/targets/esp32/mqtt/Makefile b/targets/esp32/mqtt/Makefile new file mode 100644 index 0000000..b40d8ef --- /dev/null +++ b/targets/esp32/mqtt/Makefile @@ -0,0 +1,18 @@ +all: + platformio -f run + +upload: + platformio -f run --target upload + +clean: + platformio -f run --target clean + +program: + platformio -f run --target program + +uploadfs: + platformio -f run --target uploadfs + +update: + platformio -f update + \ No newline at end of file diff --git a/targets/esp32/mqtt/README.md b/targets/esp32/mqtt/README.md new file mode 100644 index 0000000..9272bff --- /dev/null +++ b/targets/esp32/mqtt/README.md @@ -0,0 +1,22 @@ +# MQTTS- esp32 target +## Requirements +1. Mainflux broker details including: hostname, ThingID, Thing Credentials and Channel ID +2. [PlatformIO](https://platformio.org/) + + +## Configure +1. Edit the [config file](include/config.h) with your broker details. +2. Update the [cnetwork.c](src/cnetwork.c) with your network details. +3. COnfigure the platform io file for your specific target. + +## Build +The project can be built by utilising the make file within the target directory + +```bash +make +``` +## Flash +Platform io generate a build directory with the fimware.bin within it. Use the make command to flash to board +```bash +make upload +``` diff --git a/targets/esp32/mqtt/src/cnetwork.c b/targets/esp32/mqtt/src/cnetwork.c index 0d7198e..2a3f523 100644 --- a/targets/esp32/mqtt/src/cnetwork.c +++ b/targets/esp32/mqtt/src/cnetwork.c @@ -1,4 +1,4 @@ -/***** +/** Implements a network interface fpr the esp. Current interface is wifi. **/ @@ -28,7 +28,7 @@ static void wifi_event_handler(void *arg, esp_event_base_t event_base, } } -// Wi-fi initial +// Wifi initial void wifi_init_softap(void) { ESP_ERROR_CHECK(esp_netif_init()); diff --git a/targets/esp32/mqtt/src/main.c b/targets/esp32/mqtt/src/main.c index 160693b..d7bc60e 100644 --- a/targets/esp32/mqtt/src/main.c +++ b/targets/esp32/mqtt/src/main.c @@ -107,7 +107,7 @@ static void mqtt_app_start(void) esp_mqtt_client_start(client); } -// main app called by rtos +// Main app called by rtos void app_main(void) { // Defualt start up logs for ESP -IDF @@ -126,6 +126,6 @@ void app_main(void) ESP_ERROR_CHECK(esp_netif_init()); ESP_ERROR_CHECK(esp_event_loop_create_default()); // Run main application - wifi_init_softap(); + ESP_ERROR_CHECK(wifi_init_softap()); mqtt_app_start(); } From bb0c3297c9af8162bfcface756567b2ddd450e41 Mon Sep 17 00:00:00 2001 From: 1998-felix Date: Thu, 24 Aug 2023 14:41:12 +0300 Subject: [PATCH 04/15] Add spaces on h files Signed-off-by: 1998-felix --- targets/esp32/mqtt/include/cnetwork.h | 2 +- targets/esp32/mqtt/include/config.h | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/targets/esp32/mqtt/include/cnetwork.h b/targets/esp32/mqtt/include/cnetwork.h index 7b2470c..57dc175 100644 --- a/targets/esp32/mqtt/include/cnetwork.h +++ b/targets/esp32/mqtt/include/cnetwork.h @@ -18,4 +18,4 @@ static void wifi_event_handler(void *arg, esp_event_base_t event_base, void wifi_init_softap(void); -#endif \ No newline at end of file +#endif diff --git a/targets/esp32/mqtt/include/config.h b/targets/esp32/mqtt/include/config.h index 3437fce..a61a948 100644 --- a/targets/esp32/mqtt/include/config.h +++ b/targets/esp32/mqtt/include/config.h @@ -9,3 +9,4 @@ char mfTopic[150]; const char *server = " "; #endif + From 69076011ae63b7292744c99dc9a6f103d588cd13 Mon Sep 17 00:00:00 2001 From: 1998-felix Date: Mon, 28 Aug 2023 07:31:03 +0300 Subject: [PATCH 05/15] Format code Signed-off-by: 1998-felix --- targets/stm32/mqtt/include/MQTTClientapp.h | 19 +++--- targets/stm32/mqtt/src/MQTTClientapp.c | 16 +++-- targets/stm32/mqtt/src/MQTTInterface.c | 75 ++++++++++++++-------- 3 files changed, 68 insertions(+), 42 deletions(-) diff --git a/targets/stm32/mqtt/include/MQTTClientapp.h b/targets/stm32/mqtt/include/MQTTClientapp.h index 71945c9..5d71636 100644 --- a/targets/stm32/mqtt/include/MQTTClientapp.h +++ b/targets/stm32/mqtt/include/MQTTClientapp.h @@ -1,27 +1,26 @@ - #ifndef MQTT_CLIENT_APP_H_ #define MQTT_CLIENT_APP_H_ +#include + #include "MQTTClient.h" #include "MQTTInterface.h" #include "cmsis_os.h" #include "config.h" -#include - -#define MQTT_PORT 1883 -#define MQTT_BUFSIZE 1024 +#define MQTT_PORT 1883 +#define MQTT_BUFSIZE 1024 -Network net; -MQTTClient mqttClient; +Network net; +MQTTClient mqttClient; -uint8_t sndBuffer[MQTT_BUFSIZE]; +uint8_t sndBuffer[MQTT_BUFSIZE]; uint8_t rcvBuffer[MQTT_BUFSIZE]; uint8_t msgBuffer[MQTT_BUFSIZE]; void mqttClientSubTask(void const *argument); void mqttClientPubTask(void const *argument); -int mqttConnectBroker(void); -void mqttMessageArrived(MessageData* msg); +int mqttConnectBroker(void); +void mqttMessageArrived(MessageData *msg); #endif diff --git a/targets/stm32/mqtt/src/MQTTClientapp.c b/targets/stm32/mqtt/src/MQTTClientapp.c index a1e84b8..616562e 100644 --- a/targets/stm32/mqtt/src/MQTTClientapp.c +++ b/targets/stm32/mqtt/src/MQTTClientapp.c @@ -1,6 +1,10 @@ #include "main.h" #include "MQTTClientapp.h" +#define MESSAGE_DELAY 1000 +#define OS_DELAY 100 +#define KEEP_ALIVE_INT 60 + void createMainfluxChannel(void) { const char *_preId = "channels/"; @@ -18,12 +22,12 @@ void mqttClientSubTask(void const *argument) { MQTTDisconnect(&mqttClient); mqttConnectBroker(); - osDelay(1000); + osDelay(MESSAGE_DELAY); } else { - MQTTYield(&mqttClient, 1000); - osDelay(100); + MQTTYield(&mqttClient, MESSAGE_DELAY); + osDelay(OS_DELAY); } } } @@ -42,7 +46,7 @@ void mqttClientPubTask(void const *argument) MQTTPublish(&mqttClient, mfTopic, &message); } - osDelay(1000); + osDelay(MESSAGE_DELAY); } } @@ -65,7 +69,7 @@ int mqttConnectBroker() return -1; } - MQTTClientInit(&mqttClient, &net, 1000, sndBuffer, sizeof(sndBuffer), rcvBuffer, sizeof(rcvBuffer)); + MQTTClientInit(&mqttClient, &net, MESSAGE_DELAY, sndBuffer, sizeof(sndBuffer), rcvBuffer, sizeof(rcvBuffer)); createMainfluxChannel(); MQTTPacket_connectData data = MQTTPacket_connectData_initializer; @@ -74,7 +78,7 @@ int mqttConnectBroker() data.clientID.cstring = "STM32F4"; data.username.cstring = mfThingId; data.password.cstring = mfThingPass; - data.keepAliveInterval = 60; + data.keepAliveInterval = KEEP_ALIVE_INT; data.cleansession = 1; ret = MQTTConnect(&mqttClient, &data); diff --git a/targets/stm32/mqtt/src/MQTTInterface.c b/targets/stm32/mqtt/src/MQTTInterface.c index 2ff714a..d1f2613 100644 --- a/targets/stm32/mqtt/src/MQTTInterface.c +++ b/targets/stm32/mqtt/src/MQTTInterface.c @@ -6,34 +6,39 @@ #include "stm32f4xx_hal.h" #include "MQTTInterface.h" - -#define MQTT_PORT 1883 +#define MQTT_PORT 1883 uint32_t MilliTimer; -char timerIsExpired(Timer *timer) { +char timerIsExpired(Timer *timer) +{ long left = timer->end_time - MilliTimer; return (left < 0); } -void timerCountDownMS(Timer *timer, unsigned int timeout) { +void timerCountDownMS(Timer *timer, unsigned int timeout) +{ timer->end_time = MilliTimer + timeout; } -void timerCountDown(Timer *timer, unsigned int timeout) { +void timerCountDown(Timer *timer, unsigned int timeout) +{ timer->end_time = MilliTimer + (timeout * 1000); } -int timerLeftMS(Timer *timer) { +int timerLeftMS(Timer *timer) +{ long left = timer->end_time - MilliTimer; return (left < 0) ? 0 : left; } -void initTimer(Timer *timer) { +void initTimer(Timer *timer) +{ timer->end_time = 0; } -void newNetwork(Network *n) { +void newNetwork(Network *n) +{ n->conn = NULL; n->buf = NULL; n->offset = 0; @@ -42,14 +47,17 @@ void newNetwork(Network *n) { n->disconnect = netDisconnect; } -int connectNetwork(Network *n, char *ip, int port) { +int connectNetwork(Network *n, char *ip, int port) +{ err_t err; n->conn = netconn_new(NETCONN_TCP); - if (n->conn != NULL) { + if (n->conn != NULL) + { err = netconn_connect(n->conn, &ip, port); - if (err != ERR_OK) { + if (err != ERR_OK) + { netconn_delete(n->conn); return -1; } @@ -58,36 +66,48 @@ int connectNetwork(Network *n, char *ip, int port) { return 0; } -int netRead(Network *n, unsigned char *buffer, int len, int timeout_ms) { +int netRead(Network *n, unsigned char *buffer, int len, int timeout_ms) +{ int rc; struct netbuf *inbuf; int offset = 0; int bytes = 0; - while(bytes < len) { - if(n->buf != NULL) { + while (bytes < len) + { + if (n->buf != NULL) + { inbuf = n->buf; offset = n->offset; rc = ERR_OK; - } else { + } + else + { rc = netconn_recv(n->conn, &inbuf); offset = 0; } - if(rc != ERR_OK) { - if(rc != ERR_TIMEOUT) { + if (rc != ERR_OK) + { + if (rc != ERR_TIMEOUT) + { bytes = -1; } break; - } else { + } + else + { int nblen = netbuf_len(inbuf) - offset; - if((bytes+nblen) > len) { - netbuf_copy_partial(inbuf, buffer+bytes, len-bytes,offset); + if ((bytes + nblen) > len) + { + netbuf_copy_partial(inbuf, buffer + bytes, len - bytes, offset); n->buf = inbuf; n->offset = offset + len - bytes; bytes = len; - } else { - netbuf_copy_partial(inbuf, buffer+bytes, nblen, offset); + } + else + { + netbuf_copy_partial(inbuf, buffer + bytes, nblen, offset); bytes += nblen; netbuf_delete(inbuf); n->buf = NULL; @@ -98,14 +118,17 @@ int netRead(Network *n, unsigned char *buffer, int len, int timeout_ms) { return bytes; } -int netWrite(Network *n, unsigned char *buffer, int len, int timeout_ms) { +int netWrite(Network *n, unsigned char *buffer, int len, int timeout_ms) +{ int rc = netconn_write(n->conn, buffer, len, NETCONN_NOCOPY); - if(rc != ERR_OK) return -1; + if (rc != ERR_OK) + return -1; return len; } -void netDisconnect(Network *n) { +void netDisconnect(Network *n) +{ netconn_close(n->conn); - netconn_delete(n->conn); + netconn_delete(n->conn); n->conn = NULL; } \ No newline at end of file From 7adb0d95de024f829e7f2e03d91ffe63d8aed87e Mon Sep 17 00:00:00 2001 From: 1998-felix Date: Tue, 29 Aug 2023 07:44:20 +0300 Subject: [PATCH 06/15] Update Makefile Signed-off-by: 1998-felix --- targets/esp32/mqtt/Makefile | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/targets/esp32/mqtt/Makefile b/targets/esp32/mqtt/Makefile index b40d8ef..a0c84eb 100644 --- a/targets/esp32/mqtt/Makefile +++ b/targets/esp32/mqtt/Makefile @@ -1,18 +1,12 @@ -all: - platformio -f run - -upload: - platformio -f run --target upload - -clean: - platformio -f run --target clean - -program: - platformio -f run --target program - -uploadfs: - platformio -f run --target uploadfs - -update: - platformio -f update - \ No newline at end of file +define platformio + platformio -f run --target $(1) +endef + +run-%: + $(call platformio,$*) + +upload: run-upload +clean: run-clean +program: run-program +uploadfs:run-uploadfs +update: run-update From 30c419a155904b808b0a560187e3f2188c1ea10e Mon Sep 17 00:00:00 2001 From: 1998-felix Date: Tue, 29 Aug 2023 09:48:54 +0300 Subject: [PATCH 07/15] Update function name Signed-off-by: 1998-felix --- targets/esp32/mqtt/src/main.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/targets/esp32/mqtt/src/main.c b/targets/esp32/mqtt/src/main.c index d7bc60e..ff286b4 100644 --- a/targets/esp32/mqtt/src/main.c +++ b/targets/esp32/mqtt/src/main.c @@ -33,7 +33,7 @@ static void log_error_if_nonzero(const char *message, int error_code) ESP_LOGE(TAG, "Last error %s: 0x%x", message, error_code); } } -void create_mainflux_channel(void) +void create_mainflux_topic(void) { const char *_preId = "channels/"; const char *_postId = "/messages"; @@ -48,7 +48,7 @@ static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_ esp_mqtt_event_handle_t event = event_data; esp_mqtt_client_handle_t client = event->client; int msg_id; - create_mainflux_channel(); + create_mainflux_topic(); switch ((esp_mqtt_event_id_t)event_id) { case MQTT_EVENT_CONNECTED: From 157dbb06eded818a66ce4dad751c20ba97f7b558 Mon Sep 17 00:00:00 2001 From: 1998-felix Date: Wed, 30 Aug 2023 02:35:42 +0300 Subject: [PATCH 08/15] Change variable name Signed-off-by: 1998-felix --- targets/esp32/mqtt/include/config.h | 2 +- targets/esp32/mqtt/src/main.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/targets/esp32/mqtt/include/config.h b/targets/esp32/mqtt/include/config.h index a61a948..f1f9cc7 100644 --- a/targets/esp32/mqtt/include/config.h +++ b/targets/esp32/mqtt/include/config.h @@ -2,7 +2,7 @@ #define CONFIG_H const char *mfThingId = " "; -const char *mfThingPass = " "; +const char *mfThingKey = " "; const char *mfChannelId = " "; char mfTopic[150]; diff --git a/targets/esp32/mqtt/src/main.c b/targets/esp32/mqtt/src/main.c index ff286b4..f2a8c96 100644 --- a/targets/esp32/mqtt/src/main.c +++ b/targets/esp32/mqtt/src/main.c @@ -100,7 +100,7 @@ static void mqtt_app_start(void) .broker.address.uri = server, .credentials.client_id = CLIENT_ID, .credentials.username = mfThingId, - .credentials.authentication.password = mfThingPass, + .credentials.authentication.password = mfThingKey, }; esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg); esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL); From 92066082406a9f15dbb34ce71aafbcae991dbde2 Mon Sep 17 00:00:00 2001 From: 1998-felix Date: Thu, 31 Aug 2023 07:44:48 +0300 Subject: [PATCH 09/15] Change function name Signed-off-by: 1998-felix --- targets/esp32/mqtt/.vscode/extensions.json | 10 ++++++++++ targets/esp32/mqtt/src/main.c | 4 ++-- 2 files changed, 12 insertions(+), 2 deletions(-) create mode 100644 targets/esp32/mqtt/.vscode/extensions.json diff --git a/targets/esp32/mqtt/.vscode/extensions.json b/targets/esp32/mqtt/.vscode/extensions.json new file mode 100644 index 0000000..080e70d --- /dev/null +++ b/targets/esp32/mqtt/.vscode/extensions.json @@ -0,0 +1,10 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ], + "unwantedRecommendations": [ + "ms-vscode.cpptools-extension-pack" + ] +} diff --git a/targets/esp32/mqtt/src/main.c b/targets/esp32/mqtt/src/main.c index f2a8c96..7850ea2 100644 --- a/targets/esp32/mqtt/src/main.c +++ b/targets/esp32/mqtt/src/main.c @@ -33,7 +33,7 @@ static void log_error_if_nonzero(const char *message, int error_code) ESP_LOGE(TAG, "Last error %s: 0x%x", message, error_code); } } -void create_mainflux_topic(void) +void format_mainflux_message_topic(void) { const char *_preId = "channels/"; const char *_postId = "/messages"; @@ -48,7 +48,7 @@ static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_ esp_mqtt_event_handle_t event = event_data; esp_mqtt_client_handle_t client = event->client; int msg_id; - create_mainflux_topic(); + format_mainflux_message_topic(); switch ((esp_mqtt_event_id_t)event_id) { case MQTT_EVENT_CONNECTED: From 4aaeba3078cefa64790b62c2e2a394ea41166f74 Mon Sep 17 00:00:00 2001 From: 1998-felix Date: Fri, 1 Sep 2023 14:47:31 +0300 Subject: [PATCH 10/15] Cleaning up Signed-off-by: 1998-felix --- targets/esp32/mqtt/.gitignore | 5 +---- targets/esp32/mqtt/.vscode/extensions.json | 10 ---------- targets/esp32/mqtt/include/config.h | 3 ++- targets/esp32/mqtt/src/main.c | 3 --- 4 files changed, 3 insertions(+), 18 deletions(-) delete mode 100644 targets/esp32/mqtt/.vscode/extensions.json diff --git a/targets/esp32/mqtt/.gitignore b/targets/esp32/mqtt/.gitignore index c493534..03e294b 100644 --- a/targets/esp32/mqtt/.gitignore +++ b/targets/esp32/mqtt/.gitignore @@ -1,6 +1,3 @@ .pio -.vscode/.browse.c_cpp.db* -.vscode/c_cpp_properties.json -.vscode/launch.json -.vscode/ipch +.vscode sdkconfig.esp32-c3-devkitc-02 diff --git a/targets/esp32/mqtt/.vscode/extensions.json b/targets/esp32/mqtt/.vscode/extensions.json deleted file mode 100644 index 080e70d..0000000 --- a/targets/esp32/mqtt/.vscode/extensions.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - // See http://go.microsoft.com/fwlink/?LinkId=827846 - // for the documentation about the extensions.json format - "recommendations": [ - "platformio.platformio-ide" - ], - "unwantedRecommendations": [ - "ms-vscode.cpptools-extension-pack" - ] -} diff --git a/targets/esp32/mqtt/include/config.h b/targets/esp32/mqtt/include/config.h index f1f9cc7..f5b56a6 100644 --- a/targets/esp32/mqtt/include/config.h +++ b/targets/esp32/mqtt/include/config.h @@ -1,6 +1,8 @@ #ifndef CONFIG_H #define CONFIG_H +#define CLIENTID "" + const char *mfThingId = " "; const char *mfThingKey = " "; const char *mfChannelId = " "; @@ -9,4 +11,3 @@ char mfTopic[150]; const char *server = " "; #endif - diff --git a/targets/esp32/mqtt/src/main.c b/targets/esp32/mqtt/src/main.c index 7850ea2..0070784 100644 --- a/targets/esp32/mqtt/src/main.c +++ b/targets/esp32/mqtt/src/main.c @@ -22,8 +22,6 @@ #include "cnetwork.h" #include "config.h" -#define CLIENT_ID "ESP32" - static const char *TAG = "MQTT_MAINFLUX"; static void log_error_if_nonzero(const char *message, int error_code) @@ -44,7 +42,6 @@ void format_mainflux_message_topic(void) static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) { - ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%" PRIi32 "", base, event_id); esp_mqtt_event_handle_t event = event_data; esp_mqtt_client_handle_t client = event->client; int msg_id; From 77e505e20a3b7bda86f2b6be97895ed2e57e5ef8 Mon Sep 17 00:00:00 2001 From: 1998-felix Date: Mon, 4 Sep 2023 14:41:46 +0300 Subject: [PATCH 11/15] Add coap support Signed-off-by: 1998-felix --- targets/esp32/coap/.gitignore | 3 + targets/esp32/coap/CMakeLists.txt | 6 + targets/esp32/coap/README.md | 0 targets/esp32/coap/platformio.ini | 14 ++ targets/esp32/coap/src/CMakeLists.txt | 6 + targets/esp32/coap/src/idf_component.yml | 5 + targets/esp32/coap/src/main.c | 290 +++++++++++++++++++++++ 7 files changed, 324 insertions(+) create mode 100644 targets/esp32/coap/.gitignore create mode 100644 targets/esp32/coap/CMakeLists.txt create mode 100644 targets/esp32/coap/README.md create mode 100644 targets/esp32/coap/platformio.ini create mode 100644 targets/esp32/coap/src/CMakeLists.txt create mode 100644 targets/esp32/coap/src/idf_component.yml create mode 100644 targets/esp32/coap/src/main.c diff --git a/targets/esp32/coap/.gitignore b/targets/esp32/coap/.gitignore new file mode 100644 index 0000000..469705b --- /dev/null +++ b/targets/esp32/coap/.gitignore @@ -0,0 +1,3 @@ +.pio +.vscode +sdkconfig.esp32doit-devkit-v1 diff --git a/targets/esp32/coap/CMakeLists.txt b/targets/esp32/coap/CMakeLists.txt new file mode 100644 index 0000000..e776a83 --- /dev/null +++ b/targets/esp32/coap/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) + +set(EXTRA_COMPONENT_DIRS $ENV{IDF_PATH}/examples/common_components/protocol_examples_common) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(coap_client) diff --git a/targets/esp32/coap/README.md b/targets/esp32/coap/README.md new file mode 100644 index 0000000..e69de29 diff --git a/targets/esp32/coap/platformio.ini b/targets/esp32/coap/platformio.ini new file mode 100644 index 0000000..6bcbd9b --- /dev/null +++ b/targets/esp32/coap/platformio.ini @@ -0,0 +1,14 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:esp32doit-devkit-v1] +platform = espressif32 +board = esp32doit-devkit-v1 +framework = espidf diff --git a/targets/esp32/coap/src/CMakeLists.txt b/targets/esp32/coap/src/CMakeLists.txt new file mode 100644 index 0000000..ab3ad38 --- /dev/null +++ b/targets/esp32/coap/src/CMakeLists.txt @@ -0,0 +1,6 @@ +# This file was automatically generated for projects +# without default 'CMakeLists.txt' file. + +FILE(GLOB_RECURSE app_sources ${CMAKE_SOURCE_DIR}/src/*.*) + +idf_component_register(SRCS ${app_sources}) diff --git a/targets/esp32/coap/src/idf_component.yml b/targets/esp32/coap/src/idf_component.yml new file mode 100644 index 0000000..d99d1f9 --- /dev/null +++ b/targets/esp32/coap/src/idf_component.yml @@ -0,0 +1,5 @@ +dependencies: + espressif/coap: + version: ^4.3.0 +description: CoAP Client +version: 1.0.0 diff --git a/targets/esp32/coap/src/main.c b/targets/esp32/coap/src/main.c new file mode 100644 index 0000000..04810a7 --- /dev/null +++ b/targets/esp32/coap/src/main.c @@ -0,0 +1,290 @@ +#include +#include +#include +#include + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/event_groups.h" +#include "esp_log.h" +#include "esp_wifi.h" +#include "esp_event.h" +#include "nvs_flash.h" + +#include "protocol_examples_common.h" + +#include "coap3/coap.h" + + +#ifndef CONFIG_COAP_CLIENT_SUPPORT +#error COAP_CLIENT_SUPPORT needs to be enabled +#endif + +#define COAP_DEFAULT_TIME_SEC 60 +e EXAMPLE_COAP_PSK_KEY CONFIG_EXAMPLE_COAP_PSK_KEY +#define EXAMPLE_COAP_PSK_IDENTITY CONFIG_EXAMPLE_COAP_PSK_IDENTITY +#define EXAMPLE_COAP_LOG_DEFAULT_LEVEL CONFIG_COAP_LOG_DEFAULT_LEVEL +#define COAP_DEFAULT_DEMO_URI CONFIG_EXAMPLE_TARGET_DOMAIN_URI + +const static char *TAG = "CoAP_client"; + +static int resp_wait = 1; +static coap_optlist_t *optlist = NULL; +static int wait_ms; + +static coap_response_t +message_handler(coap_session_t *session, + const coap_pdu_t *sent, + const coap_pdu_t *received, + const coap_mid_t mid) +{ + const unsigned char *data = NULL; + size_t data_len; + size_t offset; + size_t total; + coap_pdu_code_t rcvd_code = coap_pdu_get_code(received); + + if (COAP_RESPONSE_CLASS(rcvd_code) == 2) { + if (coap_get_data_large(received, &data_len, &data, &offset, &total)) { + if (data_len != total) { + printf("Unexpected partial data received offset %u, length %u\n", offset, data_len); + } + printf("Received:\n%.*s\n", (int)data_len, data); + resp_wait = 0; + } + return COAP_RESPONSE_OK; + } + printf("%d.%02d", (rcvd_code >> 5), rcvd_code & 0x1F); + if (coap_get_data_large(received, &data_len, &data, &offset, &total)) { + printf(": "); + while (data_len--) { + printf("%c", isprint(*data) ? *data : '.'); + data++; + } + } + printf("\n"); + resp_wait = 0; + return COAP_RESPONSE_OK; +} + +static void +coap_log_handler (coap_log_t level, const char *message) +{ + uint32_t esp_level = ESP_LOG_INFO; + const char *cp = strchr(message, '\n'); + + while (cp) { + ESP_LOG_LEVEL(esp_level, TAG, "%.*s", (int)(cp - message), message); + message = cp + 1; + cp = strchr(message, '\n'); + } + if (message[0] != '\000') { + ESP_LOG_LEVEL(esp_level, TAG, "%s", message); + } +} + +static int +coap_build_optlist(coap_uri_t *uri) +{ +#define BUFSIZE 40 + unsigned char _buf[BUFSIZE]; + unsigned char *buf; + size_t buflen; + int res; + + optlist = NULL; + + if (uri->scheme == COAP_URI_SCHEME_COAPS && !coap_dtls_is_supported()) { + ESP_LOGE(TAG, "MbedTLS DTLS Client Mode not configured"); + return 0; + } + if (uri->scheme == COAP_URI_SCHEME_COAPS_TCP && !coap_tls_is_supported()) { + ESP_LOGE(TAG, "MbedTLS TLS Client Mode not configured"); + return 0; + } + if (uri->scheme == COAP_URI_SCHEME_COAP_TCP && !coap_tcp_is_supported()) { + ESP_LOGE(TAG, "TCP Client Mode not configured"); + return 0; + } + + if (uri->path.length) { + buflen = BUFSIZE; + buf = _buf; + res = coap_split_path(uri->path.s, uri->path.length, buf, &buflen); + + while (res--) { + coap_insert_optlist(&optlist, + coap_new_optlist(COAP_OPTION_URI_PATH, + coap_opt_length(buf), + coap_opt_value(buf))); + + buf += coap_opt_size(buf); + } + } + + if (uri->query.length) { + buflen = BUFSIZE; + buf = _buf; + res = coap_split_query(uri->query.s, uri->query.length, buf, &buflen); + + while (res--) { + coap_insert_optlist(&optlist, + coap_new_optlist(COAP_OPTION_URI_QUERY, + coap_opt_length(buf), + coap_opt_value(buf))); + + buf += coap_opt_size(buf); + } + } + return 1; +} + +static void coap_example_client(void *p) +{ + coap_address_t dst_addr; + static coap_uri_t uri; + const char *server_uri = COAP_DEFAULT_DEMO_URI; + coap_context_t *ctx = NULL; + coap_session_t *session = NULL; + coap_pdu_t *request = NULL; + unsigned char token[8]; + size_t tokenlength; + coap_addr_info_t *info_list = NULL; + coap_proto_t proto; + char tmpbuf[INET6_ADDRSTRLEN]; + + /* Initialize libcoap library */ + coap_startup(); + + /* Set up the CoAP logging */ + coap_set_log_handler(coap_log_handler); + coap_set_log_level(EXAMPLE_COAP_LOG_DEFAULT_LEVEL); + + /* Set up the CoAP context */ + ctx = coap_new_context(NULL); + if (!ctx) { + ESP_LOGE(TAG, "coap_new_context() failed"); + goto clean_up; + } + coap_context_set_block_mode(ctx, + COAP_BLOCK_USE_LIBCOAP | COAP_BLOCK_SINGLE_BODY); + + coap_register_response_handler(ctx, message_handler); + + if (coap_split_uri((const uint8_t *)server_uri, strlen(server_uri), &uri) == -1) { + ESP_LOGE(TAG, "CoAP server uri %s error", server_uri); + goto clean_up; + } + if (!coap_build_optlist(&uri)) { + goto clean_up; + } + + info_list = coap_resolve_address_info(&uri.host, uri.port, uri.port, + uri.port, uri.port, + 0, + 1 << uri.scheme, + COAP_RESOLVE_TYPE_REMOTE); + + if (info_list == NULL) { + ESP_LOGE(TAG, "failed to resolve address"); + goto clean_up; + } + proto = info_list->proto; + memcpy(&dst_addr, &info_list->addr, sizeof(dst_addr)); + coap_free_address_info(info_list); + + /* This is to keep the test suites happy */ + coap_print_ip_addr(&dst_addr, tmpbuf, sizeof(tmpbuf)); + ESP_LOGI(TAG, "DNS lookup succeeded. IP=%s", tmpbuf); + + /* + * Note that if the URI starts with just coap:// (not coaps://) the + * session will still be plain text. + */ + if (uri.scheme == COAP_URI_SCHEME_COAPS || uri.scheme == COAP_URI_SCHEME_COAPS_TCP || uri.scheme == COAP_URI_SCHEME_COAPS_WS) { +#ifndef CONFIG_MBEDTLS_TLS_CLIENT + ESP_LOGE(TAG, "MbedTLS (D)TLS Client Mode not configured"); + goto clean_up; +#endif /* CONFIG_MBEDTLS_TLS_CLIENT */ + +#ifdef CONFIG_COAP_MBEDTLS_PSK + session = coap_start_psk_session(ctx, &dst_addr, &uri, proto); +#endif /* CONFIG_COAP_MBEDTLS_PSK */ + +#ifdef CONFIG_COAP_MBEDTLS_PKI + session = coap_start_pki_session(ctx, &dst_addr, &uri, proto); +#endif /* CONFIG_COAP_MBEDTLS_PKI */ + } else { + session = coap_new_client_session(ctx, NULL, &dst_addr, proto); + } + if (!session) { + ESP_LOGE(TAG, "coap_new_client_session() failed"); + goto clean_up; + } +#ifdef CONFIG_COAP_WEBSOCKETS + if (proto == COAP_PROTO_WS || proto == COAP_PROTO_WSS) { + coap_ws_set_host_request(session, &uri.host); + } +#endif /* CONFIG_COAP_WEBSOCKETS */ + + while (1) { + request = coap_new_pdu(coap_is_mcast(&dst_addr) ? COAP_MESSAGE_NON : COAP_MESSAGE_CON, + COAP_REQUEST_CODE_GET, session); + if (!request) { + ESP_LOGE(TAG, "coap_new_pdu() failed"); + goto clean_up; + } + /* Add in an unique token */ + coap_session_new_token(session, &tokenlength, token); + coap_add_token(request, tokenlength, token); + coap_add_optlist_pdu(request, &optlist); + + resp_wait = 1; + coap_send(session, request); + + wait_ms = COAP_DEFAULT_TIME_SEC * 1000; + + while (resp_wait) { + int result = coap_io_process(ctx, wait_ms > 1000 ? 1000 : wait_ms); + if (result >= 0) { + if (result >= wait_ms) { + ESP_LOGE(TAG, "No response from server"); + break; + } else { + wait_ms -= result; + } + } + } + for (int countdown = 10; countdown >= 0; countdown--) { + ESP_LOGI(TAG, "%d... ", countdown); + vTaskDelay(1000 / portTICK_PERIOD_MS); + } + ESP_LOGI(TAG, "Starting again!"); + } + +clean_up: + if (optlist) { + coap_delete_optlist(optlist); + optlist = NULL; + } + if (session) { + coap_session_release(session); + } + if (ctx) { + coap_free_context(ctx); + } + coap_cleanup(); + + ESP_LOGI(TAG, "Finished"); + vTaskDelete(NULL); +} + +void app_main(void) +{ + ESP_ERROR_CHECK( nvs_flash_init() ); + ESP_ERROR_CHECK(esp_netif_init()); + ESP_ERROR_CHECK(esp_event_loop_create_default()); + ESP_ERROR_CHECK(example_connect()); + + xTaskCreate(coap_example_client, "coap", 8 * 1024, NULL, 5, NULL); +} From 8e1b68f1d933ed465cb7afcbce4f447f2489c544 Mon Sep 17 00:00:00 2001 From: 1998-felix Date: Wed, 6 Sep 2023 13:16:13 +0300 Subject: [PATCH 12/15] Add config file Signed-off-by: 1998-felix --- targets/esp32/coap/include/config.h | 13 +++ targets/esp32/coap/src/main.c | 128 ++++++++++++++++------------ 2 files changed, 88 insertions(+), 53 deletions(-) create mode 100644 targets/esp32/coap/include/config.h diff --git a/targets/esp32/coap/include/config.h b/targets/esp32/coap/include/config.h new file mode 100644 index 0000000..10354bf --- /dev/null +++ b/targets/esp32/coap/include/config.h @@ -0,0 +1,13 @@ +#ifndef CONFIG_H +#define CONFIG_H + +#define CLIENTID "" + +const char *mfThingId = " "; +const char *mfThingKey = " "; +const char *mfChannelId = " "; +char mfTopic[150]; + +const char *server = " "; + +#endif \ No newline at end of file diff --git a/targets/esp32/coap/src/main.c b/targets/esp32/coap/src/main.c index 04810a7..3535dc2 100644 --- a/targets/esp32/coap/src/main.c +++ b/targets/esp32/coap/src/main.c @@ -15,16 +15,7 @@ #include "coap3/coap.h" - -#ifndef CONFIG_COAP_CLIENT_SUPPORT -#error COAP_CLIENT_SUPPORT needs to be enabled -#endif - #define COAP_DEFAULT_TIME_SEC 60 -e EXAMPLE_COAP_PSK_KEY CONFIG_EXAMPLE_COAP_PSK_KEY -#define EXAMPLE_COAP_PSK_IDENTITY CONFIG_EXAMPLE_COAP_PSK_IDENTITY -#define EXAMPLE_COAP_LOG_DEFAULT_LEVEL CONFIG_COAP_LOG_DEFAULT_LEVEL -#define COAP_DEFAULT_DEMO_URI CONFIG_EXAMPLE_TARGET_DOMAIN_URI const static char *TAG = "CoAP_client"; @@ -32,11 +23,10 @@ static int resp_wait = 1; static coap_optlist_t *optlist = NULL; static int wait_ms; -static coap_response_t -message_handler(coap_session_t *session, - const coap_pdu_t *sent, - const coap_pdu_t *received, - const coap_mid_t mid) +static coap_response_t message_handler(coap_session_t *session, + const coap_pdu_t *sent, + const coap_pdu_t *received, + const coap_mid_t mid) { const unsigned char *data = NULL; size_t data_len; @@ -44,9 +34,12 @@ message_handler(coap_session_t *session, size_t total; coap_pdu_code_t rcvd_code = coap_pdu_get_code(received); - if (COAP_RESPONSE_CLASS(rcvd_code) == 2) { - if (coap_get_data_large(received, &data_len, &data, &offset, &total)) { - if (data_len != total) { + if (COAP_RESPONSE_CLASS(rcvd_code) == 2) + { + if (coap_get_data_large(received, &data_len, &data, &offset, &total)) + { + if (data_len != total) + { printf("Unexpected partial data received offset %u, length %u\n", offset, data_len); } printf("Received:\n%.*s\n", (int)data_len, data); @@ -55,9 +48,11 @@ message_handler(coap_session_t *session, return COAP_RESPONSE_OK; } printf("%d.%02d", (rcvd_code >> 5), rcvd_code & 0x1F); - if (coap_get_data_large(received, &data_len, &data, &offset, &total)) { + if (coap_get_data_large(received, &data_len, &data, &offset, &total)) + { printf(": "); - while (data_len--) { + while (data_len--) + { printf("%c", isprint(*data) ? *data : '.'); data++; } @@ -67,24 +62,24 @@ message_handler(coap_session_t *session, return COAP_RESPONSE_OK; } -static void -coap_log_handler (coap_log_t level, const char *message) +static void coap_log_handler(coap_log_t level, const char *message) { uint32_t esp_level = ESP_LOG_INFO; const char *cp = strchr(message, '\n'); - while (cp) { + while (cp) + { ESP_LOG_LEVEL(esp_level, TAG, "%.*s", (int)(cp - message), message); message = cp + 1; cp = strchr(message, '\n'); } - if (message[0] != '\000') { + if (message[0] != '\000') + { ESP_LOG_LEVEL(esp_level, TAG, "%s", message); } } -static int -coap_build_optlist(coap_uri_t *uri) +static int coap_build_optlist(coap_uri_t *uri) { #define BUFSIZE 40 unsigned char _buf[BUFSIZE]; @@ -94,25 +89,30 @@ coap_build_optlist(coap_uri_t *uri) optlist = NULL; - if (uri->scheme == COAP_URI_SCHEME_COAPS && !coap_dtls_is_supported()) { + if (uri->scheme == COAP_URI_SCHEME_COAPS && !coap_dtls_is_supported()) + { ESP_LOGE(TAG, "MbedTLS DTLS Client Mode not configured"); return 0; } - if (uri->scheme == COAP_URI_SCHEME_COAPS_TCP && !coap_tls_is_supported()) { + if (uri->scheme == COAP_URI_SCHEME_COAPS_TCP && !coap_tls_is_supported()) + { ESP_LOGE(TAG, "MbedTLS TLS Client Mode not configured"); return 0; } - if (uri->scheme == COAP_URI_SCHEME_COAP_TCP && !coap_tcp_is_supported()) { + if (uri->scheme == COAP_URI_SCHEME_COAP_TCP && !coap_tcp_is_supported()) + { ESP_LOGE(TAG, "TCP Client Mode not configured"); return 0; } - if (uri->path.length) { + if (uri->path.length) + { buflen = BUFSIZE; buf = _buf; res = coap_split_path(uri->path.s, uri->path.length, buf, &buflen); - while (res--) { + while (res--) + { coap_insert_optlist(&optlist, coap_new_optlist(COAP_OPTION_URI_PATH, coap_opt_length(buf), @@ -122,12 +122,14 @@ coap_build_optlist(coap_uri_t *uri) } } - if (uri->query.length) { + if (uri->query.length) + { buflen = BUFSIZE; buf = _buf; res = coap_split_query(uri->query.s, uri->query.length, buf, &buflen); - while (res--) { + while (res--) + { coap_insert_optlist(&optlist, coap_new_optlist(COAP_OPTION_URI_QUERY, coap_opt_length(buf), @@ -141,9 +143,9 @@ coap_build_optlist(coap_uri_t *uri) static void coap_example_client(void *p) { - coap_address_t dst_addr; + coap_address_t dst_addr; static coap_uri_t uri; - const char *server_uri = COAP_DEFAULT_DEMO_URI; + const char *server_uri = COAP_DEFAULT_DEMO_URI; coap_context_t *ctx = NULL; coap_session_t *session = NULL; coap_pdu_t *request = NULL; @@ -162,7 +164,8 @@ static void coap_example_client(void *p) /* Set up the CoAP context */ ctx = coap_new_context(NULL); - if (!ctx) { + if (!ctx) + { ESP_LOGE(TAG, "coap_new_context() failed"); goto clean_up; } @@ -171,11 +174,13 @@ static void coap_example_client(void *p) coap_register_response_handler(ctx, message_handler); - if (coap_split_uri((const uint8_t *)server_uri, strlen(server_uri), &uri) == -1) { + if (coap_split_uri((const uint8_t *)server_uri, strlen(server_uri), &uri) == -1) + { ESP_LOGE(TAG, "CoAP server uri %s error", server_uri); goto clean_up; } - if (!coap_build_optlist(&uri)) { + if (!coap_build_optlist(&uri)) + { goto clean_up; } @@ -185,7 +190,8 @@ static void coap_example_client(void *p) 1 << uri.scheme, COAP_RESOLVE_TYPE_REMOTE); - if (info_list == NULL) { + if (info_list == NULL) + { ESP_LOGE(TAG, "failed to resolve address"); goto clean_up; } @@ -201,7 +207,8 @@ static void coap_example_client(void *p) * Note that if the URI starts with just coap:// (not coaps://) the * session will still be plain text. */ - if (uri.scheme == COAP_URI_SCHEME_COAPS || uri.scheme == COAP_URI_SCHEME_COAPS_TCP || uri.scheme == COAP_URI_SCHEME_COAPS_WS) { + if (uri.scheme == COAP_URI_SCHEME_COAPS || uri.scheme == COAP_URI_SCHEME_COAPS_TCP || uri.scheme == COAP_URI_SCHEME_COAPS_WS) + { #ifndef CONFIG_MBEDTLS_TLS_CLIENT ESP_LOGE(TAG, "MbedTLS (D)TLS Client Mode not configured"); goto clean_up; @@ -214,23 +221,29 @@ static void coap_example_client(void *p) #ifdef CONFIG_COAP_MBEDTLS_PKI session = coap_start_pki_session(ctx, &dst_addr, &uri, proto); #endif /* CONFIG_COAP_MBEDTLS_PKI */ - } else { + } + else + { session = coap_new_client_session(ctx, NULL, &dst_addr, proto); } - if (!session) { + if (!session) + { ESP_LOGE(TAG, "coap_new_client_session() failed"); goto clean_up; } #ifdef CONFIG_COAP_WEBSOCKETS - if (proto == COAP_PROTO_WS || proto == COAP_PROTO_WSS) { + if (proto == COAP_PROTO_WS || proto == COAP_PROTO_WSS) + { coap_ws_set_host_request(session, &uri.host); } #endif /* CONFIG_COAP_WEBSOCKETS */ - while (1) { + while (1) + { request = coap_new_pdu(coap_is_mcast(&dst_addr) ? COAP_MESSAGE_NON : COAP_MESSAGE_CON, COAP_REQUEST_CODE_GET, session); - if (!request) { + if (!request) + { ESP_LOGE(TAG, "coap_new_pdu() failed"); goto clean_up; } @@ -244,18 +257,24 @@ static void coap_example_client(void *p) wait_ms = COAP_DEFAULT_TIME_SEC * 1000; - while (resp_wait) { + while (resp_wait) + { int result = coap_io_process(ctx, wait_ms > 1000 ? 1000 : wait_ms); - if (result >= 0) { - if (result >= wait_ms) { + if (result >= 0) + { + if (result >= wait_ms) + { ESP_LOGE(TAG, "No response from server"); break; - } else { + } + else + { wait_ms -= result; } } } - for (int countdown = 10; countdown >= 0; countdown--) { + for (int countdown = 10; countdown >= 0; countdown--) + { ESP_LOGI(TAG, "%d... ", countdown); vTaskDelay(1000 / portTICK_PERIOD_MS); } @@ -263,14 +282,17 @@ static void coap_example_client(void *p) } clean_up: - if (optlist) { + if (optlist) + { coap_delete_optlist(optlist); optlist = NULL; } - if (session) { + if (session) + { coap_session_release(session); } - if (ctx) { + if (ctx) + { coap_free_context(ctx); } coap_cleanup(); @@ -281,7 +303,7 @@ static void coap_example_client(void *p) void app_main(void) { - ESP_ERROR_CHECK( nvs_flash_init() ); + ESP_ERROR_CHECK(nvs_flash_init()); ESP_ERROR_CHECK(esp_netif_init()); ESP_ERROR_CHECK(esp_event_loop_create_default()); ESP_ERROR_CHECK(example_connect()); From 586c7e7ffb67904644e389f690eafa0cb867fcf8 Mon Sep 17 00:00:00 2001 From: 1998-felix Date: Mon, 4 Sep 2023 14:41:46 +0300 Subject: [PATCH 13/15] Add coap support Signed-off-by: 1998-felix --- targets/esp32/coap/.gitignore | 3 + targets/esp32/coap/CMakeLists.txt | 6 + targets/esp32/coap/README.md | 0 targets/esp32/coap/platformio.ini | 14 ++ targets/esp32/coap/src/CMakeLists.txt | 6 + targets/esp32/coap/src/idf_component.yml | 5 + targets/esp32/coap/src/main.c | 290 +++++++++++++++++++++++ 7 files changed, 324 insertions(+) create mode 100644 targets/esp32/coap/.gitignore create mode 100644 targets/esp32/coap/CMakeLists.txt create mode 100644 targets/esp32/coap/README.md create mode 100644 targets/esp32/coap/platformio.ini create mode 100644 targets/esp32/coap/src/CMakeLists.txt create mode 100644 targets/esp32/coap/src/idf_component.yml create mode 100644 targets/esp32/coap/src/main.c diff --git a/targets/esp32/coap/.gitignore b/targets/esp32/coap/.gitignore new file mode 100644 index 0000000..469705b --- /dev/null +++ b/targets/esp32/coap/.gitignore @@ -0,0 +1,3 @@ +.pio +.vscode +sdkconfig.esp32doit-devkit-v1 diff --git a/targets/esp32/coap/CMakeLists.txt b/targets/esp32/coap/CMakeLists.txt new file mode 100644 index 0000000..e776a83 --- /dev/null +++ b/targets/esp32/coap/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.16) + +set(EXTRA_COMPONENT_DIRS $ENV{IDF_PATH}/examples/common_components/protocol_examples_common) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(coap_client) diff --git a/targets/esp32/coap/README.md b/targets/esp32/coap/README.md new file mode 100644 index 0000000..e69de29 diff --git a/targets/esp32/coap/platformio.ini b/targets/esp32/coap/platformio.ini new file mode 100644 index 0000000..6bcbd9b --- /dev/null +++ b/targets/esp32/coap/platformio.ini @@ -0,0 +1,14 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:esp32doit-devkit-v1] +platform = espressif32 +board = esp32doit-devkit-v1 +framework = espidf diff --git a/targets/esp32/coap/src/CMakeLists.txt b/targets/esp32/coap/src/CMakeLists.txt new file mode 100644 index 0000000..ab3ad38 --- /dev/null +++ b/targets/esp32/coap/src/CMakeLists.txt @@ -0,0 +1,6 @@ +# This file was automatically generated for projects +# without default 'CMakeLists.txt' file. + +FILE(GLOB_RECURSE app_sources ${CMAKE_SOURCE_DIR}/src/*.*) + +idf_component_register(SRCS ${app_sources}) diff --git a/targets/esp32/coap/src/idf_component.yml b/targets/esp32/coap/src/idf_component.yml new file mode 100644 index 0000000..d99d1f9 --- /dev/null +++ b/targets/esp32/coap/src/idf_component.yml @@ -0,0 +1,5 @@ +dependencies: + espressif/coap: + version: ^4.3.0 +description: CoAP Client +version: 1.0.0 diff --git a/targets/esp32/coap/src/main.c b/targets/esp32/coap/src/main.c new file mode 100644 index 0000000..04810a7 --- /dev/null +++ b/targets/esp32/coap/src/main.c @@ -0,0 +1,290 @@ +#include +#include +#include +#include + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/event_groups.h" +#include "esp_log.h" +#include "esp_wifi.h" +#include "esp_event.h" +#include "nvs_flash.h" + +#include "protocol_examples_common.h" + +#include "coap3/coap.h" + + +#ifndef CONFIG_COAP_CLIENT_SUPPORT +#error COAP_CLIENT_SUPPORT needs to be enabled +#endif + +#define COAP_DEFAULT_TIME_SEC 60 +e EXAMPLE_COAP_PSK_KEY CONFIG_EXAMPLE_COAP_PSK_KEY +#define EXAMPLE_COAP_PSK_IDENTITY CONFIG_EXAMPLE_COAP_PSK_IDENTITY +#define EXAMPLE_COAP_LOG_DEFAULT_LEVEL CONFIG_COAP_LOG_DEFAULT_LEVEL +#define COAP_DEFAULT_DEMO_URI CONFIG_EXAMPLE_TARGET_DOMAIN_URI + +const static char *TAG = "CoAP_client"; + +static int resp_wait = 1; +static coap_optlist_t *optlist = NULL; +static int wait_ms; + +static coap_response_t +message_handler(coap_session_t *session, + const coap_pdu_t *sent, + const coap_pdu_t *received, + const coap_mid_t mid) +{ + const unsigned char *data = NULL; + size_t data_len; + size_t offset; + size_t total; + coap_pdu_code_t rcvd_code = coap_pdu_get_code(received); + + if (COAP_RESPONSE_CLASS(rcvd_code) == 2) { + if (coap_get_data_large(received, &data_len, &data, &offset, &total)) { + if (data_len != total) { + printf("Unexpected partial data received offset %u, length %u\n", offset, data_len); + } + printf("Received:\n%.*s\n", (int)data_len, data); + resp_wait = 0; + } + return COAP_RESPONSE_OK; + } + printf("%d.%02d", (rcvd_code >> 5), rcvd_code & 0x1F); + if (coap_get_data_large(received, &data_len, &data, &offset, &total)) { + printf(": "); + while (data_len--) { + printf("%c", isprint(*data) ? *data : '.'); + data++; + } + } + printf("\n"); + resp_wait = 0; + return COAP_RESPONSE_OK; +} + +static void +coap_log_handler (coap_log_t level, const char *message) +{ + uint32_t esp_level = ESP_LOG_INFO; + const char *cp = strchr(message, '\n'); + + while (cp) { + ESP_LOG_LEVEL(esp_level, TAG, "%.*s", (int)(cp - message), message); + message = cp + 1; + cp = strchr(message, '\n'); + } + if (message[0] != '\000') { + ESP_LOG_LEVEL(esp_level, TAG, "%s", message); + } +} + +static int +coap_build_optlist(coap_uri_t *uri) +{ +#define BUFSIZE 40 + unsigned char _buf[BUFSIZE]; + unsigned char *buf; + size_t buflen; + int res; + + optlist = NULL; + + if (uri->scheme == COAP_URI_SCHEME_COAPS && !coap_dtls_is_supported()) { + ESP_LOGE(TAG, "MbedTLS DTLS Client Mode not configured"); + return 0; + } + if (uri->scheme == COAP_URI_SCHEME_COAPS_TCP && !coap_tls_is_supported()) { + ESP_LOGE(TAG, "MbedTLS TLS Client Mode not configured"); + return 0; + } + if (uri->scheme == COAP_URI_SCHEME_COAP_TCP && !coap_tcp_is_supported()) { + ESP_LOGE(TAG, "TCP Client Mode not configured"); + return 0; + } + + if (uri->path.length) { + buflen = BUFSIZE; + buf = _buf; + res = coap_split_path(uri->path.s, uri->path.length, buf, &buflen); + + while (res--) { + coap_insert_optlist(&optlist, + coap_new_optlist(COAP_OPTION_URI_PATH, + coap_opt_length(buf), + coap_opt_value(buf))); + + buf += coap_opt_size(buf); + } + } + + if (uri->query.length) { + buflen = BUFSIZE; + buf = _buf; + res = coap_split_query(uri->query.s, uri->query.length, buf, &buflen); + + while (res--) { + coap_insert_optlist(&optlist, + coap_new_optlist(COAP_OPTION_URI_QUERY, + coap_opt_length(buf), + coap_opt_value(buf))); + + buf += coap_opt_size(buf); + } + } + return 1; +} + +static void coap_example_client(void *p) +{ + coap_address_t dst_addr; + static coap_uri_t uri; + const char *server_uri = COAP_DEFAULT_DEMO_URI; + coap_context_t *ctx = NULL; + coap_session_t *session = NULL; + coap_pdu_t *request = NULL; + unsigned char token[8]; + size_t tokenlength; + coap_addr_info_t *info_list = NULL; + coap_proto_t proto; + char tmpbuf[INET6_ADDRSTRLEN]; + + /* Initialize libcoap library */ + coap_startup(); + + /* Set up the CoAP logging */ + coap_set_log_handler(coap_log_handler); + coap_set_log_level(EXAMPLE_COAP_LOG_DEFAULT_LEVEL); + + /* Set up the CoAP context */ + ctx = coap_new_context(NULL); + if (!ctx) { + ESP_LOGE(TAG, "coap_new_context() failed"); + goto clean_up; + } + coap_context_set_block_mode(ctx, + COAP_BLOCK_USE_LIBCOAP | COAP_BLOCK_SINGLE_BODY); + + coap_register_response_handler(ctx, message_handler); + + if (coap_split_uri((const uint8_t *)server_uri, strlen(server_uri), &uri) == -1) { + ESP_LOGE(TAG, "CoAP server uri %s error", server_uri); + goto clean_up; + } + if (!coap_build_optlist(&uri)) { + goto clean_up; + } + + info_list = coap_resolve_address_info(&uri.host, uri.port, uri.port, + uri.port, uri.port, + 0, + 1 << uri.scheme, + COAP_RESOLVE_TYPE_REMOTE); + + if (info_list == NULL) { + ESP_LOGE(TAG, "failed to resolve address"); + goto clean_up; + } + proto = info_list->proto; + memcpy(&dst_addr, &info_list->addr, sizeof(dst_addr)); + coap_free_address_info(info_list); + + /* This is to keep the test suites happy */ + coap_print_ip_addr(&dst_addr, tmpbuf, sizeof(tmpbuf)); + ESP_LOGI(TAG, "DNS lookup succeeded. IP=%s", tmpbuf); + + /* + * Note that if the URI starts with just coap:// (not coaps://) the + * session will still be plain text. + */ + if (uri.scheme == COAP_URI_SCHEME_COAPS || uri.scheme == COAP_URI_SCHEME_COAPS_TCP || uri.scheme == COAP_URI_SCHEME_COAPS_WS) { +#ifndef CONFIG_MBEDTLS_TLS_CLIENT + ESP_LOGE(TAG, "MbedTLS (D)TLS Client Mode not configured"); + goto clean_up; +#endif /* CONFIG_MBEDTLS_TLS_CLIENT */ + +#ifdef CONFIG_COAP_MBEDTLS_PSK + session = coap_start_psk_session(ctx, &dst_addr, &uri, proto); +#endif /* CONFIG_COAP_MBEDTLS_PSK */ + +#ifdef CONFIG_COAP_MBEDTLS_PKI + session = coap_start_pki_session(ctx, &dst_addr, &uri, proto); +#endif /* CONFIG_COAP_MBEDTLS_PKI */ + } else { + session = coap_new_client_session(ctx, NULL, &dst_addr, proto); + } + if (!session) { + ESP_LOGE(TAG, "coap_new_client_session() failed"); + goto clean_up; + } +#ifdef CONFIG_COAP_WEBSOCKETS + if (proto == COAP_PROTO_WS || proto == COAP_PROTO_WSS) { + coap_ws_set_host_request(session, &uri.host); + } +#endif /* CONFIG_COAP_WEBSOCKETS */ + + while (1) { + request = coap_new_pdu(coap_is_mcast(&dst_addr) ? COAP_MESSAGE_NON : COAP_MESSAGE_CON, + COAP_REQUEST_CODE_GET, session); + if (!request) { + ESP_LOGE(TAG, "coap_new_pdu() failed"); + goto clean_up; + } + /* Add in an unique token */ + coap_session_new_token(session, &tokenlength, token); + coap_add_token(request, tokenlength, token); + coap_add_optlist_pdu(request, &optlist); + + resp_wait = 1; + coap_send(session, request); + + wait_ms = COAP_DEFAULT_TIME_SEC * 1000; + + while (resp_wait) { + int result = coap_io_process(ctx, wait_ms > 1000 ? 1000 : wait_ms); + if (result >= 0) { + if (result >= wait_ms) { + ESP_LOGE(TAG, "No response from server"); + break; + } else { + wait_ms -= result; + } + } + } + for (int countdown = 10; countdown >= 0; countdown--) { + ESP_LOGI(TAG, "%d... ", countdown); + vTaskDelay(1000 / portTICK_PERIOD_MS); + } + ESP_LOGI(TAG, "Starting again!"); + } + +clean_up: + if (optlist) { + coap_delete_optlist(optlist); + optlist = NULL; + } + if (session) { + coap_session_release(session); + } + if (ctx) { + coap_free_context(ctx); + } + coap_cleanup(); + + ESP_LOGI(TAG, "Finished"); + vTaskDelete(NULL); +} + +void app_main(void) +{ + ESP_ERROR_CHECK( nvs_flash_init() ); + ESP_ERROR_CHECK(esp_netif_init()); + ESP_ERROR_CHECK(esp_event_loop_create_default()); + ESP_ERROR_CHECK(example_connect()); + + xTaskCreate(coap_example_client, "coap", 8 * 1024, NULL, 5, NULL); +} From 6cc5aaa8c7d2b25fccadfbb8e702c969d714b0f5 Mon Sep 17 00:00:00 2001 From: 1998-felix Date: Wed, 6 Sep 2023 13:16:13 +0300 Subject: [PATCH 14/15] Add config file Signed-off-by: 1998-felix --- targets/esp32/coap/include/config.h | 13 +++ targets/esp32/coap/src/main.c | 128 ++++++++++++++++------------ 2 files changed, 88 insertions(+), 53 deletions(-) create mode 100644 targets/esp32/coap/include/config.h diff --git a/targets/esp32/coap/include/config.h b/targets/esp32/coap/include/config.h new file mode 100644 index 0000000..10354bf --- /dev/null +++ b/targets/esp32/coap/include/config.h @@ -0,0 +1,13 @@ +#ifndef CONFIG_H +#define CONFIG_H + +#define CLIENTID "" + +const char *mfThingId = " "; +const char *mfThingKey = " "; +const char *mfChannelId = " "; +char mfTopic[150]; + +const char *server = " "; + +#endif \ No newline at end of file diff --git a/targets/esp32/coap/src/main.c b/targets/esp32/coap/src/main.c index 04810a7..3535dc2 100644 --- a/targets/esp32/coap/src/main.c +++ b/targets/esp32/coap/src/main.c @@ -15,16 +15,7 @@ #include "coap3/coap.h" - -#ifndef CONFIG_COAP_CLIENT_SUPPORT -#error COAP_CLIENT_SUPPORT needs to be enabled -#endif - #define COAP_DEFAULT_TIME_SEC 60 -e EXAMPLE_COAP_PSK_KEY CONFIG_EXAMPLE_COAP_PSK_KEY -#define EXAMPLE_COAP_PSK_IDENTITY CONFIG_EXAMPLE_COAP_PSK_IDENTITY -#define EXAMPLE_COAP_LOG_DEFAULT_LEVEL CONFIG_COAP_LOG_DEFAULT_LEVEL -#define COAP_DEFAULT_DEMO_URI CONFIG_EXAMPLE_TARGET_DOMAIN_URI const static char *TAG = "CoAP_client"; @@ -32,11 +23,10 @@ static int resp_wait = 1; static coap_optlist_t *optlist = NULL; static int wait_ms; -static coap_response_t -message_handler(coap_session_t *session, - const coap_pdu_t *sent, - const coap_pdu_t *received, - const coap_mid_t mid) +static coap_response_t message_handler(coap_session_t *session, + const coap_pdu_t *sent, + const coap_pdu_t *received, + const coap_mid_t mid) { const unsigned char *data = NULL; size_t data_len; @@ -44,9 +34,12 @@ message_handler(coap_session_t *session, size_t total; coap_pdu_code_t rcvd_code = coap_pdu_get_code(received); - if (COAP_RESPONSE_CLASS(rcvd_code) == 2) { - if (coap_get_data_large(received, &data_len, &data, &offset, &total)) { - if (data_len != total) { + if (COAP_RESPONSE_CLASS(rcvd_code) == 2) + { + if (coap_get_data_large(received, &data_len, &data, &offset, &total)) + { + if (data_len != total) + { printf("Unexpected partial data received offset %u, length %u\n", offset, data_len); } printf("Received:\n%.*s\n", (int)data_len, data); @@ -55,9 +48,11 @@ message_handler(coap_session_t *session, return COAP_RESPONSE_OK; } printf("%d.%02d", (rcvd_code >> 5), rcvd_code & 0x1F); - if (coap_get_data_large(received, &data_len, &data, &offset, &total)) { + if (coap_get_data_large(received, &data_len, &data, &offset, &total)) + { printf(": "); - while (data_len--) { + while (data_len--) + { printf("%c", isprint(*data) ? *data : '.'); data++; } @@ -67,24 +62,24 @@ message_handler(coap_session_t *session, return COAP_RESPONSE_OK; } -static void -coap_log_handler (coap_log_t level, const char *message) +static void coap_log_handler(coap_log_t level, const char *message) { uint32_t esp_level = ESP_LOG_INFO; const char *cp = strchr(message, '\n'); - while (cp) { + while (cp) + { ESP_LOG_LEVEL(esp_level, TAG, "%.*s", (int)(cp - message), message); message = cp + 1; cp = strchr(message, '\n'); } - if (message[0] != '\000') { + if (message[0] != '\000') + { ESP_LOG_LEVEL(esp_level, TAG, "%s", message); } } -static int -coap_build_optlist(coap_uri_t *uri) +static int coap_build_optlist(coap_uri_t *uri) { #define BUFSIZE 40 unsigned char _buf[BUFSIZE]; @@ -94,25 +89,30 @@ coap_build_optlist(coap_uri_t *uri) optlist = NULL; - if (uri->scheme == COAP_URI_SCHEME_COAPS && !coap_dtls_is_supported()) { + if (uri->scheme == COAP_URI_SCHEME_COAPS && !coap_dtls_is_supported()) + { ESP_LOGE(TAG, "MbedTLS DTLS Client Mode not configured"); return 0; } - if (uri->scheme == COAP_URI_SCHEME_COAPS_TCP && !coap_tls_is_supported()) { + if (uri->scheme == COAP_URI_SCHEME_COAPS_TCP && !coap_tls_is_supported()) + { ESP_LOGE(TAG, "MbedTLS TLS Client Mode not configured"); return 0; } - if (uri->scheme == COAP_URI_SCHEME_COAP_TCP && !coap_tcp_is_supported()) { + if (uri->scheme == COAP_URI_SCHEME_COAP_TCP && !coap_tcp_is_supported()) + { ESP_LOGE(TAG, "TCP Client Mode not configured"); return 0; } - if (uri->path.length) { + if (uri->path.length) + { buflen = BUFSIZE; buf = _buf; res = coap_split_path(uri->path.s, uri->path.length, buf, &buflen); - while (res--) { + while (res--) + { coap_insert_optlist(&optlist, coap_new_optlist(COAP_OPTION_URI_PATH, coap_opt_length(buf), @@ -122,12 +122,14 @@ coap_build_optlist(coap_uri_t *uri) } } - if (uri->query.length) { + if (uri->query.length) + { buflen = BUFSIZE; buf = _buf; res = coap_split_query(uri->query.s, uri->query.length, buf, &buflen); - while (res--) { + while (res--) + { coap_insert_optlist(&optlist, coap_new_optlist(COAP_OPTION_URI_QUERY, coap_opt_length(buf), @@ -141,9 +143,9 @@ coap_build_optlist(coap_uri_t *uri) static void coap_example_client(void *p) { - coap_address_t dst_addr; + coap_address_t dst_addr; static coap_uri_t uri; - const char *server_uri = COAP_DEFAULT_DEMO_URI; + const char *server_uri = COAP_DEFAULT_DEMO_URI; coap_context_t *ctx = NULL; coap_session_t *session = NULL; coap_pdu_t *request = NULL; @@ -162,7 +164,8 @@ static void coap_example_client(void *p) /* Set up the CoAP context */ ctx = coap_new_context(NULL); - if (!ctx) { + if (!ctx) + { ESP_LOGE(TAG, "coap_new_context() failed"); goto clean_up; } @@ -171,11 +174,13 @@ static void coap_example_client(void *p) coap_register_response_handler(ctx, message_handler); - if (coap_split_uri((const uint8_t *)server_uri, strlen(server_uri), &uri) == -1) { + if (coap_split_uri((const uint8_t *)server_uri, strlen(server_uri), &uri) == -1) + { ESP_LOGE(TAG, "CoAP server uri %s error", server_uri); goto clean_up; } - if (!coap_build_optlist(&uri)) { + if (!coap_build_optlist(&uri)) + { goto clean_up; } @@ -185,7 +190,8 @@ static void coap_example_client(void *p) 1 << uri.scheme, COAP_RESOLVE_TYPE_REMOTE); - if (info_list == NULL) { + if (info_list == NULL) + { ESP_LOGE(TAG, "failed to resolve address"); goto clean_up; } @@ -201,7 +207,8 @@ static void coap_example_client(void *p) * Note that if the URI starts with just coap:// (not coaps://) the * session will still be plain text. */ - if (uri.scheme == COAP_URI_SCHEME_COAPS || uri.scheme == COAP_URI_SCHEME_COAPS_TCP || uri.scheme == COAP_URI_SCHEME_COAPS_WS) { + if (uri.scheme == COAP_URI_SCHEME_COAPS || uri.scheme == COAP_URI_SCHEME_COAPS_TCP || uri.scheme == COAP_URI_SCHEME_COAPS_WS) + { #ifndef CONFIG_MBEDTLS_TLS_CLIENT ESP_LOGE(TAG, "MbedTLS (D)TLS Client Mode not configured"); goto clean_up; @@ -214,23 +221,29 @@ static void coap_example_client(void *p) #ifdef CONFIG_COAP_MBEDTLS_PKI session = coap_start_pki_session(ctx, &dst_addr, &uri, proto); #endif /* CONFIG_COAP_MBEDTLS_PKI */ - } else { + } + else + { session = coap_new_client_session(ctx, NULL, &dst_addr, proto); } - if (!session) { + if (!session) + { ESP_LOGE(TAG, "coap_new_client_session() failed"); goto clean_up; } #ifdef CONFIG_COAP_WEBSOCKETS - if (proto == COAP_PROTO_WS || proto == COAP_PROTO_WSS) { + if (proto == COAP_PROTO_WS || proto == COAP_PROTO_WSS) + { coap_ws_set_host_request(session, &uri.host); } #endif /* CONFIG_COAP_WEBSOCKETS */ - while (1) { + while (1) + { request = coap_new_pdu(coap_is_mcast(&dst_addr) ? COAP_MESSAGE_NON : COAP_MESSAGE_CON, COAP_REQUEST_CODE_GET, session); - if (!request) { + if (!request) + { ESP_LOGE(TAG, "coap_new_pdu() failed"); goto clean_up; } @@ -244,18 +257,24 @@ static void coap_example_client(void *p) wait_ms = COAP_DEFAULT_TIME_SEC * 1000; - while (resp_wait) { + while (resp_wait) + { int result = coap_io_process(ctx, wait_ms > 1000 ? 1000 : wait_ms); - if (result >= 0) { - if (result >= wait_ms) { + if (result >= 0) + { + if (result >= wait_ms) + { ESP_LOGE(TAG, "No response from server"); break; - } else { + } + else + { wait_ms -= result; } } } - for (int countdown = 10; countdown >= 0; countdown--) { + for (int countdown = 10; countdown >= 0; countdown--) + { ESP_LOGI(TAG, "%d... ", countdown); vTaskDelay(1000 / portTICK_PERIOD_MS); } @@ -263,14 +282,17 @@ static void coap_example_client(void *p) } clean_up: - if (optlist) { + if (optlist) + { coap_delete_optlist(optlist); optlist = NULL; } - if (session) { + if (session) + { coap_session_release(session); } - if (ctx) { + if (ctx) + { coap_free_context(ctx); } coap_cleanup(); @@ -281,7 +303,7 @@ static void coap_example_client(void *p) void app_main(void) { - ESP_ERROR_CHECK( nvs_flash_init() ); + ESP_ERROR_CHECK(nvs_flash_init()); ESP_ERROR_CHECK(esp_netif_init()); ESP_ERROR_CHECK(esp_event_loop_create_default()); ESP_ERROR_CHECK(example_connect()); From 99b3b963ceed1073d6f6d2ec50395a5d4d73ef15 Mon Sep 17 00:00:00 2001 From: "felix.gateru" Date: Fri, 13 Oct 2023 13:15:08 +0300 Subject: [PATCH 15/15] Append CoAP config Signed-off-by: felix.gateru --- targets/esp32/coap/include/cnetwork.h | 0 targets/esp32/coap/src/CMakeLists.txt | 6 - targets/esp32/coap/src/cnetwork.c | 0 targets/esp32/coap/src/idf_component.yml | 5 - targets/esp32/coap/src/main.c | 156 +++++------------------ 5 files changed, 29 insertions(+), 138 deletions(-) create mode 100644 targets/esp32/coap/include/cnetwork.h delete mode 100644 targets/esp32/coap/src/CMakeLists.txt create mode 100644 targets/esp32/coap/src/cnetwork.c diff --git a/targets/esp32/coap/include/cnetwork.h b/targets/esp32/coap/include/cnetwork.h new file mode 100644 index 0000000..e69de29 diff --git a/targets/esp32/coap/src/CMakeLists.txt b/targets/esp32/coap/src/CMakeLists.txt deleted file mode 100644 index ab3ad38..0000000 --- a/targets/esp32/coap/src/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -# This file was automatically generated for projects -# without default 'CMakeLists.txt' file. - -FILE(GLOB_RECURSE app_sources ${CMAKE_SOURCE_DIR}/src/*.*) - -idf_component_register(SRCS ${app_sources}) diff --git a/targets/esp32/coap/src/cnetwork.c b/targets/esp32/coap/src/cnetwork.c new file mode 100644 index 0000000..e69de29 diff --git a/targets/esp32/coap/src/idf_component.yml b/targets/esp32/coap/src/idf_component.yml index d99d1f9..e69de29 100644 --- a/targets/esp32/coap/src/idf_component.yml +++ b/targets/esp32/coap/src/idf_component.yml @@ -1,5 +0,0 @@ -dependencies: - espressif/coap: - version: ^4.3.0 -description: CoAP Client -version: 1.0.0 diff --git a/targets/esp32/coap/src/main.c b/targets/esp32/coap/src/main.c index 3535dc2..c4407a7 100644 --- a/targets/esp32/coap/src/main.c +++ b/targets/esp32/coap/src/main.c @@ -12,17 +12,27 @@ #include "nvs_flash.h" #include "protocol_examples_common.h" - #include "coap3/coap.h" +#include "config.h" +#include "cnetwork.h" -#define COAP_DEFAULT_TIME_SEC 60 - -const static char *TAG = "CoAP_client"; +const static char *TAG = CLIENTID; static int resp_wait = 1; static coap_optlist_t *optlist = NULL; static int wait_ms; + +void format_mainflux_message_topic(void) +{ + const char *_preId = "channels/"; + const char *_postId = "/messages"; + strcpy(mfTopic, _preId); + strcat(mfTopic, mfChannelId); + strcat(mfTopic, _postId); +} + + static coap_response_t message_handler(coap_session_t *session, const coap_pdu_t *sent, const coap_pdu_t *received, @@ -79,73 +89,11 @@ static void coap_log_handler(coap_log_t level, const char *message) } } -static int coap_build_optlist(coap_uri_t *uri) -{ -#define BUFSIZE 40 - unsigned char _buf[BUFSIZE]; - unsigned char *buf; - size_t buflen; - int res; - - optlist = NULL; - - if (uri->scheme == COAP_URI_SCHEME_COAPS && !coap_dtls_is_supported()) - { - ESP_LOGE(TAG, "MbedTLS DTLS Client Mode not configured"); - return 0; - } - if (uri->scheme == COAP_URI_SCHEME_COAPS_TCP && !coap_tls_is_supported()) - { - ESP_LOGE(TAG, "MbedTLS TLS Client Mode not configured"); - return 0; - } - if (uri->scheme == COAP_URI_SCHEME_COAP_TCP && !coap_tcp_is_supported()) - { - ESP_LOGE(TAG, "TCP Client Mode not configured"); - return 0; - } - - if (uri->path.length) - { - buflen = BUFSIZE; - buf = _buf; - res = coap_split_path(uri->path.s, uri->path.length, buf, &buflen); - - while (res--) - { - coap_insert_optlist(&optlist, - coap_new_optlist(COAP_OPTION_URI_PATH, - coap_opt_length(buf), - coap_opt_value(buf))); - - buf += coap_opt_size(buf); - } - } - - if (uri->query.length) - { - buflen = BUFSIZE; - buf = _buf; - res = coap_split_query(uri->query.s, uri->query.length, buf, &buflen); - - while (res--) - { - coap_insert_optlist(&optlist, - coap_new_optlist(COAP_OPTION_URI_QUERY, - coap_opt_length(buf), - coap_opt_value(buf))); - - buf += coap_opt_size(buf); - } - } - return 1; -} - -static void coap_example_client(void *p) +static void coap_client(void *p) { - coap_address_t dst_addr; - static coap_uri_t uri; - const char *server_uri = COAP_DEFAULT_DEMO_URI; + coap_address_t uri; + static coap_uri_t dst_addr; + const char *server_uri = server; coap_context_t *ctx = NULL; coap_session_t *session = NULL; coap_pdu_t *request = NULL; @@ -155,14 +103,11 @@ static void coap_example_client(void *p) coap_proto_t proto; char tmpbuf[INET6_ADDRSTRLEN]; - /* Initialize libcoap library */ coap_startup(); - /* Set up the CoAP logging */ coap_set_log_handler(coap_log_handler); - coap_set_log_level(EXAMPLE_COAP_LOG_DEFAULT_LEVEL); + coap_set_log_level(COAP_LOG_DEFAULT_LEVEL); - /* Set up the CoAP context */ ctx = coap_new_context(NULL); if (!ctx) { @@ -179,10 +124,6 @@ static void coap_example_client(void *p) ESP_LOGE(TAG, "CoAP server uri %s error", server_uri); goto clean_up; } - if (!coap_build_optlist(&uri)) - { - goto clean_up; - } info_list = coap_resolve_address_info(&uri.host, uri.port, uri.port, uri.port, uri.port, @@ -193,52 +134,19 @@ static void coap_example_client(void *p) if (info_list == NULL) { ESP_LOGE(TAG, "failed to resolve address"); - goto clean_up; + clean_up(); } proto = info_list->proto; memcpy(&dst_addr, &info_list->addr, sizeof(dst_addr)); coap_free_address_info(info_list); - - /* This is to keep the test suites happy */ - coap_print_ip_addr(&dst_addr, tmpbuf, sizeof(tmpbuf)); - ESP_LOGI(TAG, "DNS lookup succeeded. IP=%s", tmpbuf); - - /* - * Note that if the URI starts with just coap:// (not coaps://) the - * session will still be plain text. - */ - if (uri.scheme == COAP_URI_SCHEME_COAPS || uri.scheme == COAP_URI_SCHEME_COAPS_TCP || uri.scheme == COAP_URI_SCHEME_COAPS_WS) - { -#ifndef CONFIG_MBEDTLS_TLS_CLIENT - ESP_LOGE(TAG, "MbedTLS (D)TLS Client Mode not configured"); - goto clean_up; -#endif /* CONFIG_MBEDTLS_TLS_CLIENT */ - -#ifdef CONFIG_COAP_MBEDTLS_PSK - session = coap_start_psk_session(ctx, &dst_addr, &uri, proto); -#endif /* CONFIG_COAP_MBEDTLS_PSK */ - -#ifdef CONFIG_COAP_MBEDTLS_PKI - session = coap_start_pki_session(ctx, &dst_addr, &uri, proto); -#endif /* CONFIG_COAP_MBEDTLS_PKI */ - } - else - { - session = coap_new_client_session(ctx, NULL, &dst_addr, proto); - } + session = coap_new_client_session(ctx, NULL, &dst_addr, proto); if (!session) { ESP_LOGE(TAG, "coap_new_client_session() failed"); - goto clean_up; - } -#ifdef CONFIG_COAP_WEBSOCKETS - if (proto == COAP_PROTO_WS || proto == COAP_PROTO_WSS) - { - coap_ws_set_host_request(session, &uri.host); + clean_up(); } -#endif /* CONFIG_COAP_WEBSOCKETS */ - while (1) + while (true) { request = coap_new_pdu(coap_is_mcast(&dst_addr) ? COAP_MESSAGE_NON : COAP_MESSAGE_CON, COAP_REQUEST_CODE_GET, session); @@ -247,7 +155,6 @@ static void coap_example_client(void *p) ESP_LOGE(TAG, "coap_new_pdu() failed"); goto clean_up; } - /* Add in an unique token */ coap_session_new_token(session, &tokenlength, token); coap_add_token(request, tokenlength, token); coap_add_optlist_pdu(request, &optlist); @@ -255,7 +162,7 @@ static void coap_example_client(void *p) resp_wait = 1; coap_send(session, request); - wait_ms = COAP_DEFAULT_TIME_SEC * 1000; + wait_ms = COAP_DEFAULT_TIME_SEC * MS_COUNT; while (resp_wait) { @@ -280,13 +187,9 @@ static void coap_example_client(void *p) } ESP_LOGI(TAG, "Starting again!"); } - -clean_up: - if (optlist) - { - coap_delete_optlist(optlist); - optlist = NULL; - } +} +void clean_up() +{ if (session) { coap_session_release(session); @@ -300,13 +203,12 @@ static void coap_example_client(void *p) ESP_LOGI(TAG, "Finished"); vTaskDelete(NULL); } - void app_main(void) { ESP_ERROR_CHECK(nvs_flash_init()); ESP_ERROR_CHECK(esp_netif_init()); ESP_ERROR_CHECK(esp_event_loop_create_default()); - ESP_ERROR_CHECK(example_connect()); + ESP_ERROR_CHECK(wifi_init_softap()); - xTaskCreate(coap_example_client, "coap", 8 * 1024, NULL, 5, NULL); + xTaskCreate(coap_client, "coap", COAP_BUFFSIZE, NULL, COAP_TIMEOUT, NULL); }