We have generated data and stored it in SQL. Now we need to do an analysis and generate a report based on this data. We shall describe how to do this.
We have done the following in different chapters of this website.
https://www.hemelix.com/plc/structured-text-programming/ (Programming in Structured Text)
https://www.hemelix.com/scada-hmi/twincat-hmi/animation-in-twincat-hmi/ (Animation of image)
https://www.hemelix.com/scada-hmi/twincat-hmi/data-grid-view/ (How to display data from HMI to SQL and vice versa)
https://www.hemelix.com/automation/raspberry-pi/ (How to program in Raspberry Pi)
https://www.hemelix.com/sql/ (How to work with HMI and database)
https://www.hemelix.com/plc/structured-text-mqtt/ (What is MQTT and how to use it)
https://www.hemelix.com/automation/structured-text-mqtt-node-red-mssql/ (What is Node-RED and saving data to SQL)
On this page, we shall use all this knowledge to generate a report.
Still updating, follow us!
Figure 01: Fitting reporting architecture in the Beckhoff automation system.
Automated Industrial Reporting with TwinCAT HMI, Node.js, and PostgreSQL
Figure 02: Sample HMI allows saving a few properties to DB and sending a report automatically (under development)
We shall use a DC motor and it will be run by PLC by using Modbus. The motor can be started or stopped manually. The motor can reach maximum speed for a certain time and it can change the speed during operation. It will record the maximum speed and how long it was running at that speed. All information can be included in a report which can be sent to our client by email.
Figure 03: Saving data to cloud, architecture provided by Beckhoff
React -> NodeJS -> PGDatabase
Create the project folder
Open PowerShell and execute:
cd C:\Temp
mkdir TankMonitoring
cd TankMonitoring
We will create two separate applications inside this folder:
TankMonitoring/
│
├── backend/ Node.js + Express
│ ├── server.js
│ ├── db.js
│ └── .env
│
└── frontend/ React + Vite
└── src/
├── App.jsx
└── main.jsx
Create the PostgreSQL database
Open pgAdmin 4 and create a database named:
TankMonitoringDB
Open the Query Tool for that database and execute:
CREATE TABLE tank_data (
id SERIAL PRIMARY KEY,
tank_name VARCHAR(100) NOT NULL,
tank_level DOUBLE PRECISION NOT NULL,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);
Create the Node.JS backend
cd C:\Temp\TankMonitoring
mkdir backend
cd backend
npm init -y
Install the required packages:
npm install express pg cors dotenv
These packages provide the HTTP server, PostgreSQL connection, cross-origin access, and environment configuration.
Create db.js
This file manages the database connection.
require("dotenv").config();
const { Pool } = require("pg");
const pool = new Pool({
host: process.env.DB_HOST,
port: Number(process.env.DB_PORT),
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
});
module.exports = pool;Create .env
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=your_password
DB_NAME=TankMonitoringDB
Create server.js
This is the main backend application.
const express = require("express");
const cors = require("cors");
const pool = require("./db");
const app = express();
app.use(cors({
origin: "http://localhost:5173"
}));
app.use(express.json());
// GET: Read all tank records
app.get("/api/tanks", async (req, res) => {
try {
const result = await pool.query(
"SELECT * FROM tank_data ORDER BY id DESC"
);
res.json(result.rows);
} catch (err) {
console.error(err);
res.status(500).json({ error: "Database error" });
}
});
// POST: Insert a new tank record
app.post("/api/tanks", async (req, res) => {
try {
const { tank_name, tank_level } = req.body;
if (
typeof tank_name !== "string" ||
!tank_name.trim() ||
typeof tank_level !== "number" ||
!Number.isFinite(tank_level)
) {
return res.status(400).json({
error: "Valid tank name and numeric level required"
});
}
const result = await pool.query(
`INSERT INTO tank_data (tank_name, tank_level)
VALUES ($1, $2)
RETURNING *`,
[tank_name.trim(), tank_level]
);
res.status(201).json(result.rows[0]);
} catch (err) {
console.error(err);
res.status(500).json({ error: "Database error" });
}
});
// DELETE: Remove a record
app.delete("/api/tanks/:id", async (req, res) => {
try {
const id = Number(req.params.id);
if (!Number.isSafeInteger(id) || id <= 0) {
return res.status(400).json({
error: "Invalid record ID"
});
}
const result = await pool.query(
"DELETE FROM tank_data WHERE id = $1 RETURNING id",
[id]
);
if (result.rowCount === 0) {
return res.status(404).json({
error: "Record not found"
});
}
res.json({ message: "Record deleted" });
} catch (err) {
console.error(err);
res.status(500).json({ error: "Database error" });
}
});
app.listen(3001, () => {
console.log("Backend running at http://localhost:3001");
});
Supabase Edge Functions (Connecting remote PG)
Supabase Edge Functions to connect to the remote database.
Supabase → Edge Function → Remote Database
import { Client } from "pg";
const client = new Client({
host: "remote-host",
user: "user",
password: "password",
database: "db",
port: 5432
});
await client.connect();
Here is a simple Node.js example that connects to a remote PostgreSQL database and retrieves data. The standard library used is pg (node-postgres).
1. Install the PostgreSQL client
Run:
npm install pg
2. Example Node.js script
import pkg from "pg";
const { Client } = pkg;
async function fetchData() {
const client = new Client({
host: "REMOTE_DB_HOST", // e.g. 192.168.1.10 or db.example.com
port: 5432,
user: "REMOTE_DB_USER",
password: "REMOTE_DB_PASSWORD",
database: "REMOTE_DB_NAME",
ssl: false // change to true if your database requires SSL
});
try {
// connect to database
await client.connect();
console.log("Connected to remote PostgreSQL");
// run a query
const result = await client.query(
"SELECT id, name, email FROM users LIMIT 5"
);
// print rows
console.log("Query result:");
result.rows.forEach(row => {
console.log(row);
});
} catch (error) {
console.error("Error:", error);
} finally {
// close connection
await client.end();
console.log("Connection closed");
}
}
fetchData();
3. Example output
Connected to remote PostgreSQL
Query result:
{ id: 1, name: 'Alice', email: 'alice@email.com' }
{ id: 2, name: 'Bob', email: 'bob@email.com' }
Connection closed
Mendix
=> Reporting tool provided by Siemens
=> Put login ON/OFF Security | Security level
References:
=> https://www.youtube.com/watch?v=c7q3jOkhDqI&list=PLlCoaeocBmj18t98JJhE7l4FwOOHz1DzW
=> https://home.mendix.com/index.html
=> https://academy.mendix.com/link/paths/31/Become-a-Rapid-Developer
=> https://www.youtube.com/@MendixWithMe
=> https://www.youtube.com/watch?v=w5HlzrWjm1c
=> https://www.youtube.com/watch?v=PxbvBzlALG8
=> https://supabase.com/docs/guides/telemetry/reports
=> https://www.youtube.com/watch?v=ydz7Dj5QHKY&list=PL4cUxeGkcC9hUb6sHthUEwG7r9VDPBMKO&index=1 (Supabase tutorial)
=> https://react.dev/learn (React tutorial)
=> https://recharts.github.io/en-US/api/DefaultLegendContent/
=> https://www.youtube.com/watch?v=wYpCWwD1oz0&list=PLEYW3pZS6IQ_a-iYAno4VsZonrikphq8L (Re chart video)
=> https://www.corbado.com/blog/react-express-crud-app-mysql
What Next
Now learn how to send email by using C# and JS,
Browse https://www.hemelix.com/automation/send-email-by-js-and-csharp/
Ask questions related to Hemelix sample code and design at Google group https://groups.google.com/g/hemelix