ESP8266 http收发数据

1.先修改基础配置 

make menuconfig

打开配置菜单

选择component config 

然后选择

 修改波特率为115200

保存退出 

2.修改彩色日志打印的

在component config目录下找到log output

 选中点击空格关掉彩色日志输出,这样正常串口打印就没有乱码了

然后保存退出

3.串口接收json,http发送云代码

设备 HTTP 接入 | ThingsCloud 使用文档

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "driver/uart.h"
#include "driver/gpio.h"
#include "esp_wifi.h"
#include "esp_event_loop.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_http_client.h"
#include "cJSON.h"
#include <stdio.h>
#include <string.h>#define LED_GPIO 2
#define PROJECT_KEY "*"char g_wifi_ssid[64] = "";
char g_wifi_pass[64] = "";
char g_post_json[512] = "";SemaphoreHandle_t xPostSemaphore;// WiFi Event Handler
esp_err_t event_handler(void *ctx, system_event_t *event)
{switch (event->event_id){case SYSTEM_EVENT_STA_START:esp_wifi_connect();break;case SYSTEM_EVENT_STA_GOT_IP:printf("Got IP: %s\n", ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));break;case SYSTEM_EVENT_STA_DISCONNECTED:printf("Disconnected, retrying...\n");esp_wifi_connect();break;default:break;}return ESP_OK;
}// init once
void wifi_driver_init()
{tcpip_adapter_init();ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();ESP_ERROR_CHECK(esp_wifi_init(&cfg));ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));ESP_ERROR_CHECK(esp_wifi_start());
}//  change WiFi connect
void wifi_connect()
{wifi_config_t wifi_config = {0};strcpy((char *)wifi_config.sta.ssid, g_wifi_ssid);strcpy((char *)wifi_config.sta.password, g_wifi_pass);// 先断开esp_wifi_disconnect();vTaskDelay(pdMS_TO_TICKS(100));// 设置新配置ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));// 连接ESP_ERROR_CHECK(esp_wifi_connect());
}// uart receive task
void uart_receive_task(void *pvParams)
{const int uart_num = UART_NUM_0;uart_config_t uart_config = {.baud_rate = 115200,.data_bits = UART_DATA_8_BITS,.parity    = UART_PARITY_DISABLE,.stop_bits = UART_STOP_BITS_1,.flow_ctrl = UART_HW_FLOWCTRL_DISABLE};uart_param_config(uart_num, &uart_config);uart_driver_install(uart_num, 2048, 0, 0, NULL, 0);uint8_t data[512];while (1){int len = uart_read_bytes(uart_num, data, sizeof(data) - 1, pdMS_TO_TICKS(1000));if (len > 0){data[len] = '\0';printf("UART Received: %s\n", data);cJSON *root = cJSON_Parse((char *)data);if (!root){printf("JSON Parse Error\n");}else{cJSON *ssid = cJSON_GetObjectItem(root, "ssid");cJSON *pass = cJSON_GetObjectItem(root, "pass");if (ssid && pass){// WiFi 账号密码配置strncpy(g_wifi_ssid, ssid->valuestring, sizeof(g_wifi_ssid) - 1);strncpy(g_wifi_pass, pass->valuestring, sizeof(g_wifi_pass) - 1);printf("Set WiFi SSID: %s\n", g_wifi_ssid);printf("Set WiFi PASS: %s\n", g_wifi_pass);wifi_connect();}else{// 透传 POST 数据strncpy(g_post_json, (char *)data, sizeof(g_post_json) - 1);g_post_json[sizeof(g_post_json) - 1] = '\0';printf("POST JSON set: %s\n", g_post_json);xSemaphoreGive(xPostSemaphore); // 通知 POST 任务}cJSON_Delete(root);}}}
}// HTTP POST task
void http_post_task(void *pvParameters)
{while (1){if (xSemaphoreTake(xPostSemaphore, portMAX_DELAY) == pdTRUE){esp_http_client_config_t config = {.url = "http://sh-3-api.iot-api.com/device/v1/<*your tocken>/attributes",};esp_http_client_handle_t client = esp_http_client_init(&config);esp_http_client_set_method(client, HTTP_METHOD_POST);esp_http_client_set_header(client, "Content-Type", "application/json");esp_http_client_set_header(client, "Project-Key", PROJECT_KEY);esp_http_client_set_post_field(client, g_post_json, strlen(g_post_json));esp_err_t err = esp_http_client_perform(client);if (err == ESP_OK){printf("HTTP POST Status = %d, content_length = %d\n",esp_http_client_get_status_code(client),esp_http_client_get_content_length(client));}else{printf("HTTP POST request failed: %s\n", esp_err_to_name(err));}esp_http_client_cleanup(client);}}
}// LED task
void led_blink_task(void *pvParams)
{gpio_set_direction(LED_GPIO, GPIO_MODE_OUTPUT);while (1){gpio_set_level(LED_GPIO, 1);vTaskDelay(pdMS_TO_TICKS(500));gpio_set_level(LED_GPIO, 0);vTaskDelay(pdMS_TO_TICKS(500));}
}// Main
void app_main()
{nvs_flash_init();wifi_driver_init();xPostSemaphore = xSemaphoreCreateBinary();xTaskCreate(uart_receive_task, "uart_receive_task", 4096, NULL, 5, NULL);xTaskCreate(http_post_task, "http_post_task", 8192, NULL, 5, NULL);xTaskCreate(led_blink_task, "led_blink_task", 2048, NULL, 5, NULL);
}

4.使用方法

(1)串口接收数据配网(不要有空格)

{"ssid":"***","pass":"********"}

(2)串口接收数据http发送云(不要有空格,数据可以自己往后添加)

{"temperature":115,"humidity":32.2,"switch":true}

5.效果

6.get线程获取云服务数据(需要修改两个url的token)

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "driver/uart.h"
#include "driver/gpio.h"
#include "esp_wifi.h"
#include "esp_event_loop.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_http_client.h"
#include "cJSON.h"
#include <stdio.h>
#include <string.h>#define LED_GPIO 2
#define PROJECT_KEY "*"char g_wifi_ssid[64] = "";
char g_wifi_pass[64] = "";
char g_post_json[512] = "";SemaphoreHandle_t xPostSemaphore;// WiFi Event Handler
esp_err_t event_handler(void *ctx, system_event_t *event)
{switch (event->event_id){case SYSTEM_EVENT_STA_START:esp_wifi_connect();break;case SYSTEM_EVENT_STA_GOT_IP:printf("Got IP: %s\n", ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));break;case SYSTEM_EVENT_STA_DISCONNECTED:printf("Disconnected, retrying...\n");esp_wifi_connect();break;default:break;}return ESP_OK;
}// init once
void wifi_driver_init()
{tcpip_adapter_init();ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();ESP_ERROR_CHECK(esp_wifi_init(&cfg));ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));ESP_ERROR_CHECK(esp_wifi_start());
}//  change WiFi connect
void wifi_connect()
{wifi_config_t wifi_config = {0};strcpy((char *)wifi_config.sta.ssid, g_wifi_ssid);strcpy((char *)wifi_config.sta.password, g_wifi_pass);// 先断开esp_wifi_disconnect();vTaskDelay(pdMS_TO_TICKS(100));// 设置新配置ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));// 连接ESP_ERROR_CHECK(esp_wifi_connect());
}// 串口接收任务
void uart_receive_task(void *pvParams)
{const int uart_num = UART_NUM_0;uart_config_t uart_config = {.baud_rate = 115200,.data_bits = UART_DATA_8_BITS,.parity    = UART_PARITY_DISABLE,.stop_bits = UART_STOP_BITS_1,.flow_ctrl = UART_HW_FLOWCTRL_DISABLE};uart_param_config(uart_num, &uart_config);uart_driver_install(uart_num, 2048, 0, 0, NULL, 0);uint8_t data[512];while (1){int len = uart_read_bytes(uart_num, data, sizeof(data) - 1, pdMS_TO_TICKS(1000));if (len > 0){data[len] = '\0';printf("UART Received: %s\n", data);cJSON *root = cJSON_Parse((char *)data);if (!root){printf("JSON Parse Error\n");}else{cJSON *ssid = cJSON_GetObjectItem(root, "ssid");cJSON *pass = cJSON_GetObjectItem(root, "pass");if (ssid && pass){// WiFi 账号密码配置strncpy(g_wifi_ssid, ssid->valuestring, sizeof(g_wifi_ssid) - 1);strncpy(g_wifi_pass, pass->valuestring, sizeof(g_wifi_pass) - 1);printf("Set WiFi SSID: %s\n", g_wifi_ssid);printf("Set WiFi PASS: %s\n", g_wifi_pass);wifi_connect();}else{// 透传 POST 数据strncpy(g_post_json, (char *)data, sizeof(g_post_json) - 1);g_post_json[sizeof(g_post_json) - 1] = '\0';printf("POST JSON set: %s\n", g_post_json);xSemaphoreGive(xPostSemaphore); // 通知 POST 任务}cJSON_Delete(root);}}}
}// HTTP POST 任务
void http_post_task(void *pvParameters)
{while (1){if (xSemaphoreTake(xPostSemaphore, portMAX_DELAY) == pdTRUE){esp_http_client_config_t config = {.url = "http://sh-3-api.iot-api.com/device/v1/******/attributes",};esp_http_client_handle_t client = esp_http_client_init(&config);esp_http_client_set_method(client, HTTP_METHOD_POST);esp_http_client_set_header(client, "Content-Type", "application/json");esp_http_client_set_header(client, "Project-Key", PROJECT_KEY);esp_http_client_set_post_field(client, g_post_json, strlen(g_post_json));esp_err_t err = esp_http_client_perform(client);if (err == ESP_OK){printf("HTTP POST Status = %d, content_length = %d\n",esp_http_client_get_status_code(client),esp_http_client_get_content_length(client));}else{printf("HTTP POST request failed: %s\n", esp_err_to_name(err));}esp_http_client_cleanup(client);}}
}// ========== HTTP GET Task ==========
void http_get_task(void *pvParameters)
{while (1){esp_http_client_config_t config = {.url = "http://sh-3-api.iot-api.com/device/v1/*****/attributes",};esp_http_client_handle_t client = esp_http_client_init(&config);esp_http_client_set_method(client, HTTP_METHOD_GET);esp_http_client_set_header(client, "Content-Type", "application/json");esp_http_client_set_header(client, "Project-Key", PROJECT_KEY);esp_err_t err = esp_http_client_perform(client);if (err == ESP_OK){printf("HTTP GET Status = %d, content_length = %d\n",esp_http_client_get_status_code(client),esp_http_client_get_content_length(client));// ========== 循环读取完整内容 ==========char buffer[512];int total_len = 0;while (1){int data_read = esp_http_client_read(client, buffer, sizeof(buffer) - 1);if (data_read <= 0)break;buffer[data_read] = 0; // 添加结束符printf("%s", buffer);  // 分块打印total_len += data_read;}printf("\n[Total Read Length: %d]\n", total_len);}else{printf("HTTP GET request failed: %s\n", esp_err_to_name(err));}esp_http_client_cleanup(client);vTaskDelay(pdMS_TO_TICKS(15000)); // 每15s获取一次}
}// LED 任务
void led_blink_task(void *pvParams)
{gpio_set_direction(LED_GPIO, GPIO_MODE_OUTPUT);while (1){gpio_set_level(LED_GPIO, 1);vTaskDelay(pdMS_TO_TICKS(500));gpio_set_level(LED_GPIO, 0);vTaskDelay(pdMS_TO_TICKS(500));}
}// Main
void app_main()
{nvs_flash_init();wifi_driver_init();xPostSemaphore = xSemaphoreCreateBinary();xTaskCreate(uart_receive_task, "uart_receive_task", 4096, NULL, 5, NULL);xTaskCreate(http_post_task, "http_post_task", 8192, NULL, 5, NULL);xTaskCreate(http_get_task, "http_get_task", 8192, NULL, 5, NULL);xTaskCreate(led_blink_task, "led_blink_task", 2048, NULL, 5, NULL);
}

7.效果(连接过的wifi会保存flash,每次发送WiFi账密,会重新连接)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/web/90540.shtml
繁体地址,请注明出处:http://hk.pswp.cn/web/90540.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ZLMediaKit 源代码入门

ZLMediaKit 是一个基于 C11 开发的高性能流媒体服务器框架&#xff0c;支持 RTSP、RTMP、HLS、HTTP-FLV 等协议。以下是源代码入门的详细指南&#xff1a; 1. 源码结构概览 主要目录结构&#xff1a; text ZLMediaKit/ ├── cmake/ # CMake 构建配置 ├── …

智能Agent场景实战指南 Day 21:Agent自主学习与改进机制

【智能Agent场景实战指南 Day 21】Agent自主学习与改进机制 文章内容 开篇 欢迎来到"智能Agent场景实战指南"系列的第21天&#xff01;今天我们将深入探讨智能Agent的自主学习与改进机制——这是使Agent能够持续提升性能、适应动态环境的核心能力。在真实业务场景…

微信小程序中英文切换miniprogram-i18n-plus

原生微信小程序使用 miniprogram-i18n-plus第一步&#xff1a;npm install miniprogram-i18n-plus -S安装完成后&#xff0c;会在项目文件文件夹 node_modules文件里生成 miniprogram-i18n-plus&#xff0c; 然后在工具栏-工具-构建npm&#xff0c;然后看到miniprogram_npm里面…

LeetCode 127:单词接龙

LeetCode 127&#xff1a;单词接龙问题本质&#xff1a;最短转换序列的长度 给定两个单词 beginWord 和 endWord&#xff0c;以及字典 wordList&#xff0c;要求找到从 beginWord 到 endWord 的最短转换序列&#xff08;每次转换仅改变一个字母&#xff0c;且中间单词必须在 wo…

docker搭建ray集群

1. 安装docker 已安装过docker 没安装流程 启动 Docker 服务&#xff1a; sudo systemctl start docker sudo systemctl enable docker # 设置开机即启动docker验证 Docker 是否安装成功&#xff1a; docker --version2. 部署ray # 先停止docker服务 systemctl stop docker…

【iOS】SideTable

文章目录前言1️⃣Side Table 的核心作用&#xff1a;扩展对象元数据存储1.1 传统对象的内存限制1.2 Side Table 的定位&#xff1a;集中式元数据仓库2️⃣Side Table 的底层结构与关联2.1 Side Table 与 isa 指针的关系2.2 Side Table 的存储结构2.3 SideTable 的工作流程3️⃣…

【Spring Cloud Gateway 实战系列】高级篇:服务网格集成、安全增强与全链路压测

一、服务网格集成&#xff1a;Gateway与Istio的协同作战在微服务架构向服务网格演进的过程中&#xff0c;Spring Cloud Gateway可与Istio形成互补——Gateway负责南北向流量&#xff08;客户端到集群&#xff09;的入口管理&#xff0c;Istio负责东西向流量&#xff08;集群内服…

一文说清楚Hive

Hive作为Apache Hadoop生态的核心数据仓库工具&#xff0c;其设计初衷是为熟悉SQL的用户提供大规模数据离线处理能力。以下从底层计算框架、优点、场景、注意事项及实践案例五个维度展开说明。 一、Hive底层分布式计算框架对比 Hive本身不直接执行计算&#xff0c;而是将HQL转换…

SeaweedFS深度解析(三):裸金属单机和集群部署

#作者&#xff1a;闫乾苓 文章目录2.2.4 S3 Server&#xff08;兼容 Amazon S3 的接口&#xff09;2.2.5 Weed&#xff08;命令行工具&#xff09;3、裸金属单机和集群部署3.1 裸金属单机部署3.1.1安装 SeaweedFS3.1.2 以Master模式启动2.2.4 S3 Server&#xff08;兼容 Amazon…

相机ROI 参数

相机的 ROI&#xff08;Region of Interest&#xff0c;感兴趣区域&#xff09; 参数&#xff0c;是指通过设置图像传感器上 特定区域 作为有效成像区域&#xff0c;从而只采集该区域的图像数据&#xff0c;而忽略其他部分。这一功能常用于工业相机、科研相机、高速相机等场景&…

Vue基础(24)_VueCompinent构造函数、Vue实例对象与组件实例对象

分析上一节代码中的school组件&#xff1a;该组件是一个名为VueCompinent的构造函数。截取部分vue.js源码&#xff0c;分析Vue.extend&#xff1a;// 定义一个名为VueComponent的构造函数对象Sub&#xff0c;往Sub对象调用_init(options)方法&#xff0c;参数为配置项&#xff…

萤石云替代产品摄像头方案萤石云不支持TCP本地连接-东方仙盟

不断试错东方仙盟深耕科研测评&#xff0c;聚焦前沿领域&#xff0c;以严谨标准评估成果&#xff0c;追踪技术突破&#xff0c;在探索与验证中持续精进&#xff0c;为科研发展提供参考&#xff0c;助力探路前行 萤石云价格萤石云的不便于使用 家庭场景&#xff1a;成本可控与隐…

C51:用DS1302时钟读取和设置时间

因为在ds1302.c文件中包含了写ds1302&#xff08;51向ds1302写数据&#xff09;和读ds1302&#xff08;51从ds1302读数据&#xff09;的两个函数&#xff0c;我们根据文件中提供的函数来写读取时间和设置时间的函数即可ds1302.c文件源码如下&#xff0c;需要的同学可以参考一下…

webrtc整体架构

WebRTC&#xff08;Web Real-Time Communication&#xff09;是一套支持浏览器和移动应用进行实时音视频通信的开源技术标准&#xff0c;其架构设计围绕 “实时性”“低延迟”“跨平台” 和 “安全性” 展开&#xff0c;整体可分为核心引擎层、API 层、支撑服务层三大部分&…

浅析PCIe 6.0 ATS地址转换功能

在现代高性能计算和虚拟化系统中,地址转换(Address Translation)是一个至关重要的机制。随着 PCIe 设备(如 GPU、网卡、存储控制器)直接访问系统内存的能力增强,设备对虚拟内存的访问需求日益增长。 为了提升性能并确保安全访问,Address Translation Services(ATS) 应…

【前端】ikun-pptx编辑器前瞻问题二: pptx的压缩包结构,以及xml正文树及对应元素介绍

文章目录PPTX文件本质&#xff1a;一个压缩包核心文件解析1. 幻灯片内容文件 (ppt/slides/slideX.xml)2. 元素类型解析文本框元素 (p:sp)图片元素 (p:pic)单位系统开发注意事项参考工具pptx渲染路线图PPTX文件本质&#xff1a;一个压缩包 PPTX文件实际上是一个遵循Open XML标准…

分布式任务调度实战:XXL-JOB与Elastic-Job深度解析

告别传统定时任务的局限&#xff0c;拥抱分布式调度的强大与灵活 在现代分布式系统中&#xff0c;高效可靠的任务调度已成为系统架构的核心需求。面对传统方案&#xff08;如Timer、Quartz&#xff09;在分布式环境下的不足&#xff0c;开发者急需支持集群调度、故障转移和可视…

Windows 11下纯软件模拟虚拟机的设备模拟与虚拟化(仅终端和网络)

Windows 11下用GCC的C代码实现的虚拟机需要终端输入/输出&#xff08;如串口或虚拟控制台&#xff09;和网络连接&#xff0c;但不需要完整的硬件设备&#xff08;如磁盘、显卡、USB 等&#xff09;。在终端输入/输出方面&#xff0c;参考qemu的源代码&#xff0c;但不调用qemu…

CCF-GESP 等级考试 2025年6月认证Python六级真题解析

1 单选题&#xff08;每题 2 分&#xff0c;共 30 分&#xff09;第1题 下列哪一项不是面向对象编程&#xff08;OOP&#xff09;的基本特征&#xff1f;&#xff08; &#xff09;A. 继承 (Inheritance) B. 封装 (Encapsul…

C++中的deque

1. 什么是 Deque&#xff1f; 核心概念&#xff1a; Deque 是 “Double-Ended Queue”&#xff08;双端队列&#xff09;的缩写。你可以把它想象成一个可以在两端&#xff08;头部和尾部&#xff09;高效地进行添加或删除操作的线性数据结构。关键特性&#xff1a; 双端操作&am…