feat: Introduce TinyMqttClient interface and implementation, update auth store for MQTT connection management

This commit is contained in:
2026-02-08 23:59:48 +07:00
parent 66028d934a
commit 85af2da6ad
6 changed files with 38 additions and 45 deletions

4
src/lib/interface.ts Normal file
View File

@@ -0,0 +1,4 @@
export interface ITinyMqttClient {
connect(): void;
disconnect(): void;
}

View File

@@ -1,5 +1,7 @@
import { ITinyMqttClient } from "./interface";
export type MessageCallback = (topic: string, payload: string) => void;
export class TinyMqttClient {
export class TinyMqttClient implements ITinyMqttClient {
private ws: WebSocket | null = null;
private encoder = new TextEncoder();
private decoder = new TextDecoder();

View File

@@ -195,20 +195,11 @@ const createAppRouter = () => {
router.beforeEach((to, from, next) => {
const auth = useAuthStore();
const head = inject(headSymbol);
let client: any;
(head as any).push(to.meta.head || {});
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (!auth.user) {
if(client?.disconnect) (client as any)?.disconnect();
next({ name: "login" });
} else {
client = new TinyMqttClient(
'wss://broker.emqx.io:8084/mqtt',
[['ecos1231231'+auth.user.id+'#'].join("/")],
(topic, msg) => console.log(`Tín hiệu nhận được [${topic}]:`, msg)
);
client.connect();
next();
}
} else {

View File

@@ -2,6 +2,7 @@ import { defineStore } from 'pinia';
import { useRouter } from 'vue-router';
import { ref } from 'vue';
import { client, ResponseResponse, type ModelUser } from '@/api/client';
import { TinyMqttClient } from '@/lib/liteMqtt';
export const useAuthStore = defineStore('auth', () => {
const user = ref<ModelUser | null>(null);
@@ -9,7 +10,25 @@ export const useAuthStore = defineStore('auth', () => {
const loading = ref(false);
const error = ref<string | null>(null);
const initialized = ref(false);
watch(user, (newUser) => {
if (import.meta.env.SSR) return;
let client: TinyMqttClient | undefined;
if (newUser?.id) {
client = new TinyMqttClient(
// 'wss://broker.emqx.io:8084/mqtt',
'wss://mqtt-dashboard.com:8884/mqtt',
[['ecos1231231',newUser.id,'#'].join("/")],
(topic, msg) => console.log(`Tín hiệu nhận được [${topic}]:`, msg)
);
client.connect();
// client.auth.clearToken();
}
else {
if(client?.disconnect) client.disconnect();
client = undefined;
}
}, { deep: true });
// Initial check for session could go here if there was a /me endpoint or token check
async function init() {
if (initialized.value) return;