Read history with SQL
What you build
Read access to the history and the alarm journal of Line 1 from your own tools. mii Lite keeps its history in its embedded PostgreSQL. A read-only role, mii_reader, can see four views in the schema mii_data. You connect with psql, with Python, from Excel or Power BI, and from Grafana, and you run queries on the demo plant data.
Time: about 30 minutes.
- mii Lite with the pipeline of Your first pipeline collecting for at least an hour. The alarm queries need Alarm on a limit.
- Access to the Lite host's configuration, to switch the public PostgreSQL port on.
psql(PostgreSQL client 14 or newer), or Python 3.10 or newer.
The views mii_data.* exist only when the historian is PostgreSQL, which is the case for mii Lite. The plant stack (ClickHouse) does not have them. For the plant stack use the public API with an API key (see API keys).
What you can see
| View | Content |
|---|---|
mii_data.samples | History: ts (timestamptz), path, tag_id, value (double precision), value_text, quality (good, uncertain, bad, unknown). |
mii_data.latest | The newest sample of every tag. Same columns as samples. |
mii_data.tags | tag_id, path, enterprise, site, area, work_center, work_unit (null for a six-part path), equipment, tag. |
mii_data.alarms | The alarm journal: ts, path, tag_id, kind, event, from_state, to_state, priority, value, value_text, message. |
path is <enterprise>/<site>/<area>/<work center>/<equipment>/<tag>, built from the ISA-95 codes, for example DEMOFOODS/IZMIR/BOTTLING/LINE1/FILLER/Speed.
The role is limited on purpose: read-only, no superuser, 10 connections, statement timeout 60 seconds, idle-in-transaction timeout 60 seconds. History is kept for 90 days by default. The tables under the views are private and may change; use only the views.
Step by step
1. Switch the public PostgreSQL port on
- Windows
- Linux
- Docker
Add to C:\ProgramData\MakeIntelligent\config\mii.env:
MI_LITE_PG_PUBLIC=on
Restart and open the port (the installer opens only 8080):
& "C:\Program Files\MakeIntelligent\mii.exe" stop
& "C:\Program Files\MakeIntelligent\mii.exe" start
New-NetFirewallRule -DisplayName "MakeIntelligent Lite PostgreSQL (5433)" -Direction Inbound -Protocol TCP -LocalPort 5433 -Action Allow
Add to /var/lib/makeintelligent/config/mii.env:
MI_LITE_PG_PUBLIC=on
sudo systemctl restart makeintelligent
Open 5433/tcp in your firewall if one is active. The installer opens only 8080.
The image has MI_LITE_PG_PUBLIC=on by default. Publish the port: -p 5433:5433 or use --network host.
The default port is 5433 (MI_LITE_PG_PORT), the database is makeitintelligent.
2. Get the login
The login is in the restricted file DATA-ACCESS.txt in the data folder. It is written only while an outside access is open.
sudo cat /var/lib/makeintelligent/DATA-ACCESS.txt # Linux
docker exec mii cat /data/DATA-ACCESS.txt # Docker
On Windows open C:\ProgramData\MakeIntelligent\DATA-ACCESS.txt as Administrator. It holds the user mii_reader, its password and example queries. The password is also in secrets\pg-reader.password.
If Lite uses an external PostgreSQL (MI_LITE_PG_URL, development only), the outside access is reported closed.
3. Connect with psql
psql "host=<lite-host> port=5433 dbname=makeitintelligent user=mii_reader"
Enter the password. Try:
\dv mii_data.*
SELECT count(*) FROM mii_data.tags;
You should see four views and a tag count of at least six (the Filler tags) plus the Compressor tags from the alarm tutorial.
4. Example queries
Latest value of every Filler tag
SELECT t.tag, l.value, l.quality, l.ts
FROM mii_data.latest l
JOIN mii_data.tags t ON t.path = l.path
WHERE t.equipment = 'Filler'
ORDER BY t.tag;
tag | value | quality | ts
--------------+-----------+---------+-------------------------------
GoodCount | 14872 | good | 2026-12-02 10:15:30.123+00
Pressure | 3.21 | good | 2026-12-02 10:15:30.123+00
RejectCount | 181 | good | 2026-12-02 10:15:30.123+00
Speed | 116 | good | 2026-12-02 10:15:30.123+00
State | 1 | good | 2026-12-02 10:15:30.123+00
Temperature | 4.1 | good | 2026-12-02 10:15:30.123+00
Filler speed, hourly average of the last 24 hours (good readings only)
SELECT date_trunc('hour', s.ts) AS hour,
round(avg(s.value)::numeric, 1) AS avg_speed,
max(s.value) AS max_speed,
count(*) AS n
FROM mii_data.samples s
WHERE s.path = 'DEMOFOODS/IZMIR/BOTTLING/LINE1/FILLER/Speed'
AND s.quality = 'good'
AND s.ts >= now() - interval '24 hours'
GROUP BY 1
ORDER BY 1;
Expect an average of 100 to 115 over a full hour (stops pull it down) and a maximum near 120.
Share of time the Filler ran in the last 8 hours (a rough availability)
SELECT round(100.0 * avg((value = 1)::int), 1) AS running_percent
FROM mii_data.samples
WHERE path = 'DEMOFOODS/IZMIR/BOTTLING/LINE1/FILLER/State'
AND quality = 'good'
AND ts >= now() - interval '8 hours';
This counts samples, so it only equals the time share when the poll interval is steady. The OEE page does the exact calculation.
Bottles produced today
SELECT max(value) - min(value) AS good_bottles
FROM mii_data.samples
WHERE path = 'DEMOFOODS/IZMIR/BOTTLING/LINE1/FILLER/GoodCount'
AND quality = 'good'
AND ts >= date_trunc('day', now());
A counter that wraps or is reset gives a wrong result with this simple query.
Compressor pressure at or above the limit in the last day
SELECT date_trunc('minute', ts) AS minute, max(value) AS max_bar
FROM mii_data.samples
WHERE path = 'DEMOFOODS/IZMIR/UTILITIES/AIR/COMPRESSOR/Pressure'
AND quality = 'good'
AND value >= 8.0
AND ts >= now() - interval '24 hours'
GROUP BY 1
ORDER BY 1;
The alarm journal
SELECT ts, priority, event, from_state, to_state, value, message
FROM mii_data.alarms
WHERE path LIKE '%/Compressor/%'
ORDER BY ts DESC
LIMIT 20;
5. Read from Python
- psycopg 3
- SQLAlchemy
pip install "psycopg[binary]" pandas
import os
import pandas as pd
import psycopg
conn = psycopg.connect(
host="lite-host", port=5433, dbname="makeitintelligent",
user="mii_reader", password=os.environ["MII_PG_PASSWORD"],
)
sql = """
SELECT date_trunc('minute', ts) AS minute, avg(value) AS speed
FROM mii_data.samples
WHERE path = %s AND quality = 'good' AND ts >= now() - interval '6 hours'
GROUP BY 1 ORDER BY 1
"""
with conn.cursor() as cur:
cur.execute(sql, ("DEMOFOODS/IZMIR/BOTTLING/LINE1/FILLER/Speed",))
df = pd.DataFrame(cur.fetchall(), columns=["minute", "speed"])
print(df.tail())
print("mean speed:", round(df["speed"].mean(), 1), "bottles/min")
import os
import pandas as pd
from sqlalchemy import create_engine, text
url = f"postgresql+psycopg://mii_reader:{os.environ['MII_PG_PASSWORD']}@lite-host:5433/makeitintelligent"
engine = create_engine(url)
df = pd.read_sql(text("SELECT * FROM mii_data.latest"), engine)
print(df)
Keep the password in an environment variable or a secret store, never in the script. Use at most a few connections: the role allows 10.
6. Excel and Power BI
These tools talk to PostgreSQL with a standard driver. Use the same host, port, database, user and password as above.
- Power BI Desktop: Get data, PostgreSQL database, server
lite-host:5433, databasemakeitintelligent, then choose Import or DirectQuery and select the viewsmii_data.samplesandmii_data.tags. Prefer a SQL statement with a time filter (like the hourly query above) over importing the wholesamplesview. - Excel: install the PostgreSQL ODBC driver (psqlODBC) and create a data source with the same settings, then Data, Get Data, From Other Sources, From ODBC. Paste an aggregating query in the advanced options.
- Always filter by
tsand aggregate in SQL. The 60-second statement timeout stops a query that reads months of one-second data.
The Excel and Power BI steps follow the vendors' standard PostgreSQL connectors. Menus differ by version.
7. Grafana
-
In Grafana open Connections, Data sources, Add data source, PostgreSQL.
-
Host URL
lite-host:5433, Databasemakeitintelligent, Usermii_reader, Password fromDATA-ACCESS.txt. Set TLS/SSL mode as your network requires. -
Create a panel with this query in code mode, format Time series:
SELECT$__timeGroupAlias(ts, '1m'),avg(value) AS "Filler speed"FROM mii_data.samplesWHERE $__timeFilter(ts)AND path = 'DEMOFOODS/IZMIR/BOTTLING/LINE1/FILLER/Speed'AND quality = 'good'GROUP BY 1ORDER BY 1 -
Add a second query for the Compressor pressure and a threshold line at 8.0.
Because the role is read-only, a mistake in a Grafana query cannot change anything in mii.
Check it works
-
\dv mii_data.*listsalarms,latest,samplesandtags. - The latest-values query returns six Filler rows with quality
good. - The hourly average of
Speedis between about 100 and 118. -
INSERT INTO mii_data.samples ...fails: the role is read-only. - After an alarm raised,
mii_data.alarmshas anactivaterow.
Next steps
Historian
Retention, disk guard and exports.
API keys
Read-only REST access for programs, also on the plant stack.
Claude with MCP
Ask questions in plain language instead of SQL.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Connection refused or timed out | MI_LITE_PG_PUBLIC is not on, the port is blocked, or the service was not restarted. | Check mii.env, restart, open port 5433. |
DATA-ACCESS.txt does not exist | No outside access is open, or Lite uses an external PostgreSQL. | Switch MI_LITE_PG_PUBLIC=on and restart. |
password authentication failed | Old password, or the role was recreated. | Read the file again, or secrets\pg-reader.password. |
permission denied for table samples | You use the private tables under mi.*. | Use mii_data.samples. |
canceling statement due to statement timeout | The query ran longer than 60 seconds. | Narrow ts, filter by path, aggregate. |
too many connections for role "mii_reader" | More than 10 connections. | Close idle clients, use a pool of 2 to 3. |
| No rows for the Filler | Wrong path (names instead of codes), or tags not bound to equipment. | Run SELECT path FROM mii_data.tags; and copy the path. |
Rows have value NULL | Quality is bad: a bad sample never stores a value. | Filter with quality = 'good'. |
| Old data is missing | Built-in retention is 90 days, and Free mode wipes history every 3 hours. | Check Settings → Plant historian, upload a licence. |