|
|
@@ -3,10 +3,10 @@ const { join } = require('path');
|
|
|
const { fork } = require('child_process');
|
|
|
const { platform } = require('process');
|
|
|
const mqtt = require('mqtt')
|
|
|
-const client = mqtt.connect('mqtt://127.0.0.1:49800', { manualConnect: true })
|
|
|
const sleep = (ms) => new Promise(res => setTimeout(res, ms));
|
|
|
class MainSerivce {
|
|
|
- #mqttChannel = ''
|
|
|
+ #mqttChannel = null
|
|
|
+ #client = null
|
|
|
constructor() {
|
|
|
Menu.setApplicationMenu(null) // 去掉菜单栏
|
|
|
app.commandLine.appendSwitch('wm-window-animations-disabled') // 拖动闪屏
|
|
|
@@ -121,7 +121,7 @@ class MainSerivce {
|
|
|
} else if (evt === 'minWin') {
|
|
|
this.mainWin.minimize()
|
|
|
} else if (evt === 'closeWin') {
|
|
|
- client.end()
|
|
|
+ this.#closeMqtt()
|
|
|
this.mainWin.close()
|
|
|
} else if (evt === 'maxWin') {
|
|
|
const { width, height } = screen.getPrimaryDisplay().size
|
|
|
@@ -130,24 +130,26 @@ class MainSerivce {
|
|
|
this.mainWin.center()
|
|
|
}
|
|
|
} else if (evt === 'loginMqtt') {
|
|
|
- client.options.username = data.room
|
|
|
- client.options.password = data.name
|
|
|
- client.connect()
|
|
|
+ this.#initMqtt(data)
|
|
|
} else if (evt === 'closeMqtt') {
|
|
|
- client.end()
|
|
|
+ this.#closeMqtt()
|
|
|
} else if (evt === 'sendMqtt') {
|
|
|
try {
|
|
|
const db = JSON.stringify(data)
|
|
|
- if (client.connected && this.#mqttChannel) client.publish(this.#mqttChannel, db)
|
|
|
+ if (this.#client.connected && this.#mqttChannel) this.#client.publish(this.#mqttChannel, db)
|
|
|
} catch (error) {
|
|
|
console.log(error);
|
|
|
}
|
|
|
}
|
|
|
})
|
|
|
+ }
|
|
|
|
|
|
+ #initMqtt(data) {
|
|
|
+ this.#closeMqtt()
|
|
|
+ this.#client = mqtt.connect('mqtt://127.0.0.1:49800', { username: data.room, password: data.name })
|
|
|
// 监听
|
|
|
- client.on('connect', () => this.mainWin.webContents.send('message', { type: 'connect' }))
|
|
|
- client.on('message', (_, msg, __) => {
|
|
|
+ this.#client.on('connect', () => this.mainWin.webContents.send('message', { type: 'connect' }))
|
|
|
+ this.#client.on('message', (_, msg, __) => {
|
|
|
try {
|
|
|
const db = JSON.parse(msg.toString())
|
|
|
if (db.type === 'join') this.#mqttChannel = db.channel
|
|
|
@@ -156,11 +158,13 @@ class MainSerivce {
|
|
|
console.log(error);
|
|
|
}
|
|
|
})
|
|
|
- client.on('error', (e) => {
|
|
|
- this.#mqttChannel = ''
|
|
|
- this.mainWin.webContents.send('message', { type: 'disconnect' })
|
|
|
- client.end(true)
|
|
|
- })
|
|
|
+ this.#client.on('error', (e) => this.#closeMqtt())
|
|
|
+ }
|
|
|
+
|
|
|
+ #closeMqtt() {
|
|
|
+ if (this.#client) this.#client.end()
|
|
|
+ this.#client = null
|
|
|
+ this.#mqttChannel = null
|
|
|
}
|
|
|
|
|
|
connectLogi() {
|