Compare commits

..

3 Commits

8 changed files with 262 additions and 290 deletions

View File

@ -15,6 +15,7 @@ export enum ProductType {
WL = 'WL', WL = 'WL',
GD = 'GD', GD = 'GD',
CUR = 'CUR', CUR = 'CUR',
CUR_2 = 'CUR_2',
PC = 'PC', PC = 'PC',
FOUR_S = '4S', FOUR_S = '4S',
SIX_S = '6S', SIX_S = '6S',

View File

@ -24,7 +24,6 @@ import { PowerClampEnergyEnum } from '@app/common/constants/power.clamp.enargy.e
import { PresenceSensorEnum } from '@app/common/constants/presence.sensor.enum'; import { PresenceSensorEnum } from '@app/common/constants/presence.sensor.enum';
import { OccupancyService } from '@app/common/helper/services/occupancy.service'; import { OccupancyService } from '@app/common/helper/services/occupancy.service';
import { AqiDataService } from '@app/common/helper/services/aqi.data.service'; import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
import { DataSource, QueryRunner } from 'typeorm';
@Injectable() @Injectable()
export class DeviceStatusFirebaseService { export class DeviceStatusFirebaseService {
private tuya: TuyaContext; private tuya: TuyaContext;
@ -36,7 +35,6 @@ export class DeviceStatusFirebaseService {
private readonly occupancyService: OccupancyService, private readonly occupancyService: OccupancyService,
private readonly aqiDataService: AqiDataService, private readonly aqiDataService: AqiDataService,
private deviceStatusLogRepository: DeviceStatusLogRepository, private deviceStatusLogRepository: DeviceStatusLogRepository,
private readonly dataSource: DataSource,
) { ) {
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY'); const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
const secretKey = this.configService.get<string>('auth-config.SECRET_KEY'); const secretKey = this.configService.get<string>('auth-config.SECRET_KEY');
@ -81,46 +79,28 @@ export class DeviceStatusFirebaseService {
async addDeviceStatusToFirebase( async addDeviceStatusToFirebase(
addDeviceStatusDto: AddDeviceStatusDto, addDeviceStatusDto: AddDeviceStatusDto,
): Promise<AddDeviceStatusDto | null> { ): Promise<AddDeviceStatusDto | null> {
const queryRunner = this.dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try { try {
const device = await this.getDeviceByDeviceTuyaUuid( const device = await this.getDeviceByDeviceTuyaUuid(
addDeviceStatusDto.deviceTuyaUuid, addDeviceStatusDto.deviceTuyaUuid,
queryRunner,
); );
if (device?.uuid) { if (device?.uuid) {
const result = await this.createDeviceStatusFirebase( return await this.createDeviceStatusFirebase({
{ deviceUuid: device.uuid,
deviceUuid: device.uuid, ...addDeviceStatusDto,
...addDeviceStatusDto, productType: device.productDevice.prodType,
productType: device.productDevice.prodType, });
},
queryRunner,
);
await queryRunner.commitTransaction();
return result;
} }
// Return null if device not found or no UUID // Return null if device not found or no UUID
await queryRunner.rollbackTransaction();
return null; return null;
} catch (error) { } catch (error) {
await queryRunner.rollbackTransaction(); // Handle the error silently, perhaps log it internally or ignore it
return null; return null;
} finally {
await queryRunner.release();
} }
} }
async getDeviceByDeviceTuyaUuid(
deviceTuyaUuid: string,
queryRunner?: QueryRunner,
) {
const repo = queryRunner
? queryRunner.manager.getRepository(this.deviceRepository.target)
: this.deviceRepository;
return await repo.findOne({ async getDeviceByDeviceTuyaUuid(deviceTuyaUuid: string) {
return await this.deviceRepository.findOne({
where: { where: {
deviceTuyaUuid, deviceTuyaUuid,
isActive: true, isActive: true,
@ -128,7 +108,6 @@ export class DeviceStatusFirebaseService {
relations: ['productDevice'], relations: ['productDevice'],
}); });
} }
async getDevicesInstructionStatus(deviceUuid: string) { async getDevicesInstructionStatus(deviceUuid: string) {
try { try {
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid); const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
@ -174,14 +153,9 @@ export class DeviceStatusFirebaseService {
} }
async getDeviceByDeviceUuid( async getDeviceByDeviceUuid(
deviceUuid: string, deviceUuid: string,
withProductDevice = true, withProductDevice: boolean = true,
queryRunner?: QueryRunner,
) { ) {
const repo = queryRunner return await this.deviceRepository.findOne({
? queryRunner.manager.getRepository(this.deviceRepository.target)
: this.deviceRepository;
return await repo.findOne({
where: { where: {
uuid: deviceUuid, uuid: deviceUuid,
isActive: true, isActive: true,
@ -189,20 +163,21 @@ export class DeviceStatusFirebaseService {
...(withProductDevice && { relations: ['productDevice'] }), ...(withProductDevice && { relations: ['productDevice'] }),
}); });
} }
async createDeviceStatusFirebase( async createDeviceStatusFirebase(
addDeviceStatusDto: AddDeviceStatusDto, addDeviceStatusDto: AddDeviceStatusDto,
queryRunner?: QueryRunner,
): Promise<any> { ): Promise<any> {
const dataRef = ref( const dataRef = ref(
this.firebaseDb, this.firebaseDb,
`device-status/${addDeviceStatusDto.deviceUuid}`, `device-status/${addDeviceStatusDto.deviceUuid}`,
); );
// Step 1: Update Firebase Realtime Database // Use a transaction to handle concurrent updates
await runTransaction(dataRef, (existingData) => { await runTransaction(dataRef, (existingData) => {
if (!existingData) existingData = {}; if (!existingData) {
existingData = {};
}
// Assign default values if fields are not present
if (!existingData.deviceTuyaUuid) { if (!existingData.deviceTuyaUuid) {
existingData.deviceTuyaUuid = addDeviceStatusDto.deviceTuyaUuid; existingData.deviceTuyaUuid = addDeviceStatusDto.deviceTuyaUuid;
} }
@ -216,15 +191,18 @@ export class DeviceStatusFirebaseService {
existingData.status = []; existingData.status = [];
} }
// Merge incoming status with existing status // Create a map to track existing status codes
const statusMap = new Map( const statusMap = new Map(
existingData.status.map((item) => [item.code, item.value]), existingData.status.map((item) => [item.code, item.value]),
); );
// Update or add status codes
for (const statusItem of addDeviceStatusDto.status) { for (const statusItem of addDeviceStatusDto.status) {
statusMap.set(statusItem.code, statusItem.value); statusMap.set(statusItem.code, statusItem.value);
} }
// Convert the map back to an array format
existingData.status = Array.from(statusMap, ([code, value]) => ({ existingData.status = Array.from(statusMap, ([code, value]) => ({
code, code,
value, value,
@ -233,9 +211,9 @@ export class DeviceStatusFirebaseService {
return existingData; return existingData;
}); });
// Step 2: Save device status log entries // Save logs to your repository
const newLogs = addDeviceStatusDto.log.properties.map((property) => const newLogs = addDeviceStatusDto.log.properties.map((property) => {
this.deviceStatusLogRepository.create({ return this.deviceStatusLogRepository.create({
deviceId: addDeviceStatusDto.deviceUuid, deviceId: addDeviceStatusDto.deviceUuid,
deviceTuyaId: addDeviceStatusDto.deviceTuyaUuid, deviceTuyaId: addDeviceStatusDto.deviceTuyaUuid,
productId: addDeviceStatusDto.log.productId, productId: addDeviceStatusDto.log.productId,
@ -244,19 +222,10 @@ export class DeviceStatusFirebaseService {
value: property.value, value: property.value,
eventId: addDeviceStatusDto.log.dataId, eventId: addDeviceStatusDto.log.dataId,
eventTime: new Date(property.time).toISOString(), eventTime: new Date(property.time).toISOString(),
}), });
); });
await this.deviceStatusLogRepository.save(newLogs);
if (queryRunner) {
const repo = queryRunner.manager.getRepository(
this.deviceStatusLogRepository.target,
);
await repo.save(newLogs);
} else {
await this.deviceStatusLogRepository.save(newLogs);
}
// Step 3: Trigger additional data services
if (addDeviceStatusDto.productType === ProductType.PC) { if (addDeviceStatusDto.productType === ProductType.PC) {
const energyCodes = new Set([ const energyCodes = new Set([
PowerClampEnergyEnum.ENERGY_CONSUMED, PowerClampEnergyEnum.ENERGY_CONSUMED,
@ -300,8 +269,7 @@ export class DeviceStatusFirebaseService {
addDeviceStatusDto.deviceUuid, addDeviceStatusDto.deviceUuid,
); );
} }
// Return the updated data
// Step 4: Return updated Firebase status
const snapshot: DataSnapshot = await get(dataRef); const snapshot: DataSnapshot = await get(dataRef);
return snapshot.val(); return snapshot.val();
} }

View File

@ -36,18 +36,9 @@ export class AqiDataService {
procedureFileName: string, procedureFileName: string,
params: (string | number | null)[], params: (string | number | null)[],
): Promise<void> { ): Promise<void> {
const queryRunner = this.dataSource.createQueryRunner(); const query = this.loadQuery(procedureFolderName, procedureFileName);
await queryRunner.connect(); await this.dataSource.query(query, params);
try { console.log(`Procedure ${procedureFileName} executed successfully.`);
const query = this.loadQuery(procedureFolderName, procedureFileName);
await queryRunner.query(query, params);
console.log(`Procedure ${procedureFileName} executed successfully.`);
} catch (err) {
console.error(`Failed to execute procedure ${procedureFileName}:`, err);
throw err;
} finally {
await queryRunner.release();
}
} }
private loadQuery(folderName: string, fileName: string): string { private loadQuery(folderName: string, fileName: string): string {

View File

@ -57,18 +57,9 @@ export class OccupancyService {
procedureFileName: string, procedureFileName: string,
params: (string | number | null)[], params: (string | number | null)[],
): Promise<void> { ): Promise<void> {
const queryRunner = this.dataSource.createQueryRunner(); const query = this.loadQuery(procedureFolderName, procedureFileName);
await queryRunner.connect(); await this.dataSource.query(query, params);
try { console.log(`Procedure ${procedureFileName} executed successfully.`);
const query = this.loadQuery(procedureFolderName, procedureFileName);
await queryRunner.query(query, params);
console.log(`Procedure ${procedureFileName} executed successfully.`);
} catch (err) {
console.error(`Failed to execute procedure ${procedureFileName}:`, err);
throw err;
} finally {
await queryRunner.release();
}
} }
private loadQuery(folderName: string, fileName: string): string { private loadQuery(folderName: string, fileName: string): string {

View File

@ -46,21 +46,12 @@ export class PowerClampService {
procedureFileName: string, procedureFileName: string,
params: (string | number | null)[], params: (string | number | null)[],
): Promise<void> { ): Promise<void> {
const queryRunner = this.dataSource.createQueryRunner(); const query = this.loadQuery(
await queryRunner.connect(); 'fact_device_energy_consumed',
try { procedureFileName,
const query = this.loadQuery( );
'fact_device_energy_consumed', await this.dataSource.query(query, params);
procedureFileName, console.log(`Procedure ${procedureFileName} executed successfully.`);
);
await queryRunner.query(query, params);
console.log(`Procedure ${procedureFileName} executed successfully.`);
} catch (err) {
console.error(`Failed to execute procedure ${procedureFileName}:`, err);
throw err;
} finally {
await queryRunner.release();
}
} }
private loadQuery(folderName: string, fileName: string): string { private loadQuery(folderName: string, fileName: string): string {

View File

@ -0,0 +1,28 @@
interface BaseCommand {
code: string;
value: any;
}
export interface ControlCur2Command extends BaseCommand {
code: 'control';
value: 'open' | 'close' | 'stop';
}
export interface ControlCur2PercentCommand extends BaseCommand {
code: 'percent_control';
value: 10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100;
}
export interface ControlCur2AccurateCalibrationCommand extends BaseCommand {
code: 'accurate_calibration';
value: 'start' | 'end'; // Assuming this is a numeric value for calibration
}
export interface ControlCur2TDirectionConCommand extends BaseCommand {
code: 'control_t_direction_con';
value: 'forward' | 'back';
}
export interface ControlCur2QuickCalibrationCommand extends BaseCommand {
code: 'tr_timecon';
value: number; // between 10 and 120
}
export interface ControlCur2MotorModeCommand extends BaseCommand {
code: 'elec_machinery_mode';
value: 'strong_power' | 'dry_contact';
}

View File

@ -0,0 +1,32 @@
import {
ControlCur2AccurateCalibrationCommand,
ControlCur2Command,
ControlCur2PercentCommand,
ControlCur2QuickCalibrationCommand,
ControlCur2TDirectionConCommand,
} from 'src/device/commands/cur2-commands';
export enum ScheduleProductType {
CUR_2 = 'CUR_2',
}
export const DeviceFunctionMap: {
[T in ScheduleProductType]: (body: DeviceFunction[T]) => any;
} = {
[ScheduleProductType.CUR_2]: ({ code, value }) => {
return [
{
code,
value,
},
];
},
};
type DeviceFunction = {
[ScheduleProductType.CUR_2]:
| ControlCur2Command
| ControlCur2PercentCommand
| ControlCur2AccurateCalibrationCommand
| ControlCur2TDirectionConCommand
| ControlCur2QuickCalibrationCommand;
};

View File

@ -1,6 +1,6 @@
import { Injectable, HttpException, HttpStatus } from '@nestjs/common'; import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
import { import {
AddScheduleDto, AddScheduleDto,
EnableScheduleDto, EnableScheduleDto,
@ -11,14 +11,14 @@ import {
getDeviceScheduleInterface, getDeviceScheduleInterface,
} from '../interfaces/get.schedule.interface'; } from '../interfaces/get.schedule.interface';
import { convertKeysToCamelCase } from '@app/common/helper/camelCaseConverter';
import { DeviceRepository } from '@app/common/modules/device/repositories';
import { ProductType } from '@app/common/constants/product-type.enum'; import { ProductType } from '@app/common/constants/product-type.enum';
import { convertKeysToCamelCase } from '@app/common/helper/camelCaseConverter';
import { convertTimestampToDubaiTime } from '@app/common/helper/convertTimestampToDubaiTime'; import { convertTimestampToDubaiTime } from '@app/common/helper/convertTimestampToDubaiTime';
import { import {
getEnabledDays, getEnabledDays,
getScheduleStatus, getScheduleStatus,
} from '@app/common/helper/getScheduleStatus'; } from '@app/common/helper/getScheduleStatus';
import { DeviceRepository } from '@app/common/modules/device/repositories';
@Injectable() @Injectable()
export class ScheduleService { export class ScheduleService {
@ -49,22 +49,11 @@ export class ScheduleService {
} }
// Corrected condition for supported device types // Corrected condition for supported device types
if ( this.ensureProductTypeSupportedForSchedule(
deviceDetails.productDevice.prodType !== ProductType.THREE_G && ProductType[deviceDetails.productDevice.prodType],
deviceDetails.productDevice.prodType !== ProductType.ONE_G && );
deviceDetails.productDevice.prodType !== ProductType.TWO_G &&
deviceDetails.productDevice.prodType !== ProductType.WH && return this.enableScheduleDeviceInTuya(
deviceDetails.productDevice.prodType !== ProductType.ONE_1TG &&
deviceDetails.productDevice.prodType !== ProductType.TWO_2TG &&
deviceDetails.productDevice.prodType !== ProductType.THREE_3TG &&
deviceDetails.productDevice.prodType !== ProductType.GD
) {
throw new HttpException(
'This device is not supported for schedule',
HttpStatus.BAD_REQUEST,
);
}
return await this.enableScheduleDeviceInTuya(
deviceDetails.deviceTuyaUuid, deviceDetails.deviceTuyaUuid,
enableScheduleDto, enableScheduleDto,
); );
@ -75,29 +64,6 @@ export class ScheduleService {
); );
} }
} }
async enableScheduleDeviceInTuya(
deviceId: string,
enableScheduleDto: EnableScheduleDto,
): Promise<addScheduleDeviceInterface> {
try {
const path = `/v2.0/cloud/timer/device/${deviceId}/state`;
const response = await this.tuya.request({
method: 'PUT',
path,
body: {
enable: enableScheduleDto.enable,
timer_id: enableScheduleDto.scheduleId,
},
});
return response as addScheduleDeviceInterface;
} catch (error) {
throw new HttpException(
'Error while updating schedule from Tuya',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
async deleteDeviceSchedule(deviceUuid: string, scheduleId: string) { async deleteDeviceSchedule(deviceUuid: string, scheduleId: string) {
try { try {
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid); const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
@ -107,21 +73,10 @@ export class ScheduleService {
} }
// Corrected condition for supported device types // Corrected condition for supported device types
if ( this.ensureProductTypeSupportedForSchedule(
deviceDetails.productDevice.prodType !== ProductType.THREE_G && ProductType[deviceDetails.productDevice.prodType],
deviceDetails.productDevice.prodType !== ProductType.ONE_G && );
deviceDetails.productDevice.prodType !== ProductType.TWO_G &&
deviceDetails.productDevice.prodType !== ProductType.WH &&
deviceDetails.productDevice.prodType !== ProductType.ONE_1TG &&
deviceDetails.productDevice.prodType !== ProductType.TWO_2TG &&
deviceDetails.productDevice.prodType !== ProductType.THREE_3TG &&
deviceDetails.productDevice.prodType !== ProductType.GD
) {
throw new HttpException(
'This device is not supported for schedule',
HttpStatus.BAD_REQUEST,
);
}
return await this.deleteScheduleDeviceInTuya( return await this.deleteScheduleDeviceInTuya(
deviceDetails.deviceTuyaUuid, deviceDetails.deviceTuyaUuid,
scheduleId, scheduleId,
@ -133,25 +88,6 @@ export class ScheduleService {
); );
} }
} }
async deleteScheduleDeviceInTuya(
deviceId: string,
scheduleId: string,
): Promise<addScheduleDeviceInterface> {
try {
const path = `/v2.0/cloud/timer/device/${deviceId}/batch?timer_ids=${scheduleId}`;
const response = await this.tuya.request({
method: 'DELETE',
path,
});
return response as addScheduleDeviceInterface;
} catch (error) {
throw new HttpException(
'Error while deleting schedule from Tuya',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
async addDeviceSchedule(deviceUuid: string, addScheduleDto: AddScheduleDto) { async addDeviceSchedule(deviceUuid: string, addScheduleDto: AddScheduleDto) {
try { try {
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid); const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
@ -160,22 +96,10 @@ export class ScheduleService {
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND); throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
} }
// Corrected condition for supported device types this.ensureProductTypeSupportedForSchedule(
if ( ProductType[deviceDetails.productDevice.prodType],
deviceDetails.productDevice.prodType !== ProductType.THREE_G && );
deviceDetails.productDevice.prodType !== ProductType.ONE_G &&
deviceDetails.productDevice.prodType !== ProductType.TWO_G &&
deviceDetails.productDevice.prodType !== ProductType.WH &&
deviceDetails.productDevice.prodType !== ProductType.ONE_1TG &&
deviceDetails.productDevice.prodType !== ProductType.TWO_2TG &&
deviceDetails.productDevice.prodType !== ProductType.THREE_3TG &&
deviceDetails.productDevice.prodType !== ProductType.GD
) {
throw new HttpException(
'This device is not supported for schedule',
HttpStatus.BAD_REQUEST,
);
}
await this.addScheduleDeviceInTuya( await this.addScheduleDeviceInTuya(
deviceDetails.deviceTuyaUuid, deviceDetails.deviceTuyaUuid,
addScheduleDto, addScheduleDto,
@ -187,40 +111,6 @@ export class ScheduleService {
); );
} }
} }
async addScheduleDeviceInTuya(
deviceId: string,
addScheduleDto: AddScheduleDto,
): Promise<addScheduleDeviceInterface> {
try {
const convertedTime = convertTimestampToDubaiTime(addScheduleDto.time);
const loops = getScheduleStatus(addScheduleDto.days);
const path = `/v2.0/cloud/timer/device/${deviceId}`;
const response = await this.tuya.request({
method: 'POST',
path,
body: {
time: convertedTime.time,
timezone_id: 'Asia/Dubai',
loops: `${loops}`,
functions: [
{
code: addScheduleDto.function.code,
value: addScheduleDto.function.value,
},
],
category: `category_${addScheduleDto.category}`,
},
});
return response as addScheduleDeviceInterface;
} catch (error) {
throw new HttpException(
'Error adding schedule from Tuya',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
async getDeviceScheduleByCategory(deviceUuid: string, category: string) { async getDeviceScheduleByCategory(deviceUuid: string, category: string) {
try { try {
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid); const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
@ -229,21 +119,10 @@ export class ScheduleService {
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND); throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
} }
// Corrected condition for supported device types // Corrected condition for supported device types
if ( this.ensureProductTypeSupportedForSchedule(
deviceDetails.productDevice.prodType !== ProductType.THREE_G && ProductType[deviceDetails.productDevice.prodType],
deviceDetails.productDevice.prodType !== ProductType.ONE_G && );
deviceDetails.productDevice.prodType !== ProductType.TWO_G &&
deviceDetails.productDevice.prodType !== ProductType.WH &&
deviceDetails.productDevice.prodType !== ProductType.ONE_1TG &&
deviceDetails.productDevice.prodType !== ProductType.TWO_2TG &&
deviceDetails.productDevice.prodType !== ProductType.THREE_3TG &&
deviceDetails.productDevice.prodType !== ProductType.GD
) {
throw new HttpException(
'This device is not supported for schedule',
HttpStatus.BAD_REQUEST,
);
}
const schedules = await this.getScheduleDeviceInTuya( const schedules = await this.getScheduleDeviceInTuya(
deviceDetails.deviceTuyaUuid, deviceDetails.deviceTuyaUuid,
category, category,
@ -270,7 +149,82 @@ export class ScheduleService {
); );
} }
} }
async getScheduleDeviceInTuya( async updateDeviceSchedule(
deviceUuid: string,
updateScheduleDto: UpdateScheduleDto,
) {
try {
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) {
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
}
// Corrected condition for supported device types
this.ensureProductTypeSupportedForSchedule(
ProductType[deviceDetails.productDevice.prodType],
);
await this.updateScheduleDeviceInTuya(
deviceDetails.deviceTuyaUuid,
updateScheduleDto,
);
} catch (error) {
throw new HttpException(
error.message || 'Error While Updating Schedule',
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
private getDeviceByDeviceUuid(
deviceUuid: string,
withProductDevice: boolean = true,
) {
return this.deviceRepository.findOne({
where: {
uuid: deviceUuid,
isActive: true,
},
...(withProductDevice && { relations: ['productDevice'] }),
});
}
private async addScheduleDeviceInTuya(
deviceId: string,
addScheduleDto: AddScheduleDto,
): Promise<addScheduleDeviceInterface> {
try {
const convertedTime = convertTimestampToDubaiTime(addScheduleDto.time);
const loops = getScheduleStatus(addScheduleDto.days);
const path = `/v2.0/cloud/timer/device/${deviceId}`;
const response = await this.tuya.request({
method: 'POST',
path,
body: {
time: convertedTime.time,
timezone_id: 'Asia/Dubai',
loops: `${loops}`,
functions: [
{
...addScheduleDto.function,
},
],
category: `category_${addScheduleDto.category}`,
},
});
return response as addScheduleDeviceInterface;
} catch (error) {
throw new HttpException(
'Error adding schedule from Tuya',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
private async getScheduleDeviceInTuya(
deviceId: string, deviceId: string,
category: string, category: string,
): Promise<getDeviceScheduleInterface> { ): Promise<getDeviceScheduleInterface> {
@ -291,57 +245,8 @@ export class ScheduleService {
); );
} }
} }
async getDeviceByDeviceUuid(
deviceUuid: string,
withProductDevice: boolean = true,
) {
return await this.deviceRepository.findOne({
where: {
uuid: deviceUuid,
isActive: true,
},
...(withProductDevice && { relations: ['productDevice'] }),
});
}
async updateDeviceSchedule(
deviceUuid: string,
updateScheduleDto: UpdateScheduleDto,
) {
try {
const deviceDetails = await this.getDeviceByDeviceUuid(deviceUuid);
if (!deviceDetails || !deviceDetails.deviceTuyaUuid) { private async updateScheduleDeviceInTuya(
throw new HttpException('Device Not Found', HttpStatus.NOT_FOUND);
}
// Corrected condition for supported device types
if (
deviceDetails.productDevice.prodType !== ProductType.THREE_G &&
deviceDetails.productDevice.prodType !== ProductType.ONE_G &&
deviceDetails.productDevice.prodType !== ProductType.TWO_G &&
deviceDetails.productDevice.prodType !== ProductType.WH &&
deviceDetails.productDevice.prodType !== ProductType.ONE_1TG &&
deviceDetails.productDevice.prodType !== ProductType.TWO_2TG &&
deviceDetails.productDevice.prodType !== ProductType.THREE_3TG &&
deviceDetails.productDevice.prodType !== ProductType.GD
) {
throw new HttpException(
'This device is not supported for schedule',
HttpStatus.BAD_REQUEST,
);
}
await this.updateScheduleDeviceInTuya(
deviceDetails.deviceTuyaUuid,
updateScheduleDto,
);
} catch (error) {
throw new HttpException(
error.message || 'Error While Updating Schedule',
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
async updateScheduleDeviceInTuya(
deviceId: string, deviceId: string,
updateScheduleDto: UpdateScheduleDto, updateScheduleDto: UpdateScheduleDto,
): Promise<addScheduleDeviceInterface> { ): Promise<addScheduleDeviceInterface> {
@ -376,4 +281,69 @@ export class ScheduleService {
); );
} }
} }
private async enableScheduleDeviceInTuya(
deviceId: string,
enableScheduleDto: EnableScheduleDto,
): Promise<addScheduleDeviceInterface> {
try {
const path = `/v2.0/cloud/timer/device/${deviceId}/state`;
const response = await this.tuya.request({
method: 'PUT',
path,
body: {
enable: enableScheduleDto.enable,
timer_id: enableScheduleDto.scheduleId,
},
});
return response as addScheduleDeviceInterface;
} catch (error) {
throw new HttpException(
'Error while updating schedule from Tuya',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
private async deleteScheduleDeviceInTuya(
deviceId: string,
scheduleId: string,
): Promise<addScheduleDeviceInterface> {
try {
const path = `/v2.0/cloud/timer/device/${deviceId}/batch?timer_ids=${scheduleId}`;
const response = await this.tuya.request({
method: 'DELETE',
path,
});
return response as addScheduleDeviceInterface;
} catch (error) {
throw new HttpException(
'Error while deleting schedule from Tuya',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
private ensureProductTypeSupportedForSchedule(deviceType: ProductType): void {
if (
![
ProductType.THREE_G,
ProductType.ONE_G,
ProductType.TWO_G,
ProductType.WH,
ProductType.ONE_1TG,
ProductType.TWO_2TG,
ProductType.THREE_3TG,
ProductType.GD,
ProductType.CUR_2,
].includes(deviceType)
) {
throw new HttpException(
'This device is not supported for schedule',
HttpStatus.BAD_REQUEST,
);
}
}
} }