mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-15 10:25:23 +00:00
add automation
This commit is contained in:
@ -133,4 +133,45 @@ export class TuyaService {
|
|||||||
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async createAutomation(
|
||||||
|
spaceId: string,
|
||||||
|
automationName: string,
|
||||||
|
effectiveTime: any,
|
||||||
|
decisionExpr: string,
|
||||||
|
conditions: any[],
|
||||||
|
actions: any[],
|
||||||
|
) {
|
||||||
|
const path = `/v2.0/cloud/scene/rule`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await this.tuya.request({
|
||||||
|
method: 'POST',
|
||||||
|
path,
|
||||||
|
body: {
|
||||||
|
space_id: spaceId,
|
||||||
|
name: automationName,
|
||||||
|
effective_time: {
|
||||||
|
...effectiveTime,
|
||||||
|
timezone_id: 'Asia/Dubai',
|
||||||
|
},
|
||||||
|
type: 'automation',
|
||||||
|
decision_expr: decisionExpr,
|
||||||
|
conditions: conditions,
|
||||||
|
actions: actions,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.success) {
|
||||||
|
throw new HttpException(response.msg, HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new HttpException(
|
||||||
|
error.message || 'Failed to create automation in Tuya',
|
||||||
|
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,12 +8,14 @@ import { DeviceService } from 'src/device/services';
|
|||||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||||
import { ProductRepository } from '@app/common/modules/product/repositories';
|
import { ProductRepository } from '@app/common/modules/product/repositories';
|
||||||
import { DeviceStatusFirebaseModule } from '@app/common/firebase/devices-status/devices-status.module';
|
import { DeviceStatusFirebaseModule } from '@app/common/firebase/devices-status/devices-status.module';
|
||||||
|
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ConfigModule, SpaceRepositoryModule, DeviceStatusFirebaseModule],
|
imports: [ConfigModule, SpaceRepositoryModule, DeviceStatusFirebaseModule],
|
||||||
controllers: [AutomationController],
|
controllers: [AutomationController],
|
||||||
providers: [
|
providers: [
|
||||||
AutomationService,
|
AutomationService,
|
||||||
|
TuyaService,
|
||||||
SpaceRepository,
|
SpaceRepository,
|
||||||
DeviceService,
|
DeviceService,
|
||||||
DeviceRepository,
|
DeviceRepository,
|
||||||
|
@ -16,9 +16,11 @@ import { TuyaContext } from '@tuya/tuya-connector-nodejs';
|
|||||||
import { convertKeysToSnakeCase } from '@app/common/helper/snakeCaseConverter';
|
import { convertKeysToSnakeCase } from '@app/common/helper/snakeCaseConverter';
|
||||||
import { DeviceService } from 'src/device/services';
|
import { DeviceService } from 'src/device/services';
|
||||||
import {
|
import {
|
||||||
|
Action,
|
||||||
AddAutomationInterface,
|
AddAutomationInterface,
|
||||||
AutomationDetailsResult,
|
AutomationDetailsResult,
|
||||||
AutomationResponseData,
|
AutomationResponseData,
|
||||||
|
Condition,
|
||||||
DeleteAutomationInterface,
|
DeleteAutomationInterface,
|
||||||
GetAutomationBySpaceInterface,
|
GetAutomationBySpaceInterface,
|
||||||
} from '../interface/automation.interface';
|
} from '../interface/automation.interface';
|
||||||
@ -27,6 +29,7 @@ import {
|
|||||||
ActionExecutorEnum,
|
ActionExecutorEnum,
|
||||||
EntityTypeEnum,
|
EntityTypeEnum,
|
||||||
} from '@app/common/constants/automation.enum';
|
} from '@app/common/constants/automation.enum';
|
||||||
|
import { TuyaService } from '@app/common/integrations/tuya/services/tuya.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AutomationService {
|
export class AutomationService {
|
||||||
@ -35,6 +38,7 @@ export class AutomationService {
|
|||||||
private readonly configService: ConfigService,
|
private readonly configService: ConfigService,
|
||||||
private readonly spaceRepository: SpaceRepository,
|
private readonly spaceRepository: SpaceRepository,
|
||||||
private readonly deviceService: DeviceService,
|
private readonly deviceService: DeviceService,
|
||||||
|
private readonly tuyaService: TuyaService,
|
||||||
) {
|
) {
|
||||||
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');
|
||||||
@ -48,77 +52,39 @@ export class AutomationService {
|
|||||||
|
|
||||||
async addAutomation(addAutomationDto: AddAutomationDto, spaceTuyaId = null) {
|
async addAutomation(addAutomationDto: AddAutomationDto, spaceTuyaId = null) {
|
||||||
try {
|
try {
|
||||||
let tuyaSpaceId;
|
const { automationName, effectiveTime, decisionExpr } = addAutomationDto;
|
||||||
if (!spaceTuyaId) {
|
const space = await this.getSpaceByUuid(addAutomationDto.spaceUuid);
|
||||||
const space = await this.getSpaceByUuid(addAutomationDto.spaceUuid);
|
|
||||||
|
|
||||||
tuyaSpaceId = space.spaceTuyaUuid;
|
const actions = await this.processEntities<Action>(
|
||||||
if (!space) {
|
addAutomationDto.actions,
|
||||||
throw new BadRequestException(
|
'actionExecutor',
|
||||||
`Invalid space UUID ${addAutomationDto.spaceUuid}`,
|
{ [ActionExecutorEnum.DEVICE_ISSUE]: true },
|
||||||
);
|
this.deviceService,
|
||||||
}
|
|
||||||
} else {
|
|
||||||
tuyaSpaceId = spaceTuyaId;
|
|
||||||
}
|
|
||||||
|
|
||||||
const actions = addAutomationDto.actions.map((action) =>
|
|
||||||
convertKeysToSnakeCase(action),
|
|
||||||
);
|
|
||||||
const conditions = addAutomationDto.conditions.map((condition) =>
|
|
||||||
convertKeysToSnakeCase(condition),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
for (const action of actions) {
|
const conditions = await this.processEntities<Condition>(
|
||||||
if (action.action_executor === ActionExecutorEnum.DEVICE_ISSUE) {
|
addAutomationDto.conditions,
|
||||||
const device = await this.deviceService.getDeviceByDeviceUuid(
|
'entityType',
|
||||||
action.entity_id,
|
{ [EntityTypeEnum.DEVICE_REPORT]: true },
|
||||||
false,
|
this.deviceService,
|
||||||
);
|
);
|
||||||
if (device) {
|
|
||||||
action.entity_id = device.deviceTuyaUuid;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const condition of conditions) {
|
const response = (await this.tuyaService.createAutomation(
|
||||||
if (condition.entity_type === EntityTypeEnum.DEVICE_REPORT) {
|
space.spaceTuyaUuid,
|
||||||
const device = await this.deviceService.getDeviceByDeviceUuid(
|
automationName,
|
||||||
condition.entity_id,
|
effectiveTime,
|
||||||
false,
|
decisionExpr,
|
||||||
);
|
conditions,
|
||||||
if (device) {
|
actions,
|
||||||
condition.entity_id = device.deviceTuyaUuid;
|
)) as AddAutomationInterface;
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const path = `/v2.0/cloud/scene/rule`;
|
|
||||||
const response: AddAutomationInterface = await this.tuya.request({
|
|
||||||
method: 'POST',
|
|
||||||
path,
|
|
||||||
body: {
|
|
||||||
space_id: tuyaSpaceId,
|
|
||||||
name: addAutomationDto.automationName,
|
|
||||||
effective_time: {
|
|
||||||
...addAutomationDto.effectiveTime,
|
|
||||||
timezone_id: 'Asia/Dubai',
|
|
||||||
},
|
|
||||||
type: 'automation',
|
|
||||||
decision_expr: addAutomationDto.decisionExpr,
|
|
||||||
conditions: conditions,
|
|
||||||
actions: actions,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
if (!response.success) {
|
|
||||||
throw new HttpException(response.msg, HttpStatus.BAD_REQUEST);
|
|
||||||
}
|
|
||||||
return {
|
return {
|
||||||
id: response.result.id,
|
id: response?.result.id,
|
||||||
};
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
console.log(err);
|
||||||
if (err instanceof BadRequestException) {
|
if (err instanceof BadRequestException) {
|
||||||
throw err; // Re-throw BadRequestException
|
throw err;
|
||||||
} else {
|
} else {
|
||||||
throw new HttpException(
|
throw new HttpException(
|
||||||
err.message || 'Automation not found',
|
err.message || 'Automation not found',
|
||||||
@ -127,6 +93,7 @@ export class AutomationService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async getSpaceByUuid(spaceUuid: string) {
|
async getSpaceByUuid(spaceUuid: string) {
|
||||||
try {
|
try {
|
||||||
const space = await this.spaceRepository.findOne({
|
const space = await this.spaceRepository.findOne({
|
||||||
@ -189,6 +156,7 @@ export class AutomationService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async getTapToRunSceneDetailsTuya(
|
async getTapToRunSceneDetailsTuya(
|
||||||
sceneUuid: string,
|
sceneUuid: string,
|
||||||
): Promise<AutomationDetailsResult> {
|
): Promise<AutomationDetailsResult> {
|
||||||
@ -425,4 +393,42 @@ export class AutomationService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async processEntities<T extends Action | Condition>(
|
||||||
|
entities: T[], // Accepts either Action[] or Condition[]
|
||||||
|
lookupKey: keyof T, // The key to look up, specific to T
|
||||||
|
entityTypeOrExecutorMap: {
|
||||||
|
[key in ActionExecutorEnum | EntityTypeEnum]?: boolean;
|
||||||
|
},
|
||||||
|
deviceService: {
|
||||||
|
getDeviceByDeviceUuid: (
|
||||||
|
id: string,
|
||||||
|
flag: boolean,
|
||||||
|
) => Promise<{ deviceTuyaUuid: string } | null>;
|
||||||
|
},
|
||||||
|
): Promise<T[]> {
|
||||||
|
// Returns the same type as provided in the input
|
||||||
|
return Promise.all(
|
||||||
|
entities.map(async (entity) => {
|
||||||
|
// Convert keys to snake case (assuming a utility function exists)
|
||||||
|
const processedEntity = convertKeysToSnakeCase(entity) as T;
|
||||||
|
|
||||||
|
// Check if entity needs device UUID lookup
|
||||||
|
const key = processedEntity[lookupKey];
|
||||||
|
if (
|
||||||
|
entityTypeOrExecutorMap[key as ActionExecutorEnum | EntityTypeEnum]
|
||||||
|
) {
|
||||||
|
const device = await deviceService.getDeviceByDeviceUuid(
|
||||||
|
processedEntity.entityId,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
if (device) {
|
||||||
|
processedEntity.entityId = device.deviceTuyaUuid;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return processedEntity;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -20,35 +20,42 @@ export class SpaceDeviceService {
|
|||||||
|
|
||||||
async listDevicesInSpace(params: GetSpaceParam): Promise<BaseResponseDto> {
|
async listDevicesInSpace(params: GetSpaceParam): Promise<BaseResponseDto> {
|
||||||
const { spaceUuid, communityUuid } = params;
|
const { spaceUuid, communityUuid } = params;
|
||||||
|
try {
|
||||||
|
const space = await this.validateCommunityAndSpace(
|
||||||
|
communityUuid,
|
||||||
|
spaceUuid,
|
||||||
|
);
|
||||||
|
|
||||||
const space = await this.validateCommunityAndSpace(
|
const detailedDevices = await Promise.all(
|
||||||
communityUuid,
|
space.devices.map(async (device) => {
|
||||||
spaceUuid,
|
const tuyaDetails = await this.getDeviceDetailsByDeviceIdTuya(
|
||||||
);
|
device.deviceTuyaUuid,
|
||||||
|
);
|
||||||
|
|
||||||
const detailedDevices = await Promise.all(
|
return {
|
||||||
space.devices.map(async (device) => {
|
uuid: device.uuid,
|
||||||
const tuyaDetails = await this.getDeviceDetailsByDeviceIdTuya(
|
deviceTuyaUuid: device.deviceTuyaUuid,
|
||||||
device.deviceTuyaUuid,
|
productUuid: device.productDevice.uuid,
|
||||||
);
|
productType: device.productDevice.prodType,
|
||||||
|
isActive: device.isActive,
|
||||||
|
createdAt: device.createdAt,
|
||||||
|
updatedAt: device.updatedAt,
|
||||||
|
...tuyaDetails,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return new SuccessResponseDto({
|
||||||
uuid: device.uuid,
|
data: detailedDevices,
|
||||||
deviceTuyaUuid: device.deviceTuyaUuid,
|
message: 'Successfully retrieved list of devices',
|
||||||
productUuid: device.productDevice.uuid,
|
});
|
||||||
productType: device.productDevice.prodType,
|
} catch (error) {
|
||||||
isActive: device.isActive,
|
console.error('Error listing devices in space:', error);
|
||||||
createdAt: device.createdAt,
|
throw new HttpException(
|
||||||
updatedAt: device.updatedAt,
|
error.message || 'Failed to retrieve devices in space',
|
||||||
...tuyaDetails,
|
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
};
|
);
|
||||||
}),
|
}
|
||||||
);
|
|
||||||
|
|
||||||
return new SuccessResponseDto({
|
|
||||||
data: detailedDevices,
|
|
||||||
message: 'Successfully retrieved list of devices',
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async validateCommunityAndSpace(communityUuid: string, spaceUuid: string) {
|
async validateCommunityAndSpace(communityUuid: string, spaceUuid: string) {
|
||||||
@ -80,7 +87,6 @@ export class SpaceDeviceService {
|
|||||||
deviceId: string,
|
deviceId: string,
|
||||||
): Promise<GetDeviceDetailsInterface> {
|
): Promise<GetDeviceDetailsInterface> {
|
||||||
try {
|
try {
|
||||||
// Fetch details from TuyaService
|
|
||||||
const tuyaDeviceDetails =
|
const tuyaDeviceDetails =
|
||||||
await this.tuyaService.getDeviceDetails(deviceId);
|
await this.tuyaService.getDeviceDetails(deviceId);
|
||||||
|
|
||||||
@ -101,7 +107,7 @@ export class SpaceDeviceService {
|
|||||||
} as GetDeviceDetailsInterface;
|
} as GetDeviceDetailsInterface;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new HttpException(
|
throw new HttpException(
|
||||||
'Error fetching device details from Tuya',
|
`Error fetching device details from Tuya for device id ${deviceId}`,
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user