Digital Twin

Energy Digital Twin: Modeling Consumption in Real Time

How to model a site's energy flows as a digital twin fed by meters streaming over MQTT, then use it to find waste and test efficiency scenarios before spending money.

Digital twin energy diagram showing electricity, gas and compressed air flows across a site with live meter readings
Run this on your own MQTT brokerGet a private, managed MQTT broker on the Free plan and start from ready-made code samples.
Try it free Code samples No card required

A digital twin energy model shows where every kilowatt goes across a site, in real time, and lets you test what-if scenarios before you invest in efficiency projects. This guide explains how to model energy flows, how to stream metered data over MQTT, and how to use the twin to find waste and evaluate changes.

What an Energy Digital Twin Models

Monthly utility bills tell you how much you spent; they do not tell you why. An energy twin models the site as a network of flows:

  • Sources: grid supply, on-site solar, generators, gas supply
  • Conversion assets: transformers, compressors (electricity to compressed air), boilers (gas to heat), chillers (electricity to cooling)
  • Distribution: switchboards, sub-distribution panels, air and steam headers
  • Consumers: production lines, HVAC zones, lighting circuits, individual large machines

Each node has live measurements (power, energy, flow, pressure, temperature) and each edge carries a quantity from one node to another. When the measured inflow to a node does not match the sum of its outflows, the gap is either an unmetered load, a loss, or a leak. That simple balance check is one of the most useful things an energy twin does.

For the broader concept of twins, the digital twin technology guide is the place to start.

Why Model Energy as a Twin Instead of a Dashboard

A dashboard plots meter values. A twin adds structure and context:

Question Dashboard Energy digital twin
How much did Line 2 use yesterday? Yes Yes
How much of the main feeder is unaccounted for? Hard, needs manual math Computed continuously from the flow model
What does Line 2 consume while idle? Only if someone correlates manually Yes, because production state is in the twin
What if we lower compressor pressure by 0.5 bar? No Yes, with a compressor model
Which assets dominate the base load at night? Partly Yes, ranked by node

The key differences are the topology (what feeds what) and the link to operating state. Energy per unit produced, idle consumption and base load are only meaningful when energy data and production data share a backbone.

Streaming Metered Data via MQTT

Meters and gateways

Most industrial and commercial meters expose Modbus TCP or Modbus RTU. A gateway reads registers on a schedule and publishes values to MQTT. Common options:

  1. Node-RED with Modbus nodes on an industrial PC or Raspberry Pi
  2. Telegraf with its Modbus input and MQTT output plugins
  3. Meters or data loggers with built-in MQTT publishing

Publish both instantaneous power (kW) and cumulative energy counters (kWh). Counters are more robust: if a few messages are lost, the next counter value still gives the correct total for the period.

Topic design

Follow the site hierarchy so the twin's topology maps naturally to topics:

connectmq/<site>/<area>/<asset>/energy

connectmq/site1/utilities/main-feeder/energy
connectmq/site1/utilities/compressor1/energy
connectmq/site1/production/line2/energy
connectmq/site1/production/line2/state
connectmq/site1/building/hvac-ahu1/energy

A payload such as this keeps units explicit:

{
  "powerKw": 42.7,
  "energyKwh": 183245.6,
  "voltageV": 400.2,
  "powerFactor": 0.93,
  "ts": 1792152000
}

A managed MQTT broker gives meter gateways in several buildings or sites a single secure endpoint, and twin services subscribe with wildcards such as connectmq/site1/+/+/energy.

Hands-On: A Live Energy Balance

This example runs on the free public MQTT broker at broker.connectmq.com with simulated meters. Do not publish real site data on the public broker, since it is readable by anyone.

The script below simulates a main feeder and three sub-meters, and a second part of the same program acts as the twin's balance service, publishing the unaccounted share:

import json
import random
import threading
import time
import uuid

import paho.mqtt.client as mqtt

RUN = "energy-5c21"  # change to your own unique id
BASE = f"connectmq/demo/{RUN}/site1"
SUBMETERS = ["production/line2", "utilities/compressor1", "building/hvac-ahu1"]
latest = {}


def simulate(pub):
    while True:
        loads = {
            "production/line2": random.uniform(30, 45),
            "utilities/compressor1": random.uniform(18, 25),
            "building/hvac-ahu1": random.uniform(8, 12),
        }
        unmetered = random.uniform(6, 9)  # the waste the twin should find
        main = sum(loads.values()) + unmetered
        pub.publish(f"{BASE}/utilities/main-feeder/energy", json.dumps({"powerKw": round(main, 2)}))
        for path, kw in loads.items():
            pub.publish(f"{BASE}/{path}/energy", json.dumps({"powerKw": round(kw, 2)}))
        time.sleep(5)


def on_connect(client, userdata, flags, reason_code, properties):
    client.subscribe(f"{BASE}/+/+/energy")


def on_message(client, userdata, msg):
    node = msg.topic[len(BASE) + 1 : -len("/energy")]
    latest[node] = json.loads(msg.payload)["powerKw"]
    if "utilities/main-feeder" in latest and all(s in latest for s in SUBMETERS):
        main = latest["utilities/main-feeder"]
        gap = main - sum(latest[s] for s in SUBMETERS)
        result = {"mainKw": main, "unaccountedKw": round(gap, 2), "unaccountedPct": round(100 * gap / main, 1)}
        client.publish(f"{BASE}/twin/balance", json.dumps(result), qos=1, retain=True)
        print(result)


twin = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=f"energy-twin-{uuid.uuid4().hex[:6]}")
twin.on_connect = on_connect
twin.on_message = on_message
twin.connect("broker.connectmq.com", 1883, keepalive=30)

sim = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=f"meter-sim-{uuid.uuid4().hex[:6]}")
sim.connect("broker.connectmq.com", 1883, keepalive=30)
sim.loop_start()
threading.Thread(target=simulate, args=(sim,), daemon=True).start()

twin.loop_forever()

The balance service will report a steady unaccounted share. On a real site, that number points you to a missing sub-meter, an unknown load or losses worth investigating.

Testing Efficiency Scenarios

Once the twin reflects reality, you can ask what-if questions with simple models attached to nodes:

  • Compressed air pressure reduction: model compressor power as a function of discharge pressure and demand. A widely used rule of thumb is that lower system pressure reduces compressor energy; the twin lets you estimate the effect using your own measured load profile rather than generic figures.
  • Leak repair: measure compressor power during non-production hours when air demand should be near zero. That base load approximates leakage; the twin shows the energy that a repair campaign could recover.
  • Load shifting: replay a week of metered data with flexible loads moved to off-peak hours to see the effect on peak demand.
  • Idle shutdown policies: combine line state with line energy to see how much is consumed while idle, and simulate automatic standby after a set idle time.

Keep scenario calculations in your own services or notebooks, reading history from a time-series database. The broker's role is to deliver the live data reliably; it does not store history or run models.

Implementation Checklist

  1. Draw the site's single-line diagram and energy flow topology before buying meters.
  2. Identify the largest consumers and meter them first; the long tail can be estimated.
  3. Choose a polling interval that matches the question: 1 to 15 seconds for process correlation, a minute for building loads.
  4. Publish cumulative counters as well as power.
  5. Publish production state on the same broker so energy per unit and idle consumption can be computed.
  6. Persist data with a subscriber (Telegraf to InfluxDB, or a Python script to TimescaleDB).
  7. Add a balance check per distribution node and review gaps weekly.
  8. Use ConnectMQ's threshold alert rules for simple limits such as unexpected night-time base load.

Common Pitfalls

  • Mixed units and scaling factors. Modbus registers often need scaling. Validate gateway readings against the meter display.
  • Unsynchronized sampling. Comparing a main meter read at second 0 with sub-meters read at second 40 creates false gaps. Average over aligned windows.
  • Only metering electricity. Gas, steam and compressed air often hide the largest savings.
  • No ownership. An energy twin needs someone who reviews it regularly and turns findings into actions.

Energy modeling combines well with a building digital twin for HVAC loads and a factory digital twin for production lines.

Stream Your Energy Data with ConnectMQ

ConnectMQ offers a secure, managed MQTT backbone for meter gateways and twin services, with TLS on port 8883 and WebSocket access for browser dashboards. Sign up free at app.connectmq.com, no credit card required, create a Serverless broker and connect your first meter gateway in minutes.

Frequently Asked Questions

What is a digital twin for energy?

It is a live model of a site's energy sources, conversion assets, distribution and consumers, fed by meter data, that shows where energy goes and lets you test efficiency changes.

How often should energy meters publish data?

It depends on the question. Every few seconds suits correlation with process events, while one-minute intervals are usually enough for building loads and billing analysis.

Can I connect Modbus energy meters to MQTT?

Yes. A gateway such as Node-RED or Telegraf reads the Modbus registers and publishes values to MQTT topics that the twin subscribes to.

Does the MQTT broker store my energy history?

No. The broker delivers live messages. Use a separate subscriber to write data into a time-series database for history and scenario analysis.

Related articles

All articles →

Your private MQTT broker is a few clicks away

Create an account, get your broker credentials and connect your first device — no servers to install, patch or scale.