mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-11-26 08:04:53 +00:00
105 lines
2.8 KiB
TypeScript
105 lines
2.8 KiB
TypeScript
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;
|
|
private readonly isDevEnv: boolean;
|
|
|
|
constructor(
|
|
private readonly configService: ConfigService,
|
|
private readonly deviceStatusFirebaseService: DeviceStatusFirebaseService,
|
|
) {
|
|
this.isDevEnv =
|
|
this.configService.get<string>('NODE_ENV') === 'development';
|
|
|
|
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.PROD,
|
|
maxRetryTimes: 100,
|
|
});
|
|
|
|
if (this.configService.get<string>('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 {
|
|
const { devId, status, logData } = this.extractMessageData(message);
|
|
|
|
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
|
deviceTuyaUuid: devId,
|
|
status: status,
|
|
log: logData,
|
|
});
|
|
|
|
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);
|
|
});
|
|
}
|
|
private extractMessageData(message: any): {
|
|
devId: string;
|
|
status: any;
|
|
logData: any;
|
|
} {
|
|
const payloadData = message.payload.data;
|
|
|
|
if (this.isDevEnv) {
|
|
return {
|
|
devId: payloadData.bizData?.devId,
|
|
status: payloadData.bizData?.properties,
|
|
logData: payloadData.bizData,
|
|
};
|
|
} else {
|
|
return {
|
|
devId: payloadData.devId,
|
|
status: payloadData.status,
|
|
logData: payloadData,
|
|
};
|
|
}
|
|
}
|
|
|
|
// private logDeviceData(devId: string, status: any, logData: any): void {
|
|
// console.log('Device ID:', devId);
|
|
// console.log('Status:', status);
|
|
// console.log('Full Data:', logData);
|
|
// }
|
|
}
|