I'm using aedes as my custom MQTT broker and PubSubClient at the ESP32 side, together with the ArduinoJSON package.
My server test code:
import Aedes from "aedes";
import net from "net";
let port = process.env.MQTT_PORT || 1883; // MQTT Port
const id = "MY_SERVER";
const aedes = new Aedes({
id: id,
});
aedes.on("client", async (client) => {
console.log("Client conntected...");
});
aedes.on("subscribe", async (subscriptions, client) => {
let topic = "cmd/" + client.id;
let msg = {
topic: topic,
type: "test",
param: "p1"
};
console.log("Sending command...")
console.log(msg);
this.aedes.publish(msg);
});
let server = net.createServer(aedes.handle, options);
server.listen(port, () => {
console.log(`Find the server at: mqtt://localhost:${port}/`);
});
When running I'm getting:
Client connected...
Sending command...
{ topic: 'cmd/4CA9A712B42A', type: 'test', param: 'p1' }
At the client (ESP32) side I have my PubSubClient callback as follows:
void callback(char *topic, byte *payload, unsigned int length)
{
Serial.println("Message received.....");
StaticJsonDocument<256> doc;
deserializeJson(doc, payload, length);
char *command = doc["type"];
char *param = doc["param"];
Serial.println(command);
Serial.println(param);
}
The callback is being called property after subscription - but I'm not being able to parse the payload:
Message received.....
<empty line>
<empty line>
How can I fix the server or client to allow then to send/parse correctly the payload.
Serial.write(payload, length);in the callback and show us what it prints?payloadproperty when sending message:let msg = {topic: topic, payload: JSON.stringify({type: "test", param: "p1"})}did the trick.