#include <stdint.h>
#include <asm/delay.h>
-
+#if 0
+// WebSocket日志控制宏
+#define WS_LOG_ERROR(fmt, ...) printf("[WS_ERROR] " fmt "\n", ##__VA_ARGS__)
+#define WS_LOG_WARNING(fmt, ...) printf("[WS_WARN] " fmt "\n", ##__VA_ARGS__)
+#define WS_LOG_INFO(fmt, ...) printf("[WS_INFO] " fmt "\n", ##__VA_ARGS__)
+#define WS_LOG_DEBUG(fmt, ...) printf("[WS_DEBUG] " fmt "\n", ##__VA_ARGS__)
+#else
+// 可以通过注释/取消注释来控制日志级别
+#define WS_LOG_ERROR(fmt, ...) printf("[WS_ERROR] " fmt "\n", ##__VA_ARGS__)
+#define WS_LOG_WARNING(fmt, ...) printf("[WS_WARN] " fmt "\n", ##__VA_ARGS__)
+#define WS_LOG_INFO(fmt, ...) printf("[WS_INFO] " fmt "\n", ##__VA_ARGS__)
+#define WS_LOG_DEBUG(fmt, ...)
+#endif
extern osStatus_t osDelay(uint32_t ticks);
#define cat1_msleep(ms) LOS_Msleep(ms) /* osDelay(1) : 1ms */
url->error_message = bk_strdup(error_msg);
if (!url->error_message) {
// 若分配失败,输出提示信息
- printf("Memory allocation failed for error message.\n");
+ WS_LOG_ERROR("Memory allocation failed for error message.");
}
}
// 解析URL的函数
BK_URL parse_url(const char *url) {
- printf("parse_url url=%s.\n",url);
+ WS_LOG_WARNING("parse_url url=%s", url);
BK_URL result = {NULL, NULL, 0, NULL, NULL, 0, NULL};
char *temp_url_t = bk_strdup(url);
char *temp_url = temp_url_t;
unsigned char encoded[WEBSOCKET_KEY_LEN * 2];
size_t olen;
mbedtls_base64_encode(encoded, sizeof(encoded), &olen, (const unsigned char *)key, strlen(key));
- printf("generate_websocket_key %s %d\r\n",encoded ,olen);
+ WS_LOG_WARNING("generate_websocket_key %s %d", encoded, olen);
if(olen>=(WEBSOCKET_KEY_LEN))
olen=WEBSOCKET_KEY_LEN;
*/
int send_handshake(WebSocketClient *client,const char *headers,char *response,int response_len) {
char key[WEBSOCKET_KEY_LEN+1];
- printf("send_handshake1");
+ WS_LOG_INFO("send_handshake1");
if(client==NULL|| response==NULL || response_len<=0)
{
- printf("send_handshake client or response is NULL , or response_len <= 0\r\n");
+ WS_LOG_ERROR("send_handshake client or response is NULL , or response_len <= 0");
return -1;
}
char accept_key[64];
int ret = 0;
generate_accept_key(key, accept_key);
- printf("send_handshake2");
+ WS_LOG_INFO("send_handshake2");
char *request =( char *)aic_zalloc(BUFFER_SIZE);
if(request==NULL)
{
- printf("request aic_zalloc erro");
+ WS_LOG_ERROR("request aic_zalloc error");
return -1;
}
client->path,client->query , client->host,client->port, accept_key,client->host,client->port);
}
- printf("send_handshake request:\r\n%s",request);
+ WS_LOG_WARNING("send_handshake request:\r\n%s", request);
// 发送WebSocket握手请求并等待响应
- printf("发送WebSocket握手请求...\r\n");
+ WS_LOG_INFO("发送WebSocket握手请求...");
ret = tcp_send_and_wait_response(client->tcp_handle, (uint8_t *)request, strlen(request), (uint8_t *)response, response_len, 1000);
if (ret < 0) {
- printf("WebSocket握手发送失败: %d\r\n", ret);
+ WS_LOG_ERROR("WebSocket握手发送失败: %d", ret);
ret = -1;
} else {
- printf("WebSocket握手发送成功,接收到 %d 字节响应\r\n", ret);
+ WS_LOG_INFO("WebSocket握手发送成功,接收到 %d 字节响应", ret);
// 检查响应内容
if (ret > 0 && response[0] != '\0') {
- printf("WebSocket握手响应:\r\n%s\r\n", response);
+ WS_LOG_WARNING("WebSocket握手响应:\r\n%s", response);
// 检查是否包含"HTTP/1.1 101"
if (strstr(response, "HTTP/1.1 101") != NULL) {
- printf("WebSocket握手成功!\r\n");
+ WS_LOG_INFO("WebSocket握手成功!");
client->handshake = 1;
} else {
- printf("WebSocket握手失败:响应不是101状态码\r\n");
+ WS_LOG_ERROR("WebSocket握手失败:响应不是101状态码");
ret = -1;
}
} else {
- printf("WebSocket握手失败:无响应数据\r\n");
+ WS_LOG_ERROR("WebSocket握手失败:无响应数据");
ret = -1;
}
}
free(request);
- printf("send_handshake3 返回: %d\r\n", ret);
+ WS_LOG_INFO("send_handshake3 返回: %d", ret);
return ret;
}
if(client==NULL||message==NULL )
{
- WEARABLE_LOGE(WEARABLE_LOG_MODULE_APP,"send_websocket_message client or message is NULL %s %s\r\n",client,message);
+ WS_LOG_ERROR("send_websocket_message client or message is NULL %s %s", client, message);
return -1;
}
uint8_t* frame=( uint8_t *)aic_zalloc(message_len + 50);
int ret = -1;
if(!frame)
{
- WEARABLE_LOGE(WEARABLE_LOG_MODULE_APP,"send_websocket_message zalloc error\r\n");
+ WS_LOG_ERROR("send_websocket_message zalloc error");
return -1;
}
// 第一个字节:FIN = 1, 设置 opcode
offset += message_len;
// 发送帧
- WEARABLE_LOGE(WEARABLE_LOG_MODULE_APP,"offset %d\r\n",offset);
+ WS_LOG_DEBUG("offset %d", offset);
int ret_tcp_send_data=tcp_send_data(client->tcp_handle, frame, offset);
if (ret_tcp_send_data < 0) {
- WEARABLE_LOGE(WEARABLE_LOG_MODULE_APP,"lwip_send message failed %d\r\n",ret_tcp_send_data);
+ WS_LOG_ERROR("lwip_send message failed %d", ret_tcp_send_data);
ret = -1;
goto send_websocket_message_ERROR;
}
void _tcp_on_connect_cb(tcp_handle_t handle, bool success)
{
- printf("tcp_on_connect_cb %p %d\r\n", handle, success);
+ WS_LOG_INFO("tcp_on_connect_cb %p %d", handle, success);
if (success) {
// 连接成功,查找对应的WebSocket客户端
extern WebSocketClient * get_ws_client_by_handle(void* handle);
WebSocketClient * client = get_ws_client_by_handle(handle);
if (client != NULL) {
- printf("连接成功,开始WebSocket握手\r\n");
+ WS_LOG_INFO("连接成功,开始WebSocket握手");
// 等待连接稳定后再发送握手
- printf("等待TCP连接稳定...\r\n");
+ WS_LOG_INFO("等待TCP连接稳定...");
msleep(100); // 等待100ms让连接稳定
// 发送WebSocket握手请求
const int max_retries = 3;
while (retry_count < max_retries) {
- printf("WebSocket握手尝试 #%d...\r\n", retry_count + 1);
+ WS_LOG_INFO("WebSocket握手尝试 #%d...", retry_count + 1);
int bytes_received = send_handshake(client, NULL, buffer, BUFFER_SIZE);
if (bytes_received < 0) {
retry_count++;
if (retry_count < max_retries) {
- printf("WebSocket握手失败,等待重试...\r\n");
+ WS_LOG_INFO("WebSocket握手失败,等待重试...");
msleep(500); // 等待500ms后重试
continue;
} else {
- printf("WebSocket握手失败,已达到最大重试次数\r\n");
+ WS_LOG_INFO("WebSocket握手失败,已达到最大重试次数");
tcp_manager_close(client->tcp_handle);
}
} else {
- printf("WebSocket握手发送成功\r\n");
+ WS_LOG_INFO("WebSocket握手发送成功");
break;
}
}
free(buffer);
}
} else {
- printf("未找到对应的WebSocket客户端\r\n");
+ WS_LOG_INFO("未找到对应的WebSocket客户端");
}
} else {
- printf("TCP连接失败\r\n");
+ WS_LOG_INFO("TCP连接失败");
}
}
void _tcp_on_disconnect_cb(tcp_handle_t handle)
{
- printf("tcp_on_disconnect_cb %d\r\n",handle);
+ WS_LOG_INFO("tcp_on_disconnect_cb %d", handle);
}
void _tcp_on_data_received_cb(tcp_handle_t handle, uint8_t* data, uint16_t datalen)
{
- printf("tcp_on_data_received_cb 0x%0X %d\r\n",handle,datalen);
+ WS_LOG_INFO("tcp_on_data_received_cb 0x%0X %d", handle, datalen);
extern WebSocketClient * get_ws_client_by_handle(void* handle);
WebSocketClient * client = get_ws_client_by_handle(handle);
if(client==NULL)
{
- printf("get_ws_client failed\r\n");
+ WS_LOG_ERROR("get_ws_client failed");
return;
}
// 使用WebSocket解析器处理数据
int processed = ws_process_received_data(client, data, datalen);
if (processed < 0) {
- printf("WebSocket packet processing failed\n");
+ WS_LOG_ERROR("WebSocket packet processing failed");
return;
}
- printf("Processed %d bytes %s %s of WebSocket data\n", processed,client->host,client->path);
+ WS_LOG_WARNING("Processed %d bytes %s %s of WebSocket data", processed, client->host, client->path);
}
// 初始化 WebSocket 客户端
WebSocketClient *init_websocket_client(const char *url, const char *headers,uint8_t use_dns) {
err_t ret = 0;
if (!url) {
- printf("init_websocket_client Error: URL is NULL\n");
+ WS_LOG_ERROR("init_websocket_client Error: URL is NULL");
return NULL;
}
parsed_url = parse_url(url);//解析url
if (parsed_url.error) {
- printf("init_websocket_client Error: %s", parsed_url.error_message);
+ WS_LOG_ERROR("init_websocket_client Error: %s", parsed_url.error_message);
goto client_ERROR;
} else {
- printf("Protocol: %s", parsed_url.protocol);
- printf("Host: %s\n", parsed_url.host);
- printf("Port: %d\n", parsed_url.port);
- printf("Path: %s\n", parsed_url.path);
- printf("Query: %s\n", parsed_url.query);
+ WS_LOG_INFO("Protocol: %s", parsed_url.protocol);
+ WS_LOG_INFO("Host: %s", parsed_url.host);
+ WS_LOG_INFO("Port: %d", parsed_url.port);
+ WS_LOG_INFO("Path: %s", parsed_url.path);
+ WS_LOG_INFO("Query: %s", parsed_url.query);
}
client = (WebSocketClient *)aic_zalloc(sizeof(WebSocketClient)) ;
memset_s(client,sizeof(WebSocketClient),0,sizeof(WebSocketClient));
if(!client)
{
- printf("init_websocket_client alloc error: Failed to allocate memory for WebSocketClient\n");
+ WS_LOG_ERROR("init_websocket_client alloc error: Failed to allocate memory for WebSocketClient");
goto client_ERROR;
}
if(client->tcp_handle == NULL)
{
- printf("init_websocket_client Error: TCP connection failed for %s:%d\n", parsed_url.host, parsed_url.port);
+ WS_LOG_ERROR("init_websocket_client Error: TCP connection failed for %s:%d", parsed_url.host, parsed_url.port);
goto client_ERROR;
}
- printf("socket creation success\n");
+ WS_LOG_INFO("socket creation success");
strcpy(client->host, parsed_url.host);
strcpy(client->path, parsed_url.path);
/* 初始化WebSocket解析器 */
client->parser = ws_parser_init();
if (!client->parser) {
- printf("init_websocket_client Error: Failed to initialize WebSocket parser\n");
+ WS_LOG_ERROR("init_websocket_client Error: Failed to initialize WebSocket parser");
goto client_ERROR;
}
/* 握手将在连接成功回调中发送,这里不再立即发送 */
- printf("WebSocket客户端初始化完成,等待TCP连接建立\r\n");
+ WS_LOG_INFO("WebSocket客户端初始化完成,等待TCP连接建立");
// if(strstr(buffer,"HTTP/1.1 101") == NULL)
// {
// free(buffer);
free_url(parsed_url);
- printf("init_websocket_client end 2");
+ WS_LOG_INFO("init_websocket_client end 2");
return client;
client_ERROR:
- printf("init_websocket_client Error: Initialization failed, cleaning up...\n");
+ WS_LOG_ERROR("init_websocket_client Error: Initialization failed, cleaning up...");
if(client){
free(client);
client = NULL;
{
//移植建议: 此处调用 tcp_manager_close 进行关闭, 不必使用 lwip_close
- printf("lwip_close_websocket_client %s %s",client->host,client->path);
+ WS_LOG_INFO("lwip_close_websocket_client %s %s", client->host, client->path);
// 释放WebSocket解析器
if (client->parser) {
int ws_process_received_data(WebSocketClient *client, const uint8_t *data, size_t len)
{
if (!client || !data || len == 0 || !client->parser) {
- printf("ws_process_received_data: invalid parameters - client=%p, data=%p, len=%zu, parser=%p\n",
+ WS_LOG_ERROR("ws_process_received_data: invalid parameters - client=%p, data=%p, len=%zu, parser=%p",
client, data, len, client->parser);
return -1;
}
// ========== 新增:打印收到的所有原始数据 ==========
// printf("\n=== WebSocket Raw Data Received ===\n");
// printf("Client: %s:%s\n", client->host, client->path);
- printf("Total bytes: %zu\n", len);
+ WS_LOG_WARNING("Total bytes: %zu", len);
// printf("Raw data (hex): ");
// // 打印所有数据的十六进制表示
// for (size_t i = 0; i < len; i++) {
// bool valid_rsv = (rsv == 0);
// printf(" * Valid RSV: %s\n", valid_rsv ? "YES" : "NO");
// }
- printf("=====================================\n\n");
+ WS_LOG_WARNING("=====================================");
ws_parser_t* parser = client->parser;
int total_processed = 0;
const uint8_t* current_data = data;
size_t remaining_len = len;
- printf("ws_process_received_data: processing %zu bytes for client %s:%s\n",
+ WS_LOG_DEBUG("ws_process_received_data: processing %zu bytes for client %s:%s",
len, client->host, client->path);
// 循环处理数据,支持连续帧
while (remaining_len > 0) {
- printf("ws_process_received_data: processing remaining %zu bytes, current offset: %zu\n",
+ WS_LOG_DEBUG("ws_process_received_data: processing remaining %zu bytes, current offset: %zu",
remaining_len, current_data - data);
// 在解析前打印当前解析器状态
- printf("ws_process_received_data: parser state before parsing:\n");
+ WS_LOG_DEBUG("ws_process_received_data: parser state before parsing:");
// ws_parser_debug_state(parser);
// 使用新的解析器处理当前数据段
if(result <= 0)
{
- printf("ws_process_received_data: parsing error, reset parser,find next frame. Remaining: %zu bytes\n", remaining_len);
+ WS_LOG_ERROR("ws_process_received_data: parsing error, reset parser,find next frame. Remaining: %zu bytes", remaining_len);
ws_parser_reset(parser);
return -1;
}
remaining_len -= result;
// 在解析后打印解析器状态
- printf("ws_process_received_data: parser state after parsing:\n");
+ WS_LOG_DEBUG("ws_process_received_data: parser state after parsing:");
// ws_parser_debug_state(parser);
ws_parse_state_t ws_stat = ws_parser_get_state(parser);
const uint8_t* payload = ws_get_payload(parser);
size_t payload_len = ws_get_payload_length(parser);
- printf("ws_process_received_data: frame complete, total bytes: %d, payload bytes: %zu %s\n",
+ WS_LOG_DEBUG("ws_process_received_data: frame complete, total bytes: %d, payload bytes: %zu %s",
result, payload_len,client->path);
if (header && payload) {
- printf("WebSocket frame received: opcode=0x%02X, fin=%d, payload_len=%llu\n",
+ WS_LOG_DEBUG("WebSocket frame received: opcode=0x%02X, fin=%d, payload_len=%llu",
header->opcode, header->fin, header->payload_len);
// printf("payload = %s\n",payload);
// 根据操作码处理不同类型的消息
switch (header->opcode) {
case WS_PING:
- printf("Received WebSocket PING\n");
+ WS_LOG_DEBUG("Received WebSocket PING");
// TODO: 自动回复PONG
break;
case WS_PONG:
- printf("Received WebSocket PONG\n");
+ WS_LOG_DEBUG("Received WebSocket PONG");
break;
case WS_CLOSE:
- printf("Received WebSocket CLOSE\n");
+ WS_LOG_DEBUG("Received WebSocket CLOSE");
// 调用回调函数处理关闭帧
if (client->packet_callback) {
client->packet_callback((uint8_t*)payload, payload_len, (WebSocketMessageType)WS_CLOSE);
break;
default:
- printf("Unknown WebSocket opcode: 0x%02X\n", header->opcode);
+ WS_LOG_DEBUG("Unknown WebSocket opcode: 0x%02X", header->opcode);
break;
}
// 重要:在数据处理完成后再重置解析器状态
// 这样可以确保数据被正确处理后再清理状态
- printf("ws_process_received_data: data processing complete, resetting parser\n");
+ WS_LOG_DEBUG("ws_process_received_data: data processing complete, resetting parser");
ws_parser_reset(parser);
- printf("ws_process_received_data: frame processed, moving to next frame. Remaining: %zu bytes\n", remaining_len);
+ WS_LOG_DEBUG("ws_process_received_data: frame processed, moving to next frame. Remaining: %zu bytes", remaining_len);
} else {
- printf("ws_process_received_data: invalid payload data - header=%p, payload=%p, payload_len=%zu\n",
+ WS_LOG_DEBUG("ws_process_received_data: invalid payload data - header=%p, payload=%p, payload_len=%zu",
header, payload, payload_len);
return -1;
}
// 解析错误,重置parser
ws_parser_reset(parser);
- printf("ws_process_received_data: parsing error, find next frame. Remaining: %zu bytes\n", remaining_len);
+ WS_LOG_DEBUG("ws_process_received_data: parsing error, find next frame. Remaining: %zu bytes", remaining_len);
} else {
// 数据不完整,继续等待更多数据
- printf("ws_process_received_data: frame incomplete, waiting for more data\n");
+ WS_LOG_DEBUG("ws_process_received_data: frame incomplete, waiting for more data");
}
}
- printf("ws_process_received_data: total processed: %d bytes\n", total_processed);
+ WS_LOG_DEBUG("ws_process_received_data: total processed: %d bytes", total_processed);
return total_processed;
}