forked from dyf/dyf-vue-ui
修改mqtt根据端口地址,走ws或者wss协议
This commit is contained in:
@ -1,4 +1,4 @@
|
||||
import { ref, onUnmounted } from 'vue'; // 修复:导入必要的Vue API
|
||||
|
||||
import * as Paho from 'paho-mqtt';
|
||||
|
||||
// MQTT消息类型定义
|
||||
@ -9,61 +9,60 @@ export interface MqttMessage {
|
||||
retained: boolean;
|
||||
time: Date;
|
||||
}
|
||||
|
||||
// 订阅选项
|
||||
export interface SubscribeOptions {
|
||||
qos: 0 | 1 | 2;
|
||||
}
|
||||
|
||||
// MQTT配置信息
|
||||
const MQTT_CONFIG = {
|
||||
// 连接地址(添加协议类型)
|
||||
protocol: 'ws', // 关键:明确协议(ws或wss)
|
||||
host: '47.120.79.150',
|
||||
port: 9083,
|
||||
// 认证信息
|
||||
username: 'admin',
|
||||
password: '#YtvpSfCNG',
|
||||
// 客户端ID(添加时间戳确保唯一性)
|
||||
clientId: `vue3-mqtt-client-${Date.now()}-${Math.random().toString(36).substring(2, 10)}`,
|
||||
// 连接选项
|
||||
cleanSession: true,
|
||||
keepAliveInterval: 60,
|
||||
reconnect: true,
|
||||
// 根据当前页面协议自动选择MQTT配置
|
||||
const getMqttConfig = () => {
|
||||
// 检测当前页面协议(http: 或 https:)
|
||||
const isHttps = window.location.protocol === 'https:';
|
||||
return {
|
||||
// 自动切换协议:https页面用wss,http页面用ws
|
||||
protocol: isHttps ? 'wss' : 'ws',
|
||||
host: 'www.cnxhyc.com',
|
||||
// 自动切换端口:https对应9084,http对应9083
|
||||
port: isHttps ? 9084 : 9083,
|
||||
// 认证信息
|
||||
username: 'admin',
|
||||
password: '#YtvpSfCNG',
|
||||
clientId: `vue3-mqtt-client-${Date.now()}-${Math.random().toString(36).substring(2, 10)}`,
|
||||
cleanSession: true,
|
||||
keepAliveInterval: 60,
|
||||
reconnect: true,
|
||||
};
|
||||
};
|
||||
const MQTT_CONFIG = getMqttConfig();
|
||||
|
||||
// MQTT客户端组合式API
|
||||
export function useMqtt() {
|
||||
// 客户端实例
|
||||
let client: Paho.Client | null = null;
|
||||
|
||||
// 状态管理(修复:已导入ref)
|
||||
const connected = ref(false);
|
||||
const connecting = ref(false);
|
||||
const error = ref<Error | null>(null);
|
||||
const messages = ref<MqttMessage[]>([]);
|
||||
const subscribedTopics = ref<string[]>([]);
|
||||
|
||||
// 事件回调
|
||||
const connectCallbacks: (() => void)[] = [];
|
||||
const messageCallbacks: ((message: MqttMessage) => void)[] = [];
|
||||
const errorCallbacks: ((err: Error) => void)[] = [];
|
||||
const disconnectCallbacks: (() => void)[] = [];
|
||||
|
||||
// 修复:移除无用的p0参数,connect方法不接受回调(通过onConnect注册)
|
||||
const connect = () => {
|
||||
if (connected.value || connecting.value) return;
|
||||
connecting.value = true;
|
||||
error.value = null;
|
||||
|
||||
|
||||
try {
|
||||
// 创建客户端实例(添加协议参数)
|
||||
client = new Paho.Client(
|
||||
MQTT_CONFIG.host,
|
||||
MQTT_CONFIG.host,
|
||||
MQTT_CONFIG.port,
|
||||
MQTT_CONFIG.clientId
|
||||
);
|
||||
|
||||
|
||||
// 设置连接选项
|
||||
const connectOptions: Paho.ConnectOptions = {
|
||||
userName: MQTT_CONFIG.username,
|
||||
@ -71,7 +70,8 @@ export function useMqtt() {
|
||||
cleanSession: MQTT_CONFIG.cleanSession,
|
||||
keepAliveInterval: MQTT_CONFIG.keepAliveInterval,
|
||||
reconnect: MQTT_CONFIG.reconnect,
|
||||
|
||||
useSSL: MQTT_CONFIG.protocol === 'wss', // 关键:根据协议自动启用 SSL
|
||||
|
||||
// 连接成功回调
|
||||
onSuccess: () => {
|
||||
console.log('MQTT连接成功');
|
||||
@ -79,7 +79,7 @@ export function useMqtt() {
|
||||
connecting.value = false;
|
||||
connectCallbacks.forEach(cb => cb()); // 触发所有连接成功回调
|
||||
},
|
||||
|
||||
|
||||
// 连接失败回调
|
||||
onFailure: (err) => {
|
||||
console.error('MQTT连接失败:', err);
|
||||
@ -89,7 +89,7 @@ export function useMqtt() {
|
||||
errorCallbacks.forEach(cb => cb(error.value!));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// 设置客户端回调
|
||||
client.onConnectionLost = (responseObject) => {
|
||||
if (responseObject.errorCode !== 0) {
|
||||
@ -97,12 +97,12 @@ export function useMqtt() {
|
||||
error.value = new Error(responseObject.errorMessage || '连接丢失');
|
||||
errorCallbacks.forEach(cb => cb(error.value!));
|
||||
}
|
||||
|
||||
|
||||
connected.value = false;
|
||||
connecting.value = false;
|
||||
disconnectCallbacks.forEach(cb => cb());
|
||||
};
|
||||
|
||||
|
||||
// 消息接收回调
|
||||
client.onMessageArrived = (message) => {
|
||||
const newMessage: MqttMessage = {
|
||||
@ -112,11 +112,11 @@ export function useMqtt() {
|
||||
retained: message.retained,
|
||||
time: new Date()
|
||||
};
|
||||
|
||||
|
||||
messages.value.push(newMessage);
|
||||
messageCallbacks.forEach(cb => cb(newMessage));
|
||||
};
|
||||
|
||||
|
||||
// 连接服务器
|
||||
client.connect(connectOptions);
|
||||
} catch (err) {
|
||||
@ -127,18 +127,18 @@ export function useMqtt() {
|
||||
errorCallbacks.forEach(cb => cb(error.value!));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// 断开连接
|
||||
const disconnect = () => {
|
||||
if (!client || !connected.value) return;
|
||||
|
||||
|
||||
client.disconnect();
|
||||
client = null;
|
||||
connected.value = false;
|
||||
subscribedTopics.value = [];
|
||||
disconnectCallbacks.forEach(cb => cb());
|
||||
};
|
||||
|
||||
|
||||
// 订阅主题
|
||||
const subscribe = (topic: string, options: SubscribeOptions): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
@ -146,12 +146,12 @@ export function useMqtt() {
|
||||
reject(new Error('未连接到MQTT服务器'));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (subscribedTopics.value.includes(topic)) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
client.subscribe(topic, {
|
||||
qos: options.qos,
|
||||
onSuccess: () => {
|
||||
@ -166,7 +166,7 @@ export function useMqtt() {
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
// 取消订阅
|
||||
const unsubscribe = (topic: string): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
@ -174,12 +174,12 @@ export function useMqtt() {
|
||||
reject(new Error('未连接到MQTT服务器'));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (!subscribedTopics.value.includes(topic)) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
client.unsubscribe(topic, {
|
||||
onSuccess: () => {
|
||||
console.log(`取消订阅主题成功: ${topic}`);
|
||||
@ -193,7 +193,7 @@ export function useMqtt() {
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
// 发布消息
|
||||
const publish = (
|
||||
topic: string,
|
||||
@ -205,47 +205,47 @@ export function useMqtt() {
|
||||
reject(new Error('未连接到MQTT服务器'));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (!topic) {
|
||||
reject(new Error('主题不能为空'));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
const message = new Paho.Message(
|
||||
typeof payload === 'string' ? payload : payload.toString()
|
||||
);
|
||||
|
||||
|
||||
message.destinationName = topic;
|
||||
message.qos = options.qos;
|
||||
message.retained = options.retained ?? false;
|
||||
|
||||
|
||||
client.send(message);
|
||||
resolve();
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
// 事件注册
|
||||
const onConnect = (callback: () => void) => {
|
||||
connectCallbacks.push(callback);
|
||||
};
|
||||
|
||||
|
||||
const onMessage = (callback: (message: MqttMessage) => void) => {
|
||||
messageCallbacks.push(callback);
|
||||
};
|
||||
|
||||
|
||||
const onError = (callback: (err: Error) => void) => {
|
||||
errorCallbacks.push(callback);
|
||||
};
|
||||
|
||||
|
||||
const onDisconnect = (callback: () => void) => {
|
||||
disconnectCallbacks.push(callback);
|
||||
};
|
||||
|
||||
|
||||
// 组件卸载时断开连接
|
||||
onUnmounted(() => {
|
||||
disconnect();
|
||||
});
|
||||
|
||||
|
||||
return {
|
||||
connected,
|
||||
connecting,
|
||||
|
||||
Reference in New Issue
Block a user