mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-08-25 21:19:40 +00:00
441 lines
14 KiB
TypeScript
441 lines
14 KiB
TypeScript
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
|
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
|
import {
|
|
HttpException,
|
|
HttpStatus,
|
|
Injectable,
|
|
NotFoundException,
|
|
} from '@nestjs/common';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
|
import {
|
|
Database,
|
|
DataSnapshot,
|
|
get,
|
|
ref,
|
|
runTransaction,
|
|
} from 'firebase/database';
|
|
import { GetDeviceDetailsFunctionsStatusInterface } from 'src/device/interfaces/get.device.interface';
|
|
import { firebaseDataBase } from '../../firebase.config';
|
|
import { AddDeviceStatusDto } from '../dtos/add.devices-status.dto';
|
|
@Injectable()
|
|
export class DeviceStatusFirebaseService {
|
|
private tuya: TuyaContext;
|
|
private firebaseDb: Database;
|
|
private readonly isDevEnv: boolean;
|
|
|
|
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
|
|
try {
|
|
this.firebaseDb = firebaseDataBase(this.configService);
|
|
} catch (error) {
|
|
console.warn('Firebase initialization failed, continuing without Firebase:', error.message);
|
|
this.firebaseDb = null;
|
|
}
|
|
this.isDevEnv =
|
|
this.configService.get<string>('NODE_ENV') === 'development';
|
|
}
|
|
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 addBatchDeviceStatusToOurDb(
|
|
batch: {
|
|
deviceTuyaUuid: string;
|
|
status: any;
|
|
log: any;
|
|
device: any;
|
|
}[],
|
|
): Promise<void> {
|
|
console.log(`🔁 Preparing logs from batch of ${batch.length} items...`);
|
|
|
|
const allLogs = [];
|
|
|
|
for (const item of batch) {
|
|
const device = item.device;
|
|
|
|
if (!device?.uuid) {
|
|
console.log(`⛔ Skipped unknown device: ${item.deviceTuyaUuid}`);
|
|
continue;
|
|
}
|
|
|
|
// Determine properties based on environment
|
|
const properties =
|
|
this.isDevEnv && Array.isArray(item.log?.properties)
|
|
? item.log.properties
|
|
: Array.isArray(item.status)
|
|
? item.status
|
|
: null;
|
|
|
|
if (!properties) {
|
|
console.log(
|
|
`⛔ Skipped invalid status/properties for device: ${item.deviceTuyaUuid}`,
|
|
);
|
|
continue;
|
|
}
|
|
|
|
const logs = properties.map((property) =>
|
|
this.deviceStatusLogRepository.create({
|
|
deviceId: device.uuid,
|
|
deviceTuyaId: item.deviceTuyaUuid,
|
|
productId: device.productDevice?.uuid,
|
|
log: item.log,
|
|
code: property.code,
|
|
value: property.value,
|
|
eventId: item.log?.dataId,
|
|
eventTime: new Date(
|
|
this.isDevEnv ? property.time : property.t,
|
|
).toISOString(),
|
|
}),
|
|
);
|
|
|
|
allLogs.push(...logs);
|
|
}
|
|
|
|
console.log(`📝 Total logs to insert: ${allLogs.length}`);
|
|
|
|
const chunkSize = 300;
|
|
let insertedCount = 0;
|
|
|
|
for (let i = 0; i < allLogs.length; i += chunkSize) {
|
|
const chunk = allLogs.slice(i, i + chunkSize);
|
|
try {
|
|
const result = await this.deviceStatusLogRepository
|
|
.createQueryBuilder()
|
|
.insert()
|
|
.into('device-status-log')
|
|
.values(chunk)
|
|
.orIgnore()
|
|
.execute();
|
|
|
|
insertedCount += result.identifiers.length;
|
|
console.log(
|
|
`✅ Inserted ${result.identifiers.length} / ${chunk.length} logs (chunk)`,
|
|
);
|
|
} catch (error) {
|
|
console.error('❌ Insert error (skipped chunk):', error.message);
|
|
}
|
|
}
|
|
|
|
console.log(`✅ Total logs inserted: ${insertedCount} / ${allLogs.length}`);
|
|
}
|
|
|
|
async addDeviceStatusToFirebase(
|
|
addDeviceStatusDto: AddDeviceStatusDto & { device?: any },
|
|
): Promise<AddDeviceStatusDto | null> {
|
|
try {
|
|
let device = addDeviceStatusDto.device;
|
|
if (!device) {
|
|
device = await this.getDeviceByDeviceTuyaUuid(
|
|
addDeviceStatusDto.deviceTuyaUuid,
|
|
);
|
|
}
|
|
if (device?.uuid) {
|
|
return await this.createDeviceStatusFirebase({
|
|
deviceUuid: device.uuid,
|
|
...addDeviceStatusDto,
|
|
productType: device.productDevice?.prodType,
|
|
});
|
|
}
|
|
// Return null if device not found or no UUID
|
|
return null;
|
|
} catch (error) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async getDeviceByDeviceTuyaUuid(deviceTuyaUuid: string) {
|
|
return await this.deviceRepository.findOne({
|
|
where: {
|
|
deviceTuyaUuid,
|
|
isActive: true,
|
|
},
|
|
relations: ['productDevice'],
|
|
});
|
|
}
|
|
async getAllDevices() {
|
|
return await this.deviceRepository.find({
|
|
where: {
|
|
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> {
|
|
// Check if Firebase is available
|
|
if (!this.firebaseDb) {
|
|
console.warn('Firebase not available, skipping Firebase operations');
|
|
// Still process the database logs but skip Firebase operations
|
|
await this.processDeviceStatusLogs(addDeviceStatusDto);
|
|
return { message: 'Device status processed without Firebase' };
|
|
}
|
|
|
|
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;
|
|
});
|
|
|
|
// Return the updated data
|
|
const snapshot: DataSnapshot = await get(dataRef);
|
|
return snapshot.val();
|
|
}
|
|
|
|
private async processDeviceStatusLogs(addDeviceStatusDto: AddDeviceStatusDto): Promise<void> {
|
|
if (this.isDevEnv) {
|
|
// 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);
|
|
|
|
if (addDeviceStatusDto.productType === ProductType.PC) {
|
|
const energyCodes = new Set([
|
|
PowerClampEnergyEnum.ENERGY_CONSUMED,
|
|
PowerClampEnergyEnum.ENERGY_CONSUMED_A,
|
|
PowerClampEnergyEnum.ENERGY_CONSUMED_B,
|
|
PowerClampEnergyEnum.ENERGY_CONSUMED_C,
|
|
]);
|
|
|
|
const energyStatus = addDeviceStatusDto?.log?.properties?.find(
|
|
(status) => energyCodes.has(status.code),
|
|
);
|
|
|
|
if (energyStatus) {
|
|
await this.powerClampService.updateEnergyConsumedHistoricalData(
|
|
addDeviceStatusDto.deviceUuid,
|
|
);
|
|
}
|
|
}
|
|
|
|
if (
|
|
addDeviceStatusDto.productType === ProductType.CPS ||
|
|
addDeviceStatusDto.productType === ProductType.WPS
|
|
) {
|
|
const occupancyCodes = new Set([PresenceSensorEnum.PRESENCE_STATE]);
|
|
|
|
const occupancyStatus = addDeviceStatusDto?.log?.properties?.find(
|
|
(status) => occupancyCodes.has(status.code),
|
|
);
|
|
|
|
if (occupancyStatus) {
|
|
await this.occupancyService.updateOccupancySensorHistoricalData(
|
|
addDeviceStatusDto.deviceUuid,
|
|
);
|
|
await this.occupancyService.updateOccupancySensorHistoricalDurationData(
|
|
addDeviceStatusDto.deviceUuid,
|
|
);
|
|
}
|
|
}
|
|
if (addDeviceStatusDto.productType === ProductType.AQI) {
|
|
await this.aqiDataService.updateAQISensorHistoricalData(
|
|
addDeviceStatusDto.deviceUuid,
|
|
);
|
|
}
|
|
} else {
|
|
// Save logs to your repository
|
|
const newLogs = addDeviceStatusDto?.status.map((property) => {
|
|
return this.deviceStatusLogRepository.create({
|
|
deviceId: addDeviceStatusDto.deviceUuid,
|
|
deviceTuyaId: addDeviceStatusDto.deviceTuyaUuid,
|
|
productId: addDeviceStatusDto.log.productKey,
|
|
log: addDeviceStatusDto.log,
|
|
code: property.code,
|
|
value: property.value,
|
|
eventId: addDeviceStatusDto.log.dataId,
|
|
eventTime: new Date(property.t).toISOString(),
|
|
});
|
|
});
|
|
await this.deviceStatusLogRepository.save(newLogs);
|
|
|
|
if (addDeviceStatusDto.productType === ProductType.PC) {
|
|
const energyCodes = new Set([
|
|
PowerClampEnergyEnum.ENERGY_CONSUMED,
|
|
PowerClampEnergyEnum.ENERGY_CONSUMED_A,
|
|
PowerClampEnergyEnum.ENERGY_CONSUMED_B,
|
|
PowerClampEnergyEnum.ENERGY_CONSUMED_C,
|
|
]);
|
|
|
|
const energyStatus = addDeviceStatusDto?.status?.find((status) => {
|
|
return energyCodes.has(status.code as PowerClampEnergyEnum);
|
|
});
|
|
|
|
if (energyStatus) {
|
|
await this.powerClampService.updateEnergyConsumedHistoricalData(
|
|
addDeviceStatusDto.deviceUuid,
|
|
);
|
|
}
|
|
}
|
|
|
|
if (
|
|
addDeviceStatusDto.productType === ProductType.CPS ||
|
|
addDeviceStatusDto.productType === ProductType.WPS
|
|
) {
|
|
const occupancyCodes = new Set([PresenceSensorEnum.PRESENCE_STATE]);
|
|
|
|
const occupancyStatus = addDeviceStatusDto?.status?.find((status) => {
|
|
return occupancyCodes.has(status.code as PresenceSensorEnum);
|
|
});
|
|
|
|
if (occupancyStatus) {
|
|
await this.occupancyService.updateOccupancySensorHistoricalData(
|
|
addDeviceStatusDto.deviceUuid,
|
|
);
|
|
await this.occupancyService.updateOccupancySensorHistoricalDurationData(
|
|
addDeviceStatusDto.deviceUuid,
|
|
);
|
|
}
|
|
}
|
|
|
|
if (addDeviceStatusDto.productType === ProductType.AQI) {
|
|
await this.aqiDataService.updateAQISensorHistoricalData(
|
|
addDeviceStatusDto.deviceUuid,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|