|
@@ -1,94 +1,3 @@
|
|
|
-import '../../public/mqtt/dist/mqtt.min'
|
|
|
-import { MqttClient } from './mqtt/types'
|
|
|
-declare const window: any
|
|
|
-var _mqttMessageCallback: any = null
|
|
|
-
|
|
|
-/**
|
|
|
- * mqtt订阅
|
|
|
- * @param topics 主题['a','b']
|
|
|
- * @param callback 消息回调
|
|
|
- */
|
|
|
-export const onSubscribe = (topics: string[], callback: any) => {
|
|
|
- console.log(topics)
|
|
|
- _mqttMessageCallback = callback
|
|
|
- if (window.client == null) {
|
|
|
- useMqtt()
|
|
|
- }
|
|
|
- topics.forEach(topic => {
|
|
|
- window.client?.subscribe(topic, () => { })
|
|
|
- })
|
|
|
- window.client?.on('message', (topic: string, payload: any) => {
|
|
|
- if (_mqttMessageCallback != null) {
|
|
|
- _mqttMessageCallback(topic, payload)
|
|
|
- }
|
|
|
- })
|
|
|
-}
|
|
|
-
|
|
|
-/**
|
|
|
- * mqtt取消订阅
|
|
|
- * @param topic 主题
|
|
|
- */
|
|
|
-export const onUnsubscribe = (topic: string) => {
|
|
|
- window.client?.unsubscribe(topic, () => {
|
|
|
- _mqttMessageCallback = null
|
|
|
- })
|
|
|
-}
|
|
|
-
|
|
|
-/**
|
|
|
- * 实时数据
|
|
|
- */
|
|
|
-export const useMqtt = () => {
|
|
|
- const userInfo = JSON.parse(localStorage.getItem('user') as string)
|
|
|
- const { userId, securityCode } = userInfo
|
|
|
- const { mqtt } = window as any
|
|
|
- const mqttOptions = {
|
|
|
- clean: true,
|
|
|
- connectTimeout: 10000,
|
|
|
- port: 443,
|
|
|
- clientId: `2${Date.now()}`, //提取到配置文件
|
|
|
- username: `${userId}`, //提取到配置文件
|
|
|
- password: securityCode //提取到配置文件
|
|
|
- }
|
|
|
- console.log(mqttOptions)
|
|
|
- if (window.client == null) {
|
|
|
- console.log('初始化mqtt')
|
|
|
- window.client = mqtt.connect('wss://mqtt.hldcloud.cn/mqtt', mqttOptions)
|
|
|
- }
|
|
|
- window.client.on('connect', () => {
|
|
|
- console.log('mqtt连接成功')
|
|
|
- })
|
|
|
-
|
|
|
- window.client.on('reconnect', () => {
|
|
|
- console.log('mqtt正在重连')
|
|
|
- })
|
|
|
-
|
|
|
- window.client.on('disconnect', () => {
|
|
|
- console.log('mqtt断开连接disconnect')
|
|
|
- })
|
|
|
-
|
|
|
- window.client.on('close', () => {
|
|
|
- console.log('mqtt断开连接close')
|
|
|
- })
|
|
|
-
|
|
|
- window.client.on('error', (e: any) => {
|
|
|
- console.log('mqtt无法连接error' + e.message)
|
|
|
- if (e.code == 4) {
|
|
|
- //用户名密码错误
|
|
|
- window.client.end()
|
|
|
- window.client = null
|
|
|
- alert("该账号在多个设备上登录,为避免部分功能无法使用,请退出账号重新登录")
|
|
|
- }
|
|
|
- })
|
|
|
-
|
|
|
-}
|
|
|
-
|
|
|
-export function isTrue(e: any) {
|
|
|
- if (e === true || e === 'true') {
|
|
|
- return true
|
|
|
- }
|
|
|
- return false
|
|
|
-}
|
|
|
-
|
|
|
/**
|
|
|
* 清除对象中的字符串前后空格
|
|
|
* @param target 目标对象
|