mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-11 15:48:09 +00:00
Compare commits
19 Commits
add-queue-
...
temp-fix-t
Author | SHA1 | Date | |
---|---|---|---|
c0a069b460 | |||
324661e1ee | |||
a83424f45b | |||
71f6ccb4db | |||
68692b7c8b | |||
4d60c1ed54 | |||
27dbe04299 | |||
9bebcb2f3e | |||
43ab0030f0 | |||
c48adb73b5 | |||
d255e6811e | |||
e58d2d4831 | |||
147cf0b582 | |||
4e6b6f6ac5 | |||
932a3efd1c | |||
0a1ccad120 | |||
f337e6c681 | |||
f5bf857071 | |||
37b582f521 |
@ -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',
|
||||||
|
@ -126,7 +126,7 @@ import { VisitorPasswordEntity } from '../modules/visitor-password/entities';
|
|||||||
extra: {
|
extra: {
|
||||||
charset: 'utf8mb4',
|
charset: 'utf8mb4',
|
||||||
max: 100, // set pool max size
|
max: 100, // set pool max size
|
||||||
idleTimeoutMillis: 5000, // close idle clients after 5 second
|
idleTimeoutMillis: 3000, // 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)
|
||||||
},
|
},
|
||||||
|
@ -3,28 +3,12 @@ import { DeviceStatusFirebaseController } from './controllers/devices-status.con
|
|||||||
import { DeviceStatusFirebaseService } from './services/devices-status.service';
|
import { DeviceStatusFirebaseService } from './services/devices-status.service';
|
||||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories/device-status.repository';
|
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories/device-status.repository';
|
||||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
|
||||||
import {
|
|
||||||
PowerClampHourlyRepository,
|
|
||||||
PowerClampDailyRepository,
|
|
||||||
PowerClampMonthlyRepository,
|
|
||||||
} from '@app/common/modules/power-clamp/repositories';
|
|
||||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
|
||||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
|
||||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
providers: [
|
providers: [
|
||||||
DeviceStatusFirebaseService,
|
DeviceStatusFirebaseService,
|
||||||
DeviceRepository,
|
DeviceRepository,
|
||||||
DeviceStatusLogRepository,
|
DeviceStatusLogRepository,
|
||||||
PowerClampService,
|
|
||||||
PowerClampHourlyRepository,
|
|
||||||
PowerClampDailyRepository,
|
|
||||||
PowerClampMonthlyRepository,
|
|
||||||
SqlLoaderService,
|
|
||||||
OccupancyService,
|
|
||||||
AqiDataService,
|
|
||||||
],
|
],
|
||||||
controllers: [DeviceStatusFirebaseController],
|
controllers: [DeviceStatusFirebaseController],
|
||||||
exports: [DeviceStatusFirebaseService, DeviceStatusLogRepository],
|
exports: [DeviceStatusFirebaseService, DeviceStatusLogRepository],
|
||||||
|
@ -18,12 +18,6 @@ import {
|
|||||||
runTransaction,
|
runTransaction,
|
||||||
} from 'firebase/database';
|
} from 'firebase/database';
|
||||||
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
import { DeviceStatusLogRepository } from '@app/common/modules/device-status-log/repositories';
|
||||||
import { ProductType } from '@app/common/constants/product-type.enum';
|
|
||||||
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
|
||||||
import { PowerClampEnergyEnum } from '@app/common/constants/power.clamp.enargy.enum';
|
|
||||||
import { PresenceSensorEnum } from '@app/common/constants/presence.sensor.enum';
|
|
||||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
|
||||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class DeviceStatusFirebaseService {
|
export class DeviceStatusFirebaseService {
|
||||||
private tuya: TuyaContext;
|
private tuya: TuyaContext;
|
||||||
@ -31,9 +25,6 @@ export class DeviceStatusFirebaseService {
|
|||||||
constructor(
|
constructor(
|
||||||
private readonly configService: ConfigService,
|
private readonly configService: ConfigService,
|
||||||
private readonly deviceRepository: DeviceRepository,
|
private readonly deviceRepository: DeviceRepository,
|
||||||
private readonly powerClampService: PowerClampService,
|
|
||||||
private readonly occupancyService: OccupancyService,
|
|
||||||
private readonly aqiDataService: AqiDataService,
|
|
||||||
private deviceStatusLogRepository: DeviceStatusLogRepository,
|
private deviceStatusLogRepository: DeviceStatusLogRepository,
|
||||||
) {
|
) {
|
||||||
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
|
const accessKey = this.configService.get<string>('auth-config.ACCESS_KEY');
|
||||||
@ -76,47 +67,89 @@ export class DeviceStatusFirebaseService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async addDeviceStatusToOurDb(
|
async addBatchDeviceStatusToOurDb(
|
||||||
addDeviceStatusDto: AddDeviceStatusDto,
|
batch: { deviceTuyaUuid: string; status: any; log: any }[],
|
||||||
): Promise<AddDeviceStatusDto | null> {
|
deviceCache: Map<string, any>,
|
||||||
try {
|
): Promise<void> {
|
||||||
const device = await this.getDeviceByDeviceTuyaUuid(
|
const allLogs = [];
|
||||||
addDeviceStatusDto.deviceTuyaUuid,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (device?.uuid) {
|
console.log(
|
||||||
return await this.createDeviceStatusInOurDb({
|
`🧠 Preparing logs from batch of ${batch.length} items using cached devices only...`,
|
||||||
deviceUuid: device.uuid,
|
);
|
||||||
...addDeviceStatusDto,
|
|
||||||
productType: device.productDevice.prodType,
|
for (const item of batch) {
|
||||||
});
|
const device = deviceCache.get(item.deviceTuyaUuid);
|
||||||
|
|
||||||
|
if (!device?.uuid) {
|
||||||
|
console.log(
|
||||||
|
`⛔ Ignored unknown device in batch: ${item.deviceTuyaUuid}`,
|
||||||
|
);
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
// Return null if device not found or no UUID
|
|
||||||
return null;
|
const logs = item.log.properties.map((property) =>
|
||||||
} catch (error) {
|
this.deviceStatusLogRepository.create({
|
||||||
// Handle the error silently, perhaps log it internally or ignore it
|
deviceId: device.uuid,
|
||||||
return null;
|
deviceTuyaId: item.deviceTuyaUuid,
|
||||||
|
productId: item.log.productId,
|
||||||
|
log: item.log,
|
||||||
|
code: property.code,
|
||||||
|
value: property.value,
|
||||||
|
eventId: item.log.dataId,
|
||||||
|
eventTime: new Date(property.time).toISOString(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
allLogs.push(...logs);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log(`📝 Total logs to insert: ${allLogs.length}`);
|
||||||
|
const chunkSize = 300;
|
||||||
|
let insertedCount = 0;
|
||||||
|
|
||||||
|
for (let i = 0; i < allLogs.length; i += chunkSize) {
|
||||||
|
const chunk = allLogs.slice(i, i + chunkSize);
|
||||||
|
try {
|
||||||
|
const result = await this.deviceStatusLogRepository
|
||||||
|
.createQueryBuilder()
|
||||||
|
.insert()
|
||||||
|
.into('device-status-log') // or use DeviceStatusLogEntity
|
||||||
|
.values(chunk)
|
||||||
|
.orIgnore() // skip duplicates
|
||||||
|
.execute();
|
||||||
|
|
||||||
|
insertedCount += result.identifiers.length;
|
||||||
|
console.log(
|
||||||
|
`✅ Inserted ${result.identifiers.length} / ${chunk.length} logs (chunk)`,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Insert error (skipped chunk):', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`✅ Total logs inserted: ${insertedCount} / ${allLogs.length}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
async addDeviceStatusToFirebase(
|
async addDeviceStatusToFirebase(
|
||||||
addDeviceStatusDto: AddDeviceStatusDto,
|
addDeviceStatusDto: AddDeviceStatusDto,
|
||||||
|
deviceCache: Map<string, any>,
|
||||||
): Promise<AddDeviceStatusDto | null> {
|
): Promise<AddDeviceStatusDto | null> {
|
||||||
try {
|
try {
|
||||||
const device = await this.getDeviceByDeviceTuyaUuid(
|
const device = deviceCache.get(addDeviceStatusDto.deviceTuyaUuid);
|
||||||
addDeviceStatusDto.deviceTuyaUuid,
|
if (!device?.uuid) {
|
||||||
);
|
console.log(
|
||||||
|
`⛔ Skipping Firebase update for unknown device: ${addDeviceStatusDto.deviceTuyaUuid}`,
|
||||||
if (device?.uuid) {
|
);
|
||||||
return await this.createDeviceStatusFirebase({
|
return null;
|
||||||
deviceUuid: device.uuid,
|
|
||||||
...addDeviceStatusDto,
|
|
||||||
productType: device.productDevice.prodType,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
// Return null if device not found or no UUID
|
|
||||||
return null;
|
// Ensure product info and uuid are attached
|
||||||
|
addDeviceStatusDto.deviceUuid = device.uuid;
|
||||||
|
addDeviceStatusDto.productUuid = device.productDevice?.uuid;
|
||||||
|
addDeviceStatusDto.productType = device.productDevice?.prodType;
|
||||||
|
|
||||||
|
return await this.createDeviceStatusFirebase(addDeviceStatusDto);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Handle the error silently, perhaps log it internally or ignore it
|
console.error('❌ Error in addDeviceStatusToFirebase:', error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -237,66 +270,4 @@ export class DeviceStatusFirebaseService {
|
|||||||
const snapshot: DataSnapshot = await get(dataRef);
|
const snapshot: DataSnapshot = await get(dataRef);
|
||||||
return snapshot.val();
|
return snapshot.val();
|
||||||
}
|
}
|
||||||
async createDeviceStatusInOurDb(
|
|
||||||
addDeviceStatusDto: AddDeviceStatusDto,
|
|
||||||
): Promise<any> {
|
|
||||||
// Save logs to your repository
|
|
||||||
const newLogs = addDeviceStatusDto.log.properties.map((property) => {
|
|
||||||
return this.deviceStatusLogRepository.create({
|
|
||||||
deviceId: addDeviceStatusDto.deviceUuid,
|
|
||||||
deviceTuyaId: addDeviceStatusDto.deviceTuyaUuid,
|
|
||||||
productId: addDeviceStatusDto.log.productId,
|
|
||||||
log: addDeviceStatusDto.log,
|
|
||||||
code: property.code,
|
|
||||||
value: property.value,
|
|
||||||
eventId: addDeviceStatusDto.log.dataId,
|
|
||||||
eventTime: new Date(property.time).toISOString(),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
await this.deviceStatusLogRepository.save(newLogs);
|
|
||||||
|
|
||||||
if (addDeviceStatusDto.productType === ProductType.PC) {
|
|
||||||
const energyCodes = new Set([
|
|
||||||
PowerClampEnergyEnum.ENERGY_CONSUMED,
|
|
||||||
PowerClampEnergyEnum.ENERGY_CONSUMED_A,
|
|
||||||
PowerClampEnergyEnum.ENERGY_CONSUMED_B,
|
|
||||||
PowerClampEnergyEnum.ENERGY_CONSUMED_C,
|
|
||||||
]);
|
|
||||||
|
|
||||||
const energyStatus = addDeviceStatusDto?.log?.properties?.find((status) =>
|
|
||||||
energyCodes.has(status.code),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (energyStatus) {
|
|
||||||
await this.powerClampService.updateEnergyConsumedHistoricalData(
|
|
||||||
addDeviceStatusDto.deviceUuid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
addDeviceStatusDto.productType === ProductType.CPS ||
|
|
||||||
addDeviceStatusDto.productType === ProductType.WPS
|
|
||||||
) {
|
|
||||||
const occupancyCodes = new Set([PresenceSensorEnum.PRESENCE_STATE]);
|
|
||||||
|
|
||||||
const occupancyStatus = addDeviceStatusDto?.log?.properties?.find(
|
|
||||||
(status) => occupancyCodes.has(status.code),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (occupancyStatus) {
|
|
||||||
await this.occupancyService.updateOccupancySensorHistoricalData(
|
|
||||||
addDeviceStatusDto.deviceUuid,
|
|
||||||
);
|
|
||||||
await this.occupancyService.updateOccupancySensorHistoricalDurationData(
|
|
||||||
addDeviceStatusDto.deviceUuid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (addDeviceStatusDto.productType === ProductType.AQI) {
|
|
||||||
await this.aqiDataService.updateAQISensorHistoricalData(
|
|
||||||
addDeviceStatusDto.deviceUuid,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -8,7 +8,10 @@ import { TuyaWebSocketService } from './services/tuya.web.socket.service';
|
|||||||
import { OneSignalService } from './services/onesignal.service';
|
import { OneSignalService } from './services/onesignal.service';
|
||||||
import { DeviceMessagesService } from './services/device.messages.service';
|
import { DeviceMessagesService } from './services/device.messages.service';
|
||||||
import { DeviceRepositoryModule } from '../modules/device/device.repository.module';
|
import { DeviceRepositoryModule } from '../modules/device/device.repository.module';
|
||||||
import { DeviceNotificationRepository } from '../modules/device/repositories';
|
import {
|
||||||
|
DeviceNotificationRepository,
|
||||||
|
DeviceRepository,
|
||||||
|
} from '../modules/device/repositories';
|
||||||
import { DeviceStatusFirebaseModule } from '../firebase/devices-status/devices-status.module';
|
import { DeviceStatusFirebaseModule } from '../firebase/devices-status/devices-status.module';
|
||||||
import { CommunityPermissionService } from './services/community.permission.service';
|
import { CommunityPermissionService } from './services/community.permission.service';
|
||||||
import { CommunityRepository } from '../modules/community/repositories';
|
import { CommunityRepository } from '../modules/community/repositories';
|
||||||
@ -27,6 +30,7 @@ import { SosHandlerService } from './services/sos.handler.service';
|
|||||||
DeviceNotificationRepository,
|
DeviceNotificationRepository,
|
||||||
CommunityRepository,
|
CommunityRepository,
|
||||||
SosHandlerService,
|
SosHandlerService,
|
||||||
|
DeviceRepository,
|
||||||
],
|
],
|
||||||
exports: [
|
exports: [
|
||||||
HelperHashService,
|
HelperHashService,
|
||||||
|
@ -1,44 +1,63 @@
|
|||||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
|
||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { SqlLoaderService } from './sql-loader.service';
|
|
||||||
import { DataSource } from 'typeorm';
|
import { DataSource } from 'typeorm';
|
||||||
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
||||||
|
import { SqlLoaderService } from './sql-loader.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AqiDataService {
|
export class AqiDataService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly sqlLoader: SqlLoaderService,
|
private readonly sqlLoader: SqlLoaderService,
|
||||||
private readonly dataSource: DataSource,
|
private readonly dataSource: DataSource,
|
||||||
private readonly deviceRepository: DeviceRepository,
|
|
||||||
) {}
|
) {}
|
||||||
async updateAQISensorHistoricalData(deviceUuid: string): Promise<void> {
|
|
||||||
try {
|
|
||||||
const now = new Date();
|
|
||||||
const dateStr = now.toLocaleDateString('en-CA'); // YYYY-MM-DD
|
|
||||||
const device = await this.deviceRepository.findOne({
|
|
||||||
where: { uuid: deviceUuid },
|
|
||||||
relations: ['spaceDevice'],
|
|
||||||
});
|
|
||||||
|
|
||||||
await this.executeProcedure(
|
async updateAQISensorHistoricalData(): Promise<void> {
|
||||||
'fact_daily_space_aqi',
|
try {
|
||||||
'proceduce_update_daily_space_aqi',
|
const { dateStr } = this.getFormattedDates();
|
||||||
[dateStr, device.spaceDevice?.uuid],
|
|
||||||
);
|
// Execute all procedures in parallel
|
||||||
|
await Promise.all([
|
||||||
|
this.executeProcedureWithRetry(
|
||||||
|
'proceduce_update_daily_space_aqi',
|
||||||
|
[dateStr],
|
||||||
|
'fact_daily_space_aqi',
|
||||||
|
),
|
||||||
|
]);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to insert or update aqi data:', err);
|
console.error('Failed to update AQI sensor historical data:', err);
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
private getFormattedDates(): { dateStr: string } {
|
||||||
private async executeProcedure(
|
const now = new Date();
|
||||||
procedureFolderName: string,
|
return {
|
||||||
|
dateStr: now.toLocaleDateString('en-CA'), // YYYY-MM-DD
|
||||||
|
};
|
||||||
|
}
|
||||||
|
private async executeProcedureWithRetry(
|
||||||
procedureFileName: string,
|
procedureFileName: string,
|
||||||
params: (string | number | null)[],
|
params: (string | number | null)[],
|
||||||
|
folderName: string,
|
||||||
|
retries = 3,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const query = this.loadQuery(procedureFolderName, procedureFileName);
|
try {
|
||||||
await this.dataSource.query(query, params);
|
const query = this.loadQuery(folderName, procedureFileName);
|
||||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
await this.dataSource.query(query, params);
|
||||||
|
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||||
|
} catch (err) {
|
||||||
|
if (retries > 0) {
|
||||||
|
const delayMs = 1000 * (4 - retries); // Exponential backoff
|
||||||
|
console.warn(`Retrying ${procedureFileName} (${retries} retries left)`);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||||
|
return this.executeProcedureWithRetry(
|
||||||
|
procedureFileName,
|
||||||
|
params,
|
||||||
|
folderName,
|
||||||
|
retries - 1,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
console.error(`Failed to execute ${procedureFileName}:`, err);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private loadQuery(folderName: string, fileName: string): string {
|
private loadQuery(folderName: string, fileName: string): string {
|
||||||
|
@ -1,65 +1,68 @@
|
|||||||
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
|
||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { SqlLoaderService } from './sql-loader.service';
|
|
||||||
import { DataSource } from 'typeorm';
|
import { DataSource } from 'typeorm';
|
||||||
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
||||||
|
import { SqlLoaderService } from './sql-loader.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class OccupancyService {
|
export class OccupancyService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly sqlLoader: SqlLoaderService,
|
private readonly sqlLoader: SqlLoaderService,
|
||||||
private readonly dataSource: DataSource,
|
private readonly dataSource: DataSource,
|
||||||
private readonly deviceRepository: DeviceRepository,
|
|
||||||
) {}
|
) {}
|
||||||
async updateOccupancySensorHistoricalDurationData(
|
|
||||||
deviceUuid: string,
|
|
||||||
): Promise<void> {
|
|
||||||
try {
|
|
||||||
const now = new Date();
|
|
||||||
const dateStr = now.toLocaleDateString('en-CA'); // YYYY-MM-DD
|
|
||||||
const device = await this.deviceRepository.findOne({
|
|
||||||
where: { uuid: deviceUuid },
|
|
||||||
relations: ['spaceDevice'],
|
|
||||||
});
|
|
||||||
|
|
||||||
await this.executeProcedure(
|
async updateOccupancyDataProcedures(): Promise<void> {
|
||||||
'fact_daily_space_occupancy_duration',
|
try {
|
||||||
'procedure_update_daily_space_occupancy_duration',
|
const { dateStr } = this.getFormattedDates();
|
||||||
[dateStr, device.spaceDevice?.uuid],
|
|
||||||
);
|
// Execute all procedures in parallel
|
||||||
|
await Promise.all([
|
||||||
|
this.executeProcedureWithRetry(
|
||||||
|
'procedure_update_fact_space_occupancy',
|
||||||
|
[dateStr],
|
||||||
|
'fact_space_occupancy_count',
|
||||||
|
),
|
||||||
|
this.executeProcedureWithRetry(
|
||||||
|
'procedure_update_daily_space_occupancy_duration',
|
||||||
|
[dateStr],
|
||||||
|
'fact_daily_space_occupancy_duration',
|
||||||
|
),
|
||||||
|
]);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to insert or update occupancy duration data:', err);
|
console.error('Failed to update occupancy data:', err);
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async updateOccupancySensorHistoricalData(deviceUuid: string): Promise<void> {
|
private getFormattedDates(): { dateStr: string } {
|
||||||
try {
|
const now = new Date();
|
||||||
const now = new Date();
|
return {
|
||||||
const dateStr = now.toLocaleDateString('en-CA'); // YYYY-MM-DD
|
dateStr: now.toLocaleDateString('en-CA'), // YYYY-MM-DD
|
||||||
const device = await this.deviceRepository.findOne({
|
};
|
||||||
where: { uuid: deviceUuid },
|
|
||||||
relations: ['spaceDevice'],
|
|
||||||
});
|
|
||||||
|
|
||||||
await this.executeProcedure(
|
|
||||||
'fact_space_occupancy_count',
|
|
||||||
'procedure_update_fact_space_occupancy',
|
|
||||||
[dateStr, device.spaceDevice?.uuid],
|
|
||||||
);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Failed to insert or update occupancy data:', err);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
private async executeProcedureWithRetry(
|
||||||
private async executeProcedure(
|
|
||||||
procedureFolderName: string,
|
|
||||||
procedureFileName: string,
|
procedureFileName: string,
|
||||||
params: (string | number | null)[],
|
params: (string | number | null)[],
|
||||||
|
folderName: string,
|
||||||
|
retries = 3,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const query = this.loadQuery(procedureFolderName, procedureFileName);
|
try {
|
||||||
await this.dataSource.query(query, params);
|
const query = this.loadQuery(folderName, procedureFileName);
|
||||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
await this.dataSource.query(query, params);
|
||||||
|
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||||
|
} catch (err) {
|
||||||
|
if (retries > 0) {
|
||||||
|
const delayMs = 1000 * (4 - retries); // Exponential backoff
|
||||||
|
console.warn(`Retrying ${procedureFileName} (${retries} retries left)`);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||||
|
return this.executeProcedureWithRetry(
|
||||||
|
procedureFileName,
|
||||||
|
params,
|
||||||
|
folderName,
|
||||||
|
retries - 1,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
console.error(`Failed to execute ${procedureFileName}:`, err);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private loadQuery(folderName: string, fileName: string): string {
|
private loadQuery(folderName: string, fileName: string): string {
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { SqlLoaderService } from './sql-loader.service';
|
|
||||||
import { DataSource } from 'typeorm';
|
import { DataSource } from 'typeorm';
|
||||||
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
import { SQL_PROCEDURES_PATH } from '@app/common/constants/sql-query-path';
|
||||||
|
import { SqlLoaderService } from './sql-loader.service';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class PowerClampService {
|
export class PowerClampService {
|
||||||
@ -10,48 +10,72 @@ export class PowerClampService {
|
|||||||
private readonly dataSource: DataSource,
|
private readonly dataSource: DataSource,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async updateEnergyConsumedHistoricalData(deviceUuid: string): Promise<void> {
|
async updateEnergyConsumedHistoricalData(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const now = new Date();
|
const { dateStr, monthYear } = this.getFormattedDates();
|
||||||
const dateStr = now.toLocaleDateString('en-CA'); // YYYY-MM-DD
|
|
||||||
const hour = now.getHours();
|
|
||||||
const monthYear = now
|
|
||||||
.toLocaleDateString('en-US', {
|
|
||||||
month: '2-digit',
|
|
||||||
year: 'numeric',
|
|
||||||
})
|
|
||||||
.replace('/', '-'); // MM-YYYY
|
|
||||||
|
|
||||||
await this.executeProcedure(
|
// Execute all procedures in parallel
|
||||||
'fact_hourly_device_energy_consumed_procedure',
|
await Promise.all([
|
||||||
[deviceUuid, dateStr, hour],
|
this.executeProcedureWithRetry(
|
||||||
);
|
'fact_hourly_device_energy_consumed_procedure',
|
||||||
|
[dateStr],
|
||||||
await this.executeProcedure(
|
'fact_device_energy_consumed',
|
||||||
'fact_daily_device_energy_consumed_procedure',
|
),
|
||||||
[deviceUuid, dateStr],
|
this.executeProcedureWithRetry(
|
||||||
);
|
'fact_daily_device_energy_consumed_procedure',
|
||||||
|
[dateStr],
|
||||||
await this.executeProcedure(
|
'fact_device_energy_consumed',
|
||||||
'fact_monthly_device_energy_consumed_procedure',
|
),
|
||||||
[deviceUuid, monthYear],
|
this.executeProcedureWithRetry(
|
||||||
);
|
'fact_monthly_device_energy_consumed_procedure',
|
||||||
|
[monthYear],
|
||||||
|
'fact_device_energy_consumed',
|
||||||
|
),
|
||||||
|
]);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to insert or update energy data:', err);
|
console.error('Failed to update energy consumption data:', err);
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async executeProcedure(
|
private getFormattedDates(): { dateStr: string; monthYear: string } {
|
||||||
|
const now = new Date();
|
||||||
|
return {
|
||||||
|
dateStr: now.toLocaleDateString('en-CA'), // YYYY-MM-DD
|
||||||
|
monthYear: now
|
||||||
|
.toLocaleDateString('en-US', {
|
||||||
|
month: '2-digit',
|
||||||
|
year: 'numeric',
|
||||||
|
})
|
||||||
|
.replace('/', '-'), // MM-YYYY
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async executeProcedureWithRetry(
|
||||||
procedureFileName: string,
|
procedureFileName: string,
|
||||||
params: (string | number | null)[],
|
params: (string | number | null)[],
|
||||||
|
folderName: string,
|
||||||
|
retries = 3,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const query = this.loadQuery(
|
try {
|
||||||
'fact_device_energy_consumed',
|
const query = this.loadQuery(folderName, procedureFileName);
|
||||||
procedureFileName,
|
await this.dataSource.query(query, params);
|
||||||
);
|
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
||||||
await this.dataSource.query(query, params);
|
} catch (err) {
|
||||||
console.log(`Procedure ${procedureFileName} executed successfully.`);
|
if (retries > 0) {
|
||||||
|
const delayMs = 1000 * (4 - retries); // Exponential backoff
|
||||||
|
console.warn(`Retrying ${procedureFileName} (${retries} retries left)`);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||||
|
return this.executeProcedureWithRetry(
|
||||||
|
procedureFileName,
|
||||||
|
params,
|
||||||
|
folderName,
|
||||||
|
retries - 1,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
console.error(`Failed to execute ${procedureFileName}:`, err);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private loadQuery(folderName: string, fileName: string): string {
|
private loadQuery(folderName: string, fileName: string): string {
|
||||||
|
@ -16,45 +16,53 @@ export class SosHandlerService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleSosEventFirebase(devId: string, logData: any): Promise<void> {
|
async handleSosEventFirebase(
|
||||||
|
devId: string,
|
||||||
|
logData: any,
|
||||||
|
deviceCache: Map<string, any>,
|
||||||
|
): Promise<void> {
|
||||||
try {
|
try {
|
||||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase(
|
||||||
deviceTuyaUuid: devId,
|
{
|
||||||
status: [{ code: 'sos', value: true }],
|
deviceTuyaUuid: devId,
|
||||||
log: logData,
|
status: [{ code: 'sos', value: true }],
|
||||||
});
|
log: logData,
|
||||||
|
},
|
||||||
|
deviceCache,
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
deviceTuyaUuid: devId,
|
||||||
|
status: [{ code: 'sos', value: true }],
|
||||||
|
log: logData,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
deviceCache,
|
||||||
|
);
|
||||||
|
|
||||||
setTimeout(async () => {
|
setTimeout(async () => {
|
||||||
try {
|
try {
|
||||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase(
|
||||||
deviceTuyaUuid: devId,
|
{
|
||||||
status: [{ code: 'sos', value: false }],
|
deviceTuyaUuid: devId,
|
||||||
log: logData,
|
status: [{ code: 'sos', value: false }],
|
||||||
});
|
log: logData,
|
||||||
} catch (err) {
|
},
|
||||||
this.logger.error('Failed to send SOS false value', err);
|
deviceCache,
|
||||||
}
|
);
|
||||||
}, 2000);
|
|
||||||
} catch (err) {
|
|
||||||
this.logger.error('Failed to send SOS true value', err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async handleSosEventOurDb(devId: string, logData: any): Promise<void> {
|
await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb(
|
||||||
try {
|
[
|
||||||
await this.deviceStatusFirebaseService.addDeviceStatusToOurDb({
|
{
|
||||||
deviceTuyaUuid: devId,
|
deviceTuyaUuid: devId,
|
||||||
status: [{ code: 'sos', value: true }],
|
status: [{ code: 'sos', value: false }],
|
||||||
log: logData,
|
log: logData,
|
||||||
});
|
},
|
||||||
|
],
|
||||||
setTimeout(async () => {
|
deviceCache,
|
||||||
try {
|
);
|
||||||
await this.deviceStatusFirebaseService.addDeviceStatusToOurDb({
|
|
||||||
deviceTuyaUuid: devId,
|
|
||||||
status: [{ code: 'sos', value: false }],
|
|
||||||
log: logData,
|
|
||||||
});
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.error('Failed to send SOS false value', err);
|
this.logger.error('Failed to send SOS false value', err);
|
||||||
}
|
}
|
||||||
|
@ -3,6 +3,7 @@ import TuyaWebsocket from '../../config/tuya-web-socket-config';
|
|||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
import { DeviceStatusFirebaseService } from '@app/common/firebase/devices-status/services/devices-status.service';
|
||||||
import { SosHandlerService } from './sos.handler.service';
|
import { SosHandlerService } from './sos.handler.service';
|
||||||
|
import { DeviceRepository } from '@app/common/modules/device/repositories';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TuyaWebSocketService {
|
export class TuyaWebSocketService {
|
||||||
@ -16,11 +17,13 @@ export class TuyaWebSocketService {
|
|||||||
}[] = [];
|
}[] = [];
|
||||||
|
|
||||||
private isProcessing = false;
|
private isProcessing = false;
|
||||||
|
private deviceCache: Map<string, any> = new Map();
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly configService: ConfigService,
|
private readonly configService: ConfigService,
|
||||||
private readonly deviceStatusFirebaseService: DeviceStatusFirebaseService,
|
private readonly deviceStatusFirebaseService: DeviceStatusFirebaseService,
|
||||||
private readonly sosHandlerService: SosHandlerService,
|
private readonly sosHandlerService: SosHandlerService,
|
||||||
|
private readonly deviceRepository: DeviceRepository,
|
||||||
) {
|
) {
|
||||||
this.isDevEnv =
|
this.isDevEnv =
|
||||||
this.configService.get<string>('NODE_ENV') === 'development';
|
this.configService.get<string>('NODE_ENV') === 'development';
|
||||||
@ -33,13 +36,34 @@ export class TuyaWebSocketService {
|
|||||||
maxRetryTimes: 100,
|
maxRetryTimes: 100,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
this.loadAllActiveDevices();
|
||||||
|
|
||||||
|
// Reload device cache every 1 hour
|
||||||
|
setInterval(() => this.loadAllActiveDevices(), 60 * 60 * 1000);
|
||||||
|
|
||||||
if (this.configService.get<string>('tuya-config.TRUN_ON_TUYA_SOCKET')) {
|
if (this.configService.get<string>('tuya-config.TRUN_ON_TUYA_SOCKET')) {
|
||||||
this.setupEventHandlers();
|
this.setupEventHandlers();
|
||||||
this.client.start();
|
this.client.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Trigger the queue processor every 2 seconds
|
// Trigger the queue processor every 15 seconds
|
||||||
setInterval(() => this.processQueue(), 10000);
|
setInterval(() => this.processQueue(), 15000);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadAllActiveDevices(): Promise<void> {
|
||||||
|
const devices = await this.deviceRepository.find({
|
||||||
|
where: { isActive: true },
|
||||||
|
relations: ['productDevice'],
|
||||||
|
});
|
||||||
|
|
||||||
|
this.deviceCache.clear();
|
||||||
|
devices.forEach((device) => {
|
||||||
|
this.deviceCache.set(device.deviceTuyaUuid, device);
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`🔄 Device cache reloaded: ${this.deviceCache.size} active devices at ${new Date().toISOString()}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private setupEventHandlers() {
|
private setupEventHandlers() {
|
||||||
@ -51,15 +75,30 @@ 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 (!Array.isArray(logData?.properties)) return;
|
||||||
|
|
||||||
|
const device = this.deviceCache.get(devId);
|
||||||
|
if (!device) {
|
||||||
|
// console.log(`⛔ Ignored unknown device: ${devId}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (this.sosHandlerService.isSosTriggered(status)) {
|
if (this.sosHandlerService.isSosTriggered(status)) {
|
||||||
await this.sosHandlerService.handleSosEventFirebase(devId, logData);
|
await this.sosHandlerService.handleSosEventFirebase(
|
||||||
|
devId,
|
||||||
|
logData,
|
||||||
|
this.deviceCache,
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
// Firebase real-time update
|
// Firebase real-time update
|
||||||
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase({
|
await this.deviceStatusFirebaseService.addDeviceStatusToFirebase(
|
||||||
deviceTuyaUuid: devId,
|
{
|
||||||
status: status,
|
deviceTuyaUuid: devId,
|
||||||
log: logData,
|
status,
|
||||||
});
|
log: logData,
|
||||||
|
},
|
||||||
|
this.deviceCache,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Push to internal queue
|
// Push to internal queue
|
||||||
@ -93,32 +132,31 @@ export class TuyaWebSocketService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
private async processQueue() {
|
private async processQueue() {
|
||||||
if (this.isProcessing || this.messageQueue.length === 0) return;
|
if (this.isProcessing) {
|
||||||
|
console.log('⏳ Skipping: still processing previous batch');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.messageQueue.length === 0) return;
|
||||||
|
|
||||||
this.isProcessing = true;
|
this.isProcessing = true;
|
||||||
|
|
||||||
const batch = [...this.messageQueue];
|
const batch = [...this.messageQueue];
|
||||||
this.messageQueue = [];
|
this.messageQueue = [];
|
||||||
|
|
||||||
|
console.log(`🔁 Processing batch of size: ${batch.length}`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
for (const item of batch) {
|
await this.deviceStatusFirebaseService.addBatchDeviceStatusToOurDb(
|
||||||
if (this.sosHandlerService.isSosTriggered(item.status)) {
|
batch.map((item) => ({
|
||||||
await this.sosHandlerService.handleSosEventOurDb(
|
deviceTuyaUuid: item.devId,
|
||||||
item.devId,
|
status: item.status,
|
||||||
item.logData,
|
log: item.logData,
|
||||||
);
|
})),
|
||||||
} else {
|
this.deviceCache,
|
||||||
await this.deviceStatusFirebaseService.addDeviceStatusToOurDb({
|
);
|
||||||
deviceTuyaUuid: item.devId,
|
|
||||||
status: item.status,
|
|
||||||
log: item.logData,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error processing batch:', error);
|
console.error('❌ Error processing batch:', error);
|
||||||
// Re-add the batch to the queue for retry
|
this.messageQueue.unshift(...batch); // retry
|
||||||
this.messageQueue.unshift(...batch);
|
|
||||||
} finally {
|
} finally {
|
||||||
this.isProcessing = false;
|
this.isProcessing = false;
|
||||||
}
|
}
|
||||||
|
@ -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,7 +1,6 @@
|
|||||||
WITH params AS (
|
WITH params AS (
|
||||||
SELECT
|
SELECT
|
||||||
$1::uuid AS device_id,
|
$1::date AS target_date
|
||||||
$2::date AS target_date
|
|
||||||
),
|
),
|
||||||
total_energy AS (
|
total_energy AS (
|
||||||
SELECT
|
SELECT
|
||||||
@ -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,
|
$1::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,7 +1,6 @@
|
|||||||
WITH params AS (
|
WITH params AS (
|
||||||
SELECT
|
SELECT
|
||||||
$1::uuid AS device_id,
|
$1::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 (
|
||||||
SELECT
|
SELECT
|
||||||
@ -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,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
|
|
||||||
),
|
),
|
||||||
|
|
||||||
device_logs AS (
|
device_logs AS (
|
||||||
@ -87,8 +86,7 @@ SELECT summary.space_id,
|
|||||||
count_total_presence_detected
|
count_total_presence_detected
|
||||||
FROM summary
|
FROM summary
|
||||||
JOIN params P ON true
|
JOIN params P ON true
|
||||||
where summary.space_id = P.space_id
|
where (P.event_date IS NULL or summary.event_date::date = P.event_date)
|
||||||
and (P.event_date IS NULL or summary.event_date::date = P.event_date)
|
|
||||||
ORDER BY space_id, event_date)
|
ORDER BY space_id, event_date)
|
||||||
|
|
||||||
|
|
||||||
|
42
package-lock.json
generated
42
package-lock.json
generated
@ -18,6 +18,7 @@
|
|||||||
"@nestjs/jwt": "^10.2.0",
|
"@nestjs/jwt": "^10.2.0",
|
||||||
"@nestjs/passport": "^10.0.3",
|
"@nestjs/passport": "^10.0.3",
|
||||||
"@nestjs/platform-express": "^10.0.0",
|
"@nestjs/platform-express": "^10.0.0",
|
||||||
|
"@nestjs/schedule": "^6.0.0",
|
||||||
"@nestjs/swagger": "^7.3.0",
|
"@nestjs/swagger": "^7.3.0",
|
||||||
"@nestjs/terminus": "^11.0.0",
|
"@nestjs/terminus": "^11.0.0",
|
||||||
"@nestjs/throttler": "^6.4.0",
|
"@nestjs/throttler": "^6.4.0",
|
||||||
@ -2538,6 +2539,19 @@
|
|||||||
"@nestjs/core": "^10.0.0"
|
"@nestjs/core": "^10.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@nestjs/schedule": {
|
||||||
|
"version": "6.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@nestjs/schedule/-/schedule-6.0.0.tgz",
|
||||||
|
"integrity": "sha512-aQySMw6tw2nhitELXd3EiRacQRgzUKD9mFcUZVOJ7jPLqIBvXOyvRWLsK9SdurGA+jjziAlMef7iB5ZEFFoQpw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"cron": "4.3.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@nestjs/common": "^10.0.0 || ^11.0.0",
|
||||||
|
"@nestjs/core": "^10.0.0 || ^11.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@nestjs/schematics": {
|
"node_modules/@nestjs/schematics": {
|
||||||
"version": "10.2.3",
|
"version": "10.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/@nestjs/schematics/-/schematics-10.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/@nestjs/schematics/-/schematics-10.2.3.tgz",
|
||||||
@ -3215,6 +3229,12 @@
|
|||||||
"@types/node": "*"
|
"@types/node": "*"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/luxon": {
|
||||||
|
"version": "3.6.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/luxon/-/luxon-3.6.2.tgz",
|
||||||
|
"integrity": "sha512-R/BdP7OxEMc44l2Ex5lSXHoIXTB2JLNa3y2QISIbr58U/YcsffyQrYW//hZSdrfxrjRZj3GcUoxMPGdO8gSYuw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@types/methods": {
|
"node_modules/@types/methods": {
|
||||||
"version": "1.1.4",
|
"version": "1.1.4",
|
||||||
"resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz",
|
"resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz",
|
||||||
@ -5426,6 +5446,19 @@
|
|||||||
"devOptional": true,
|
"devOptional": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/cron": {
|
||||||
|
"version": "4.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/cron/-/cron-4.3.0.tgz",
|
||||||
|
"integrity": "sha512-ciiYNLfSlF9MrDqnbMdRWFiA6oizSF7kA1osPP9lRzNu0Uu+AWog1UKy7SkckiDY2irrNjeO6qLyKnXC8oxmrw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/luxon": "~3.6.0",
|
||||||
|
"luxon": "~3.6.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.x"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/cross-spawn": {
|
"node_modules/cross-spawn": {
|
||||||
"version": "7.0.6",
|
"version": "7.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||||
@ -9777,6 +9810,15 @@
|
|||||||
"yallist": "^3.0.2"
|
"yallist": "^3.0.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/luxon": {
|
||||||
|
"version": "3.6.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/luxon/-/luxon-3.6.1.tgz",
|
||||||
|
"integrity": "sha512-tJLxrKJhO2ukZ5z0gyjY1zPh3Rh88Ej9P7jNrZiHMUXHae1yvI2imgOZtL1TO8TW6biMMKfTtAOoEJANgtWBMQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/magic-string": {
|
"node_modules/magic-string": {
|
||||||
"version": "0.30.8",
|
"version": "0.30.8",
|
||||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.8.tgz",
|
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.8.tgz",
|
||||||
|
@ -30,6 +30,7 @@
|
|||||||
"@nestjs/jwt": "^10.2.0",
|
"@nestjs/jwt": "^10.2.0",
|
||||||
"@nestjs/passport": "^10.0.3",
|
"@nestjs/passport": "^10.0.3",
|
||||||
"@nestjs/platform-express": "^10.0.0",
|
"@nestjs/platform-express": "^10.0.0",
|
||||||
|
"@nestjs/schedule": "^6.0.0",
|
||||||
"@nestjs/swagger": "^7.3.0",
|
"@nestjs/swagger": "^7.3.0",
|
||||||
"@nestjs/terminus": "^11.0.0",
|
"@nestjs/terminus": "^11.0.0",
|
||||||
"@nestjs/throttler": "^6.4.0",
|
"@nestjs/throttler": "^6.4.0",
|
||||||
|
@ -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,18 +35,32 @@ 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';
|
||||||
import { WeatherModule } from './weather/weather.module';
|
import { WeatherModule } from './weather/weather.module';
|
||||||
|
import { ScheduleModule as NestScheduleModule } from '@nestjs/schedule';
|
||||||
|
import { SchedulerModule } from './scheduler/scheduler.module';
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
ConfigModule.forRoot({
|
ConfigModule.forRoot({
|
||||||
load: config,
|
load: config,
|
||||||
}),
|
}),
|
||||||
/* ThrottlerModule.forRoot({
|
ThrottlerModule.forRoot({
|
||||||
throttlers: [{ ttl: 100000, limit: 30 }],
|
throttlers: [{ ttl: 60000, limit: 100 }],
|
||||||
}), */
|
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,
|
||||||
@ -82,16 +96,18 @@ import { WeatherModule } from './weather/weather.module';
|
|||||||
OccupancyModule,
|
OccupancyModule,
|
||||||
WeatherModule,
|
WeatherModule,
|
||||||
AqiModule,
|
AqiModule,
|
||||||
|
SchedulerModule,
|
||||||
|
NestScheduleModule.forRoot(),
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
{
|
{
|
||||||
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 {}
|
||||||
|
@ -30,6 +30,8 @@ import { PowerClampService } from '@app/common/helper/services/power.clamp.servi
|
|||||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||||
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 { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||||
|
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ConfigModule, SpaceRepositoryModule],
|
imports: [ConfigModule, SpaceRepositoryModule],
|
||||||
@ -59,6 +61,8 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
|||||||
SqlLoaderService,
|
SqlLoaderService,
|
||||||
OccupancyService,
|
OccupancyService,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
|
PresenceSensorDailySpaceRepository,
|
||||||
|
AqiSpaceDailyPollutantStatsRepository,
|
||||||
],
|
],
|
||||||
exports: [],
|
exports: [],
|
||||||
})
|
})
|
||||||
|
@ -64,6 +64,8 @@ import {
|
|||||||
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||||
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 { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||||
|
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ConfigModule, SpaceRepositoryModule, UserRepositoryModule],
|
imports: [ConfigModule, SpaceRepositoryModule, UserRepositoryModule],
|
||||||
@ -118,6 +120,8 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
|||||||
SqlLoaderService,
|
SqlLoaderService,
|
||||||
OccupancyService,
|
OccupancyService,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
|
PresenceSensorDailySpaceRepository,
|
||||||
|
AqiSpaceDailyPollutantStatsRepository,
|
||||||
],
|
],
|
||||||
exports: [CommunityService, SpacePermissionService],
|
exports: [CommunityService, SpacePermissionService],
|
||||||
})
|
})
|
||||||
|
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';
|
||||||
|
}
|
@ -30,6 +30,8 @@ import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service
|
|||||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||||
|
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||||
|
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ConfigModule, DeviceRepositoryModule],
|
imports: [ConfigModule, DeviceRepositoryModule],
|
||||||
controllers: [DoorLockController],
|
controllers: [DoorLockController],
|
||||||
@ -58,6 +60,8 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
|||||||
OccupancyService,
|
OccupancyService,
|
||||||
CommunityRepository,
|
CommunityRepository,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
|
PresenceSensorDailySpaceRepository,
|
||||||
|
AqiSpaceDailyPollutantStatsRepository,
|
||||||
],
|
],
|
||||||
exports: [DoorLockService],
|
exports: [DoorLockService],
|
||||||
})
|
})
|
||||||
|
@ -28,6 +28,8 @@ import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service
|
|||||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||||
|
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||||
|
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ConfigModule, DeviceRepositoryModule],
|
imports: [ConfigModule, DeviceRepositoryModule],
|
||||||
controllers: [GroupController],
|
controllers: [GroupController],
|
||||||
@ -55,6 +57,8 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
|||||||
OccupancyService,
|
OccupancyService,
|
||||||
CommunityRepository,
|
CommunityRepository,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
|
PresenceSensorDailySpaceRepository,
|
||||||
|
AqiSpaceDailyPollutantStatsRepository,
|
||||||
],
|
],
|
||||||
exports: [GroupService],
|
exports: [GroupService],
|
||||||
})
|
})
|
||||||
|
@ -82,6 +82,8 @@ import { SubspaceProductAllocationService } from 'src/space/services/subspace/su
|
|||||||
import { TagService as NewTagService } from 'src/tags/services';
|
import { TagService as NewTagService } from 'src/tags/services';
|
||||||
import { UserDevicePermissionService } from 'src/user-device-permission/services';
|
import { UserDevicePermissionService } from 'src/user-device-permission/services';
|
||||||
import { UserService, UserSpaceService } from 'src/users/services';
|
import { UserService, UserSpaceService } from 'src/users/services';
|
||||||
|
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||||
|
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ConfigModule, InviteUserRepositoryModule, CommunityModule],
|
imports: [ConfigModule, InviteUserRepositoryModule, CommunityModule],
|
||||||
@ -150,6 +152,8 @@ import { UserService, UserSpaceService } from 'src/users/services';
|
|||||||
SqlLoaderService,
|
SqlLoaderService,
|
||||||
OccupancyService,
|
OccupancyService,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
|
PresenceSensorDailySpaceRepository,
|
||||||
|
AqiSpaceDailyPollutantStatsRepository,
|
||||||
],
|
],
|
||||||
exports: [InviteUserService],
|
exports: [InviteUserService],
|
||||||
})
|
})
|
||||||
|
15
src/main.ts
15
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,20 +21,6 @@ async function bootstrap() {
|
|||||||
|
|
||||||
app.use(new RequestContextMiddleware().use);
|
app.use(new RequestContextMiddleware().use);
|
||||||
|
|
||||||
app.use(
|
|
||||||
rateLimit({
|
|
||||||
windowMs: 5 * 60 * 1000,
|
|
||||||
max: 500,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
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,
|
||||||
|
@ -60,6 +60,8 @@ import { SubspaceProductAllocationService } from 'src/space/services/subspace/su
|
|||||||
import { TagService } from 'src/tags/services';
|
import { TagService } from 'src/tags/services';
|
||||||
import { PowerClampController } from './controllers';
|
import { PowerClampController } from './controllers';
|
||||||
import { PowerClampService as PowerClamp } from './services/power-clamp.service';
|
import { PowerClampService as PowerClamp } from './services/power-clamp.service';
|
||||||
|
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||||
|
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ConfigModule],
|
imports: [ConfigModule],
|
||||||
controllers: [PowerClampController],
|
controllers: [PowerClampController],
|
||||||
@ -109,6 +111,8 @@ import { PowerClampService as PowerClamp } from './services/power-clamp.service'
|
|||||||
SubspaceModelProductAllocationRepoitory,
|
SubspaceModelProductAllocationRepoitory,
|
||||||
OccupancyService,
|
OccupancyService,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
|
PresenceSensorDailySpaceRepository,
|
||||||
|
AqiSpaceDailyPollutantStatsRepository,
|
||||||
],
|
],
|
||||||
exports: [PowerClamp],
|
exports: [PowerClamp],
|
||||||
})
|
})
|
||||||
|
@ -67,6 +67,8 @@ import { ProjectUserController } from './controllers/project-user.controller';
|
|||||||
import { CreateOrphanSpaceHandler } from './handler';
|
import { CreateOrphanSpaceHandler } from './handler';
|
||||||
import { ProjectService } from './services';
|
import { ProjectService } from './services';
|
||||||
import { ProjectUserService } from './services/project-user.service';
|
import { ProjectUserService } from './services/project-user.service';
|
||||||
|
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||||
|
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||||
|
|
||||||
const CommandHandlers = [CreateOrphanSpaceHandler];
|
const CommandHandlers = [CreateOrphanSpaceHandler];
|
||||||
|
|
||||||
@ -124,6 +126,8 @@ const CommandHandlers = [CreateOrphanSpaceHandler];
|
|||||||
SqlLoaderService,
|
SqlLoaderService,
|
||||||
OccupancyService,
|
OccupancyService,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
|
PresenceSensorDailySpaceRepository,
|
||||||
|
AqiSpaceDailyPollutantStatsRepository,
|
||||||
],
|
],
|
||||||
exports: [ProjectService, CqrsModule],
|
exports: [ProjectService, CqrsModule],
|
||||||
})
|
})
|
||||||
|
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,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
25
src/scheduler/scheduler.module.ts
Normal file
25
src/scheduler/scheduler.module.ts
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import { DatabaseModule } from '@app/common/database/database.module';
|
||||||
|
import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service';
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
|
import { SchedulerService } from './scheduler.service';
|
||||||
|
import { ScheduleModule as NestScheduleModule } from '@nestjs/schedule';
|
||||||
|
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||||
|
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||||
|
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
NestScheduleModule.forRoot(),
|
||||||
|
TypeOrmModule.forFeature([]),
|
||||||
|
DatabaseModule,
|
||||||
|
],
|
||||||
|
providers: [
|
||||||
|
SchedulerService,
|
||||||
|
SqlLoaderService,
|
||||||
|
PowerClampService,
|
||||||
|
OccupancyService,
|
||||||
|
AqiDataService,
|
||||||
|
],
|
||||||
|
})
|
||||||
|
export class SchedulerModule {}
|
92
src/scheduler/scheduler.service.ts
Normal file
92
src/scheduler/scheduler.service.ts
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { Cron, CronExpression } from '@nestjs/schedule';
|
||||||
|
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||||
|
import { PowerClampService } from '@app/common/helper/services/power.clamp.service';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SchedulerService {
|
||||||
|
constructor(
|
||||||
|
private readonly powerClampService: PowerClampService,
|
||||||
|
private readonly occupancyService: OccupancyService,
|
||||||
|
private readonly aqiDataService: AqiDataService,
|
||||||
|
) {
|
||||||
|
console.log('SchedulerService initialized!');
|
||||||
|
}
|
||||||
|
|
||||||
|
@Cron(CronExpression.EVERY_HOUR)
|
||||||
|
async runHourlyProcedures() {
|
||||||
|
console.log('\n======== Starting Procedures ========');
|
||||||
|
console.log(new Date().toISOString(), 'Scheduler running...');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const results = await Promise.allSettled([
|
||||||
|
this.executeTask(
|
||||||
|
() => this.powerClampService.updateEnergyConsumedHistoricalData(),
|
||||||
|
'Energy Consumption',
|
||||||
|
),
|
||||||
|
this.executeTask(
|
||||||
|
() => this.occupancyService.updateOccupancyDataProcedures(),
|
||||||
|
'Occupancy Data',
|
||||||
|
),
|
||||||
|
this.executeTask(
|
||||||
|
() => this.aqiDataService.updateAQISensorHistoricalData(),
|
||||||
|
'AQI Data',
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
|
||||||
|
this.logResults(results);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('MAIN SCHEDULER ERROR:', error);
|
||||||
|
if (error.stack) {
|
||||||
|
console.error('Error stack:', error.stack);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async executeTask(
|
||||||
|
task: () => Promise<void>,
|
||||||
|
name: string,
|
||||||
|
): Promise<{ name: string; status: string }> {
|
||||||
|
try {
|
||||||
|
console.log(`[${new Date().toISOString()}] Starting ${name} task...`);
|
||||||
|
await task();
|
||||||
|
console.log(
|
||||||
|
`[${new Date().toISOString()}] ${name} task completed successfully`,
|
||||||
|
);
|
||||||
|
return { name, status: 'success' };
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
`[${new Date().toISOString()}] ${name} task failed:`,
|
||||||
|
error.message,
|
||||||
|
);
|
||||||
|
if (error.stack) {
|
||||||
|
console.error('Task error stack:', error.stack);
|
||||||
|
}
|
||||||
|
return { name, status: 'failed' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private logResults(results: PromiseSettledResult<any>[]) {
|
||||||
|
const successCount = results.filter((r) => r.status === 'fulfilled').length;
|
||||||
|
const failedCount = results.length - successCount;
|
||||||
|
|
||||||
|
console.log('\n======== Task Results ========');
|
||||||
|
console.log(`Successful tasks: ${successCount}`);
|
||||||
|
console.log(`Failed tasks: ${failedCount}`);
|
||||||
|
|
||||||
|
if (failedCount > 0) {
|
||||||
|
console.log('\n======== Failed Tasks Details ========');
|
||||||
|
results.forEach((result, index) => {
|
||||||
|
if (result.status === 'rejected') {
|
||||||
|
console.error(`Task ${index + 1} failed:`, result.reason);
|
||||||
|
if (result.reason.stack) {
|
||||||
|
console.error('Error stack:', result.reason.stack);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\n======== Scheduler Completed ========\n');
|
||||||
|
}
|
||||||
|
}
|
@ -63,6 +63,8 @@ import {
|
|||||||
import { SpaceModelService, SubSpaceModelService } from './services';
|
import { SpaceModelService, SubSpaceModelService } from './services';
|
||||||
import { SpaceModelProductAllocationService } from './services/space-model-product-allocation.service';
|
import { SpaceModelProductAllocationService } from './services/space-model-product-allocation.service';
|
||||||
import { SubspaceModelProductAllocationService } from './services/subspace/subspace-model-product-allocation.service';
|
import { SubspaceModelProductAllocationService } from './services/subspace/subspace-model-product-allocation.service';
|
||||||
|
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||||
|
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||||
|
|
||||||
const CommandHandlers = [
|
const CommandHandlers = [
|
||||||
PropogateUpdateSpaceModelHandler,
|
PropogateUpdateSpaceModelHandler,
|
||||||
@ -120,6 +122,8 @@ const CommandHandlers = [
|
|||||||
SqlLoaderService,
|
SqlLoaderService,
|
||||||
OccupancyService,
|
OccupancyService,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
|
PresenceSensorDailySpaceRepository,
|
||||||
|
AqiSpaceDailyPollutantStatsRepository,
|
||||||
],
|
],
|
||||||
exports: [CqrsModule, SpaceModelService],
|
exports: [CqrsModule, SpaceModelService],
|
||||||
})
|
})
|
||||||
|
@ -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,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -88,6 +88,8 @@ import {
|
|||||||
} from './services';
|
} from './services';
|
||||||
import { SpaceProductAllocationService } from './services/space-product-allocation.service';
|
import { SpaceProductAllocationService } from './services/space-product-allocation.service';
|
||||||
import { SubspaceProductAllocationService } from './services/subspace/subspace-product-allocation.service';
|
import { SubspaceProductAllocationService } from './services/subspace/subspace-product-allocation.service';
|
||||||
|
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||||
|
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||||
|
|
||||||
export const CommandHandlers = [DisableSpaceHandler];
|
export const CommandHandlers = [DisableSpaceHandler];
|
||||||
|
|
||||||
@ -161,6 +163,8 @@ export const CommandHandlers = [DisableSpaceHandler];
|
|||||||
SqlLoaderService,
|
SqlLoaderService,
|
||||||
OccupancyService,
|
OccupancyService,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
|
PresenceSensorDailySpaceRepository,
|
||||||
|
AqiSpaceDailyPollutantStatsRepository,
|
||||||
],
|
],
|
||||||
exports: [SpaceService],
|
exports: [SpaceService],
|
||||||
})
|
})
|
||||||
|
@ -32,6 +32,8 @@ import { SqlLoaderService } from '@app/common/helper/services/sql-loader.service
|
|||||||
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
import { OccupancyService } from '@app/common/helper/services/occupancy.service';
|
||||||
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
import { CommunityRepository } from '@app/common/modules/community/repositories';
|
||||||
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
||||||
|
import { PresenceSensorDailySpaceRepository } from '@app/common/modules/presence-sensor/repositories';
|
||||||
|
import { AqiSpaceDailyPollutantStatsRepository } from '@app/common/modules/aqi/repositories';
|
||||||
@Module({
|
@Module({
|
||||||
imports: [ConfigModule, DeviceRepositoryModule, DoorLockModule],
|
imports: [ConfigModule, DeviceRepositoryModule, DoorLockModule],
|
||||||
controllers: [VisitorPasswordController],
|
controllers: [VisitorPasswordController],
|
||||||
@ -61,6 +63,8 @@ import { AqiDataService } from '@app/common/helper/services/aqi.data.service';
|
|||||||
OccupancyService,
|
OccupancyService,
|
||||||
CommunityRepository,
|
CommunityRepository,
|
||||||
AqiDataService,
|
AqiDataService,
|
||||||
|
PresenceSensorDailySpaceRepository,
|
||||||
|
AqiSpaceDailyPollutantStatsRepository,
|
||||||
],
|
],
|
||||||
exports: [VisitorPasswordService],
|
exports: [VisitorPasswordService],
|
||||||
})
|
})
|
||||||
|
Reference in New Issue
Block a user