mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-15 18:27:05 +00:00
Compare commits
27 Commits
DATA-occup
...
DATA-adjus
Author | SHA1 | Date | |
---|---|---|---|
d255e6811e | |||
e58d2d4831 | |||
147cf0b582 | |||
4e6b6f6ac5 | |||
932a3efd1c | |||
0a1ccad120 | |||
f337e6c681 | |||
f5bf857071 | |||
d1d4d529a8 | |||
37b582f521 | |||
cf19f08dca | |||
ff370b2baa | |||
04f64407e1 | |||
d7eef5d03e | |||
c8d691b380 | |||
75d03366c2 | |||
52cb69cc84 | |||
a6053b3971 | |||
60d2c8330b | |||
fddd06e06d | |||
3160773c2a | |||
110ed4157a | |||
aa9e90bf08 | |||
c5dd5e28fd | |||
603e74af09 | |||
0e36f32ed6 | |||
705ceeba29 |
@ -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',
|
||||||
|
@ -125,7 +125,7 @@ import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
|
|||||||
logger: typeOrmLogger,
|
logger: typeOrmLogger,
|
||||||
extra: {
|
extra: {
|
||||||
charset: 'utf8mb4',
|
charset: 'utf8mb4',
|
||||||
max: 20, // set pool max size
|
max: 100, // set pool max size
|
||||||
idleTimeoutMillis: 5000, // close idle clients after 5 second
|
idleTimeoutMillis: 5000, // close idle clients after 5 second
|
||||||
connectionTimeoutMillis: 12_000, // return an error after 11 second if connection could not be established
|
connectionTimeoutMillis: 12_000, // return an error after 11 second if connection could not be established
|
||||||
maxUses: 7500, // close (and replace) a connection after it has been used 7500 times (see below for discussion)
|
maxUses: 7500, // close (and replace) a connection after it has been used 7500 times (see below for discussion)
|
||||||
|
@ -76,6 +76,28 @@ export class DeviceStatusFirebaseService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
async addDeviceStatusToOurDb(
|
||||||
|
addDeviceStatusDto: AddDeviceStatusDto,
|
||||||
|
): Promise<AddDeviceStatusDto | null> {
|
||||||
|
try {
|
||||||
|
const device = await this.getDeviceByDeviceTuyaUuid(
|
||||||
|
addDeviceStatusDto.deviceTuyaUuid,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (device?.uuid) {
|
||||||
|
return await this.createDeviceStatusInOurDb({
|
||||||
|
deviceUuid: device.uuid,
|
||||||
|
...addDeviceStatusDto,
|
||||||
|
productType: device.productDevice.prodType,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// 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 addDeviceStatusToFirebase(
|
async addDeviceStatusToFirebase(
|
||||||
addDeviceStatusDto: AddDeviceStatusDto,
|
addDeviceStatusDto: AddDeviceStatusDto,
|
||||||
): Promise<AddDeviceStatusDto | null> {
|
): Promise<AddDeviceStatusDto | null> {
|
||||||
@ -211,6 +233,13 @@ export class DeviceStatusFirebaseService {
|
|||||||
return existingData;
|
return existingData;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Return the updated data
|
||||||
|
const snapshot: DataSnapshot = await get(dataRef);
|
||||||
|
return snapshot.val();
|
||||||
|
}
|
||||||
|
async createDeviceStatusInOurDb(
|
||||||
|
addDeviceStatusDto: AddDeviceStatusDto,
|
||||||
|
): Promise<any> {
|
||||||
// Save logs to your repository
|
// Save logs to your repository
|
||||||
const newLogs = addDeviceStatusDto.log.properties.map((property) => {
|
const newLogs = addDeviceStatusDto.log.properties.map((property) => {
|
||||||
return this.deviceStatusLogRepository.create({
|
return this.deviceStatusLogRepository.create({
|
||||||
@ -269,8 +298,5 @@ export class DeviceStatusFirebaseService {
|
|||||||
addDeviceStatusDto.deviceUuid,
|
addDeviceStatusDto.deviceUuid,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// Return the updated data
|
|
||||||
const snapshot: DataSnapshot = await get(dataRef);
|
|
||||||
return snapshot.val();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -16,7 +16,7 @@ export class SosHandlerService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleSosEvent(devId: string, logData: any): Promise<void> {
|
async handleSosEventFirebase(devId: string, logData: any): Promise<void> {
|
||||||
try {
|
try {
|
||||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
||||||
deviceTuyaUuid: devId,
|
deviceTuyaUuid: devId,
|
||||||
@ -39,4 +39,28 @@ export class SosHandlerService {
|
|||||||
this.logger.error('Failed to send SOS true value', err);
|
this.logger.error('Failed to send SOS true value', err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async handleSosEventOurDb(devId: string, logData: any): Promise<void> {
|
||||||
|
try {
|
||||||
|
await this.deviceStatusFirebaseService.addDeviceStatusToOurDb({
|
||||||
|
deviceTuyaUuid: devId,
|
||||||
|
status: [{ code: 'sos', value: true }],
|
||||||
|
log: logData,
|
||||||
|
});
|
||||||
|
|
||||||
|
setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
await this.deviceStatusFirebaseService.addDeviceStatusToOurDb({
|
||||||
|
deviceTuyaUuid: devId,
|
||||||
|
status: [{ code: 'sos', value: false }],
|
||||||
|
log: logData,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.error('Failed to send SOS false value', err);
|
||||||
|
}
|
||||||
|
}, 2000);
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.error('Failed to send SOS true value', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,6 +9,14 @@ export class TuyaWebSocketService {
|
|||||||
private client: any;
|
private client: any;
|
||||||
private readonly isDevEnv: boolean;
|
private readonly isDevEnv: boolean;
|
||||||
|
|
||||||
|
private messageQueue: {
|
||||||
|
devId: string;
|
||||||
|
status: any;
|
||||||
|
logData: any;
|
||||||
|
}[] = [];
|
||||||
|
|
||||||
|
private isProcessing = false;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly configService: ConfigService,
|
private readonly configService: ConfigService,
|
||||||
private readonly deviceStatusFirebaseService: DeviceStatusFirebaseService,
|
private readonly deviceStatusFirebaseService: DeviceStatusFirebaseService,
|
||||||
@ -26,12 +34,12 @@ export class TuyaWebSocketService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (this.configService.get<string>('tuya-config.TRUN_ON_TUYA_SOCKET')) {
|
if (this.configService.get<string>('tuya-config.TRUN_ON_TUYA_SOCKET')) {
|
||||||
// Set up event handlers
|
|
||||||
this.setupEventHandlers();
|
this.setupEventHandlers();
|
||||||
|
|
||||||
// Start receiving messages
|
|
||||||
this.client.start();
|
this.client.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Trigger the queue processor every 2 seconds
|
||||||
|
setInterval(() => this.processQueue(), 10000);
|
||||||
}
|
}
|
||||||
|
|
||||||
private setupEventHandlers() {
|
private setupEventHandlers() {
|
||||||
@ -43,10 +51,10 @@ export class TuyaWebSocketService {
|
|||||||
this.client.message(async (ws: WebSocket, message: any) => {
|
this.client.message(async (ws: WebSocket, message: any) => {
|
||||||
try {
|
try {
|
||||||
const { devId, status, logData } = this.extractMessageData(message);
|
const { devId, status, logData } = this.extractMessageData(message);
|
||||||
|
|
||||||
if (this.sosHandlerService.isSosTriggered(status)) {
|
if (this.sosHandlerService.isSosTriggered(status)) {
|
||||||
await this.sosHandlerService.handleSosEvent(devId, logData);
|
await this.sosHandlerService.handleSosEventFirebase(devId, logData);
|
||||||
} else {
|
} else {
|
||||||
|
// Firebase real-time update
|
||||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
||||||
deviceTuyaUuid: devId,
|
deviceTuyaUuid: devId,
|
||||||
status: status,
|
status: status,
|
||||||
@ -54,9 +62,13 @@ export class TuyaWebSocketService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Push to internal queue
|
||||||
|
this.messageQueue.push({ devId, status, logData });
|
||||||
|
|
||||||
|
// Acknowledge the message
|
||||||
this.client.ackMessage(message.messageId);
|
this.client.ackMessage(message.messageId);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error processing message:', error);
|
console.error('Error receiving message:', error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -80,6 +92,38 @@ export class TuyaWebSocketService {
|
|||||||
console.error('WebSocket error:', error);
|
console.error('WebSocket error:', error);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
private async processQueue() {
|
||||||
|
if (this.isProcessing || this.messageQueue.length === 0) return;
|
||||||
|
|
||||||
|
this.isProcessing = true;
|
||||||
|
|
||||||
|
const batch = [...this.messageQueue];
|
||||||
|
this.messageQueue = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (const item of batch) {
|
||||||
|
if (this.sosHandlerService.isSosTriggered(item.status)) {
|
||||||
|
await this.sosHandlerService.handleSosEventOurDb(
|
||||||
|
item.devId,
|
||||||
|
item.logData,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
await this.deviceStatusFirebaseService.addDeviceStatusToOurDb({
|
||||||
|
deviceTuyaUuid: item.devId,
|
||||||
|
status: item.status,
|
||||||
|
log: item.logData,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error processing batch:', error);
|
||||||
|
// Re-add the batch to the queue for retry
|
||||||
|
this.messageQueue.unshift(...batch);
|
||||||
|
} finally {
|
||||||
|
this.isProcessing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private extractMessageData(message: any): {
|
private extractMessageData(message: any): {
|
||||||
devId: string;
|
devId: string;
|
||||||
status: any;
|
status: any;
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
WITH params AS (
|
WITH params AS (
|
||||||
SELECT
|
SELECT
|
||||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date,
|
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date
|
||||||
$2::uuid AS space_id
|
|
||||||
),
|
),
|
||||||
|
|
||||||
-- Query Pipeline Starts Here
|
-- Query Pipeline Starts Here
|
||||||
@ -277,7 +276,10 @@ SELECT
|
|||||||
a.daily_avg_ch2o,a.daily_max_ch2o, a.daily_min_ch2o
|
a.daily_avg_ch2o,a.daily_max_ch2o, a.daily_min_ch2o
|
||||||
FROM daily_percentages p
|
FROM daily_percentages p
|
||||||
LEFT JOIN daily_averages a
|
LEFT JOIN daily_averages a
|
||||||
ON p.space_id = a.space_id AND p.event_date = a.event_date
|
ON p.space_id = a.space_id
|
||||||
|
AND p.event_date = a.event_date
|
||||||
|
JOIN params
|
||||||
|
ON params.event_date = a.event_date
|
||||||
ORDER BY p.space_id, p.event_date)
|
ORDER BY p.space_id, p.event_date)
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
WITH params AS (
|
WITH params AS (
|
||||||
SELECT
|
SELECT
|
||||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date,
|
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date
|
||||||
$2::uuid AS space_id
|
|
||||||
),
|
),
|
||||||
|
|
||||||
presence_logs AS (
|
presence_logs AS (
|
||||||
@ -86,8 +85,7 @@ final_data AS (
|
|||||||
ROUND(LEAST(raw_occupied_seconds, 86400) / 86400.0 * 100, 2) AS occupancy_percentage
|
ROUND(LEAST(raw_occupied_seconds, 86400) / 86400.0 * 100, 2) AS occupancy_percentage
|
||||||
FROM summed_intervals s
|
FROM summed_intervals s
|
||||||
JOIN params p
|
JOIN params p
|
||||||
ON p.space_id = s.space_id
|
ON p.event_date = s.event_date
|
||||||
AND p.event_date = s.event_date
|
|
||||||
)
|
)
|
||||||
|
|
||||||
INSERT INTO public."space-daily-occupancy-duration" (
|
INSERT INTO public."space-daily-occupancy-duration" (
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
WITH params AS (
|
WITH params AS (
|
||||||
SELECT
|
SELECT
|
||||||
$1::uuid AS device_id,
|
|
||||||
$2::date AS target_date
|
$2::date AS target_date
|
||||||
),
|
),
|
||||||
total_energy AS (
|
total_energy AS (
|
||||||
@ -14,8 +13,7 @@ total_energy AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumed'
|
WHERE log.code = 'EnergyConsumed'
|
||||||
AND log.device_id = params.device_id
|
AND log.event_time::date = params.target_date
|
||||||
AND log.event_time::date = params.target_date
|
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
energy_phase_A AS (
|
energy_phase_A AS (
|
||||||
@ -29,8 +27,7 @@ energy_phase_A AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedA'
|
WHERE log.code = 'EnergyConsumedA'
|
||||||
AND log.device_id = params.device_id
|
AND log.event_time::date = params.target_date
|
||||||
AND log.event_time::date = params.target_date
|
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
energy_phase_B AS (
|
energy_phase_B AS (
|
||||||
@ -44,8 +41,7 @@ energy_phase_B AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedB'
|
WHERE log.code = 'EnergyConsumedB'
|
||||||
AND log.device_id = params.device_id
|
AND log.event_time::date = params.target_date
|
||||||
AND log.event_time::date = params.target_date
|
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
energy_phase_C AS (
|
energy_phase_C AS (
|
||||||
@ -59,8 +55,7 @@ energy_phase_C AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedC'
|
WHERE log.code = 'EnergyConsumedC'
|
||||||
AND log.device_id = params.device_id
|
AND log.event_time::date = params.target_date
|
||||||
AND log.event_time::date = params.target_date
|
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
final_data AS (
|
final_data AS (
|
||||||
|
@ -1,8 +1,6 @@
|
|||||||
WITH params AS (
|
WITH params AS (
|
||||||
SELECT
|
SELECT
|
||||||
$1::uuid AS device_id,
|
$2::date AS target_date
|
||||||
$2::date AS target_date,
|
|
||||||
$3::text AS target_hour
|
|
||||||
),
|
),
|
||||||
total_energy AS (
|
total_energy AS (
|
||||||
SELECT
|
SELECT
|
||||||
@ -15,9 +13,7 @@ total_energy AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumed'
|
WHERE log.code = 'EnergyConsumed'
|
||||||
AND log.device_id = params.device_id
|
|
||||||
AND log.event_time::date = params.target_date
|
AND log.event_time::date = params.target_date
|
||||||
AND EXTRACT(HOUR FROM log.event_time)::text = params.target_hour
|
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
energy_phase_A AS (
|
energy_phase_A AS (
|
||||||
@ -31,9 +27,7 @@ energy_phase_A AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedA'
|
WHERE log.code = 'EnergyConsumedA'
|
||||||
AND log.device_id = params.device_id
|
|
||||||
AND log.event_time::date = params.target_date
|
AND log.event_time::date = params.target_date
|
||||||
AND EXTRACT(HOUR FROM log.event_time)::text = params.target_hour
|
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
energy_phase_B AS (
|
energy_phase_B AS (
|
||||||
@ -47,9 +41,7 @@ energy_phase_B AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedB'
|
WHERE log.code = 'EnergyConsumedB'
|
||||||
AND log.device_id = params.device_id
|
|
||||||
AND log.event_time::date = params.target_date
|
AND log.event_time::date = params.target_date
|
||||||
AND EXTRACT(HOUR FROM log.event_time)::text = params.target_hour
|
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
energy_phase_C AS (
|
energy_phase_C AS (
|
||||||
@ -63,9 +55,7 @@ energy_phase_C AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedC'
|
WHERE log.code = 'EnergyConsumedC'
|
||||||
AND log.device_id = params.device_id
|
|
||||||
AND log.event_time::date = params.target_date
|
AND log.event_time::date = params.target_date
|
||||||
AND EXTRACT(HOUR FROM log.event_time)::text = params.target_hour
|
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
final_data AS (
|
final_data AS (
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
WITH params AS (
|
WITH params AS (
|
||||||
SELECT
|
SELECT
|
||||||
$1::uuid AS device_id,
|
|
||||||
$2::text AS target_month -- Format should match 'MM-YYYY'
|
$2::text AS target_month -- Format should match 'MM-YYYY'
|
||||||
),
|
),
|
||||||
total_energy AS (
|
total_energy AS (
|
||||||
@ -14,7 +13,6 @@ total_energy AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumed'
|
WHERE log.code = 'EnergyConsumed'
|
||||||
AND log.device_id = params.device_id
|
|
||||||
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
@ -29,7 +27,6 @@ energy_phase_A AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedA'
|
WHERE log.code = 'EnergyConsumedA'
|
||||||
AND log.device_id = params.device_id
|
|
||||||
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
@ -44,7 +41,6 @@ energy_phase_B AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedB'
|
WHERE log.code = 'EnergyConsumedB'
|
||||||
AND log.device_id = params.device_id
|
|
||||||
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
@ -59,7 +55,6 @@ energy_phase_C AS (
|
|||||||
MAX(log.value)::integer AS max_value
|
MAX(log.value)::integer AS max_value
|
||||||
FROM "device-status-log" log, params
|
FROM "device-status-log" log, params
|
||||||
WHERE log.code = 'EnergyConsumedC'
|
WHERE log.code = 'EnergyConsumedC'
|
||||||
AND log.device_id = params.device_id
|
|
||||||
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
AND TO_CHAR(log.event_time, 'MM-YYYY') = params.target_month
|
||||||
GROUP BY 1,2,3,4,5
|
GROUP BY 1,2,3,4,5
|
||||||
),
|
),
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
-- 1. Load all presence-related logs
|
|
||||||
WITH device_logs AS (
|
WITH device_logs AS (
|
||||||
SELECT
|
SELECT
|
||||||
device.uuid AS device_id,
|
device.uuid AS device_id,
|
||||||
@ -16,7 +15,7 @@ WITH device_logs AS (
|
|||||||
AND "device-status-log".code = 'presence_state'
|
AND "device-status-log".code = 'presence_state'
|
||||||
),
|
),
|
||||||
|
|
||||||
-- 2. Standard transitions: 'none' → 'motion' or 'presence'
|
-- 1. All 'none' → presence or motion
|
||||||
presence_transitions AS (
|
presence_transitions AS (
|
||||||
SELECT
|
SELECT
|
||||||
space_id,
|
space_id,
|
||||||
@ -24,31 +23,10 @@ presence_transitions AS (
|
|||||||
event_time::date AS event_date,
|
event_time::date AS event_date,
|
||||||
value
|
value
|
||||||
FROM device_logs
|
FROM device_logs
|
||||||
WHERE value IN ('motion', 'presence') AND prev_value = 'none'
|
WHERE (value = 'motion' OR value = 'presence') AND prev_value = 'none'
|
||||||
),
|
),
|
||||||
|
|
||||||
-- 3. Fallback: days with 'motion' or 'presence' but no 'none'
|
-- 2. Cluster events per space_id within 30s
|
||||||
fallback_daily_presence AS (
|
|
||||||
SELECT
|
|
||||||
space_id,
|
|
||||||
event_time::date AS event_date,
|
|
||||||
MIN(event_time) AS event_time,
|
|
||||||
'presence'::text AS value
|
|
||||||
FROM device_logs
|
|
||||||
WHERE value IN ('motion', 'presence', 'none')
|
|
||||||
GROUP BY space_id, event_time::date
|
|
||||||
HAVING BOOL_OR(value = 'motion') OR BOOL_OR(value = 'presence')
|
|
||||||
AND NOT BOOL_OR(value = 'none')
|
|
||||||
),
|
|
||||||
|
|
||||||
-- 4. Merge both detection sources
|
|
||||||
all_presence_events AS (
|
|
||||||
SELECT * FROM presence_transitions
|
|
||||||
UNION ALL
|
|
||||||
SELECT space_id, event_time, event_date, value FROM fallback_daily_presence
|
|
||||||
),
|
|
||||||
|
|
||||||
-- 5. Cluster events per space_id within 30 seconds
|
|
||||||
clustered_events AS (
|
clustered_events AS (
|
||||||
SELECT
|
SELECT
|
||||||
space_id,
|
space_id,
|
||||||
@ -62,11 +40,11 @@ clustered_events AS (
|
|||||||
WHEN event_time - LAG(event_time) OVER (PARTITION BY space_id ORDER BY event_time) > INTERVAL '30 seconds'
|
WHEN event_time - LAG(event_time) OVER (PARTITION BY space_id ORDER BY event_time) > INTERVAL '30 seconds'
|
||||||
THEN 1 ELSE 0
|
THEN 1 ELSE 0
|
||||||
END AS new_cluster_flag
|
END AS new_cluster_flag
|
||||||
FROM all_presence_events
|
FROM presence_transitions
|
||||||
) marked
|
) marked
|
||||||
),
|
),
|
||||||
|
|
||||||
-- 6. Determine dominant type (motion vs presence) per cluster
|
-- 3. Determine dominant type (motion vs presence) per cluster
|
||||||
cluster_type AS (
|
cluster_type AS (
|
||||||
SELECT
|
SELECT
|
||||||
space_id,
|
space_id,
|
||||||
@ -82,7 +60,7 @@ cluster_type AS (
|
|||||||
GROUP BY space_id, event_date, cluster_id
|
GROUP BY space_id, event_date, cluster_id
|
||||||
),
|
),
|
||||||
|
|
||||||
-- 7. Count clusters by dominant type
|
-- 4. Count clusters by dominant type
|
||||||
summary AS (
|
summary AS (
|
||||||
SELECT
|
SELECT
|
||||||
space_id,
|
space_id,
|
||||||
@ -92,16 +70,15 @@ summary AS (
|
|||||||
COUNT(*) AS count_total_presence_detected
|
COUNT(*) AS count_total_presence_detected
|
||||||
FROM cluster_type
|
FROM cluster_type
|
||||||
GROUP BY space_id, event_date
|
GROUP BY space_id, event_date
|
||||||
),
|
|
||||||
|
|
||||||
-- 8. Prepare final result
|
|
||||||
final_table AS (
|
|
||||||
SELECT *
|
|
||||||
FROM summary
|
|
||||||
ORDER BY space_id, event_date
|
|
||||||
)
|
)
|
||||||
|
|
||||||
-- 9. Insert or upsert into the destination table
|
-- 5. Output
|
||||||
|
, final_table as (
|
||||||
|
SELECT *
|
||||||
|
FROM summary
|
||||||
|
ORDER BY space_id, event_date)
|
||||||
|
|
||||||
|
|
||||||
INSERT INTO public."presence-sensor-daily-space-detection" (
|
INSERT INTO public."presence-sensor-daily-space-detection" (
|
||||||
space_uuid,
|
space_uuid,
|
||||||
event_date,
|
event_date,
|
||||||
@ -120,4 +97,4 @@ ON CONFLICT (space_uuid, event_date) DO UPDATE
|
|||||||
SET
|
SET
|
||||||
count_motion_detected = EXCLUDED.count_motion_detected,
|
count_motion_detected = EXCLUDED.count_motion_detected,
|
||||||
count_presence_detected = EXCLUDED.count_presence_detected,
|
count_presence_detected = EXCLUDED.count_presence_detected,
|
||||||
count_total_presence_detected = EXCLUDED.count_total_presence_detected;
|
count_total_presence_detected = EXCLUDED.count_total_presence_detected;
|
@ -1,10 +1,8 @@
|
|||||||
WITH params AS (
|
WITH params AS (
|
||||||
SELECT
|
SELECT
|
||||||
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date,
|
TO_DATE(NULLIF($1, ''), 'YYYY-MM-DD') AS event_date
|
||||||
$2::uuid AS space_id
|
|
||||||
),
|
),
|
||||||
|
|
||||||
-- 1. Load logs
|
|
||||||
device_logs AS (
|
device_logs AS (
|
||||||
SELECT
|
SELECT
|
||||||
device.uuid AS device_id,
|
device.uuid AS device_id,
|
||||||
@ -22,7 +20,7 @@ device_logs AS (
|
|||||||
AND "device-status-log".code = 'presence_state'
|
AND "device-status-log".code = 'presence_state'
|
||||||
),
|
),
|
||||||
|
|
||||||
-- 2. Transitions from 'none' → motion/presence
|
-- 1. All 'none' → presence or motion
|
||||||
presence_transitions AS (
|
presence_transitions AS (
|
||||||
SELECT
|
SELECT
|
||||||
space_id,
|
space_id,
|
||||||
@ -30,30 +28,10 @@ presence_transitions AS (
|
|||||||
event_time::date AS event_date,
|
event_time::date AS event_date,
|
||||||
value
|
value
|
||||||
FROM device_logs
|
FROM device_logs
|
||||||
WHERE value IN ('motion', 'presence') AND prev_value = 'none'
|
WHERE (value = 'motion' OR value = 'presence') AND prev_value = 'none'
|
||||||
),
|
),
|
||||||
|
|
||||||
-- 3. Fallback: days with motion/presence but no 'none'
|
-- 2. Cluster events per space_id within 30s
|
||||||
fallback_daily_presence AS (
|
|
||||||
SELECT
|
|
||||||
space_id,
|
|
||||||
event_time::date AS event_date,
|
|
||||||
MIN(event_time) AS event_time,
|
|
||||||
'presence'::text AS value
|
|
||||||
FROM device_logs
|
|
||||||
GROUP BY space_id, event_time::date
|
|
||||||
HAVING BOOL_OR(value = 'motion') OR BOOL_OR(value = 'presence')
|
|
||||||
AND NOT BOOL_OR(value = 'none')
|
|
||||||
),
|
|
||||||
|
|
||||||
-- 4. Combine standard and fallback detections
|
|
||||||
all_presence_events AS (
|
|
||||||
SELECT * FROM presence_transitions
|
|
||||||
UNION ALL
|
|
||||||
SELECT * FROM fallback_daily_presence
|
|
||||||
),
|
|
||||||
|
|
||||||
-- 5. Cluster detections (within 30s)
|
|
||||||
clustered_events AS (
|
clustered_events AS (
|
||||||
SELECT
|
SELECT
|
||||||
space_id,
|
space_id,
|
||||||
@ -67,11 +45,11 @@ clustered_events AS (
|
|||||||
WHEN event_time - LAG(event_time) OVER (PARTITION BY space_id ORDER BY event_time) > INTERVAL '30 seconds'
|
WHEN event_time - LAG(event_time) OVER (PARTITION BY space_id ORDER BY event_time) > INTERVAL '30 seconds'
|
||||||
THEN 1 ELSE 0
|
THEN 1 ELSE 0
|
||||||
END AS new_cluster_flag
|
END AS new_cluster_flag
|
||||||
FROM all_presence_events
|
FROM presence_transitions
|
||||||
) marked
|
) marked
|
||||||
),
|
),
|
||||||
|
|
||||||
-- 6. Dominant type per cluster
|
-- 3. Determine dominant type (motion vs presence) per cluster
|
||||||
cluster_type AS (
|
cluster_type AS (
|
||||||
SELECT
|
SELECT
|
||||||
space_id,
|
space_id,
|
||||||
@ -87,7 +65,7 @@ cluster_type AS (
|
|||||||
GROUP BY space_id, event_date, cluster_id
|
GROUP BY space_id, event_date, cluster_id
|
||||||
),
|
),
|
||||||
|
|
||||||
-- 7. Count presence by type
|
-- 4. Count clusters by dominant type
|
||||||
summary AS (
|
summary AS (
|
||||||
SELECT
|
SELECT
|
||||||
space_id,
|
space_id,
|
||||||
@ -97,22 +75,21 @@ summary AS (
|
|||||||
COUNT(*) AS count_total_presence_detected
|
COUNT(*) AS count_total_presence_detected
|
||||||
FROM cluster_type
|
FROM cluster_type
|
||||||
GROUP BY space_id, event_date
|
GROUP BY space_id, event_date
|
||||||
),
|
|
||||||
|
|
||||||
-- 8. Filter by params and return final table
|
|
||||||
final_table AS (
|
|
||||||
SELECT
|
|
||||||
summary.space_id,
|
|
||||||
summary.event_date,
|
|
||||||
count_motion_detected,
|
|
||||||
count_presence_detected,
|
|
||||||
count_total_presence_detected
|
|
||||||
FROM summary
|
|
||||||
JOIN params p ON summary.space_id = p.space_id
|
|
||||||
WHERE p.event_date IS NULL OR summary.event_date = p.event_date
|
|
||||||
)
|
)
|
||||||
|
|
||||||
-- 9. Insert or upsert into the table
|
-- 5. Output
|
||||||
|
, final_table as (
|
||||||
|
SELECT summary.space_id,
|
||||||
|
summary.event_date,
|
||||||
|
count_motion_detected,
|
||||||
|
count_presence_detected,
|
||||||
|
count_total_presence_detected
|
||||||
|
FROM summary
|
||||||
|
JOIN params P ON true
|
||||||
|
where (P.event_date IS NULL or summary.event_date::date = P.event_date)
|
||||||
|
ORDER BY space_id, event_date)
|
||||||
|
|
||||||
|
|
||||||
INSERT INTO public."presence-sensor-daily-space-detection" (
|
INSERT INTO public."presence-sensor-daily-space-detection" (
|
||||||
space_uuid,
|
space_uuid,
|
||||||
event_date,
|
event_date,
|
||||||
|
@ -30,19 +30,6 @@ presence_detection AS (
|
|||||||
FROM device_logs
|
FROM device_logs
|
||||||
),
|
),
|
||||||
|
|
||||||
fallback_daily_presence AS (
|
|
||||||
SELECT
|
|
||||||
space_id,
|
|
||||||
event_time::date AS event_date,
|
|
||||||
0 AS event_hour,
|
|
||||||
COUNT(*) > 0 AS has_presence,
|
|
||||||
BOOL_OR(value = 'none') AS has_none
|
|
||||||
FROM device_logs
|
|
||||||
WHERE value IN ('motion', 'presence', 'none')
|
|
||||||
GROUP BY space_id, event_time::date
|
|
||||||
HAVING COUNT(*) > 0 AND NOT BOOL_OR(value = 'none')
|
|
||||||
),
|
|
||||||
|
|
||||||
space_level_presence_events AS (
|
space_level_presence_events AS (
|
||||||
SELECT DISTINCT
|
SELECT DISTINCT
|
||||||
pd.space_id,
|
pd.space_id,
|
||||||
@ -51,15 +38,6 @@ space_level_presence_events AS (
|
|||||||
pd.event_time
|
pd.event_time
|
||||||
FROM presence_detection pd
|
FROM presence_detection pd
|
||||||
WHERE presence_started = 1
|
WHERE presence_started = 1
|
||||||
|
|
||||||
UNION
|
|
||||||
|
|
||||||
SELECT
|
|
||||||
fdp.space_id,
|
|
||||||
fdp.event_date,
|
|
||||||
fdp.event_hour,
|
|
||||||
NULL::timestamp AS event_time
|
|
||||||
FROM fallback_daily_presence fdp
|
|
||||||
),
|
),
|
||||||
|
|
||||||
space_level_presence_summary AS (
|
space_level_presence_summary AS (
|
||||||
@ -99,4 +77,3 @@ LEFT JOIN space_level_presence_summary pds
|
|||||||
ORDER BY space_id, event_date, event_hour;
|
ORDER BY space_id, event_date, event_hour;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
import { SeederModule } from '@app/common/seed/seeder.module';
|
import { SeederModule } from '@app/common/seed/seeder.module';
|
||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { ConfigModule } from '@nestjs/config';
|
import { ConfigModule } from '@nestjs/config';
|
||||||
import { APP_INTERCEPTOR } from '@nestjs/core';
|
import { APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
|
||||||
import { WinstonModule } from 'nest-winston';
|
import { WinstonModule } from 'nest-winston';
|
||||||
import { AuthenticationModule } from './auth/auth.module';
|
import { AuthenticationModule } from './auth/auth.module';
|
||||||
import { AutomationModule } from './automation/automation.module';
|
import { AutomationModule } from './automation/automation.module';
|
||||||
@ -35,6 +35,9 @@ import { UserNotificationModule } from './user-notification/user-notification.mo
|
|||||||
import { UserModule } from './users/user.module';
|
import { UserModule } from './users/user.module';
|
||||||
import { VisitorPasswordModule } from './vistor-password/visitor-password.module';
|
import { VisitorPasswordModule } from './vistor-password/visitor-password.module';
|
||||||
|
|
||||||
|
import { ThrottlerGuard } from '@nestjs/throttler';
|
||||||
|
import { ThrottlerModule } from '@nestjs/throttler/dist/throttler.module';
|
||||||
|
import { isArray } from 'class-validator';
|
||||||
import { winstonLoggerOptions } from '../libs/common/src/logger/services/winston.logger';
|
import { winstonLoggerOptions } from '../libs/common/src/logger/services/winston.logger';
|
||||||
import { AqiModule } from './aqi/aqi.module';
|
import { AqiModule } from './aqi/aqi.module';
|
||||||
import { OccupancyModule } from './occupancy/occupancy.module';
|
import { OccupancyModule } from './occupancy/occupancy.module';
|
||||||
@ -44,9 +47,18 @@ import { WeatherModule } from './weather/weather.module';
|
|||||||
ConfigModule.forRoot({
|
ConfigModule.forRoot({
|
||||||
load: config,
|
load: config,
|
||||||
}),
|
}),
|
||||||
/* ThrottlerModule.forRoot({
|
ThrottlerModule.forRoot({
|
||||||
throttlers: [{ ttl: 100000, limit: 30 }],
|
throttlers: [{ ttl: 60000, limit: 30 }],
|
||||||
}), */
|
generateKey: (context) => {
|
||||||
|
const req = context.switchToHttp().getRequest();
|
||||||
|
console.log('Real IP:', req.headers['x-forwarded-for']);
|
||||||
|
return req.headers['x-forwarded-for']
|
||||||
|
? isArray(req.headers['x-forwarded-for'])
|
||||||
|
? req.headers['x-forwarded-for'][0].split(':')[0]
|
||||||
|
: req.headers['x-forwarded-for'].split(':')[0]
|
||||||
|
: req.ip;
|
||||||
|
},
|
||||||
|
}),
|
||||||
WinstonModule.forRoot(winstonLoggerOptions),
|
WinstonModule.forRoot(winstonLoggerOptions),
|
||||||
ClientModule,
|
ClientModule,
|
||||||
AuthenticationModule,
|
AuthenticationModule,
|
||||||
@ -88,10 +100,10 @@ import { WeatherModule } from './weather/weather.module';
|
|||||||
provide: APP_INTERCEPTOR,
|
provide: APP_INTERCEPTOR,
|
||||||
useClass: LoggingInterceptor,
|
useClass: LoggingInterceptor,
|
||||||
},
|
},
|
||||||
/* {
|
{
|
||||||
provide: APP_GUARD,
|
provide: APP_GUARD,
|
||||||
useClass: ThrottlerGuard,
|
useClass: ThrottlerGuard,
|
||||||
}, */
|
},
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class AppModule {}
|
export class AppModule {}
|
||||||
|
@ -190,24 +190,26 @@ export class CommunityService {
|
|||||||
.distinct(true);
|
.distinct(true);
|
||||||
|
|
||||||
if (includeSpaces) {
|
if (includeSpaces) {
|
||||||
qb.leftJoinAndSelect('c.spaces', 'space', 'space.disabled = false')
|
qb.leftJoinAndSelect(
|
||||||
|
'c.spaces',
|
||||||
|
'space',
|
||||||
|
'space.disabled = :disabled AND space.spaceName != :orphanSpaceName',
|
||||||
|
{ disabled: false, orphanSpaceName: ORPHAN_SPACE_NAME },
|
||||||
|
)
|
||||||
.leftJoinAndSelect('space.parent', 'parent')
|
.leftJoinAndSelect('space.parent', 'parent')
|
||||||
.leftJoinAndSelect(
|
.leftJoinAndSelect(
|
||||||
'space.children',
|
'space.children',
|
||||||
'children',
|
'children',
|
||||||
'children.disabled = :disabled',
|
'children.disabled = :disabled',
|
||||||
{ disabled: false },
|
{ disabled: false },
|
||||||
)
|
);
|
||||||
// .leftJoinAndSelect('space.spaceModel', 'spaceModel')
|
// .leftJoinAndSelect('space.spaceModel', 'spaceModel')
|
||||||
.andWhere('space.spaceName != :orphanSpaceName', {
|
|
||||||
orphanSpaceName: ORPHAN_SPACE_NAME,
|
|
||||||
})
|
|
||||||
.andWhere('space.disabled = :disabled', { disabled: false });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (search) {
|
if (search) {
|
||||||
qb.andWhere(
|
qb.andWhere(
|
||||||
`c.name ILIKE '%${search}%' ${includeSpaces ? "OR space.space_name ILIKE '%" + search + "%'" : ''}`,
|
`c.name ILIKE :search ${includeSpaces ? 'OR space.space_name ILIKE :search' : ''}`,
|
||||||
|
{ search },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -215,12 +217,21 @@ export class CommunityService {
|
|||||||
|
|
||||||
const { baseResponseDto, paginationResponseDto } =
|
const { baseResponseDto, paginationResponseDto } =
|
||||||
await customModel.findAll({ ...pageable, modelName: 'community' }, qb);
|
await customModel.findAll({ ...pageable, modelName: 'community' }, qb);
|
||||||
|
if (includeSpaces) {
|
||||||
|
baseResponseDto.data = baseResponseDto.data.map((community) => ({
|
||||||
|
...community,
|
||||||
|
spaces: this.spaceService.buildSpaceHierarchy(community.spaces || []),
|
||||||
|
}));
|
||||||
|
}
|
||||||
return new PageResponse<CommunityDto>(
|
return new PageResponse<CommunityDto>(
|
||||||
baseResponseDto,
|
baseResponseDto,
|
||||||
paginationResponseDto,
|
paginationResponseDto,
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Generic error handling
|
// Generic error handling
|
||||||
|
if (error instanceof HttpException) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
throw new HttpException(
|
throw new HttpException(
|
||||||
error.message || 'An error occurred while fetching communities.',
|
error.message || 'An error occurred while fetching communities.',
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
|
28
src/device/commands/cur2-commands.ts
Normal file
28
src/device/commands/cur2-commands.ts
Normal 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';
|
||||||
|
}
|
@ -1,11 +1,11 @@
|
|||||||
import { DeviceService } from '../services/device.service';
|
|
||||||
import { Controller, Get, Param, Query, UseGuards } from '@nestjs/common';
|
|
||||||
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
|
|
||||||
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
|
|
||||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||||
import { PermissionsGuard } from 'src/guards/permissions.guard';
|
import { EnableDisableStatusEnum } from '@app/common/constants/days.enum';
|
||||||
|
import { Controller, Get, Param, Query, UseGuards } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
import { Permissions } from 'src/decorators/permissions.decorator';
|
import { Permissions } from 'src/decorators/permissions.decorator';
|
||||||
import { GetDoorLockDevices, ProjectParam } from '../dtos';
|
import { PermissionsGuard } from 'src/guards/permissions.guard';
|
||||||
|
import { GetDevicesFilterDto, ProjectParam } from '../dtos';
|
||||||
|
import { DeviceService } from '../services/device.service';
|
||||||
|
|
||||||
@ApiTags('Device Module')
|
@ApiTags('Device Module')
|
||||||
@Controller({
|
@Controller({
|
||||||
@ -25,7 +25,7 @@ export class DeviceProjectController {
|
|||||||
})
|
})
|
||||||
async getAllDevices(
|
async getAllDevices(
|
||||||
@Param() param: ProjectParam,
|
@Param() param: ProjectParam,
|
||||||
@Query() query: GetDoorLockDevices,
|
@Query() query: GetDevicesFilterDto,
|
||||||
) {
|
) {
|
||||||
return await this.deviceService.getAllDevices(param, query);
|
return await this.deviceService.getAllDevices(param, query);
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
import { DeviceTypeEnum } from '@app/common/constants/device-type.enum';
|
import { DeviceTypeEnum } from '@app/common/constants/device-type.enum';
|
||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
import {
|
import {
|
||||||
|
IsArray,
|
||||||
IsEnum,
|
IsEnum,
|
||||||
IsNotEmpty,
|
IsNotEmpty,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
@ -41,16 +42,7 @@ export class GetDeviceLogsDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
public endTime: string;
|
public endTime: string;
|
||||||
}
|
}
|
||||||
export class GetDoorLockDevices {
|
|
||||||
@ApiProperty({
|
|
||||||
description: 'Device Type',
|
|
||||||
enum: DeviceTypeEnum,
|
|
||||||
required: false,
|
|
||||||
})
|
|
||||||
@IsEnum(DeviceTypeEnum)
|
|
||||||
@IsOptional()
|
|
||||||
public deviceType: DeviceTypeEnum;
|
|
||||||
}
|
|
||||||
export class GetDevicesBySpaceOrCommunityDto {
|
export class GetDevicesBySpaceOrCommunityDto {
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'Device Product Type',
|
description: 'Device Product Type',
|
||||||
@ -72,3 +64,23 @@ export class GetDevicesBySpaceOrCommunityDto {
|
|||||||
@IsNotEmpty({ message: 'Either spaceUuid or communityUuid must be provided' })
|
@IsNotEmpty({ message: 'Either spaceUuid or communityUuid must be provided' })
|
||||||
requireEither?: never; // This ensures at least one of them is provided
|
requireEither?: never; // This ensures at least one of them is provided
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class GetDevicesFilterDto {
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'Device Type',
|
||||||
|
enum: DeviceTypeEnum,
|
||||||
|
required: false,
|
||||||
|
})
|
||||||
|
@IsEnum(DeviceTypeEnum)
|
||||||
|
@IsOptional()
|
||||||
|
public deviceType: DeviceTypeEnum;
|
||||||
|
@ApiProperty({
|
||||||
|
description: 'List of Space IDs to filter devices',
|
||||||
|
required: false,
|
||||||
|
example: ['60d21b4667d0d8992e610c85', '60d21b4967d0d8992e610c86'],
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsUUID('4', { each: true })
|
||||||
|
public spaces?: string[];
|
||||||
|
}
|
||||||
|
@ -53,7 +53,7 @@ import { DeviceSceneParamDto } from '../dtos/device.param.dto';
|
|||||||
import {
|
import {
|
||||||
GetDeviceLogsDto,
|
GetDeviceLogsDto,
|
||||||
GetDevicesBySpaceOrCommunityDto,
|
GetDevicesBySpaceOrCommunityDto,
|
||||||
GetDoorLockDevices,
|
GetDevicesFilterDto,
|
||||||
} from '../dtos/get.device.dto';
|
} from '../dtos/get.device.dto';
|
||||||
import {
|
import {
|
||||||
controlDeviceInterface,
|
controlDeviceInterface,
|
||||||
@ -955,19 +955,20 @@ export class DeviceService {
|
|||||||
|
|
||||||
async getAllDevices(
|
async getAllDevices(
|
||||||
param: ProjectParam,
|
param: ProjectParam,
|
||||||
query: GetDoorLockDevices,
|
{ deviceType, spaces }: GetDevicesFilterDto,
|
||||||
): Promise<BaseResponseDto> {
|
): Promise<BaseResponseDto> {
|
||||||
try {
|
try {
|
||||||
await this.validateProject(param.projectUuid);
|
await this.validateProject(param.projectUuid);
|
||||||
if (query.deviceType === DeviceTypeEnum.DOOR_LOCK) {
|
if (deviceType === DeviceTypeEnum.DOOR_LOCK) {
|
||||||
return await this.getDoorLockDevices(param.projectUuid);
|
return await this.getDoorLockDevices(param.projectUuid, spaces);
|
||||||
} else if (!query.deviceType) {
|
} else if (!deviceType) {
|
||||||
const devices = await this.deviceRepository.find({
|
const devices = await this.deviceRepository.find({
|
||||||
where: {
|
where: {
|
||||||
isActive: true,
|
isActive: true,
|
||||||
spaceDevice: {
|
spaceDevice: {
|
||||||
community: { project: { uuid: param.projectUuid } },
|
uuid: spaces && spaces.length ? In(spaces) : undefined,
|
||||||
spaceName: Not(ORPHAN_SPACE_NAME),
|
spaceName: Not(ORPHAN_SPACE_NAME),
|
||||||
|
community: { project: { uuid: param.projectUuid } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
relations: [
|
relations: [
|
||||||
@ -1563,7 +1564,7 @@ export class DeviceService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async getDoorLockDevices(projectUuid: string) {
|
async getDoorLockDevices(projectUuid: string, spaces?: string[]) {
|
||||||
await this.validateProject(projectUuid);
|
await this.validateProject(projectUuid);
|
||||||
|
|
||||||
const devices = await this.deviceRepository.find({
|
const devices = await this.deviceRepository.find({
|
||||||
@ -1573,6 +1574,7 @@ export class DeviceService {
|
|||||||
},
|
},
|
||||||
spaceDevice: {
|
spaceDevice: {
|
||||||
spaceName: Not(ORPHAN_SPACE_NAME),
|
spaceName: Not(ORPHAN_SPACE_NAME),
|
||||||
|
uuid: spaces && spaces.length ? In(spaces) : undefined,
|
||||||
community: {
|
community: {
|
||||||
project: {
|
project: {
|
||||||
uuid: projectUuid,
|
uuid: projectUuid,
|
||||||
|
17
src/main.ts
17
src/main.ts
@ -3,7 +3,6 @@ import { SeederService } from '@app/common/seed/services/seeder.service';
|
|||||||
import { Logger, ValidationPipe } from '@nestjs/common';
|
import { Logger, ValidationPipe } from '@nestjs/common';
|
||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
import { json, urlencoded } from 'body-parser';
|
import { json, urlencoded } from 'body-parser';
|
||||||
import rateLimit from 'express-rate-limit';
|
|
||||||
import helmet from 'helmet';
|
import helmet from 'helmet';
|
||||||
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
|
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
|
||||||
import { setupSwaggerAuthentication } from '../libs/common/src/util/user-auth.swagger.utils';
|
import { setupSwaggerAuthentication } from '../libs/common/src/util/user-auth.swagger.utils';
|
||||||
@ -22,22 +21,6 @@ async function bootstrap() {
|
|||||||
|
|
||||||
app.use(new RequestContextMiddleware().use);
|
app.use(new RequestContextMiddleware().use);
|
||||||
|
|
||||||
app.use(
|
|
||||||
rateLimit({
|
|
||||||
windowMs: 5 * 60 * 1000,
|
|
||||||
max: 500,
|
|
||||||
standardHeaders: true,
|
|
||||||
legacyHeaders: false,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
app.use((req, res, next) => {
|
|
||||||
console.log('Real IP:', req.ip);
|
|
||||||
next();
|
|
||||||
});
|
|
||||||
|
|
||||||
app.getHttpAdapter().getInstance().set('trust proxy', 1);
|
|
||||||
|
|
||||||
app.use(
|
app.use(
|
||||||
helmet({
|
helmet({
|
||||||
contentSecurityPolicy: false,
|
contentSecurityPolicy: false,
|
||||||
|
32
src/schedule/constants/device-function-map.ts
Normal file
32
src/schedule/constants/device-function-map.ts
Normal 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;
|
||||||
|
};
|
@ -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,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -333,7 +333,12 @@ export class SpaceService {
|
|||||||
.andWhere('space.disabled = :disabled', { disabled: false });
|
.andWhere('space.disabled = :disabled', { disabled: false });
|
||||||
|
|
||||||
const space = await queryBuilder.getOne();
|
const space = await queryBuilder.getOne();
|
||||||
|
if (!space) {
|
||||||
|
throw new HttpException(
|
||||||
|
`Space with ID ${spaceUuid} not found`,
|
||||||
|
HttpStatus.NOT_FOUND,
|
||||||
|
);
|
||||||
|
}
|
||||||
return new SuccessResponseDto({
|
return new SuccessResponseDto({
|
||||||
message: `Space with ID ${spaceUuid} successfully fetched`,
|
message: `Space with ID ${spaceUuid} successfully fetched`,
|
||||||
data: space,
|
data: space,
|
||||||
@ -343,7 +348,7 @@ export class SpaceService {
|
|||||||
throw error; // If it's an HttpException, rethrow it
|
throw error; // If it's an HttpException, rethrow it
|
||||||
} else {
|
} else {
|
||||||
throw new HttpException(
|
throw new HttpException(
|
||||||
'An error occurred while deleting the community',
|
'An error occurred while fetching the space',
|
||||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -681,7 +686,7 @@ export class SpaceService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private buildSpaceHierarchy(spaces: SpaceEntity[]): SpaceEntity[] {
|
buildSpaceHierarchy(spaces: SpaceEntity[]): SpaceEntity[] {
|
||||||
const map = new Map<string, SpaceEntity>();
|
const map = new Map<string, SpaceEntity>();
|
||||||
|
|
||||||
// Step 1: Create a map of spaces by UUID
|
// Step 1: Create a map of spaces by UUID
|
||||||
|
Reference in New Issue
Block a user