Commit 28629a44 authored by Tero Ojanen's avatar Tero Ojanen
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading

.dockerignore

0 → 100644
+7 −0
Changes for .dockerignore: 7 added lines, 0 removed lines.
Original line number Diff line number Diff line
node_modules
npm-debug.log
.git
Dockerfile*
.gitignore
.env
dist
 No newline at end of file

.gitignore

0 → 100644
+143 −0
Changes for .gitignore: 143 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Mongodata
mongodata/
mongodata/**

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.*
!.env.example

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Sveltekit cache directory
.svelte-kit/

# vitepress build output
**/.vitepress/dist

# vitepress cache directory
**/.vitepress/cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# Firebase cache directory
.firebase/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v3
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions

# Vite logs files
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

ARCHITECTURE.md

0 → 100644
+36 −0
Changes for ARCHITECTURE.md: 36 added lines, 0 removed lines.
Original line number Diff line number Diff line
# System Architecture

## Overview
This repository hosts a **Fishing Industry Data Platform (PoC)** ("Kalatalous"). It combines a standard FIWARE-based infrastructure for data management with a custom Node.js application for user interaction. **NOTE: Not all components are used in the current Custom UI.**

## Components

### 1. Infrastructure Layer (Docker Stack)
The backend infrastructure runs as a set of Docker containers defined in `docker-compose.yml`.

| Service | Container Name | Port (Host) | Description |
|---------|---------------|-------------|-------------|
| **Orion-LD** | `orion_kalatalous_dame` | `1026` | **Context Broker**. The core engine. Stores current state of entities (e.g., FishingActivity, Organization). |
| **MongoDB** | `mongo_kalatalous_dame` | `27017` | Database for Orion and IoT Agent. |
| **IoT Agent** | `iot-agent_kalatalous_dame` | `4041`, `7896` | Manages IoT devices. Converts Ultralight (HTTP/MQTT) messages to NGSI-LD entities. |
| **Mosquitto** | `mosquitto_kalatalous_dame` | `1883` | MQTT Broker. Devices send data here; IoT Agent subscribes to it. |
| **QuantumLeap**| `quantumleap_kalatalous_dame`| `8668` | Persists historical data from Orion into CrateDB. |
| **CrateDB** | `crate-db_kalatalous_dame` | `4200` | Time-series database for historical data. |
| **Grafana** | `grafana_kalatalous_dame` | `3001` | Visualization dashboard connected to CrateDB. |

### 2. Application Layer (Custom UI)
A custom **Node.js + Express** application serves as the frontend.

- **Role**: Provides the user interface for entities, viewing maps, and inspecting data.
- **Tech Stack**:
  - **Runtime**: Node.js
  - **Framework**: Express.js
  - **Templating**: Handlebars (`.hbs`)
- **Key Directories**:
  - `routes/fiware.js`: Main logic for FIWARE interactions (fetching data etc.).
  - `views/`: HTML templates.
  - `scripts/`: Utility scripts (e.g., `loadEntities.js` for data ingestion).

## Development
- **Start Stack**: Run `docker compose up -d`.
- **Run UI**: Install dependencies with `npm ci` or with `npm install`. Run `npm start` in root folder on terminal. UI starts on port `3000`.
 No newline at end of file
+415 −0
Changes for Controllers/FIWARE/Alerts.js: 415 added lines, 0 removed lines.
Original line number Diff line number Diff line

const axios = require('axios');
const asyncHandler = require('express-async-handler');
let utils = require('../FIWARE/utils.js')
let logger = require('../../logger.js');

const orion = axios.create({
  baseURL: process.env.ORION_URL || 'http://localhost:1026/ngsi-ld/v1',
  headers: {
    'Content-Type': process.env.IOTA_CONTENT_TYPE || 'application/ld+json',
    'Fiware-Service': process.env.IOTA_SERVICE || 'openiot',
    'Fiware-ServicePath': process.env.IOTA_SERVICE_PATH || '/'
  },
});

const contextUrl = process.env.CONTEXT || 'https://smartdatamodels.org/context.jsonld';
const linkHeader = `<${contextUrl}>; rel="http://www.w3.org/ns/json-ld#context"; type="application/ld+json"`;

/*********************************************************************
 * Simple function to return all subscriptions
 ***********************************************************************/
async function listSubscriptions() {
  const r = await orion.get('/subscriptions', {
    headers: {
      'Accept': 'application/ld+json',
      'Link': linkHeader,
      'Content-Type': undefined
    }
  });
  return Array.isArray(r.data) ? r.data : [];
}

/*********************************************************************
 * Finalize and create threshold subscription (< or >)
 ***********************************************************************/
async function ensureOneThresholdSub({
  deviceID, deviceType, url,
  attr,
  op,                 // '<' or '>'
  threshold,          // number
  throttling = 5,     // time between when alerts are send again
  context = contextUrl
}) {

// Clean up attribute name and build the query expression (e.g. "temperature>30")
  const cleanAttr = String(attr).trim();
  const q = `${cleanAttr}${op}${threshold}`;

  // --- Check if such a subscription already exists ---
  const subs = await listSubscriptions();
  const exists = subs.some(s => {
    const entities  = s?.entities || [];
    const watched   = s?.watchedAttributes || [];
    const endpoint  = s?.notification?.endpoint?.uri || '';

    // Entity matches if ID and type matches
    const entMatch = entities.some(e =>
      e.id === deviceID &&
      (!deviceType || !e.type || e.type === deviceType)
    );

    // Subscription matches if entity, attribute, endpoint, and query all match
    return entMatch && watched.includes(cleanAttr) && endpoint === url && s.q === q;
  });

  if (exists) {
    logger.misc(`👌 Threshold subscription already exists for ${deviceID}: ${q}`);
    return;
  }

  // Build new subscription payload 
  const entitySelector = { id: deviceID };
  if (deviceType && String(deviceType).trim()) {
    entitySelector.type = String(deviceType).trim();
  }

  const payload = {
    type: 'Subscription',
    '@context': context,
    entities: [entitySelector],
    watchedAttributes: [cleanAttr],
    q,
    notification: {
      // These attributes will be sent to the notification endpoint
      attributes: [
        cleanAttr,
        'sensorType', 'city', 'building', 'room',
        'description', 'minValue', 'maxValue', 'primaryAttr'
      ],
      endpoint: { uri: url, accept: 'application/json' }
    },
    throttling
  };

  // --- Send subscription request ---
  const r = await orion.post('/subscriptions', payload);

  if (r.status !== 201) {
    logger.error(`Failed to create subscription ${q}`, r.status, r.data);
  } else {
    logger.success(`✅ Created threshold subscription for ${deviceID}: ${q}`);
  }

}

/*********************************************************************
 * Forward alert to an actual check with correct comparator.
 * Key is that we call creation method twice so we actually create two
 * separate subscriptions! Easy to add more logic if needed
 ***********************************************************************/
async function ensureOutOfRangeAlerts({
  deviceID, deviceType, url,
  attr, min, max,
  throttling = 5
}) {
  if (Number.isFinite(min)) {
    await ensureOneThresholdSub({ deviceID, deviceType, url, attr, op: '<', threshold: min, throttling });
  }
  if (Number.isFinite(max)) {
    await ensureOneThresholdSub({ deviceID, deviceType, url, attr, op: '>', threshold: max, throttling });
  }
}

/****************************************************************************************************************************
 * Main alert subscription function called when creating device. From here -> ensureOutOfRangeAlerts -> ensureOneThresholdSub
 ****************************************************************************************************************************/
async function createAlertSubscription(deviceID, deviceType, url, min, max, attribute) {
  try {
    // Ignore accidental placeholder values
    if (deviceID === 'deviceID') return;

    // Ensure device ID is in NGSI-LD URN format
    if (!deviceID.startsWith('urn:')) {
      deviceID = `urn:ngsi-ld:${deviceType}:${deviceID}`;
    }

    // Normalize attribute name
    const attributeName = attribute ? String(attribute).trim() : undefined;

    // Normalize numeric thresholds if provided
    let minValue = (min !== undefined && min !== '') ? Number(min) : undefined;
    let maxValue = (max !== undefined && max !== '') ? Number(max) : undefined;

    // If still no thresholds exist, log an error and stop
    if (!Number.isFinite(minValue) && !Number.isFinite(maxValue)) {
      logger.error(`❌ No thresholds available for ${deviceID}. Cannot create subscription.`);
      return;
    }

    // Otherwise, create subscriptions for threshold alerts (out-of-range conditions)
    await ensureOutOfRangeAlerts({
      deviceID,
      deviceType,
      url,
      attr: attributeName,
      min: Number.isFinite(minValue) ? minValue : undefined,
      max: Number.isFinite(maxValue) ? maxValue : undefined,
      throttling: 5
    });

  } catch (err) {
    console.error('❌ Internal error while creating NGSI-LD alert subscription(s).', err);
  }
}

/*********************************************************************
 * The actual listener. This is called internally when alert hits. 
 * This URL is defined in ensureOneThresholdSub function 
 ***********************************************************************/
exports.listenerAlert = async function(req, res) {
  try {
    const body = req.body || {};
    const data = Array.isArray(body.data) ? body.data : [];

    if (!data.length) {
      return res.status(200).send('No data');
    }

    // One entity per notification
    const e = data[0];

    const id          = e?.id;
    const type        = e?.type;

attrKey = e?.primaryAttr?.value

    // Build payload that is send forward. Payload need to be defined in ensureOneThresholdSub
    const v           = e?.[attrKey]?.value;
    const min         = e?.minValue?.value;
    const max         = e?.maxValue?.value;
    const city        = e?.city?.value;
    const building    = e?.building?.value;
    const room        = e?.room?.value;
    const description = e?.description?.value;

    // Write alert into log
    logger.alerts(`🔔 Alert from ${id} (${type}) — ${attrKey}=${v} — Min=${min} — Max=${max}`);

    // Send alert via email
    await utils.sendAlertEmail(id, type, v, min, max, city, building, room, description);

    res.status(200).send('OK');
  } catch (err) {
    console.error('❌ Listener error:', err);
    res.status(500).send(String(err?.message || err));
  }
};


/*************************************************************
 * List alerts: fetch entities from Orion, check their values against min/max,
 * and render only those that are outside their safe range.
 * This function has sub-functions inside it
 *************************************************************************/
exports.listAlerts = async function listAlerts(request, response) {

  /** Get static attribute value from entity. ie. temperature, city, building, room" **/
  function getAttributeValue(entity, name) {
    const attribute = entity?.[name];

    // No attribute. Return - to rendered page
    if (attribute === undefined || attribute === null) {
      return '—';
    }

    // Attribute found, return it's value
    if (typeof attribute === 'object' && attribute.hasOwnProperty('value')) {
      return attribute.value;
    }
  }

    /**********************************************
   * Returns current value. If primaryAttr attribute 
   * is not defined, use 'value' as default
   *********************************************/
function getPrimaryAttributeValue(entity) {
  if (!entity) return undefined;

  let attrName;

  // Decide the attribute name
  const primaryAttr = entity.primaryAttr;

  if (primaryAttr === undefined || primaryAttr === null) {
    // No primaryAttr at all. default name is "value"
    attrName = 'value';
  } else if (primaryAttr && primaryAttr.value !== undefined) {
    // primaryAttr looks like { value: "temperature" }
    attrName = primaryAttr.value;
  } else {
    // primaryAttr is already the name (like "temperature")
    attrName = primaryAttr;
  }

  // Read the raw attribute from the entity
  const rawValue = entity[attrName];
  if (rawValue === undefined || rawValue === null) {
    return undefined;
  }

  // If the raw attribute looks like { value: 42 }, return its value
  if (rawValue && rawValue.value !== undefined) {
    return rawValue.value;
  }

  // Otherwise just return the raw thing directly
  return rawValue;
}

  /**********************************************************
   * Main listAlerts logic 
   ************************************************************/
    try {
      // Fetch all entities from Orion Context Broker
      const orionResponse = await orion.get('/entities', {
        headers: {
          Accept: 'application/ld+json',  // Ask Orion for JSON-LD format
          Link: linkHeader,               // Provide the context link
          'Content-Type': undefined       // Not needed for GET
        },
        params: { local: true }           // Only fetch local data
      });

      // Check if Orion returned an error
      if (orionResponse.status !== 200) {
        let errorBody;

        // If the response data is already a string, use it
        if (typeof orionResponse.data === 'string') {
          errorBody = orionResponse.data;
        } else {
          // Otherwise, convert the object into a string
          errorBody = JSON.stringify(orionResponse.data);
        }

        // Send back the same error code and message
        return response
          .status(orionResponse.status)
          .send("❌ Error: " + errorBody);
      }

      // Make sure we always have an array of entities
      let allEntities;
      if (Array.isArray(orionResponse.data)) {
        allEntities = orionResponse.data;
      } else {
        allEntities = [];
      }

      // Convert each entity into a simpler object
      // and check if it is in an alert state.
      const mapped = allEntities.map(function (entity) {
        // Read the main value of the entity
        let currentValue = getPrimaryAttributeValue(entity);

        // Read thresholds
        const minValue = getAttributeValue(entity, 'minValue');
        const maxValue = getAttributeValue(entity, 'maxValue');

        // Flags that show if value is too low or too high
        let isLow = false;
        let isHigh = false;

        if (currentValue !== null && minValue !== null && currentValue < minValue) {
          isLow = true;
        }

        if (currentValue !== null && maxValue !== null && currentValue > maxValue) {
          isHigh = true;
        }

        // Normalize how we display the value
        if (currentValue === 0) {
          currentValue = 0;                // Keep 0 as 0
        } else if (currentValue === undefined || currentValue === null) {
          currentValue = '—';              // Show dash if missing
        } else if (typeof currentValue === 'string' && currentValue.trim() === '') {
          currentValue = '—';              // Show dash if empty string
        } else {
          currentValue = currentValue;     // Keep the value as is
        }

        // Build a clear object with the fields we want
        let result = {};

        result.ID = entity.id;
        result.Type = entity.type;
        result.Accuracy = getAttributeValue(entity, 'accuracy');
        result.GeoLocation = getAttributeValue(entity, 'location');
        result.City = getAttributeValue(entity, 'city');
        result.Building = getAttributeValue(entity, 'building');
        result.Room = getAttributeValue(entity, 'room');
        result.SensorType = getAttributeValue(entity, 'sensorType');
        result.SensorModel = getAttributeValue(entity, 'sensorModel');

        if (minValue === undefined || minValue === null || minValue === '') {
          result.MinValue = '—';
        } else {
          result.MinValue = minValue;
        }

        if (maxValue === undefined || maxValue === null || maxValue === '') {
          result.MaxValue = '—';
        } else {
          result.MaxValue = maxValue;
        }

        result.CurrentValue = currentValue;
        result.Description = getAttributeValue(entity, 'description');

        // Internal flags to mark alerts
        result._isLow = isLow;
        result._isHigh = isHigh;

        return result;
      });

      // Keep only the entities that are in alert state
      const entitiesInAlert = mapped.filter(function (row) {
        if (row._isLow === true || row._isHigh === true) {
          return true;
        } else {
          return false;
        }
      });

      // Render the alerts page
      return response.render('fiware/alerts.hbs', {
        title: 'FIWARE Alerts',
        entities: entitiesInAlert
      });

    } catch (error) {
      // Handle any unexpected errors
      let message;
      if (error && error.response && error.response.data) {
        message = error.response.data;
      } else if (error && error.message) {
        message = error.message;
      } else {
        message = error;
      }

      return response
        .status(500)
        .send("❌ Error fetching alerts: " + JSON.stringify(message));
    }
};

// Export Functions
module.exports = {
  listenerAlert: exports.listenerAlert,
  listAlerts: exports.listAlerts,
  createAlertSubscription
};
 No newline at end of file
+1676 −0

File added.

Preview size limit exceeded, changes collapsed.

Loading