mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-16 10:46:17 +00:00
224 lines
6.7 KiB
TypeScript
224 lines
6.7 KiB
TypeScript
import {
|
|
HttpException,
|
|
HttpStatus,
|
|
Injectable,
|
|
NotFoundException,
|
|
} from '@nestjs/common';
|
|
import { AddDeviceStatusDto } from '../dtos/add.devices-status.dto';
|
|
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
|
import { GetDeviceDetailsFunctionsStatusInterface } from 'src/device/interfaces/get.device.interface';
|
|
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { firebaseDataBase } from '../../firebase.config';
|
|
import {
|
|
Database,
|
|
DataSnapshot,
|
|
get,
|
|
ref,
|
|
runTransaction,
|
|
} from 'firebase/database';
|
|
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
|
@Injectable()
|
|
export class DeviceStatusFirebaseService {
|
|
private tuya: TuyaContext;
|
|
private firebaseDb: Database;
|
|
constructor(
|
|
private readonly configService: ConfigService,
|
|
private readonly deviceRepository: DeviceRepository,
|
|
private deviceStatusLogRepository: DeviceStatusLogRepository,
|
|
) {
|
|
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
|
|
const secretKey = this.configService.get<string>('auth-config.SECRET_KEY');
|
|
const tuyaEuUrl = this.configService.get<string>('tuya-config.TUYA_EU_URL');
|
|
this.tuya = new TuyaContext({
|
|
baseUrl: tuyaEuUrl,
|
|
accessKey,
|
|
secretKey,
|
|
});
|
|
|
|
// Initialize firebaseDb using firebaseDataBase function
|
|
this.firebaseDb = firebaseDataBase(this.configService);
|
|
}
|
|
async addDeviceStatusByDeviceUuid(
|
|
deviceTuyaUuid: string,
|
|
): Promise<AddDeviceStatusDto> {
|
|
try {
|
|
const device = await this.getDeviceByDeviceTuyaUuid(deviceTuyaUuid);
|
|
if (device.uuid) {
|
|
const deviceStatus = await this.getDevicesInstructionStatus(
|
|
device.uuid,
|
|
);
|
|
if (deviceStatus.productUuid) {
|
|
const deviceStatusSaved = await this.createDeviceStatusFirebase({
|
|
deviceUuid: device.uuid,
|
|
deviceTuyaUuid: deviceTuyaUuid,
|
|
status: deviceStatus.status,
|
|
productUuid: deviceStatus.productUuid,
|
|
productType: deviceStatus.productType,
|
|
});
|
|
|
|
return deviceStatusSaved;
|
|
}
|
|
}
|
|
} catch (error) {
|
|
throw new HttpException(
|
|
'Device Tuya UUID not found',
|
|
error.status || HttpStatus.BAD_REQUEST,
|
|
);
|
|
}
|
|
}
|
|
async addDeviceStatusToFirebase(
|
|
addDeviceStatusDto: AddDeviceStatusDto,
|
|
): Promise<AddDeviceStatusDto | null> {
|
|
try {
|
|
const device = await this.getDeviceByDeviceTuyaUuid(
|
|
addDeviceStatusDto.deviceTuyaUuid,
|
|
);
|
|
|
|
if (device?.uuid) {
|
|
return await this.createDeviceStatusFirebase({
|
|
deviceUuid: device.uuid,
|
|
...addDeviceStatusDto,
|
|
});
|
|
}
|
|
// Return null if device not found or no UUID
|
|
return null;
|
|
} catch (error) {
|
|
// Handle the error silently, perhaps log it internally or ignore it
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async getDeviceByDeviceTuyaUuid(deviceTuyaUuid: string) {
|
|
return await this.deviceRepository.findOne({
|
|
where: {
|
|
deviceTuyaUuid,
|
|
isActive: true,
|
|
},
|
|
relations: ['productDevice'],
|
|
});
|
|
}
|
|
async getDevicesInstructionStatus(deviceUuid: string) {
|
|
try {
|
|
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
|
|
|
|
if (!deviceDetails) {
|
|
throw new NotFoundException('Device Not Found');
|
|
}
|
|
const deviceStatus = await this.getDevicesInstructionStatusTuya(
|
|
deviceDetails.deviceTuyaUuid,
|
|
);
|
|
|
|
return {
|
|
productUuid: deviceDetails.productDevice.uuid,
|
|
productType: deviceDetails.productDevice.prodType,
|
|
status: deviceStatus.result[0].status,
|
|
};
|
|
} catch (error) {
|
|
throw new HttpException(
|
|
'Error fetching device functions status',
|
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
|
);
|
|
}
|
|
}
|
|
async getDevicesInstructionStatusTuya(
|
|
deviceUuid: string,
|
|
): Promise<GetDeviceDetailsFunctionsStatusInterface> {
|
|
try {
|
|
const path = `/v1.0/iot-03/devices/status`;
|
|
const response = await this.tuya.request({
|
|
method: 'GET',
|
|
path,
|
|
query: {
|
|
device_ids: deviceUuid,
|
|
},
|
|
});
|
|
return response as GetDeviceDetailsFunctionsStatusInterface;
|
|
} catch (error) {
|
|
throw new HttpException(
|
|
'Error fetching device functions status from Tuya',
|
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
|
);
|
|
}
|
|
}
|
|
async getDeviceByDeviceUuid(
|
|
deviceUuid: string,
|
|
withProductDevice: boolean = true,
|
|
) {
|
|
return await this.deviceRepository.findOne({
|
|
where: {
|
|
uuid: deviceUuid,
|
|
isActive: true,
|
|
},
|
|
...(withProductDevice && { relations: ['productDevice'] }),
|
|
});
|
|
}
|
|
async createDeviceStatusFirebase(
|
|
addDeviceStatusDto: AddDeviceStatusDto,
|
|
): Promise<any> {
|
|
const dataRef = ref(
|
|
this.firebaseDb,
|
|
`device-status/${addDeviceStatusDto.deviceUuid}`,
|
|
);
|
|
|
|
// Use a transaction to handle concurrent updates
|
|
await runTransaction(dataRef, (existingData) => {
|
|
if (!existingData) {
|
|
existingData = {};
|
|
}
|
|
|
|
// Assign default values if fields are not present
|
|
if (!existingData.deviceTuyaUuid) {
|
|
existingData.deviceTuyaUuid = addDeviceStatusDto.deviceTuyaUuid;
|
|
}
|
|
if (!existingData.productUuid) {
|
|
existingData.productUuid = addDeviceStatusDto.productUuid;
|
|
}
|
|
if (!existingData.productType) {
|
|
existingData.productType = addDeviceStatusDto.productType;
|
|
}
|
|
if (!existingData.status) {
|
|
existingData.status = [];
|
|
}
|
|
|
|
// Create a map to track existing status codes
|
|
const statusMap = new Map(
|
|
existingData.status.map((item) => [item.code, item.value]),
|
|
);
|
|
|
|
// Update or add status codes
|
|
|
|
for (const statusItem of addDeviceStatusDto.status) {
|
|
statusMap.set(statusItem.code, statusItem.value);
|
|
}
|
|
|
|
// Convert the map back to an array format
|
|
existingData.status = Array.from(statusMap, ([code, value]) => ({
|
|
code,
|
|
value,
|
|
}));
|
|
|
|
return existingData;
|
|
});
|
|
|
|
// Save logs to your repository
|
|
const newLogs = addDeviceStatusDto.log.properties.map((property) => {
|
|
return this.deviceStatusLogRepository.create({
|
|
deviceId: addDeviceStatusDto.deviceUuid,
|
|
deviceTuyaId: addDeviceStatusDto.deviceTuyaUuid,
|
|
productId: addDeviceStatusDto.log.productId,
|
|
log: addDeviceStatusDto.log,
|
|
code: property.code,
|
|
value: property.value,
|
|
eventId: addDeviceStatusDto.log.dataId,
|
|
eventTime: new Date(property.time).toISOString(),
|
|
});
|
|
});
|
|
await this.deviceStatusLogRepository.save(newLogs);
|
|
|
|
// Return the updated data
|
|
const snapshot: DataSnapshot = await get(dataRef);
|
|
return snapshot.val();
|
|
}
|
|
}
|