赞
踩
创建任务,需要分配足够大的栈空间,否则会溢出
xTaskCreatePinnedToCore(websocket_task, "websocket_task", 1024 * 32, NULL, 1,&websocket_task_handler, 1);
编写任务函数,webSocketEvent注册的回调函数
WebSocketsClient webSocket; const char *url = "/ws_device/device_id"; const char *protocol = "websocket"; void websocket_task(void *pvParameters) { (void)pvParameters; webSocket.begin(host, port, url, protocol); webSocket.onEvent(webSocketEvent); webSocket.setReconnectInterval(3000); while (1) { webSocket.loop(); } }
实现回调函数的任务
void webSocketEvent(WStype_t type, uint8_t *payload, size_t length) { switch (type) { case WStype_DISCONNECTED: { USE_SERIAL.printf("[WSc] Disconnected!\n"); break; } case WStype_CONNECTED: { USE_SERIAL.printf("[WSc] Connected to url: %s\n", payload); break; } case WStype_TEXT: { USE_SERIAL.printf("[WSc] get text: %s\n", payload); deserializeJson(doc, (char *)payload); String peripheral = doc["peripheral"]; if (peripheral == "flash_light") { flash_brightness = doc["brightness"]; } else if (peripheral == "led") { led_brightness = doc["brightness"]; } else if (peripheral == "file") { String file_name = doc["file_name"]; USE_SERIAL.println(file_name); wifi.getFile(file_name); } // USE_SERIAL.println((char*)payload); break; } case WStype_BIN: { USE_SERIAL.printf("[WSc] get binary length: %u\n", length); hexdump(payload, length); webSocket.sendBIN(payload, length); } break; case WStype_ERROR: break; case WStype_FRAGMENT_TEXT_START: break; case WStype_FRAGMENT_BIN_START: break; case WStype_FRAGMENT: break; case WStype_FRAGMENT_FIN: break; case WStype_PING: break; case WStype_PONG: break; } }
注意:回调函数在这里被限制5ms为一个时间粒度,即最快200Hz,甚至有些延迟,服务器端需要做好速度匹配
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。