BT San Technology

21 January 2026

Energy Monitoring: Measuring Energy per Unit Produced in a Way That Means Something

26 min read · Smart factory

Illustration: an electrical panel with power meters and current clamps, a pallet of finished goods in front, a tablet showing energy per unit
AI-generated illustration

This month's power bill is 8% higher than last month's. The executives ask what happened. Production says the plant made more this month. If all you have is the plant-wide total, you cannot say who is right. A higher bill could come from higher output, a switch to a product that uses more power, machines left running while waiting for material, or a worn mold that needs more force.

This article builds a kWh-per-good-piece indicator, split by shift and product, from cumulative meter data and production data. It comes with TypeScript that runs directly on Node 24 with nothing to install, and a made-up CSV you can re-run. It covers converting cumulative readings into energy per interval, separating the power used while not producing, setting a product-mix-aware baseline for comparison, and finally the electricity cost.

The real problem: dividing the total by the piece count gives a number that tells you nothing

The easiest approach is to divide total kWh by the number of pieces produced and get one kWh-per-piece figure per month. That figure moves for many reasons that have nothing to do with machine efficiency. Consider three hypothetical situations, not any customer's project.

  • A plastic injection plant makes two sizes. A small piece uses little power per piece and a large piece uses a lot. In a month when the plan favors large pieces, the average kWh per piece rises by itself even though the machines did not get worse.
  • A food packing line waits one hour for raw material on the night shift. The machines stay on, and the power used while waiting is divided over that shift's output. The night shift looks wasteful, but the problem is material delivery.
  • A mold in the stamping department wears out, so more parts are reworked or scrapped. The energy spent on bad parts is still counted as production energy. The total does not show which part is wasted.

The fix is to state clearly what each period's energy belongs to: machines off, machines on but not producing, or which product was running. Then compare each product against its own baseline. ISO 50006 calls this approach comparison against an energy baseline (EnB) through energy performance indicators (EnPI), adjusted for relevant variables such as volume and product type.

What the documents say, and what this example chooses on its own

TopicWhat the document saysEffect on our example
Indicators and baselineISO 50006 (preview edition) describes EnB and EnPI as a way to compare energy performance between periods, with adjustment for relevant variables and normalization.The example uses good-piece count by product as the relevant variable and uses the median across shifts as the baseline.
Data qualityISO 50006 discusses data quality and outliers, which must be handled before use.The example handles counter wraparound, counter resets and missing data, and flags intervals that are estimates.
Adjusting for product mixThe US ENERGY STAR EPI for plants estimates energy with adjustment for production factors, so plants with different product mixes can be compared.The example computes expected energy from that shift's product mix (mix-aware) instead of using a single average.
Cumulative meter valuesModbus registers are 16 bits wide. Larger values must be read across several registers, so check the meter manual for how it stores kWh.The example makes the counter ceiling (regMax) a parameter. Change it to match the real meter's manual.
CT and accuracy classA current transformer (CT) has a ratio and an accuracy class. The meter's reading must be multiplied by, or configured with, the ratio of the CT actually installed.The example starts from kWh values whose ratio is already set correctly. It does not simulate CT error.
Electricity tariffPEA tariff announcement in effect from the September 2026 bill, category 3.2.3 TOU (medium business, below 22 kV): energy charge Peak 4.3297 and Off Peak 2.6369 baht per kWh, demand charge 210.00 baht per kW. Peak is 09:00-22:00 Monday to Friday. Saturdays, Sundays and normal public holidays are Off Peak all day. For MEA, category 3.2.3 (below 12 kV) uses the same energy charges of 4.3297 and 2.6369 baht per kWh, with a service charge of 312.24 baht per month. The rates exclude Ft and VAT. The Ft for September-December 2026 announced by the ERC is 16.23 satang per unit, added to every kWh.The example uses these two energy charges and treats Saturday and Sunday as Off Peak, but it does not include a public holiday calendar. It excludes Ft, VAT, demand and the service charge. A plant in a different category or voltage level must change the numbers to match its own bill.
Node used to run itNode.js 24 runs .ts files by stripping types, with no compile step, and has a built-in node --test.The example does not use enum or namespace, and uses imports with the .ts extension.
Data from documents read on 2026-11-21. ISO 50006 was read from the iTeh preview edition, not the full edition.

All numbers in this article come from made-up data generated by a seeded random generator. They are not from a real plant or meter. The thresholds used (2 kW, ±15%, 12%) are choices made by this example and must be adjusted for real machines.

Files in the example

FilePurpose
energy.tsConverts cumulative kWh into energy per 5-minute interval and handles rollover, reset and missing data
shifts.tsSplits energy into base / idle / run, assigns it to products, totals by shift, sets flags and computes electricity cost
demo.tsReads the CSV and prints the report by shift and by product
energy.test.tsSix tests using node:test
gen-data.tsGenerates meter.csv and production.csv (made-up, seeded)
meter.csv, production.csvMade-up data: 4 days, 12 shifts, 1 rollover, 1 reset, and 1 gap of 40 minutes of missing data
output.txtActual output of node demo.ts
Everything is in the folder examples/energy-monitoring-per-production-unit/. Requires Node 22.6 or later (24 recommended). No npm install needed.

Step 1: From cumulative values to energy per interval

Most meters give a cumulative kWh value that keeps increasing. What we need is the energy of each period, which is the difference between two consecutive readings. That sounds easy, but three cases silently break the numbers: the counter fills up and wraps to zero (rollover), the counter is reset because the meter was replaced or the device was reset, and samples are missing because the network dropped.

A negative difference can be either a rollover or a reset. The example tells them apart by the distance from the wraparound point. If the previous value was close to the maximum, close enough that the plant running at full power during that interval could have wrapped it, add regMax. If not, treat it as a reset and use the new value as that interval's energy. For missing data, the example spreads that block of energy evenly over every missing 5-minute interval and tags it as a gap, so the report can say it is an estimate.

energy.ts
// Step 1: turn a cumulative kWh register into energy per interval.
export type Reading = { t: number; reg: number }; // t = epoch ms
export type Note = "ok" | "rollover" | "reset" | "gap";
export type Interval = { t0: number; t1: number; kwh: number; note: Note };
export type Opts = { regMax: number; stepMs: number; maxKw: number };

export function parseMeter(csv: string): Reading[] {
  return csv.trim().split("\n").slice(1).map((l) => {
    const [ts, reg] = l.split(",");
    return { t: Date.parse(ts), reg: Number(reg) };
  });
}

export function toIntervals(rs: Reading[], o: Opts): Interval[] {
  const out: Interval[] = [];
  for (let i = 1; i < rs.length; i++) {
    const a = rs[i - 1], b = rs[i];
    const dt = b.t - a.t;
    if (dt <= 0) continue; // duplicate or out-of-order sample: ignore
    let kwh = b.reg - a.reg;
    let note: Note = "ok";
    if (kwh < 0) {
      // Largest energy the plant could have used in dt. If the old value was within
      // that distance of the wrap point, the counter wrapped. Otherwise assume a reset.
      const maxKwh = (o.maxKw * dt) / 3600000;
      if (a.reg > o.regMax - maxKwh) { kwh += o.regMax; note = "rollover"; }
      else { kwh = b.reg; note = "reset"; } // simplified: assumes the new meter started at 0
    }
    const n = Math.round(dt / o.stepMs);
    if (n > 1) { // missing samples: spread the lump evenly, mark as estimated
      for (let k = 0; k < n; k++) {
        out.push({ t0: a.t + (dt * k) / n, t1: a.t + (dt * (k + 1)) / n, kwh: kwh / n, note: "gap" });
      }
    } else out.push({ t0: a.t, t1: b.t, kwh, note });
  }
  return out;
}
energy.ts: adjust the parameters regMax, stepMs and maxKw to the real meter

Spreading energy evenly over the gap is a rough estimate. If the machine switched on and off during that time, the per-interval numbers will be off, but the total stays correct. A real system should keep estimates separate from measured values all the way through to the report, as this example does by printing the word estimated at the end of the shift.

Step 2: Split energy into base load, idle power and run power

The production data says which product ran in which period, and how many good and bad pieces it made. Intervals inside a production run count as run power and are assigned to that product. For the remaining intervals, use the average power. If it is below the 2 kW threshold, the machine is considered off and only the base load remains, such as lighting and the control system. If it is above, the machine is considered left on (idle). This three-way split shows that power used while waiting for material is a management problem, not a production process problem.

shifts.ts · lines 30–35
export function classify(iv: Interval, segs: Segment[]): { state: State; product?: string } {
  const seg = segs.find((s) => iv.t0 >= s.t0 && iv.t0 < s.t1);
  if (seg) return { state: "run", product: seg.product };
  const kw = iv.kwh / ((iv.t1 - iv.t0) / H);
  return { state: kw < OFF_KW ? "base" : "idle" };
}
shifts.ts: the classify function decides interval by interval

The shift boundaries in the example are A 06-14, B 14-22 and C 22-06, and a night shift counts as belonging to the day it starts. Pieces are counted by the shift in which the run started. If a run spans two shifts, agree with production on how to count it, because this changes the per-shift numbers.

shifts.ts · lines 44–64
export function byShift(ivs: Interval[], segs: Segment[]): ShiftRow[] {
  const rows = new Map<string, ShiftRow>();
  const get = (key: string) => {
    if (!rows.has(key)) rows.set(key, { key, base: 0, idle: 0, estimated: 0, cost: 0, run: {}, good: {}, reject: {} });
    return rows.get(key)!;
  };
  for (const iv of ivs) {
    const r = get(shiftKey(iv.t0));
    const c = classify(iv, segs);
    if (c.state === "run") r.run[c.product!] = (r.run[c.product!] ?? 0) + iv.kwh;
    else r[c.state] += iv.kwh;
    if (iv.note === "gap") r.estimated += iv.kwh;
    r.cost += iv.kwh * rateAt(iv.t0);
  }
  for (const s of segs) { // pieces belong to the shift where the segment starts
    const r = get(shiftKey(s.t0));
    r.good[s.product] = (r.good[s.product] ?? 0) + s.good;
    r.reject[s.product] = (r.reject[s.product] ?? 0) + s.reject;
  }
  return [...rows.values()].sort((a, b) => a.key.localeCompare(b.key));
}
shifts.ts: the byShift function totals energy, pieces and electricity cost by shift

Step 3: A baseline per product, and mix-aware flags

The baseline for each product is its run kWh per good piece, using the median across shifts so that an abnormal shift does not drag the baseline with it. Flagging works like this. The expected energy for a shift is the sum, over products, of the product's baseline times its good-piece count. If the shift's run energy is more than 15% above expected, set the flag RUN_HIGH. If idle energy is more than 12% of the shift's total energy, set the flag IDLE_HIGH. They are separate flags because the causes differ and so do the people who need to fix them.

shifts.ts · lines 73–89
// Baseline per product = median of each shift's run kWh per good piece (robust to a few bad shifts).
export function baselines(rows: ShiftRow[]): Record<string, number> {
  const per: Record<string, number[]> = {};
  for (const r of rows) for (const p of Object.keys(r.run)) if ((r.good[p] ?? 0) >= 50) (per[p] ??= []).push(r.run[p] / r.good[p]);
  return Object.fromEntries(Object.entries(per).map(([p, v]) => [p, median(v)]));
}

export type Flag = "ok" | "RUN_HIGH" | "IDLE_HIGH";
// Mix-aware check: expected run kWh = sum(baseline * good pieces of each product in THIS shift).
export function check(r: ShiftRow, base: Record<string, number>, tol = 0.15, idleShare = 0.12) {
  const expected = Object.keys(r.run).reduce((a, p) => a + (base[p] ?? 0) * (r.good[p] ?? 0), 0);
  const ratio = expected > 0 ? runKwh(r) / expected : NaN;
  const flags: Flag[] = [];
  if (ratio > 1 + tol) flags.push("RUN_HIGH");
  if (r.idle / totalKwh(r) > idleShare) flags.push("IDLE_HIGH");
  return { expected, ratio, flags: flags.length ? flags : (["ok"] as Flag[]) };
}
shifts.ts: the baselines and check functions

A baseline built from a short period can mislead. If more than half the shifts in that period had abnormal machines, the median is wrong too. In real work, use at least several weeks of data. Separate the baseline by season or temperature if the machine produces cooling or heat. And have a process engineer confirm that the period used as the baseline was normal.

Run it and read the result

The made-up data has two products. The small piece, P-S, uses about 0.12 kWh per good piece, and the large piece, P-L, about 0.6 kWh per good piece. Three events are built in: one gap of missing data in shift A on March 3, shift A on the 4th where the machine waited for a long time, and shift B on the same day where the large-piece mold is worn. The output of node demo.ts is as follows.

output.txt
1) readings 1146, intervals 1152, notes {"ok":1142,"rollover":1,"gap":8,"reset":1}
   energy 1523.13 kWh, of which estimated (gap) 14.62 kWh
2) baseline run kWh per good piece: P-S=0.1211  P-L=0.5770
3) per shift (naive = total kWh / good pieces; fair = run kWh vs mix-aware expectation)
shift        good  rej  total  base  idle   run  naive  ratio  flag             cost(THB)
2026-03-02-A   515   12  128.1   0.0   7.9 120.2 0.249   1.00  ok                  490
2026-03-02-B   469   11  136.3   0.0   7.0 129.4 0.291   1.00  ok                  590
2026-03-02-C   776   16   99.2   0.3   5.8  93.0 0.128   0.99  ok                  261
2026-03-03-A   265    9  158.0   0.3   4.0 153.6 0.596   1.00  ok                  582  (estimated 14.6 kWh)
2026-03-03-B   514   12  128.2   0.0   8.1 120.1 0.249   1.00  ok                  555
2026-03-03-C   778   16   99.7   0.3   6.0  93.4 0.128   0.99  ok                  263
2026-03-04-A   318    8  112.8   0.3  15.9  96.7 0.355   1.00  IDLE_HIGH           435
2026-03-04-B   438   38  175.0   0.0   7.0 168.0 0.399   1.38  RUN_HIGH            758
2026-03-04-C   771   16  100.0   0.3   6.0  93.7 0.130   1.00  ok                  264
2026-03-05-A   270    9  158.3   0.3   4.0 154.0 0.586   0.99  ok                  583
2026-03-05-B   513   12  128.0   0.0   8.0 119.9 0.249   1.00  ok                  554
2026-03-05-C   765   16   99.6   0.3   6.0  93.3 0.130   1.01  ok                  263
4) all shifts: 6392 good pieces, 1523.1 kWh, 0.238 kWh/piece (one number for everything), cost 5597 THB
   PEA TOU 3.2.3 peak 4.3297 / off-peak 2.6369 THB/kWh, energy charge only (no Ft, VAT, demand charge)
5) per product over all shifts (run energy only, then with idle+base shared by run time)
   P-S: good 5038, reject 123, run 623.0 kWh = 0.1237 kWh/good, loaded 0.1312 kWh/good, energy in rejects 14.8 kWh
   P-L: good 1354, reject 52, run 812.2 kWh = 0.5999 kWh/good, loaded 0.6366 kWh/good, energy in rejects 30.0 kWh
Actual output run on 2026-11-21 with node demo.ts (Node 24). All data is made up.
  1. Part 1: 1,146 counter readings were converted into 1,152 intervals. It found 1 rollover, 1 reset, and 8 gap intervals totaling 14.62 kWh that are estimates. The total of 1,523.13 kWh matches the true energy used by the data generator, so we know the conversion did not lose or add any power.
  2. Part 2: The baselines come out at 0.1211 and 0.5770 kWh per good piece. These are close to the values used to generate the data (14 kW at 120 pieces per hour, and 22 kW at 40 pieces per hour) but not exactly equal, because the energy of bad pieces is counted with the good ones and the data has random noise.
  3. Part 3: The naive column is the shift's kWh divided by good pieces. It swings from 0.128 to 0.596 even though the machines run normally, because each shift makes a different mix of products. The ratio column, which compares against the mix-aware expected value, is about 1.00 for every shift except two.
  4. Shift 2026-03-04-A is flagged IDLE_HIGH, with 15.9 kWh of idle power. The problem is not the machine. It is a machine left on while waiting, so the cause has to be traced together with the downtime records in the production data.
  5. Shift 2026-03-04-B is flagged RUN_HIGH, with a ratio of 1.38 and 38 bad pieces against 11-12 in the other shifts. This pattern matches a worn machine or mold. The example does not prove the cause. The system only points to which shift to look at.
  6. Part 4: A single plant-wide figure of 0.238 kWh per piece hides all of this. Part 5 splits by product: the energy contained in bad pieces is about 14.8 kWh for P-S and 30.0 kWh for P-L, and when idle and base load are allocated to products in proportion to production time, the loaded value is higher than the run-only value.

The cost column counts only the energy charge under the PEA TOU 3.2.3 tariff (Peak 4.3297, Off Peak 2.6369 baht per kWh). The total across all shifts is 5,597 baht. Use this number to see how electricity cost is allocated to shifts and products, not as the bill amount. A real bill also has Ft, VAT, the monthly service charge and the peak demand charge, which is based on the month's maximum kW during Peak, and there may be a power factor penalty. This example does not simulate those parts, and a plant on a different category or voltage level will have different rates.

The test suite

The file energy.test.ts has six tests. They cover the things that give silently wrong numbers when they break: a normal difference and a duplicate sample, rollover versus reset, a gap where the total must stay the same, finding the shift for a night shift, classifying idle versus base, and the last and most important one: machines with the same efficiency but a product mix that differs fivefold. The naive numbers differ, but the ratio must be 1, and when the large product's power use is increased by 30%, exactly one flag, RUN_HIGH, must appear.

energy.test.ts · lines 46–55
test("mix-aware check: same efficiency, very different mix, naive number differs but ratio stays 1", () => {
  const row = (p: string, good: number, perPc: number): ShiftRow =>
    ({ key: p, base: 0, idle: 0, estimated: 0, cost: 0, run: { [p]: good * perPc }, good: { [p]: good }, reject: { [p]: 0 } });
  const s = row("P-S", 800, 0.12), l = row("P-L", 160, 0.6);
  const base = baselines([s, l]);
  assert.ok(Math.abs(check(s, base).ratio - 1) < 1e-9 && Math.abs(check(l, base).ratio - 1) < 1e-9);
  assert.ok(l.run["P-L"] / 160 > 4 * (s.run["P-S"] / 800)); // naive: 5x apart
  const worse = row("P-L", 160, 0.6 * 1.3);
  assert.deepEqual(check(worse, base).flags, ["RUN_HIGH"]);
});
energy.test.ts: the test for the mix-aware comparison

Running node --test energy.test.ts gave 6 passed and 0 failed on 2026-11-21.

What else to check before real use

  • Meter type and class: set the accuracy needed for analysis from the energy difference you want to detect (this is our observation, and an electrical engineer must confirm the right class). If you want to see a 3% difference, a meter and CT with errors near 3% tell you nothing.
  • CT ratio: it must be set in the meter to match the CT actually installed and recorded in the metering point document. If it is set wrong, the energy is wrong by a constant proportion in every interval, which you cannot see on a chart. Compare against a reference meter or one month of bills. Installing CTs and running the wiring is electrical work that must be done by a licensed person under Thai safety rules.
  • Meter time versus the piece counter: if the two clocks differ by five minutes, pieces at the start of a shift end up with the previous shift's energy. Sync time from a single source (NTP) and check it periodically. This example assumes the clocks match.
  • Sub-metering per machine or per line: per line is cheaper and enough to find which line is abnormal. Per machine tells you which machine but needs more metering points. Start with machines that use a lot of power or are shared, such as air compressors, whose energy must be allocated to the lines that use the air by an agreed rule.
  • Energy baseline and EnPI in the ISO 50006 sense: you must define the reference period, the relevant variables, and the threshold that counts as a real change, and you must adjust the baseline when the machine or process changes. This example only builds a simple baseline per product. It does not follow the standard's requirements, and certification to ISO 50001 is a separate matter.
  • Allocating idle and base load to products: the example allocates by production time. This is an agreement that production and cost accounting must approve. Other methods work too if they are stated clearly.

Adapting it to your business

A plastic injection plant with several products per shift

Keep a separate baseline for each machine and mold pair, because the same product on machines of different sizes uses different power. Count warm-up energy as its own item if warm-up is long.

A food packing line with a shared cold room

Cold room power is not tied directly to pieces. Measure it as a shared load, allocate it by production hours, and compare it with the outdoor temperature too. Otherwise hot weather will make the production line look worse.

A single-shift operation that wants to start simple

If you have one meter for the whole plant and make one product, you can do Steps 1 and 2 and look only at idle power per shift. This is often the data that pays off before anything else.

Common mistakes

  • Dividing total kWh by total pieces and comparing month to month, without looking at the product mix and the time machines sat idle.
  • Not handling rollover and reset, so one interval has negative or enormous energy and the whole month is wrong.
  • Filling missing data with zero, so that interval's power disappears from the report, or using an estimate without telling the reader.
  • Setting the CT ratio wrong, or changing a CT without recording it, so the numbers are wrong all the time with no warning signal.
  • The meter clock and the production data do not match, so pieces at the end of a shift fall into the next shift.
  • Setting flag thresholds by gut feeling, so the flag goes up every shift and nobody looks at it. Tune the thresholds from data in a normal period and review them regularly.
  • Counting the energy of bad pieces as the energy of good pieces without looking at them separately.

Checklist before real use

  1. Pick metering points on machines or lines that use a lot of power, and write a metering point document that records the meter brand, the CT multiplier and the location.
  2. Check the meter readings against a reference meter or the bill for at least one cycle.
  3. Sync the time of the meter, the data logger and the production data from a single source.
  4. Agree with production on counting good and bad pieces, counting runs that span shifts, and when a run starts and stops.
  5. Set the baseline per product from a normal period of at least several weeks, and record which period was used.
  6. Set the flag thresholds and flag owners: who must look when a flag goes up, and within how many hours.
  7. Test the edge cases (rollover, reset, missing data, time across shifts) before opening the report to other people.
  8. State in the report which parts are estimates and which electricity tariff was used.

Caveats of the example: all data is made up. It does not simulate meter and CT error, does not sync time, and does not adjust for temperature. Averaging over a gap in the data is a rough estimate. The thresholds of 2 kW, 15% and 12% and the method of allocating idle power are our own choices. The tariff uses only the PEA TOU 3.2.3 energy charge, excluding Ft, VAT, demand and public holidays. Use it as a learning example, not as production-ready code, and it is not electrical or ISO 50001 consulting.

References

  1. ISO 50006:2023 ฉบับพรีวิวจาก iTeh (EnB, EnPI, relevant variable, normalization, คุณภาพข้อมูล) (accessed 2026-11-21)
  2. ENERGY STAR Energy Performance Indicators for plants (ปรับพลังงานตามปัจจัยการผลิต) (accessed 2026-11-21)
  3. Modbus — Wikipedia (รีจิสเตอร์ 16 บิต) (accessed 2026-11-21)
  4. Current transformer — Wikipedia (อัตราส่วนและคลาสความแม่นยำ) (accessed 2026-11-21)
  5. Electricity meter — Wikipedia (kWh สะสมของมิเตอร์) (accessed 2026-11-21)
  6. การไฟฟ้าส่วนภูมิภาค หน้าอัตราค่าไฟ (ชี้ไปยังไฟล์อัตรา) (accessed 2026-11-21)
  7. กฟภ. อัตราค่าไฟฟ้า ใช้ตั้งแต่บิลเดือนกันยายน 2569 (ประเภท 3.2 TOU, ช่วง Peak/Off Peak) (accessed 2026-11-21)
  8. กฟน. อัตราค่าไฟฟ้าประเภท 3 กิจการขนาดกลาง (3.2.3 TOU ต่ำกว่า 12 kV, ช่วง Peak/Off Peak) (accessed 2026-11-23)
  9. กกพ. ค่า Ft งวดกันยายน-ธันวาคม 2569 ที่ 16.23 สตางค์ต่อหน่วย (ข่าว 23 ก.ค. 2569) (accessed 2026-11-23)
  10. Node.js — Test runner (node:test) (accessed 2026-11-21)
  11. Node.js — Running TypeScript natively (type stripping) (accessed 2026-11-21)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer