feat(wsClient): Update WebSocket connection to support relative paths and enhance MQTT handling
This commit is contained in:
@@ -24,6 +24,11 @@ const proxyDev: Record<string, any> = {
|
||||
target: target,
|
||||
changeOrigin: true,
|
||||
},
|
||||
'/mqtt': {
|
||||
target: target,
|
||||
changeOrigin: true,
|
||||
ws: true,
|
||||
},
|
||||
},
|
||||
test: {
|
||||
'/test': {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { apiSearchThings } from '@/services/master/ThingController';
|
||||
import { apiGetThingDetail } from '@/services/master/ThingController';
|
||||
import { wsClient } from '@/utils/wsClient';
|
||||
import {
|
||||
ArrowLeftOutlined,
|
||||
@@ -111,7 +111,7 @@ const CameraConfigPage = () => {
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
wsClient.connect('wss://gms.smatec.com.vn/mqtt', false);
|
||||
wsClient.connect('/mqtt', false);
|
||||
const unsubscribe = wsClient.subscribe((data: any) => {
|
||||
console.log('Received WS data:', data);
|
||||
});
|
||||
@@ -126,16 +126,8 @@ const CameraConfigPage = () => {
|
||||
if (!thingId) return;
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await apiSearchThings({
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
id: thingId,
|
||||
});
|
||||
if (response?.things && response.things.length > 0) {
|
||||
setThingName(response.things[0].name || thingId);
|
||||
} else {
|
||||
setThingName(thingId);
|
||||
}
|
||||
const thing = await apiGetThingDetail(thingId);
|
||||
setThingName(thing.name || thingId);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch thing info:', error);
|
||||
setThingName(thingId);
|
||||
|
||||
@@ -9,7 +9,7 @@ class WSClient {
|
||||
|
||||
/**
|
||||
* Kết nối tới WebSocket server.
|
||||
* @param url Địa chỉ WebSocket server
|
||||
* @param url Địa chỉ WebSocket server (có thể là relative path như /mqtt)
|
||||
* @param isAuthenticated Có sử dụng token xác thực hay không
|
||||
*/
|
||||
connect(url: string, isAuthenticated: boolean) {
|
||||
@@ -18,7 +18,13 @@ class WSClient {
|
||||
if (isAuthenticated) {
|
||||
token = getToken();
|
||||
}
|
||||
const wsUrl = isAuthenticated ? `${url}?token=${token}` : url;
|
||||
let wsUrl = url;
|
||||
if (url.startsWith('/')) {
|
||||
// Relative path, prepend base WebSocket URL
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
wsUrl = `${protocol}//${window.location.host}${url}`;
|
||||
}
|
||||
wsUrl = isAuthenticated ? `${wsUrl}?token=${token}` : wsUrl;
|
||||
this.ws = new ReconnectingWebSocket(wsUrl, [], {
|
||||
maxRetries: 10,
|
||||
maxReconnectionDelay: 10000,
|
||||
|
||||
Reference in New Issue
Block a user