How to send char array of sensor data to websocket client ?
I have my websocket server based on advanced echo server working fine. with following code in loop section:
void loop() {
#if WEBSOCKETS
while (WSserver.available()) {
// if there is a client that wants to connect
if(WSserver.poll()) {
//accept the connection and register callback
Serial.println("Accepting a new client!");
WebsocketsClient client = WSserver.accept();
client.onMessage(onMessage);
// store it for later use
allClients.push_back(client);
}
// check for updates in all clients
pollAllClients();
if (triggerProcessData == 1) {
processData();
triggerProcessData = 0;
}
#if MQTT
broker.loop(); // Don't forget to add loop for every broker and clients
myClient.loop();
#endif
}
#endif
} // End of loop
Now Ihave callback function in the same skech like below:
const char* data = "Data requested";
static int callback(void *data, int argc, char **argv, char **azColName) {
Serial.print((char) '[');
int i;
for (i = 0; i<(argc); i++) {
if(i)
Serial.print((char) ',');
Serial.printf("%s", argv[i] ? argv[i] : "NULL");
}
Serial.printf("],\n");
return 0;
}
Which prints data in my serial console based on request from javascript websocket client. Data in my serial console looks like below:
[1623287518,24785,1535,15,6,-22,292,49,89,250,76],
[1623287645,24785,1535,15,26,-52,294,51,94,224,48],
[1623287668,24785,1535,15,6,-22,292,49,44,249,81],
[1623287796,24785,1535,15,26,-53,294,46,97,229,36],
Now I want to send this data to websocket client who requested it but I do not know how to do it.
Can you please show me how to send the data to client?
Thanks.
The post is a bit confusing, but please make sure you consult the wiki entries on sending messages
If you want to send binary data, you have 2 main options:
- send it as raw bytes using
sendBinary. The receiving end should also expect such raw data - serialize it and send it as text. You can serialize it as base64, or JSON for example
Gil
Thank you for a link to resource. I should have read it in first place. Now in my case argv[i] is array of strings so how should I send it ? As a binary or text?
Thanks.
Thank you for a link to resource. I should have read it in first place. Now in my case argv[i] is array of strings so how should I send it ? As a binary or text?
Thanks.
Personally my preferred approach is to serialize everything as a JSON string and send it.