mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-15 10:25:23 +00:00
add tuya web socket service
This commit is contained in:
70
libs/common/src/helper/services/tuya.web.socket.service.ts
Normal file
70
libs/common/src/helper/services/tuya.web.socket.service.ts
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import TuyaWebsocket from '../../config/tuya-web-socket-config';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { OneSignalService } from './onesignal.service';
|
||||||
|
import { DeviceMessagesService } from './device.messages.service';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class TuyaWebSocketService {
|
||||||
|
private client: any; // Adjust type according to your TuyaWebsocket client
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly configService: ConfigService,
|
||||||
|
private readonly oneSignalService: OneSignalService,
|
||||||
|
private readonly deviceMessagesService: DeviceMessagesService,
|
||||||
|
) {
|
||||||
|
// Initialize the TuyaWebsocket client
|
||||||
|
this.client = new TuyaWebsocket({
|
||||||
|
accessId: this.configService.get<string>('tuya-config.TUYA_ACCESS_ID'),
|
||||||
|
accessKey: this.configService.get<string>('tuya-config.TUYA_ACCESS_KEY'),
|
||||||
|
url: TuyaWebsocket.URL.EU,
|
||||||
|
env: TuyaWebsocket.env.TEST,
|
||||||
|
maxRetryTimes: 100,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Set up event handlers
|
||||||
|
this.setupEventHandlers();
|
||||||
|
|
||||||
|
// Start receiving messages
|
||||||
|
this.client.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private setupEventHandlers() {
|
||||||
|
// Event handlers
|
||||||
|
this.client.open(() => {
|
||||||
|
console.log('open');
|
||||||
|
});
|
||||||
|
|
||||||
|
this.client.message(async (ws: WebSocket, message: any) => {
|
||||||
|
try {
|
||||||
|
await this.deviceMessagesService.getDevicesUserNotifications(
|
||||||
|
message.payload.data.bizData.devId,
|
||||||
|
message.payload.data.bizData,
|
||||||
|
);
|
||||||
|
this.client.ackMessage(message.messageId);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error processing message:', error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.client.reconnect(() => {
|
||||||
|
console.log('reconnect');
|
||||||
|
});
|
||||||
|
|
||||||
|
this.client.ping(() => {
|
||||||
|
console.log('ping');
|
||||||
|
});
|
||||||
|
|
||||||
|
this.client.pong(() => {
|
||||||
|
console.log('pong');
|
||||||
|
});
|
||||||
|
|
||||||
|
this.client.close((ws: WebSocket, ...args: any[]) => {
|
||||||
|
console.log('close', ...args);
|
||||||
|
});
|
||||||
|
|
||||||
|
this.client.error((ws: WebSocket, error: any) => {
|
||||||
|
console.error('WebSocket error:', error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user