php-mqtt / laravel-client

An MQTT client library for Laravel.
MIT License
185 stars 19 forks source link

Publish message as a bytes array #36

Closed iamaliybi closed 1 year ago

iamaliybi commented 1 year ago

How can I publish a message as a bytes array in a specific topic?

Namoshek commented 1 year ago

There are no byte arrays in PHP, but it is the same as a string. So you simply publish the string.

If, for example, you want to publish a binary file, you simply use file_get_contents($file) and publish the result:

$mqtt = new MqttClient($host, $port);
$mqtt->connect();
$mqtt->publish('device/xyz/firmware', file_get_contents($firmwareFile));
$mqtt->disconnect();
iamaliybi commented 1 year ago

This is my message: {"CMD\r\n":"FAST_SCAN\r\n","BROADCAST\r\n":"ALL\r\n"}

When I send it as a string, it doesn't work. Also, I'm using MQTT.js in Frontend side and when I publish a message as Buffer, it's working fine and when I send it as string, it doesn't work.

Namoshek commented 1 year ago

I see no reason why this shouldn't work. Please show the code that is not working for you.

iamaliybi commented 1 year ago

Sure

Javascript: (It's working fine when i send command as Buffer)

const connection= mqtt.connect("ws://IP", {
    port: Number(port),
    clientId: 'mqttjs_' + getRandomName(),
    keepalive: 20,
    clean: true,
    reconnectPeriod: 5E3,
    connectTimeout: 5E3,
});

const command = Buffer.from(`{"CMD\r\n":"FAST_SCAN\r\n","BROADCAST\r\n":"ALL\r\n"}`);

mqtt.publish("Dali/In", command);

Also when I send a command without Buffering, it doesn't work

PHP

$message = '{"CMD\r\n":"FAST_SCAN\r\n","BROADCAST\r\n":"ALL\r\n"}'; // I trying json encode, Doesn't work

$connection = new phpMQTT($server, $port, $randomClientId);
$connection->publish('Dali/In', $message, 0);
Namoshek commented 1 year ago

Besides that the \r\n in the keys and values look totally weird and uncommon to me, this might be an issue with the encoding of \r\n in PHP. There is a difference between single and double quotes in PHP, for reference see this 3v4l.org snippet).

Maybe try this to correctly build the message, if the \r\n really belongs in the message:

$message = json_encode([
    "CMD\r\n" => "FAST_SCAN\r\n",
    "BROADCAST\r\n" => "ALL\r\n"
]);
iamaliybi commented 1 year ago

doesn't work :(

iamaliybi commented 1 year ago

When I sent it as a Buffer in Javascript, i got it in MQTT as:

{'CMD
':'FAST_SCAN
','BROADCAST
':'ALL
'}

Also, I trying to send it

$message = `{"CMD
":"FAST_SCAN
","BROADCAST
":"ALL
"}`;

doesn't work again

Namoshek commented 1 year ago

That doesn't really make sense, since you are sending double quotes also in JS. But anyhow, try this:

$message = "{'CMD\r\n':'FAST_SCAN\r\n','BROADCAST\r\n':'ALL\r\n'}";