当前位置:   article > 正文

ESP32中的Websocket_esp32 websocket

esp32 websocket

ESP32中的Websocket

创建任务,需要分配足够大的栈空间,否则会溢出

xTaskCreatePinnedToCore(websocket_task, "websocket_task", 1024 * 32, NULL, 1,&websocket_task_handler, 1);
  • 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();
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

实现回调函数的任务


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;
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

注意:回调函数在这里被限制5ms为一个时间粒度,即最快200Hz,甚至有些延迟,服务器端需要做好速度匹配

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/588165
推荐阅读
相关标签
  

闽ICP备14008679号