import { Injectable } from '@nestjs/common'; import TuyaWebsocket from '../../config/tuya-web-socket-config'; import { ConfigService } from '@nestjs/config'; import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service'; @Injectable() export class TuyaWebSocketService { private client: any; // Adjust type according to your TuyaWebsocket client constructor( private readonly configService: ConfigService, private readonly deviceStatusFirebaseService: DeviceStatusFirebaseService, ) { // Initialize the TuyaWebsocket client this.client = new TuyaWebsocket({ accessId: this.configService.get('tuya-config.TUYA_ACCESS_ID'), accessKey: this.configService.get('tuya-config.TUYA_ACCESS_KEY'), url: TuyaWebsocket.URL.EU, env: TuyaWebsocket.env.TEST, maxRetryTimes: 100, }); if (this.configService.get('tuya-config.TRUN_ON_TUYA_SOCKET')) { // 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.deviceStatusFirebaseService.addDeviceStatusToFirebase({ deviceTuyaUuid: message.payload.data.bizData.devId, status: message.payload.data.bizData.properties, }); 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); }); } }