完善资料让更多小伙伴认识你,还能领取20积分哦, 立即完善>
这是我的代码: 代码: int mqtt_publish(char message[]) { int msg_id = 0; ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED"); mqtt_topic_t *mqtt_topic = get_mqtt_topic(); msg_id = esp_mqtt_client_publish(client,mqtt_topic->topic, message, 0, 1, 0); ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id); return msg_id; } mqtt_topic_t 结构在哪里: 代码: typedef struct mqtt_topic { char topic[200]; } mqtt_topic_t; 我正在从 HTTP 服务器发布请求中保存 MQTT 主题,如下所示: 代码: esp_err_t echo_post_handler(httpd_req_t *req) { nvs_handle handle; esp_err_t esp_err; char buf[200]; int ret, remaining = req->content_len; if(topic_rcvd == 0){ ESP_LOGI(TAG, "TOPIC RECVD IS 0"); } while (remaining > 0) { /* Read the data for the request */ if ((ret = httpd_req_recv(req, buf, MIN(remaining, sizeof(buf)))) <= 0) { if (ret == HTTPD_SOCK_ERR_tiMEOUT) { /* Retry receiving if timeout occurred */ continue; } return ESP_FAIL; } /* Send back the same data */ httpd_resp_send_chunk(req, buf, ret); remaining -= ret; /* Log data received */ ESP_LOGI(TAG, "=========== RECEIVED DATA =========="); ESP_LOGI(TAG, "%.*s", ret, buf); ESP_LOGI(TAG, "===================================="); http_server_send_message(HTTP_MSG_RECVD_TOPIC); topic_rcvd = 1; } esp_err_t request_sent = httpd_resp_send_chunk(req, NULL, 0); // End response esp_err = nvs_open(mqtt_client, NVS_READWRITE, &handle); if (esp_err != ESP_OK) { printf("Error in Saving (%s) n", esp_err_to_name(esp_err)); return esp_err; } //Set TOPIC esp_err = nvs_set_blob(handle, "topic", buf, 200); if (esp_err != ESP_OK) { printf("Error setting SSID (%s) n", esp_err_to_name(esp_err)); return esp_err; } esp_err = nvs_commit(handle); if (esp_err != ESP_OK) { printf("Error setting TOPIC to NVS (%s) n", esp_err_to_name(esp_err)); return esp_err; } nvs_close(handle); ESP_LOGI(TAG, "SAVED TOPIC %s", buf); return ESP_OK; } 像这样从内存中加载 MQTT 主题: 代码: bool load_mqtt_topic(void){ nvs_handle handle; esp_err_t esp_err; ESP_LOGI(TAG, "Loading MQTT Client from Flash"); if (nvs_open(mqtt_client, NVS_READONLY, &handle) == ESP_OK) { mqtt_topic_t *topic = get_mqtt_topic(); if(topic == NULL) { topic = (char*)malloc(sizeof(mqtt_topic_t)); } memset(topic, 0x00, sizeof(mqtt_topic_t)); size_t mqtt_size = sizeof(mqtt_topic_t); uint8_t *mqtt_buff = (uint8_t*)malloc(sizeof(mqtt_topic_t)); memset(mqtt_buff, 0x00, sizeof(mqtt_topic_t)); //LOAD SSID mqtt_size = sizeof(mqtt_topic_t); esp_err = nvs_get_blob(handle, "topic", mqtt_buff, &mqtt_size); if(esp_err != ESP_OK) { free(mqtt_buff); printf("NO MQTT CLIENT FOUND n"); return false; } memcpy(topic, mqtt_buff, mqtt_size); free(mqtt_buff); nvs_close(handle); printf("TOPIC %s", topic->topic); return topic->topic[0] != ' |