All files / src/platform/iot iot-gateway.service.ts

0% Statements 0/34
0% Branches 0/28
0% Functions 0/4
0% Lines 0/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125                                                                                                                                                                                                                                                         
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {
  IoTDevice,
  IoTTelemetry,
  IoTGeofence,
  IoTAlert,
} from './schemas/iot.schema';
import { EventBusService } from '../events/event-bus.service';
 
@Injectable()
export class IoTGatewayService {
  private readonly logger = new Logger(IoTGatewayService.name);
 
  constructor(
    @InjectModel(IoTDevice.name) private readonly deviceModel: Model<IoTDevice>,
    @InjectModel(IoTTelemetry.name)
    private readonly telemetryModel: Model<IoTTelemetry>,
    @InjectModel(IoTGeofence.name)
    private readonly geofenceModel: Model<IoTGeofence>,
    @InjectModel(IoTAlert.name) private readonly alertModel: Model<IoTAlert>,
    private readonly eventBus: EventBusService,
  ) {}
 
  async registerDevice(
    tenantId: string,
    params: {
      deviceId: string;
      name: string;
      deviceType: string;
      metadata?: any;
    },
  ): Promise<IoTDevice> {
    const existing = await this.deviceModel
      .findOne({ tenantId, deviceId: params.deviceId })
      .exec();
    const doc =
      existing ?? new this.deviceModel({ tenantId, deviceId: params.deviceId });
 
    doc.name = params.name;
    doc.deviceType = params.deviceType;
    if (params.metadata) doc.metadata = params.metadata;
    doc.isActive = true;
 
    await doc.save();
    return doc;
  }
 
  async ingestTelemetry(
    tenantId: string,
    deviceId: string,
    payload: Record<string, any>,
  ): Promise<void> {
    const device = await this.deviceModel
      .findOne({ tenantId, deviceId, isActive: true })
      .exec();
    if (!device) {
      this.logger.warn(
        `Telemetry ignored for inactive or unregistered device: ${deviceId}`,
      );
      return;
    }
 
    await this.telemetryModel.create({
      deviceId,
      tenantId,
      payload,
      timestamp: new Date(),
    });
 
    // Check alerts (mock triggers based on payload threshold rules)
    if (payload.temperature > 40) {
      await this.createAlert(
        tenantId,
        deviceId,
        'temp_high',
        `High temperature alert: ${payload.temperature}°C`,
        'critical',
      );
    }
 
    await this.eventBus.publish(
      'platform.iot.telemetry.ingested.v1',
      {
        tenantId,
        deviceId,
        payload,
      },
      tenantId,
    );
  }
 
  async createAlert(
    tenantId: string,
    deviceId: string,
    alertType: string,
    message: string,
    severity: 'critical' | 'warning' | 'info',
  ): Promise<IoTAlert> {
    const alert = await this.alertModel.create({
      tenantId,
      deviceId,
      alertType,
      message,
      severity,
      isResolved: false,
    });
 
    await this.eventBus.publish(
      'platform.iot.alert.triggered.v1',
      {
        tenantId,
        deviceId,
        alertType,
        message,
        severity,
      },
      tenantId,
    );
 
    return alert;
  }
}