mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-11-26 19:24:53 +00:00
Add Firebase Device Status Management Module
This commit is contained in:
@ -0,0 +1,25 @@
|
|||||||
|
import { Controller, Post, Param } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { AddDeviceStatusDto } from '../dtos/add.devices-status.dto';
|
||||||
|
import { DeviceStatusFirebaseService } from '../services/devices-status.service';
|
||||||
|
|
||||||
|
@ApiTags('Device Status Firebase Module')
|
||||||
|
@Controller({
|
||||||
|
version: '1',
|
||||||
|
path: 'device-status-firebase',
|
||||||
|
})
|
||||||
|
export class DeviceStatusFirebaseController {
|
||||||
|
constructor(
|
||||||
|
private readonly deviceStatusFirebaseService: DeviceStatusFirebaseService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@Post(':deviceTuyaUuid')
|
||||||
|
async addDeviceStatus(
|
||||||
|
@Param('deviceTuyaUuid') deviceTuyaUuid: string,
|
||||||
|
): Promise<AddDeviceStatusDto> {
|
||||||
|
return this.deviceStatusFirebaseService.addDeviceStatusByDeviceUuid(
|
||||||
|
deviceTuyaUuid,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,11 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { DeviceStatusFirebaseController } from './controllers/devices-status.controller';
|
||||||
|
import { DeviceStatusFirebaseService } from './services/devices-status.service';
|
||||||
|
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
providers: [DeviceStatusFirebaseService, DeviceRepository],
|
||||||
|
controllers: [DeviceStatusFirebaseController],
|
||||||
|
exports: [DeviceStatusFirebaseService],
|
||||||
|
})
|
||||||
|
export class DeviceStatusFirebaseModule {}
|
||||||
@ -0,0 +1,38 @@
|
|||||||
|
import {
|
||||||
|
IsString,
|
||||||
|
IsArray,
|
||||||
|
ValidateNested,
|
||||||
|
IsNotEmpty,
|
||||||
|
IsOptional,
|
||||||
|
} from 'class-validator';
|
||||||
|
import { Type } from 'class-transformer';
|
||||||
|
|
||||||
|
class StatusDto {
|
||||||
|
@IsString()
|
||||||
|
code: string;
|
||||||
|
|
||||||
|
@IsNotEmpty()
|
||||||
|
value: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class AddDeviceStatusDto {
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
deviceUuid?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
deviceTuyaUuid: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
productUuid?: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsOptional()
|
||||||
|
productType?: string;
|
||||||
|
|
||||||
|
@IsArray()
|
||||||
|
@ValidateNested({ each: true })
|
||||||
|
@Type(() => StatusDto)
|
||||||
|
status: StatusDto[];
|
||||||
|
}
|
||||||
@ -0,0 +1,192 @@
|
|||||||
|
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, set } from 'firebase/database';
|
||||||
|
@Injectable()
|
||||||
|
export class DeviceStatusFirebaseService {
|
||||||
|
private tuya: TuyaContext;
|
||||||
|
private firebaseDb: Database;
|
||||||
|
constructor(
|
||||||
|
private readonly configService: ConfigService,
|
||||||
|
private readonly deviceRepository: DeviceRepository,
|
||||||
|
) {
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
...(withProductDevice && { relations: ['productDevice'] }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async createDeviceStatusFirebase(
|
||||||
|
addDeviceStatusDto: AddDeviceStatusDto,
|
||||||
|
): Promise<any> {
|
||||||
|
const dataRef = ref(
|
||||||
|
this.firebaseDb,
|
||||||
|
`device-status/${addDeviceStatusDto.deviceUuid}`,
|
||||||
|
);
|
||||||
|
const snapshot: DataSnapshot = await get(dataRef);
|
||||||
|
const existingData = snapshot.val() || {};
|
||||||
|
|
||||||
|
// 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,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Save the updated data to Firebase
|
||||||
|
await set(dataRef, existingData);
|
||||||
|
|
||||||
|
// Return the updated data
|
||||||
|
return existingData;
|
||||||
|
}
|
||||||
|
}
|
||||||
24
libs/common/src/firebase/firebase.config.ts
Normal file
24
libs/common/src/firebase/firebase.config.ts
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
import { initializeApp } from 'firebase/app';
|
||||||
|
import { getDatabase } from 'firebase/database';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
|
||||||
|
export const initializeFirebaseApp = (configService: ConfigService) => {
|
||||||
|
const firebaseConfig = {
|
||||||
|
apiKey: configService.get<string>('FIREBASE_API_KEY'),
|
||||||
|
authDomain: configService.get<string>('FIREBASE_AUTH_DOMAIN'),
|
||||||
|
projectId: configService.get<string>('FIREBASE_PROJECT_ID'),
|
||||||
|
storageBucket: configService.get<string>('FIREBASE_STORAGE_BUCKET'),
|
||||||
|
messagingSenderId: configService.get<string>(
|
||||||
|
'FIREBASE_MESSAGING_SENDER_ID',
|
||||||
|
),
|
||||||
|
appId: configService.get<string>('FIREBASE_APP_ID'),
|
||||||
|
measurementId: configService.get<string>('FIREBASE_MEASUREMENT_ID'),
|
||||||
|
databaseURL: configService.get<string>('FIREBASE_DATABASE_URL'),
|
||||||
|
};
|
||||||
|
|
||||||
|
const app = initializeApp(firebaseConfig);
|
||||||
|
return getDatabase(app);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const firebaseDataBase = (configService: ConfigService) =>
|
||||||
|
initializeFirebaseApp(configService);
|
||||||
9
libs/common/src/firebase/firebase.shared.module.ts
Normal file
9
libs/common/src/firebase/firebase.shared.module.ts
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { DeviceStatusFirebaseModule } from './devices-status/devices-status.module';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [DeviceStatusFirebaseModule],
|
||||||
|
providers: [],
|
||||||
|
exports: [],
|
||||||
|
})
|
||||||
|
export class FirebaseSharedModule {}
|
||||||
Reference in New Issue
Block a user