83 lines
2.1 KiB
JavaScript
83 lines
2.1 KiB
JavaScript
const mqtt = require('mqtt');
|
|
|
|
let client;
|
|
|
|
export default {
|
|
/**
|
|
* 连接订阅
|
|
* @param {String} host 服务器地址
|
|
* @param {Integer} port 服务器端口
|
|
* @param {Object} conOptions 连接选项
|
|
* @param {StringOrArray} topic 订阅主题,数组
|
|
* @param {Object} subOptions 订阅选项
|
|
* @param {Function} callback 订阅回调
|
|
*/
|
|
connect: function(host, port, conOptions, topic, subOptions, callback) {
|
|
// 匹配对应protocol
|
|
let protocol = 'mqtt';
|
|
// #ifdef H5 || APP || APP-VUE
|
|
protocol = 'ws';
|
|
// #endif
|
|
// #ifdef MP-WEIXIN || APP-PLUS
|
|
protocol = 'wxs';
|
|
// #endif
|
|
// #ifdef MP-ALIPAY
|
|
protocol = 'alis';
|
|
// #endif
|
|
|
|
// 拼接Uri
|
|
const uri = protocol + "://" + host + ":" + port + "/mqtt";
|
|
|
|
// 客户端连接
|
|
client = mqtt.connect(uri, Object.assign({}, conOptions));
|
|
if (client) {
|
|
client.on('connect', function() {
|
|
if (client.connected) {
|
|
console.log(client.options.clientId, uri, 'connect ok');
|
|
|
|
client.subscribe(topic, Object.assign({}, subOptions), function(err, granted) {
|
|
if (!err) {
|
|
console.log('subscribe ok:', JSON.stringify(granted));
|
|
|
|
client.on('message', function(topic, message, packet) {
|
|
if (callback && typeof callback === "function") {
|
|
callback(topic, message);
|
|
}
|
|
});
|
|
} else {
|
|
console.error('subscribe error:', err);
|
|
}
|
|
});
|
|
} else {
|
|
console.error(client.options.clientId, uri, 'connect fail', client);
|
|
}
|
|
});
|
|
} else {
|
|
console.error(client.options.clientId, uri, 'connect error');
|
|
}
|
|
},
|
|
/**
|
|
* 发布消息
|
|
* @param {String} topic 发布主题,字符串
|
|
* @param {Object} options 发布选项
|
|
* @param {BufferOrString} message 消息
|
|
* @param {Function} callback 发布回调
|
|
*/
|
|
publish: function(topic, options, message, callback) {
|
|
if (!client) {
|
|
console.error('client not connected');
|
|
return;
|
|
}
|
|
|
|
client.publish(topic, message, Object.assign({}, options), function(err) {
|
|
if (err) {
|
|
console.error(err);
|
|
} else {
|
|
if (callback && typeof callback === 'function') {
|
|
callback(topic);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
}
|