【发布时间】:2021-12-23 11:02:42
【问题描述】:
我的项目使用sp-react-native-mqtt,我想在按下按钮时向 mqtt 主题发布消息。
Mqtt 连接代码,返回一个promise:
MQTT.createClient({
uri: 'mqtt://test.mosquitto.org:1883',
clientId: 'your_client_id'
}).then(function(client) {
client.on('closed', function() {
console.log('mqtt.event.closed');
});
client.on('error', function(msg) {
console.log('mqtt.event.error', msg);
});
client.on('message', function(msg) {
console.log('mqtt.event.message', msg);
});
client.on('connect', function() {
console.log('connected');
client.subscribe('/data', 0);
client.publish('/data', "test", 0, false);
});
client.connect();
}).catch(function(err){
console.log(err);
});
编辑:
如果我将客户端保存在一个变量中,并且我使用该变量发布我收到此错误:
let mqttClient = null;
MQTT.createClient({
uri: 'mqtt://test.mosquitto.org:1883',
clientId: 'your_client_id',
})
.then(function (client) {
mqttClient = client;
.... }
<Button
title="test"
onPress={() => {
mqttClient.publish('/data', 'message');
}}
/>
我应该如何处理? 或者如果您对如何在 react native 中使用 mqtt 或 mqtt 的其他包有任何其他建议。
谢谢!
【问题讨论】:
-
作为一项规则,主题真的不应该以
/开头(虽然在规范中允许,但它会破坏共享订阅等内容,并且它会在所有主题的开头添加一个额外的 null树)。至于您尝试过什么问题(例如,将client保存到您可以从按钮处理程序访问的变量中)? -
感谢您的回复。我试过了,但我得到了一个错误。我编辑了我的问题以将错误的图像放在那里。
-
错误非常不太可能与发布 MQTT 消息有关。它试图将 Double 对象转换为本机 double,而不是发布通常需要的东西。
-
有趣的是,如果我添加 QoS 和保留参数,我不会收到该错误,但它也不会发送消息。 mqttClient.publish('/data', 'dsdsadasdsadas', 0, true);
标签: android ios react-native mqtt