├── .gitignore ├── CMakeLists.txt ├── Makefile ├── README.md ├── firmware ├── example-v1.1.bin └── example-v1.2.bin ├── main ├── CMakeLists.txt ├── Kconfig.projbuild ├── component.mk ├── main.c ├── main.h ├── wifi.c └── wifi.h └── server_certs └── ca_cert.pem /.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | /.vscode 3 | sdkconfig* 4 | *.code-workspace 5 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # The following lines of boilerplate have to be in your project's CMakeLists 2 | # in this exact order for cmake to work correctly 3 | cmake_minimum_required(VERSION 3.5) 4 | 5 | include($ENV{IDF_PATH}/tools/cmake/project.cmake) 6 | project(esp32_ota) -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # This is a project Makefile. It is assumed the directory this Makefile resides in is a 3 | # project subdirectory. 4 | # 5 | 6 | PROJECT_NAME := esp32-ota-example 7 | 8 | include $(IDF_PATH)/make/project.mk 9 | 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ESP32 firmware sample project for OTA update using ThingsBoard and for sending telemetry to ThingsBoard. 2 | See all details in [ESP32 OTA using ThingsBoard](https://thingsboard.io/docs/samples/esp32/ota/) tutorial. 3 | 4 | ThingsBoard is an open-source server-side platform that allows you to monitor and control IoT devices. It is free for both personal and commercial usage and you can deploy it anywhere. If this is your first experience with the platform we recommend to review what-is-thingsboard page and getting-started guide. 5 | 6 | ESP32 is a series of low-cost, low-power SOC microcontrollers with integrated self-contained Wi-Fi and dual-mode Bluetooth. 7 | This sample application allow you to deliver a new firmware images to EPS32 with using ThingsBoard and OTA. 8 | -------------------------------------------------------------------------------- /firmware/example-v1.1.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thingsboard/esp32-ota/0240c7a19512f96220d2e5f2510e2482106fa543/firmware/example-v1.1.bin -------------------------------------------------------------------------------- /firmware/example-v1.2.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thingsboard/esp32-ota/0240c7a19512f96220d2e5f2510e2482106fa543/firmware/example-v1.2.bin -------------------------------------------------------------------------------- /main/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(COMPONENT_SRCS "main.c". 2 | "wifi.c") 3 | set(COMPONENT_ADD_INCLUDEDIRS ".") 4 | # Embed the server root certificate into the final binary 5 | set(COMPONENT_EMBED_TXTFILES ${IDF_PROJECT_PATH}/server_certs/ca_cert.pem) 6 | 7 | register_component() 8 | -------------------------------------------------------------------------------- /main/Kconfig.projbuild: -------------------------------------------------------------------------------- 1 | menu "ThingsBoard OTA configuration" 2 | 3 | config WIFI_SSID 4 | string "WiFi SSID" 5 | default "myssid" 6 | help 7 | SSID (network name) for the example to connect to. 8 | 9 | config WIFI_PASSWORD 10 | string "WiFi Password" 11 | default "mypassword" 12 | help 13 | WiFi password (WPA or WPA2) for the example to use. 14 | 15 | Can be left blank if the network has no security set. 16 | 17 | config MQTT_BROKER_URL 18 | string "MQTT broker URL" 19 | default "mqtt://demo.thingsboard.io" 20 | help 21 | URL to connect to ThingsBoard. 22 | 23 | config MQTT_BROKER_PORT 24 | int "MQTT broker port" 25 | default 1883 26 | help 27 | MQTT port to connect to ThingsBoard. 28 | 29 | config MQTT_ACCESS_TOKEN 30 | string "MQTT access token" 31 | default "esp32_access_token" 32 | help 33 | Access token to connect to ThingsBoard. 34 | 35 | endmenu 36 | -------------------------------------------------------------------------------- /main/component.mk: -------------------------------------------------------------------------------- 1 | # 2 | # "main" pseudo-component makefile. 3 | # 4 | # (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.) 5 | 6 | COMPONENT_EMBED_TXTFILES := ${PROJECT_PATH}/server_certs/ca_cert.pem 7 | -------------------------------------------------------------------------------- /main/main.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file main.c 3 | */ 4 | 5 | #include 6 | #include 7 | #include "freertos/FreeRTOS.h" 8 | #include "freertos/task.h" 9 | #include "esp_system.h" 10 | #include "esp_event_loop.h" 11 | #include "esp_log.h" 12 | 13 | #include "lwip/err.h" 14 | #include "lwip/sockets.h" 15 | #include "lwip/sys.h" 16 | #include "lwip/netdb.h" 17 | #include "lwip/dns.h" 18 | 19 | #include "cJSON.h" 20 | 21 | #include "main.h" 22 | #include "wifi.h" 23 | 24 | #include "esp_ota_ops.h" 25 | #include "esp_http_client.h" 26 | #include "esp_https_ota.h" 27 | #include "mqtt_client.h" 28 | 29 | #include "nvs.h" 30 | #include "nvs_flash.h" 31 | 32 | extern const uint8_t server_cert_pem_start[] asm("_binary_ca_cert_pem_start"); 33 | extern const uint8_t server_cert_pem_end[] asm("_binary_ca_cert_pem_end"); 34 | 35 | /*! Saves bit values used in application */ 36 | static EventGroupHandle_t event_group; 37 | 38 | /*! Saves OTA config received from ThingsBoard*/ 39 | static struct shared_keys 40 | { 41 | char targetFwServerUrl[256]; 42 | char targetFwVer[128]; 43 | } shared_attributes; 44 | 45 | /*! Buffer to save a received MQTT message */ 46 | static char mqtt_msg[512]; 47 | 48 | static esp_mqtt_client_handle_t mqtt_client; 49 | 50 | static void parse_ota_config(const cJSON *object) 51 | { 52 | if (object != NULL) 53 | { 54 | cJSON *server_url_response = cJSON_GetObjectItem(object, TB_SHARED_ATTR_FIELD_TARGET_FW_URL); 55 | if (cJSON_IsString(server_url_response) && (server_url_response->valuestring != NULL) && strlen(server_url_response->valuestring) < sizeof(shared_attributes.targetFwServerUrl)) 56 | { 57 | memcpy(shared_attributes.targetFwServerUrl, server_url_response->valuestring, strlen(server_url_response->valuestring)); 58 | shared_attributes.targetFwServerUrl[sizeof(shared_attributes.targetFwServerUrl) - 1] = 0; 59 | ESP_LOGI(TAG, "Received firmware URL: %s", shared_attributes.targetFwServerUrl); 60 | } 61 | 62 | cJSON *target_fw_ver_response = cJSON_GetObjectItem(object, TB_SHARED_ATTR_FIELD_TARGET_FW_VER); 63 | if (cJSON_IsString(target_fw_ver_response) && (target_fw_ver_response->valuestring != NULL) && strlen(target_fw_ver_response->valuestring) < sizeof(shared_attributes.targetFwVer)) 64 | { 65 | memcpy(shared_attributes.targetFwVer, target_fw_ver_response->valuestring, strlen(target_fw_ver_response->valuestring)); 66 | shared_attributes.targetFwVer[sizeof(shared_attributes.targetFwVer) - 1] = 0; 67 | ESP_LOGI(TAG, "Received firmware version: %s", shared_attributes.targetFwVer); 68 | } 69 | } 70 | } 71 | 72 | static esp_err_t mqtt_event_handler(esp_mqtt_event_handle_t event) 73 | { 74 | assert(event != NULL); 75 | 76 | switch (event->event_id) 77 | { 78 | case MQTT_EVENT_CONNECTED: 79 | xEventGroupClearBits(event_group, MQTT_DISCONNECTED_EVENT); 80 | xEventGroupSetBits(event_group, MQTT_CONNECTED_EVENT); 81 | ESP_LOGD(TAG, "MQTT_EVENT_CONNECTED"); 82 | break; 83 | case MQTT_EVENT_DISCONNECTED: 84 | xEventGroupClearBits(event_group, MQTT_CONNECTED_EVENT); 85 | xEventGroupSetBits(event_group, MQTT_DISCONNECTED_EVENT); 86 | ESP_LOGD(TAG, "MQTT_EVENT_DISCONNECTED"); 87 | break; 88 | case MQTT_EVENT_SUBSCRIBED: 89 | ESP_LOGD(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id); 90 | break; 91 | case MQTT_EVENT_UNSUBSCRIBED: 92 | ESP_LOGD(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id); 93 | break; 94 | case MQTT_EVENT_PUBLISHED: 95 | ESP_LOGD(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id); 96 | break; 97 | case MQTT_EVENT_DATA: 98 | ESP_LOGD(TAG, "MQTT_EVENT_DATA, msg_id=%d, %s", event->msg_id, event->topic); 99 | if (event->data_len >= (sizeof(mqtt_msg) - 1)) 100 | { 101 | ESP_LOGE(TAG, "Received MQTT message size [%d] more than expected [%d]", event->data_len, (sizeof(mqtt_msg) - 1)); 102 | return ESP_FAIL; 103 | } 104 | 105 | if (strcmp(TB_ATTRIBUTES_RESPONSE_TOPIC, event->topic) == 0) 106 | { 107 | memcpy(mqtt_msg, event->data, event->data_len); 108 | mqtt_msg[event->data_len] = 0; 109 | cJSON *attributes = cJSON_Parse(mqtt_msg); 110 | if (attributes != NULL) 111 | { 112 | cJSON *shared = cJSON_GetObjectItem(attributes, "shared"); 113 | parse_ota_config(shared); 114 | } 115 | 116 | char *attributes_string = cJSON_Print(attributes); 117 | cJSON_Delete(attributes); 118 | ESP_LOGD(TAG, "Shared attributes response: %s", attributes_string); 119 | // Free is intentional, it's client responsibility to free the result of cJSON_Print 120 | free(attributes_string); 121 | xEventGroupSetBits(event_group, OTA_CONFIG_FETCHED_EVENT); 122 | } 123 | else if (strcmp(TB_ATTRIBUTES_TOPIC, event->topic) == 0) 124 | { 125 | memcpy(mqtt_msg, event->data, MIN(event->data_len, sizeof(mqtt_msg))); 126 | mqtt_msg[event->data_len] = 0; 127 | cJSON *attributes = cJSON_Parse(mqtt_msg); 128 | parse_ota_config(attributes); 129 | char *attributes_string = cJSON_Print(attributes); 130 | cJSON_Delete(attributes); 131 | ESP_LOGD(TAG, "Shared attributes were updated on ThingsBoard: %s", attributes_string); 132 | // Free is intentional, it's client responsibility to free the result of cJSON_Print 133 | free(attributes_string); 134 | xEventGroupSetBits(event_group, OTA_CONFIG_UPDATED_EVENT); 135 | } 136 | break; 137 | case MQTT_EVENT_ERROR: 138 | ESP_LOGD(TAG, "MQTT_EVENT_ERROR"); 139 | break; 140 | case MQTT_EVENT_BEFORE_CONNECT: 141 | ESP_LOGD(TAG, "MQTT_EVENT_BEFORE_CONNECT"); 142 | break; 143 | } 144 | return ESP_OK; 145 | } 146 | 147 | esp_err_t _http_event_handler(esp_http_client_event_t *evt) 148 | { 149 | assert(evt != NULL); 150 | 151 | switch (evt->event_id) 152 | { 153 | case HTTP_EVENT_ERROR: 154 | ESP_LOGD(TAG, "HTTP_EVENT_ERROR"); 155 | break; 156 | case HTTP_EVENT_ON_CONNECTED: 157 | ESP_LOGD(TAG, "HTTP_EVENT_ON_CONNECTED"); 158 | break; 159 | case HTTP_EVENT_HEADER_SENT: 160 | ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT"); 161 | break; 162 | case HTTP_EVENT_ON_HEADER: 163 | ESP_LOGD(TAG, "HTTP_EVENT_ON_HEADER, key=%s, value=%s", evt->header_key, evt->header_value); 164 | break; 165 | case HTTP_EVENT_ON_DATA: 166 | ESP_LOGD(TAG, "HTTP_EVENT_ON_DATA, len=%d", evt->data_len); 167 | if (!esp_http_client_is_chunked_response(evt->client)) 168 | { 169 | // Write out data 170 | ESP_LOGD(TAG, "%.*s", evt->data_len, (char *)evt->data); 171 | } 172 | break; 173 | case HTTP_EVENT_ON_FINISH: 174 | ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH"); 175 | break; 176 | case HTTP_EVENT_DISCONNECTED: 177 | ESP_LOGD(TAG, "HTTP_EVENT_DISCONNECTED"); 178 | break; 179 | } 180 | return ESP_OK; 181 | } 182 | 183 | /** 184 | * @brief Main application task, it sends counter value to ThingsBoard telemetry MQTT topic. 185 | * 186 | * @param pvParameters Pointer to the task arguments 187 | */ 188 | static void main_application_task(void *pvParameters) 189 | { 190 | uint8_t counter = 0; 191 | 192 | while (1) 193 | { 194 | xEventGroupWaitBits(event_group, OTA_TASK_IN_NORMAL_STATE_EVENT, false, true, portMAX_DELAY); 195 | 196 | counter = counter < 1 ? counter + 1 : 0; 197 | 198 | cJSON *root = cJSON_CreateObject(); 199 | cJSON_AddNumberToObject(root, "counter", counter); 200 | char *post_data = cJSON_PrintUnformatted(root); 201 | esp_mqtt_client_publish(mqtt_client, TB_TELEMETRY_TOPIC, post_data, 0, 1, 0); 202 | cJSON_Delete(root); 203 | // Free is intentional, it's client responsibility to free the result of cJSON_Print 204 | free(post_data); 205 | 206 | vTaskDelay(1000 / portTICK_PERIOD_MS); 207 | } 208 | } 209 | 210 | /** 211 | * @brief Check is the current running partition label is factory 212 | * 213 | * @param running_partition_label Current running partition label 214 | * @param config_name Configuration name that specified in Kconfig, ThingsBoard OTA configuration submenu 215 | * @return true If current running partition label is 'factory' 216 | * @return false If current runnit partition label is not 'factory' 217 | */ 218 | static bool partition_is_factory(const char *running_partition_label, const char *config_name) 219 | { 220 | if (strcmp(FACTORY_PARTITION_LABEL, running_partition_label) == 0) 221 | { 222 | ESP_LOGW(TAG, "Factory partition is running. %s from config is saving to the flash memory", config_name); 223 | return true; 224 | } 225 | else 226 | { 227 | ESP_LOGE(TAG, "%s wasn't found, running partition is not '%s'", config_name, FACTORY_PARTITION_LABEL); 228 | APP_ABORT_ON_ERROR(ESP_FAIL); 229 | return false; 230 | } 231 | } 232 | 233 | /** 234 | * @brief Get MQTT broker URL to use in MQTT client. 235 | * If the flash memory is empty and running partition is 'factory' 236 | * then MQTT broker URL specified in ThingsBoard OTA configuration submenu will be saved to NVS. 237 | * If running partition is not 'factory' ('ota_0' or 'ota_1') then MQTT broker URL from NVS is used. 238 | * The application stops if running partition is not 'factory' and MQTT broker URL was not found in NVS. 239 | * 240 | * @param running_partition_label Current running partition label 241 | * @return const char* MQTT broker URL 242 | */ 243 | static const char *get_mqtt_url(const char *running_partition_label) 244 | { 245 | nvs_handle handle; 246 | APP_ABORT_ON_ERROR(nvs_open(NVS_KEY_MQTT_URL, NVS_READWRITE, &handle)); 247 | 248 | static char mqtt_url[MAX_LENGTH_TB_URL + 1]; 249 | size_t mqtt_url_len = sizeof(mqtt_url); 250 | 251 | esp_err_t result_code = nvs_get_str(handle, NVS_KEY_MQTT_URL, mqtt_url, &mqtt_url_len); 252 | if (result_code == ESP_OK) 253 | { 254 | ESP_LOGI(TAG, "MQTT URL from flash memory: %s", mqtt_url); 255 | } 256 | else if (result_code == ESP_ERR_NVS_NOT_FOUND) 257 | { 258 | if (partition_is_factory(running_partition_label, "MQTT URL")) 259 | { 260 | APP_ABORT_ON_ERROR(nvs_set_str(handle, NVS_KEY_MQTT_URL, CONFIG_MQTT_BROKER_URL)); 261 | APP_ABORT_ON_ERROR(nvs_commit(handle)); 262 | APP_ABORT_ON_ERROR(nvs_get_str(handle, NVS_KEY_MQTT_URL, mqtt_url, &mqtt_url_len)); 263 | } 264 | } 265 | else 266 | { 267 | ESP_LOGE(TAG, "Unable to to get MQTT URL from NVS"); 268 | APP_ABORT_ON_ERROR(ESP_FAIL); 269 | } 270 | 271 | nvs_close(handle); 272 | return mqtt_url; 273 | } 274 | 275 | /** 276 | * @brief Get MQTT broker port to use in MQTT client. 277 | * If the flash memory is empty and running partition is 'factory' 278 | * then MQTT broker port specified in ThingsBoard OTA configuration submenu will be saved to NVS. 279 | * If running partition is not 'factory' ('ota_0' or 'ota_1') then MQTT broker port from NVS is used. 280 | * The application stops if running partition is not 'factory' and MQTT broker port was not found in NVS. 281 | * 282 | * @param running_partition_label Current running partition label 283 | * @return const char* MQTT broker port 284 | */ 285 | static uint32_t get_mqtt_port(const char *running_partition_label) 286 | { 287 | nvs_handle handle; 288 | APP_ABORT_ON_ERROR(nvs_open(NVS_KEY_MQTT_PORT, NVS_READWRITE, &handle)); 289 | 290 | uint32_t mqtt_port; 291 | 292 | esp_err_t result_code = nvs_get_u32(handle, NVS_KEY_MQTT_PORT, &mqtt_port); 293 | if (result_code == ESP_OK) 294 | { 295 | ESP_LOGI(TAG, "MQTT port from flash memory: %d", mqtt_port); 296 | } 297 | else if (result_code == ESP_ERR_NVS_NOT_FOUND) 298 | { 299 | if (partition_is_factory(running_partition_label, "MQTT port")) 300 | { 301 | APP_ABORT_ON_ERROR(nvs_set_u32(handle, NVS_KEY_MQTT_PORT, CONFIG_MQTT_BROKER_PORT)); 302 | APP_ABORT_ON_ERROR(nvs_commit(handle)); 303 | APP_ABORT_ON_ERROR(nvs_get_u32(handle, NVS_KEY_MQTT_PORT, &mqtt_port)); 304 | } 305 | } 306 | else 307 | { 308 | ESP_LOGE(TAG, "Unable to to get MQTT port from NVS"); 309 | APP_ABORT_ON_ERROR(ESP_FAIL); 310 | } 311 | 312 | nvs_close(handle); 313 | return mqtt_port; 314 | } 315 | 316 | /** 317 | * @brief Get MQTT access token to use in MQTT client. 318 | * If the flash memory is empty and running partition is 'factory' 319 | * then MQTT broker access token specified in ThingsBoard OTA configuration submenu will be saved to NVS. 320 | * If running partition is not 'factory' ('ota_0' or 'ota_1') then MQTT broker access token from NVS is used. 321 | * The application stops if running partition is not 'factory' and MQTT broker access token was not found in NVS. 322 | * 323 | * @param running_partition_label Current running partition label 324 | * @return const char* MQTT broker access token 325 | */ 326 | static const char *get_mqtt_access_token(const char *running_partition_label) 327 | { 328 | nvs_handle handle; 329 | APP_ABORT_ON_ERROR(nvs_open(NVS_KEY_MQTT_ACCESS_TOKEN, NVS_READWRITE, &handle)); 330 | 331 | static char access_token[MAX_LENGTH_TB_ACCESS_TOKEN + 1]; 332 | size_t access_token_len = sizeof(access_token); 333 | 334 | esp_err_t result_code = nvs_get_str(handle, NVS_KEY_MQTT_ACCESS_TOKEN, access_token, &access_token_len); 335 | if (result_code == ESP_OK) 336 | { 337 | ESP_LOGI(TAG, "MQTT access token from flash memory: %s", access_token); 338 | } 339 | else if (result_code == ESP_ERR_NVS_NOT_FOUND) 340 | { 341 | if (partition_is_factory(running_partition_label, "MQTT access token")) 342 | { 343 | APP_ABORT_ON_ERROR(nvs_set_str(handle, NVS_KEY_MQTT_ACCESS_TOKEN, CONFIG_MQTT_ACCESS_TOKEN)); 344 | APP_ABORT_ON_ERROR(nvs_commit(handle)); 345 | APP_ABORT_ON_ERROR(nvs_get_str(handle, NVS_KEY_MQTT_ACCESS_TOKEN, access_token, &access_token_len)); 346 | } 347 | } 348 | else 349 | { 350 | ESP_LOGE(TAG, "Unable to to get MQTT access token from NVS"); 351 | APP_ABORT_ON_ERROR(ESP_FAIL); 352 | } 353 | 354 | nvs_close(handle); 355 | return access_token; 356 | } 357 | 358 | static void mqtt_app_start(const char *running_partition_label) 359 | { 360 | assert(running_partition_label != NULL); 361 | 362 | const char *mqtt_url = get_mqtt_url(running_partition_label); 363 | const uint32_t mqtt_port = get_mqtt_port(running_partition_label); 364 | const char *mqtt_access_token = get_mqtt_access_token(running_partition_label); 365 | 366 | esp_mqtt_client_config_t mqtt_cfg = { 367 | .uri = mqtt_url, 368 | .event_handle = mqtt_event_handler, 369 | .port = mqtt_port, 370 | .username = mqtt_access_token 371 | }; 372 | 373 | mqtt_client = esp_mqtt_client_init(&mqtt_cfg); 374 | APP_ABORT_ON_ERROR(esp_mqtt_client_start(mqtt_client)); 375 | 376 | vTaskDelay(1000 / portTICK_PERIOD_MS); 377 | } 378 | 379 | static bool fw_versions_are_equal(const char *current_ver, const char *target_ver) 380 | { 381 | assert(current_ver != NULL && target_ver != NULL); 382 | 383 | if (strcmp(current_ver, target_ver) == 0) 384 | { 385 | ESP_LOGW(TAG, "Skipping OTA, firmware versions are equal - current: %s, target: %s", FIRMWARE_VERSION, shared_attributes.targetFwVer); 386 | return true; 387 | } 388 | return false; 389 | } 390 | 391 | static bool ota_params_are_specified(struct shared_keys ota_config) 392 | { 393 | if (strlen(ota_config.targetFwServerUrl) == 0) 394 | { 395 | ESP_LOGW(TAG, "Firmware URL is not specified"); 396 | return false; 397 | } 398 | 399 | if (strlen(ota_config.targetFwVer) == 0) 400 | { 401 | ESP_LOGW(TAG, "Target firmware version is not specified"); 402 | return false; 403 | } 404 | 405 | return true; 406 | } 407 | 408 | static void start_ota(const char *current_ver, struct shared_keys ota_config) 409 | { 410 | assert(current_ver != NULL); 411 | 412 | if (!fw_versions_are_equal(current_ver, ota_config.targetFwVer) && ota_params_are_specified(ota_config)) 413 | { 414 | ESP_LOGW(TAG, "Starting OTA, firmware versions are different - current: %s, target: %s", current_ver, ota_config.targetFwVer); 415 | ESP_LOGI(TAG, "Target firmware version: %s", ota_config.targetFwVer); 416 | ESP_LOGI(TAG, "Firmware URL: %s", ota_config.targetFwServerUrl); 417 | esp_http_client_config_t config = { 418 | .url = ota_config.targetFwServerUrl, 419 | .cert_pem = (char *)server_cert_pem_start, 420 | .event_handler = _http_event_handler, 421 | }; 422 | esp_err_t ret = esp_https_ota(&config); 423 | if (ret == ESP_OK) 424 | { 425 | esp_restart(); 426 | } 427 | else 428 | { 429 | ESP_LOGE(TAG, "Firmware Upgrades Failed"); 430 | } 431 | } 432 | } 433 | 434 | static enum state connection_state(BaseType_t actual_event, const char *current_state_name) 435 | { 436 | assert(current_state_name != NULL); 437 | 438 | if (actual_event & WIFI_DISCONNECTED_EVENT) 439 | { 440 | ESP_LOGE(TAG, "%s state, Wi-Fi not connected, wait for the connect", current_state_name); 441 | return STATE_WAIT_WIFI; 442 | } 443 | 444 | if (actual_event & MQTT_DISCONNECTED_EVENT) 445 | { 446 | ESP_LOGW(TAG, "%s state, MQTT not connected, wait for the connect", current_state_name); 447 | return STATE_WAIT_MQTT; 448 | } 449 | 450 | return STATE_CONNECTION_IS_OK; 451 | } 452 | 453 | /** 454 | * @brief OTA task, it handles the shared attributes updates and starts OTA if the config received from ThingsBoard is valid. 455 | * 456 | * @param pvParameters Pointer to the task arguments 457 | */ 458 | static void ota_task(void *pvParameters) 459 | { 460 | enum state current_connection_state = STATE_CONNECTION_IS_OK; 461 | enum state state = STATE_INITIAL; 462 | BaseType_t ota_events; 463 | BaseType_t actual_event = 0x00; 464 | char running_partition_label[sizeof(((esp_partition_t *)0)->label)]; 465 | 466 | while (1) 467 | { 468 | if (state != STATE_INITIAL && state != STATE_APP_LOOP) 469 | { 470 | if (state != STATE_APP_LOOP) 471 | { 472 | xEventGroupClearBits(event_group, OTA_TASK_IN_NORMAL_STATE_EVENT); 473 | } 474 | 475 | actual_event = xEventGroupWaitBits(event_group, 476 | WIFI_CONNECTED_EVENT | WIFI_DISCONNECTED_EVENT | MQTT_CONNECTED_EVENT | MQTT_DISCONNECTED_EVENT | OTA_CONFIG_FETCHED_EVENT, 477 | false, false, portMAX_DELAY); 478 | } 479 | 480 | switch (state) 481 | { 482 | case STATE_INITIAL: 483 | { 484 | // Initialize NVS. 485 | esp_err_t err = nvs_flash_init(); 486 | if (err == ESP_ERR_NVS_NO_FREE_PAGES) 487 | { 488 | // OTA app partition table has a smaller NVS partition size than the non-OTA 489 | // partition table. This size mismatch may cause NVS initialization to fail. 490 | // If this happens, we erase NVS partition and initialize NVS again. 491 | APP_ABORT_ON_ERROR(nvs_flash_erase()); 492 | err = nvs_flash_init(); 493 | } 494 | APP_ABORT_ON_ERROR(err); 495 | 496 | const esp_partition_t *running_partition = esp_ota_get_running_partition(); 497 | strncpy(running_partition_label, running_partition->label, sizeof(running_partition_label)); 498 | ESP_LOGI(TAG, "Running partition: %s", running_partition_label); 499 | 500 | initialise_wifi(running_partition_label); 501 | state = STATE_WAIT_WIFI; 502 | break; 503 | } 504 | case STATE_WAIT_WIFI: 505 | { 506 | if (actual_event & WIFI_DISCONNECTED_EVENT) 507 | { 508 | ESP_LOGW(TAG, "WAIT_WIFI state, Wi-Fi not connected, wait for the connect"); 509 | state = STATE_WAIT_WIFI; 510 | break; 511 | } 512 | 513 | if (actual_event & WIFI_CONNECTED_EVENT) 514 | { 515 | mqtt_app_start(running_partition_label); 516 | state = STATE_WAIT_MQTT; 517 | break; 518 | } 519 | 520 | ESP_LOGE(TAG, "WAIT_WIFI state, unexpected event received: %d", actual_event); 521 | state = STATE_INITIAL; 522 | break; 523 | } 524 | case STATE_WAIT_MQTT: 525 | { 526 | current_connection_state = connection_state(actual_event, "WAIT_MQTT"); 527 | if (current_connection_state != STATE_CONNECTION_IS_OK) 528 | { 529 | state = current_connection_state; 530 | break; 531 | } 532 | 533 | if (actual_event & (WIFI_CONNECTED_EVENT | MQTT_CONNECTED_EVENT)) 534 | { 535 | ESP_LOGI(TAG, "Connected to MQTT broker %s, on port %d", CONFIG_MQTT_BROKER_URL, CONFIG_MQTT_BROKER_PORT); 536 | 537 | // Send the current firmware version to ThingsBoard 538 | cJSON *current_fw = cJSON_CreateObject(); 539 | cJSON_AddStringToObject(current_fw, TB_CLIENT_ATTR_FIELD_CURRENT_FW, FIRMWARE_VERSION); 540 | char *current_fw_attribute = cJSON_PrintUnformatted(current_fw); 541 | cJSON_Delete(current_fw); 542 | esp_mqtt_client_publish(mqtt_client, TB_ATTRIBUTES_TOPIC, current_fw_attribute, 0, 1, 0); 543 | // Free is intentional, it's client responsibility to free the result of cJSON_Print 544 | free(current_fw_attribute); 545 | 546 | // Send the shared attributes keys to receive their values 547 | esp_mqtt_client_subscribe(mqtt_client, TB_ATTRIBUTES_SUBSCRIBE_TO_RESPONSE_TOPIC, 1); 548 | esp_mqtt_client_publish(mqtt_client, TB_ATTRIBUTES_REQUEST_TOPIC, TB_SHARED_ATTR_KEYS_REQUEST, 0, 1, 0); 549 | ESP_LOGI(TAG, "Waiting for shared attributes response"); 550 | 551 | state = STATE_WAIT_OTA_CONFIG_FETCHED; 552 | break; 553 | } 554 | 555 | ESP_LOGE(TAG, "WAIT_MQTT state, unexpected event received: %d", actual_event); 556 | state = STATE_INITIAL; 557 | break; 558 | } 559 | case STATE_WAIT_OTA_CONFIG_FETCHED: 560 | { 561 | current_connection_state = connection_state(actual_event, "WAIT_OTA_CONFIG_FETCHED"); 562 | if (current_connection_state != STATE_CONNECTION_IS_OK) 563 | { 564 | state = current_connection_state; 565 | break; 566 | } 567 | 568 | if (actual_event & (WIFI_CONNECTED_EVENT | MQTT_CONNECTED_EVENT)) 569 | { 570 | if (actual_event & OTA_CONFIG_FETCHED_EVENT) 571 | { 572 | ESP_LOGI(TAG, "Shared attributes were fetched from ThingsBoard"); 573 | xEventGroupClearBits(event_group, OTA_CONFIG_FETCHED_EVENT); 574 | state = STATE_OTA_CONFIG_FETCHED; 575 | break; 576 | } 577 | 578 | state = STATE_WAIT_OTA_CONFIG_FETCHED; 579 | break; 580 | } 581 | 582 | ESP_LOGE(TAG, "WAIT_OTA_CONFIG_FETCHED state, unexpected event received: %d", actual_event); 583 | state = STATE_INITIAL; 584 | break; 585 | } 586 | case STATE_OTA_CONFIG_FETCHED: 587 | { 588 | current_connection_state = connection_state(actual_event, "OTA_CONFIG_FETCHED"); 589 | if (current_connection_state != STATE_CONNECTION_IS_OK) 590 | { 591 | state = current_connection_state; 592 | break; 593 | } 594 | 595 | if (actual_event & (WIFI_CONNECTED_EVENT | MQTT_CONNECTED_EVENT)) 596 | { 597 | 598 | start_ota(FIRMWARE_VERSION, shared_attributes); 599 | esp_mqtt_client_subscribe(mqtt_client, TB_ATTRIBUTES_TOPIC, 1); 600 | ESP_LOGI(TAG, "Subscribed to shared attributes updates"); 601 | state = STATE_APP_LOOP; 602 | break; 603 | } 604 | ESP_LOGE(TAG, "OTA_CONFIG_FETCHED state, unexpected event received: %d", actual_event); 605 | state = STATE_INITIAL; 606 | break; 607 | } 608 | case STATE_APP_LOOP: 609 | { 610 | current_connection_state = connection_state(actual_event, "APP_LOOP"); 611 | if (current_connection_state != STATE_CONNECTION_IS_OK) 612 | { 613 | state = current_connection_state; 614 | break; 615 | } 616 | 617 | if (actual_event & (WIFI_CONNECTED_EVENT | MQTT_CONNECTED_EVENT)) 618 | { 619 | ota_events = xEventGroupWaitBits(event_group, OTA_CONFIG_UPDATED_EVENT, false, true, 0); 620 | if ((ota_events & OTA_CONFIG_UPDATED_EVENT)) 621 | { 622 | start_ota(FIRMWARE_VERSION, shared_attributes); 623 | } 624 | xEventGroupClearBits(event_group, OTA_CONFIG_UPDATED_EVENT); 625 | xEventGroupSetBits(event_group, OTA_TASK_IN_NORMAL_STATE_EVENT); 626 | state = STATE_APP_LOOP; 627 | break; 628 | } 629 | 630 | ESP_LOGE(TAG, "APP_LOOP state, unexpected event received: %d", actual_event); 631 | state = STATE_INITIAL; 632 | break; 633 | } 634 | default: 635 | { 636 | ESP_LOGE(TAG, "Unexpected state"); 637 | state = STATE_INITIAL; 638 | break; 639 | } 640 | } 641 | 642 | vTaskDelay(1000 / portTICK_PERIOD_MS); 643 | } 644 | } 645 | 646 | void app_main() 647 | { 648 | event_group = xEventGroupCreate(); 649 | xTaskCreate(&ota_task, "ota_task", 8192, NULL, 5, NULL); 650 | xTaskCreate(&main_application_task, "main_application_task", 8192, NULL, 5, NULL); 651 | } 652 | 653 | void notify_wifi_connected() 654 | { 655 | xEventGroupClearBits(event_group, WIFI_DISCONNECTED_EVENT); 656 | xEventGroupSetBits(event_group, WIFI_CONNECTED_EVENT); 657 | } 658 | 659 | void notify_wifi_disconnected() 660 | { 661 | xEventGroupClearBits(event_group, WIFI_CONNECTED_EVENT); 662 | xEventGroupSetBits(event_group, WIFI_DISCONNECTED_EVENT); 663 | } 664 | -------------------------------------------------------------------------------- /main/main.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file main.h 3 | */ 4 | 5 | #ifndef PRJ_MAIN_MODULE 6 | #define PRJ_MAIN_MODULE 7 | 8 | #include "freertos/event_groups.h" 9 | 10 | /*! Identifier of the log messages produced by the application */ 11 | #define TAG "tb_ota" 12 | 13 | /*! Firmware version used for comparison after OTA config was received from ThingsBoard */ 14 | #define FIRMWARE_VERSION "v1.1" 15 | 16 | /*! Factory partiton label */ 17 | #define FACTORY_PARTITION_LABEL "factory" 18 | 19 | /*! MQTT topic to send a telemetry to ThingsBoard */ 20 | #define TB_TELEMETRY_TOPIC "v1/devices/me/telemetry" 21 | 22 | /*! MQTT topic to send the shared attributes to ThingsBoard or to receive the shared attributes if they were updated on ThingsBoard */ 23 | #define TB_ATTRIBUTES_TOPIC "v1/devices/me/attributes" 24 | 25 | /*! MQTT topic to subscribe for the receiving of the specified shared attribute after the request to ThingsBoard */ 26 | #define TB_ATTRIBUTES_SUBSCRIBE_TO_RESPONSE_TOPIC "v1/devices/me/attributes/response/+" 27 | 28 | /** 29 | * @brief MQTT topic to request the specified shared attributes from ThingsBoard. 30 | * 44332 is a request id, any integer number can be used. 31 | */ 32 | #define TB_ATTRIBUTES_REQUEST_TOPIC "v1/devices/me/attributes/request/44332" 33 | 34 | /** 35 | * @brief MQTT topic to receive the requested specified shared attributes from ThingsBoard. 36 | * 44332 is a request id, have to be the same as used for the request. 37 | */ 38 | #define TB_ATTRIBUTES_RESPONSE_TOPIC "v1/devices/me/attributes/response/44332" 39 | 40 | /*! Client attribute key to send the firmware version value to ThingsBoard */ 41 | #define TB_CLIENT_ATTR_FIELD_CURRENT_FW "currentFwVer" 42 | 43 | /*! Shared attribute keys on ThingsBoard */ 44 | #define TB_SHARED_ATTR_FIELD_TARGET_FW_URL "targetFwUrl" 45 | #define TB_SHARED_ATTR_FIELD_TARGET_FW_VER "targetFwVer" 46 | 47 | /*! Body of the request of specified shared attributes */ 48 | #define TB_SHARED_ATTR_KEYS_REQUEST "{\"sharedKeys\":\"targetFwUrl,targetFwVer\"}" 49 | 50 | /** 51 | * @brief Bit set for application events 52 | */ 53 | #define WIFI_CONNECTED_EVENT BIT0 54 | #define WIFI_DISCONNECTED_EVENT BIT1 55 | #define MQTT_CONNECTED_EVENT BIT2 56 | #define MQTT_DISCONNECTED_EVENT BIT3 57 | #define OTA_CONFIG_FETCHED_EVENT BIT4 58 | #define OTA_CONFIG_UPDATED_EVENT BIT5 59 | #define OTA_TASK_IN_NORMAL_STATE_EVENT BIT6 60 | 61 | /*! Max length of access token */ 62 | #define MAX_LENGTH_TB_ACCESS_TOKEN 20 63 | #define MAX_LENGTH_TB_URL 256 64 | 65 | /*! NVS storage key where the MQTT broker URL is saved */ 66 | #define NVS_KEY_MQTT_URL "mqtt_url" 67 | 68 | /*! NVS storage key where the MQTT broker port is saved */ 69 | #define NVS_KEY_MQTT_PORT "mqtt_port" 70 | 71 | /*! NVS storage key where the MQTT access token is saved */ 72 | #define NVS_KEY_MQTT_ACCESS_TOKEN "access_token" 73 | 74 | /** 75 | * @brief Set of states for @ref ota_task(void) 76 | */ 77 | enum state 78 | { 79 | STATE_INITIAL, 80 | STATE_WAIT_WIFI, 81 | STATE_WIFI_CONNECTED, 82 | STATE_WAIT_MQTT, 83 | STATE_MQTT_CONNECTED, 84 | STATE_WAIT_OTA_CONFIG_FETCHED, 85 | STATE_OTA_CONFIG_FETCHED, 86 | STATE_APP_LOOP, 87 | 88 | STATE_CONNECTION_IS_OK 89 | }; 90 | 91 | /*! Updates application event bits on changing Wi-Fi state */ 92 | void notify_wifi_connected(); 93 | void notify_wifi_disconnected(); 94 | 95 | /** 96 | * Macro to check the error code. 97 | * Prints the error code, error location, and the failed statement to serial output. 98 | * Unlike to ESP_ERROR_CHECK() method this macros abort the application's execution if it was built as 'release'. 99 | */ 100 | #define APP_ABORT_ON_ERROR(x) \ 101 | do \ 102 | { \ 103 | esp_err_t __err_rc = (x); \ 104 | if (__err_rc != ESP_OK) \ 105 | { \ 106 | _esp_error_check_failed(__err_rc, __FILE__, __LINE__, \ 107 | __ASSERT_FUNC, #x); \ 108 | } \ 109 | } while (0); 110 | 111 | #endif 112 | -------------------------------------------------------------------------------- /main/wifi.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file wifi.c 3 | */ 4 | 5 | #include 6 | #include 7 | 8 | #include "wifi.h" 9 | #include "main.h" 10 | 11 | #include "esp_event_loop.h" 12 | #include "esp_log.h" 13 | #include "esp_system.h" 14 | #include "esp_wifi.h" 15 | 16 | /*! Buffer to save ESP32 MAC address */ 17 | uint8_t esp32_mac[6]; 18 | 19 | static esp_err_t esp_event_handler(void *ctx, system_event_t *event) 20 | { 21 | assert(event != NULL); 22 | 23 | switch (event->event_id) 24 | { 25 | case SYSTEM_EVENT_STA_START: 26 | esp_wifi_connect(); 27 | break; 28 | case SYSTEM_EVENT_STA_GOT_IP: 29 | notify_wifi_connected(); 30 | ESP_LOGI(TAG, "Connected to WI-FI, IP address: %s", ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip)); 31 | break; 32 | case SYSTEM_EVENT_STA_DISCONNECTED: 33 | /* This is a workaround as ESP32 WiFi libs don't currently auto-reassociate. */ 34 | esp_wifi_connect(); 35 | notify_wifi_disconnected(); 36 | break; 37 | default: 38 | break; 39 | } 40 | return ESP_OK; 41 | } 42 | 43 | void initialise_wifi(const char *running_partition_label) 44 | { 45 | assert(running_partition_label != NULL); 46 | 47 | tcpip_adapter_init(); 48 | APP_ABORT_ON_ERROR(esp_event_loop_init(esp_event_handler, NULL)); 49 | wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); 50 | APP_ABORT_ON_ERROR(esp_wifi_init(&cfg)); 51 | APP_ABORT_ON_ERROR(esp_wifi_set_storage(WIFI_STORAGE_FLASH)); 52 | 53 | wifi_config_t wifi_config = {}; 54 | APP_ABORT_ON_ERROR(esp_wifi_get_config(ESP_IF_WIFI_STA, &wifi_config)); 55 | 56 | if (wifi_config.sta.ssid[0] == '\0' || wifi_config.sta.password[0] == '\0') 57 | { 58 | ESP_LOGW(TAG, "Flash memory doesn't contain any Wi-Fi credentials"); 59 | if (strcmp(FACTORY_PARTITION_LABEL, running_partition_label) == 0) 60 | { 61 | ESP_LOGW(TAG, "Factory partition is running, Wi-Fi credentials from config are used and will be saved to the flash memory"); 62 | wifi_sta_config_t wifi_sta_config = { 63 | .ssid = WIFI_SSID, 64 | .password = WIFI_PASS, 65 | }; 66 | 67 | wifi_config.sta = wifi_sta_config; 68 | } 69 | else 70 | { 71 | ESP_LOGE(TAG, "Wi-Fi credentials were not found, running partition is not '%s'", FACTORY_PARTITION_LABEL); 72 | APP_ABORT_ON_ERROR(ESP_FAIL); 73 | } 74 | } 75 | else 76 | { 77 | ESP_LOGI(TAG, "Wi-Fi credentials from flash memory: %s, %s", wifi_config.sta.ssid, wifi_config.sta.password); 78 | } 79 | 80 | APP_ABORT_ON_ERROR(esp_wifi_get_mac(ESP_IF_WIFI_STA, esp32_mac)) 81 | ESP_LOGI(TAG, "MAC address: %02X:%02X:%02X:%02X:%02X:%02X", esp32_mac[0], esp32_mac[1], esp32_mac[2], esp32_mac[3], esp32_mac[4], esp32_mac[5]); 82 | APP_ABORT_ON_ERROR(esp_wifi_set_mode(WIFI_MODE_STA)); 83 | 84 | APP_ABORT_ON_ERROR(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config)); 85 | APP_ABORT_ON_ERROR(esp_wifi_start()); 86 | } 87 | -------------------------------------------------------------------------------- /main/wifi.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file wifi.h 3 | */ 4 | 5 | #ifndef PRJ_WIFI_MODULE 6 | #define PRJ_WIFI_MODULE 7 | 8 | #include "esp_event_loop.h" 9 | #include "freertos/FreeRTOS.h" 10 | 11 | #define WIFI_SSID CONFIG_WIFI_SSID 12 | #define WIFI_PASS CONFIG_WIFI_PASSWORD 13 | 14 | void initialise_wifi(const char *running_partition_label); 15 | 16 | #endif 17 | -------------------------------------------------------------------------------- /server_certs/ca_cert.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIEsTCCA5mgAwIBAgIQBOHnpNxc8vNtwCtCuF0VnzANBgkqhkiG9w0BAQsFADBs 3 | MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 4 | d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j 5 | ZSBFViBSb290IENBMB4XDTEzMTAyMjEyMDAwMFoXDTI4MTAyMjEyMDAwMFowcDEL 6 | MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3 7 | LmRpZ2ljZXJ0LmNvbTEvMC0GA1UEAxMmRGlnaUNlcnQgU0hBMiBIaWdoIEFzc3Vy 8 | YW5jZSBTZXJ2ZXIgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC2 9 | 4C/CJAbIbQRf1+8KZAayfSImZRauQkCbztyfn3YHPsMwVYcZuU+UDlqUH1VWtMIC 10 | Kq/QmO4LQNfE0DtyyBSe75CxEamu0si4QzrZCwvV1ZX1QK/IHe1NnF9Xt4ZQaJn1 11 | itrSxwUfqJfJ3KSxgoQtxq2lnMcZgqaFD15EWCo3j/018QsIJzJa9buLnqS9UdAn 12 | 4t07QjOjBSjEuyjMmqwrIw14xnvmXnG3Sj4I+4G3FhahnSMSTeXXkgisdaScus0X 13 | sh5ENWV/UyU50RwKmmMbGZJ0aAo3wsJSSMs5WqK24V3B3aAguCGikyZvFEohQcft 14 | bZvySC/zA/WiaJJTL17jAgMBAAGjggFJMIIBRTASBgNVHRMBAf8ECDAGAQH/AgEA 15 | MA4GA1UdDwEB/wQEAwIBhjAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIw 16 | NAYIKwYBBQUHAQEEKDAmMCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdpY2Vy 17 | dC5jb20wSwYDVR0fBEQwQjBAoD6gPIY6aHR0cDovL2NybDQuZGlnaWNlcnQuY29t 18 | L0RpZ2lDZXJ0SGlnaEFzc3VyYW5jZUVWUm9vdENBLmNybDA9BgNVHSAENjA0MDIG 19 | BFUdIAAwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQuY29tL0NQ 20 | UzAdBgNVHQ4EFgQUUWj/kK8CB3U8zNllZGKiErhZcjswHwYDVR0jBBgwFoAUsT7D 21 | aQP4v0cB1JgmGggC72NkK8MwDQYJKoZIhvcNAQELBQADggEBABiKlYkD5m3fXPwd 22 | aOpKj4PWUS+Na0QWnqxj9dJubISZi6qBcYRb7TROsLd5kinMLYBq8I4g4Xmk/gNH 23 | E+r1hspZcX30BJZr01lYPf7TMSVcGDiEo+afgv2MW5gxTs14nhr9hctJqvIni5ly 24 | /D6q1UEL2tU2ob8cbkdJf17ZSHwD2f2LSaCYJkJA69aSEaRkCldUxPUd1gJea6zu 25 | xICaEnL6VpPX/78whQYwvwt/Tv9XBZ0k7YXDK/umdaisLRbvfXknsuvCnQsH6qqF 26 | 0wGjIChBWUMo0oHjqvbsezt3tkBigAVBRQHvFwY+3sAzm2fTYS5yh+Rp/BIAV0Ae 27 | cPUeybQ= 28 | -----END CERTIFICATE----- 29 | --------------------------------------------------------------------------------