const mqtt = require('mqtt');
exports.main = async (event, context) => {
return new Promise((resolve, reject) => {
// 连接到 MQTT 服务器
const client = mqtt.connect('wss://mqtt.example.com:8083/mqtt', {
username: 'your-username',
password: 'your-password',
});
// 连接成功
client.on('connect', () => {
console.log('MQTT 连接成功');
client.subscribe('test/topic', (err) => {
if (err) {
console.error('订阅失败:', err);
reject(err);
} else {
console.log('订阅成功');
}
});
});
// 接收消息
client.on('message', (topic, message) => {
console.log(`收到消息: ${message.toString()}`);
resolve({
topic,
message: message.toString(),
});
});
// 连接失败
client.on('error', (error) => {
console.error('MQTT 连接失败:', error);
reject(error);
});
});
};
注意: 需要用return new Promise((resolve, reject) => { 包起来。我没包起来,导致项目中可用,但是云函数中用不了。