node-red-contrib-voice-assistant
Version:
一个小度-小爱-猫精音箱控制NODE-RED自定义设备的节点
134 lines (133 loc) • 3.83 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const mqtt_1 = __importDefault(require("mqtt"));
class MqttClient {
constructor(username, password, url = 'mqtt://47.104.137.100:1883') {
this.connecting = false;
this.connected = false;
this.reconnecting = false;
this._onMessage = [];
this._topic = [];
this.options = {
username,
password,
clientId: 'NrMqtt_' + (1 + Math.random() * 4294967295).toString(16),
reconnectPeriod: 10000,
};
this.url = url;
}
//订阅TOPIC
subTopic(topic) {
this._topic.push(topic);
}
//订阅
_subscribe(topic) {
this._client.subscribe(topic, { qos: 0 }, function (err) {
if (!err) { }
;
});
}
//mqtt开始连接
connect() {
this.connecting = true;
try {
this._client = mqtt_1.default.connect(this.url, this.options);
this._client.setMaxListeners(0);
this._client.on('connect', this._onConnect.bind(this));
this._client.on('reconnect', this._onReconnect.bind(this));
this._client.on('close', this._onClose.bind(this));
this._client.on('error', this._onError.bind(this));
}
catch (e) {
console.log('connect', e);
}
}
publish(payload) {
this._client.publish(this.pubTopic, JSON.stringify(payload));
}
//注册消息
set onData(fn) {
this._onMessage.push(fn);
}
/**
* 消息接受
*
* */
_onData(topic, payload) {
// console.log(topic, payload);
try {
payload = JSON.parse(payload);
}
catch (_a) { }
this._onMessage.forEach((fn) => fn(null, { message: { topic, payload: payload } }));
}
/**
* mqtt连接完成
*
*/
_onConnect() {
this.connecting = false;
this.connected = true;
this.reconnecting = false;
//console.log('connected');
this._client.removeAllListeners('message');
this._client.on('message', this._onData.bind(this));
this._topic.forEach((topic) => this._subscribe(topic));
this._onMessage.forEach((fn) => fn(null, { connect: true }));
}
/**
* mqtt重连
*
*/
_onReconnect() {
this.reconnecting = true;
this.connected = false;
console.log('mqtt重连');
this._onMessage.forEach((fn) => fn(null, { reconnect: true }));
}
/**
* mqtt断开
*
*/
_onClose() {
this.connected = false;
this.connecting = false;
this.reconnecting = false;
//this._onMessage.forEach((fn) => fn('云服务断开连接'));
}
/**
* mqtt错误
*
*/
_onError(e) {
//console.log(e)
if (e.code === 4) {
this._onMessage.forEach((fn) => fn('云服务用户或密码错误'));
}
else if (e.code === 3) {
this._onMessage.forEach((fn) => fn('云服务密码错误超过6次一小时候再试'));
}
else
this._onMessage.forEach((fn) => fn('云服务断开连接'));
this.close();
}
close(done) {
if (this.connected) {
this._client.once('close', function () {
done && done();
});
this._client.end();
}
else if (this.connecting || this.reconnecting) {
this._client.end();
done && done();
}
else {
done && done();
}
}
}
exports.default = MqttClient;