Fixed automation bugs

This commit is contained in:
hannathkadher
2024-11-05 00:48:54 +04:00
parent aad794b2cd
commit a3eaa0fa3c
10 changed files with 227 additions and 151 deletions

View File

@ -0,0 +1,9 @@
import { TuyaResponseInterface } from './tuya.response.interface';
export interface AddTuyaResponseInterface extends TuyaResponseInterface {
result: {
id: string;
};
t?: number;
tid?: string;
}

View File

@ -1,2 +1,3 @@
export * from './tuya.response.interface';
export * from './tap-to-run-action.interface';
export * from './automation.interface';

View File

@ -1,5 +1,5 @@
export interface TuyaResponseInterface {
success: boolean;
msg?: string;
result: boolean;
result: boolean | { id: string };
}

View File

@ -1,7 +1,11 @@
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { TuyaContext } from '@tuya/tuya-connector-nodejs';
import { ConvertedAction, TuyaResponseInterface } from '../interfaces';
import {
AddTuyaResponseInterface,
ConvertedAction,
TuyaResponseInterface,
} from '../interfaces';
@Injectable()
export class TuyaService {
@ -144,32 +148,72 @@ export class TuyaService {
) {
const path = `/v2.0/cloud/scene/rule`;
const response: AddTuyaResponseInterface = 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;
}
async deleteAutomation(spaceId: string, automationUuid: string) {
const path = `/v2.0/cloud/scene/rule?ids=${automationUuid}&space_id=${spaceId}`;
const response = await this.tuya.request({
method: 'DELETE',
path,
});
if (!response.success) {
throw new HttpException(
'Failed to delete automation',
HttpStatus.NOT_FOUND,
);
}
return response;
}
async updateAutomationState(
spaceId: string,
automationUuid: string,
isEnable: boolean,
) {
const path = `/v2.0/cloud/scene/rule/state?space_id=${spaceId}`;
try {
const response = await this.tuya.request({
method: 'POST',
const response: TuyaResponseInterface = await this.tuya.request({
method: 'PUT',
path,
body: {
space_id: spaceId,
name: automationName,
effective_time: {
...effectiveTime,
timezone_id: 'Asia/Dubai',
},
type: 'automation',
decision_expr: decisionExpr,
conditions: conditions,
actions: actions,
ids: automationUuid,
is_enable: isEnable,
},
});
if (!response.success) {
throw new HttpException(response.msg, HttpStatus.BAD_REQUEST);
throw new HttpException('Automation not found', HttpStatus.NOT_FOUND);
}
return response.result;
return response;
} catch (error) {
throw new HttpException(
error.message || 'Failed to create automation in Tuya',
error.message || 'Failed to update automation state',
error.status || HttpStatus.INTERNAL_SERVER_ERROR,
);
}