I am having trouble understanding the callback function which occurs in many of the examples in Build Web Servers eBook – 2nd Edition (eg. pg. 287 or pg. 337)
void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {
AwsFrameInfo *info = (AwsFrameInfo*)arg;
if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
data[len] = 0;
if (strcmp((char*)data, “states”) == 0) {
notifyClients(getOutputStates());
}
else{
int gpio = atoi((char*)data);
digitalWrite(gpio, !digitalRead(gpio));
notifyClients(getOutputStates());
}
I would like to know how the code works in much more detail than in the How the Code Works section.
Hi.
The handleWebSocketMessage() message will be called when a new websocket event data happens. See the onEvent function:
void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) { switch (type) { case WS_EVT_CONNECT: Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str()); break; case WS_EVT_DISCONNECT: Serial.printf("WebSocket client #%u disconnected\n", client->id()); break; case WS_EVT_DATA: handleWebSocketMessage(arg, data, len); break; case WS_EVT_PONG: case WS_EVT_ERROR: break; } }
arg, data, and len are parameters passed automatically to the handleWebSocketMessage() callback function.
Inside the handleWebSocketMessage, arg (which is a WebSocket frame) is cast to the AwsFrameInfo type. This structure contains metadata such as whether the message is complete, its length, and its type (binary or text).
The following line:
if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
checks if the WebSocket message is complete, has the expected length, and is a text message. If so, we have a valid websocket message.
Then, we basically check the content of the received data , which is saved on the data variable, and act accordingly. The strcmp() function compares two strings character by character and returns 0 if the two strings are identical.
I hope this helps.
Regards,
Sara
Thank you very much Sara,
This is exactly what i needed to know.
Am I correct in understanding that “arg, data, and len ” and their memory locations originate <AsyncTCP.h> or <ESPAsyncWebServer.h> libraries? Hence your use of “automatically”
Thank you again for a very comprehensive and comprehensible answer
Wally