BT San Technology

26 January 2026

Collecting data from an old machine with no network port: CT clamp, count pulses and MQTT that survives network drops

26 min read · Smart factory

Illustration: an older machine with a new sensor box beside its panel, a tablet showing a run/stop timeline with unexplained stops
AI-generated illustration

A press that is more than ten years old still produces well, but it has no network port and no protocol to query, and the shift lead knows when it stops only from walking over to look or from a notebook. Buying a new machine is not the only option, because most machines already report their state through things you can measure from outside: the motor current, and the part-count signal from a sensor or switch the machine already has.

This article builds on the earlier survey article about old machines. It writes the part that sits behind the sensor: turning current into a state, counting parts correctly even when the signal bounces, summarizing into time windows, and sending the result to MQTT without losing data when the network drops. The example is TypeScript that Node 24 runs directly. All data is simulated, so it runs without a real machine. A manager can follow the explanations and tables, and an engineer can run the code.

The real problem: the machine does not talk, but reliable data is still available

Consider three hypothetical situations. They are not projects of any BT San customer.

  • A metal stamping plant: the press has no communication port. The shift lead notes 3 stops, but nobody knows that the motor current dropped in intervals while waiting for material. The machine was not broken, but it was not producing either.
  • A food packaging plant: the packing machine has a contact-type counter that outputs pulses, but when someone counts by hand, the number is higher than the real one because the switch bounces several times per part.
  • A plant with an unstable network: the gateway sends data to the server, but the Wi-Fi drops now and then. The data from the dropped periods is lost, the chart has holes, and downtime is calculated wrongly.

These three cases are solved by different pieces, and all of them are needed: reading current as a state without flicker, counting pulses with the bounce removed, and sending data in a way that survives network drops.

What the documentation says, and what this example assumes

TopicWhat the documentation saysEffect on the code and installation
Split-core CTWikipedia states that a split-core CT has a two-part or removable core and is clamped around a wire without first disconnecting the wireYou can read current from outside without touching the machine's control circuit, but access to the wires must still be done by an electrician
CT secondary sideStates that the secondary side should not be disconnected from its load (burden) while the primary side carries current, because a dangerous high voltage can appearUse a CT made for connecting to the measurement module, following that model's manual, and never leave the secondary terminals open while current flows
Switch bounceWikipedia explains contact bounce and how to filter it (debounce). The page does not give a typical bounce time for every kind of switchYou have to measure it yourself on the real machine with an oscilloscope or a fast data logger. The 20 ms in the code is an assumed value
MQTT 3.1.1OASIS specification: Remaining Length is encoded 7 bits at a time, up to 4 bytes (128 = 0x80 0x01). QoS 1 is acknowledged with PUBACK and is at least once, so a message can be duplicated. CONNECT uses protocol level 4 and has Clean SessionBe ready to receive duplicates, put a seq number in each message, and build packets that match the specification
Ready-made clientsMQTT.js is an MQTT client library for Node.js and browsers. It uses MQTT v3.1.1 by default, and has a reconnectPeriod option and a queue for QoS 0 messages while disconnected (queueQoSZero). Mosquitto is an open-source MQTT serverReal work should use a maintained client with a real broker. The hand-written encoder in this article is for learning only
TCP is a streamThe Node documentation states that net.Socket is an abstraction of a TCP socket (stream.Duplex). Data from the data event is not guaranteed to be one event per messageYou must write your own packet splitter based on length (takePackets) that handles packets that arrive incomplete or stuck together
Summary of the documents cited at the end of the article, as of the access date 2026-11-21. For real details, read the manual of the CT and measurement module you use.

Every number in the example (thresholds of 6.0 A and 4.0 A, minimum time of 10 seconds, debounce of 20 ms, production cycle of 22 seconds, the shift state table) is simulated data that we set ourselves. It does not come from a real machine or from any manufacturer's documentation.

Overview of the example

All the code is in the folder examples/retrofit-old-machine-data-collection/. It uses only Node 24 built-ins, has no npm install, and makes no network connection outside the machine (the simulated broker listens on 127.0.0.1). TypeScript runs directly with node file.ts, which strips only the types. So it does not use enum, namespace or constructor parameter properties, which the Node documentation says are not supported. It also requires the .ts extension in import statements and import type for type-only imports.

FileRole
sim.tsSimulates current every 1 second and pulse edges for an 8-hour shift, with bounce, noise and a 6-second current dip
state.tsConverts current to the states off / idle / run using hysteresis and a minimum time
pulses.tsDebounces pulses and then counts parts
metrics.tsSummarizes into 15-minute windows: time per state, part count, cycle time, abnormal gaps
mqtt.ts / fake-broker.tsA minimal MQTT 3.1.1 encoder using node:net, and a local simulated broker
store-forward.tsA queue that holds messages when sending fails and drains them in order after reconnecting
demo.ts / retrofit.test.tsA script that runs the whole pipeline with a cable disconnect, and a node:test suite with 7 cases

The pipeline is: current goes to state.ts and gives state intervals. Pulses go to pulses.ts and give the time of each part. The two are combined in metrics.ts into time windows, then sent through store-forward.ts to MQTT. Here it is step by step.

Step 1: Convert current to a state without flicker

The current of a running machine swings with the load. If you decide run whenever the current exceeds a single value, the state flickers between run and idle whenever the current hovers around that value. The example fixes this in two layers. The first is hysteresis: from idle, the current must be above 6.0 A to become run, but from run it must fall below 4.0 A to leave run. In between, the previous state is kept. The second is a minimum time: a new state must hold for at least 10 seconds before it is accepted, and once accepted, the start time is moved back to the point where the current really started heading that way.

state.ts · lines 14–40
export const DEFAULT_CFG: ClassifyConfig = { offBelow: 0.5, idleAbove: 1.0, runOn: 6.0, runOff: 4.0, minSec: 10 };

// สถานะที่กระแสนี้ "ชี้ไป" โดยดูจากสถานะปัจจุบัน (เกณฑ์ขึ้นกับทิศทาง = hysteresis)
export function candidate(cur: State, amps: number, c: ClassifyConfig): State {
  if (cur === "run") return amps < c.offBelow ? "off" : amps < c.runOff ? "idle" : "run";
  if (cur === "idle") return amps < c.offBelow ? "off" : amps >= c.runOn ? "run" : "idle";
  return amps >= c.runOn ? "run" : amps >= c.idleAbove ? "idle" : "off";
}

export function classify(samples: Sample[], cfg: ClassifyConfig = DEFAULT_CFG, initial: State = "off"): Interval[] {
  const out: Interval[] = [];
  let cur = initial;
  let start = samples[0]?.t ?? 0;
  let pending: { state: State; since: number } | null = null;
  for (const s of samples) {
    const cand = candidate(cur, s.amps, cfg);
    if (cand === cur) { pending = null; continue; }
    if (!pending || pending.state !== cand) pending = { state: cand, since: s.t };
    if (s.t - pending.since + 1 >= cfg.minSec) {
      // ยืนยันแล้ว: ย้อนเวลาเปลี่ยนไปที่ตัวอย่างแรกที่เริ่มชี้ไปทางนั้น
      out.push({ state: cur, start, end: pending.since });
      cur = cand; start = pending.since; pending = null;
    }
  }
  const last = samples.at(-1);
  if (last) out.push({ state: cur, start, end: last.t + 1 });
  return out.filter((i) => i.end > i.start);
state.ts: direction-dependent thresholds, and confirming a new state after it holds for the full time
  • The simulated data has a 6-second current dip during a run period. It is shorter than 10 seconds, so it is filtered out and not counted as a stop. If a real machine stops for less than the threshold and you want to see it, reduce the minimum time or keep short events in a separate channel.
  • When a motor starts, the current spikes briefly (inrush). The example simulates this too, and it does not cause a wrong state because the minimum time covers it.
  • The idle and run thresholds depend on the machine. Measure the real current when the machine is idle and when it is producing before you set them, and a machine whose load swings a lot may need a moving average first.
  • On a machine with several motors, the total current on the main line may not be clear. Plan a measurement point on the main motor only.

Step 2: Count parts from a bouncing pulse

A switch or contact sensor does not change level cleanly. When it changes, it often bounces as a burst of short edges. If you count every edge, you get too many parts. The example uses a simple rule: an edge counts only if the new level stays steady for at least 20 ms (a next edge that arrives sooner is treated as bounce or noise), and then only rising edges are counted.

pulses.ts · lines 3–18
// debounce: ขอบสัญญาณใดจะมีผลก็ต่อเมื่อระดับใหม่นิ่งอย่างน้อย debounceMs
// (ขอบที่ตามมาเร็วกว่านั้นถือเป็น bounce หรือสัญญาณรบกวน) แล้วนับเฉพาะขอบขึ้น
export function countPulses(edges: Edge[], debounceMs = 20): number[] {
  const rises: number[] = [];
  let level: 0 | 1 = 0;
  for (let i = 0; i < edges.length; i++) {
    const e = edges[i];
    const next = edges[i + 1];
    const stable = !next || next.tMs - e.tMs >= debounceMs;
    if (stable && e.level !== level) {
      level = e.level;
      if (level === 1) rises.push(e.tMs);
    }
  }
  return rises; // เวลา (ms) ของแต่ละชิ้นที่นับได้
}
pulses.ts: debounce, then count only rising edges at a steady enough level

The simulated data deliberately adds 1 to 3 bounce pairs per edge and 24 noise spikes 0.2 ms wide. The result is 11,330 raw edges and 1,122 parts counted, exactly the number used to generate the data. Note that this is because the simulated data was built to match the rule. On a real machine, you must measure the real bounce time and pulse width before choosing the debounce value. If it is longer than the real pulse width, parts are lost.

If the machine makes several parts per cycle, or the pulse comes from another counter (for example an encoder signal), you must convert units first. For example, 1 pulse does not always equal 1 part. Count by hand over a short period and compare before using the real numbers.

Step 3: Summarize into time windows

Sending data to the server every second is unnecessary, and wasteful on a poor network. The example summarizes into 15-minute windows, giving time per state, part count, average and median cycle time, and the number of long gaps. A long gap is the distance between two parts that exceeds 2.5 times the ideal cycle time (22 seconds in the example). It is interpreted as a stop instead of being averaged in with normal cycles.

metrics.ts · lines 26–51
export function buildWindows(iv: Interval[], pulsesMs: number[], totalSec: number, windowSec: number, idealCycleSec: number, stopFactor = 2.5): Window[] {
  const out: Window[] = [];
  for (let from = 0; from < totalSec; from += windowSec) {
    const to = Math.min(from + windowSec, totalSec);
    const idx = pulsesMs.map((t, i) => [t / 1000, i] as const).filter(([t]) => t >= from && t < to);
    const cycles: number[] = [];
    let longGaps = 0;
    for (const [t, i] of idx) {
      if (i === 0) continue;
      const gap = t - pulsesMs[i - 1] / 1000; // ใช้ชิ้นก่อนหน้าแม้อยู่คนละหน้าต่าง
      if (gap > idealCycleSec * stopFactor) longGaps++;
      else cycles.push(gap);
    }
    const sec = stateSeconds(iv, from, to);
    const mid = iv.find((i) => i.start <= to - 1 && i.end > to - 1);
    out.push({
      startSec: from, sec: to - from,
      runSec: round(sec.run, 1)!, idleSec: round(sec.idle, 1)!, offSec: round(sec.off, 1)!,
      count: idx.length,
      cycleAvgSec: round(cycles.length ? cycles.reduce((a, b) => a + b, 0) / cycles.length : null),
      cycleMedianSec: round(median(cycles)), longGaps,
      stateAtEnd: mid?.state ?? "off",
    });
  }
  return out;
}
metrics.ts: buildWindows separates normal cycles from long gaps

The data sent is one small JSON object per window, with a seq number that increases by one, the window start time in ISO 8601 UTC, and the site/line/machine names. The topic in the example is btsan-demo/plant1/line2/press07/window, which is a made-up name. Name the levels from broad to narrow so that you can subscribe to a whole line or a whole plant easily.

Step 4: Build the MQTT packet yourself, to understand what goes over the wire

This part is written for learning only. For real work, use MQTT.js or Eclipse Paho with a broker such as Mosquitto or EMQX, because those libraries handle keep-alive, reconnection, QoS 2 and the edge cases of the specification that this example does not. The encoder in the example only does CONNECT, PUBLISH at QoS 1, and waits for PUBACK.

mqtt.ts · lines 7–21
// Remaining Length: ทีละ 7 บิต บิตสูงสุดบอกว่ายังมีไบต์ต่อ (สูงสุด 4 ไบต์)
export function encodeLength(n: number): Buffer {
  const out: number[] = [];
  do { let d = n % 128; n = Math.floor(n / 128); if (n > 0) d |= 0x80; out.push(d); } while (n > 0);
  return Buffer.from(out);
}
const packet = (first: number, body: Buffer) => Buffer.concat([Buffer.from([first]), encodeLength(body.length), body]);

export function encodeConnect(clientId: string, keepAliveSec = 30): Buffer {
  const head = Buffer.concat([str("MQTT"), Buffer.from([4, 0x02, keepAliveSec >> 8, keepAliveSec & 255])]); // level 4, clean session
  return packet(0x10, Buffer.concat([head, str(clientId)]));
}
export function encodePublish(topic: string, payload: string, qos: 0 | 1, packetId = 0, retain = false): Buffer {
  const id = qos ? Buffer.from([packetId >> 8, packetId & 255]) : Buffer.alloc(0);
  return packet(0x30 | (qos << 1) | (retain ? 1 : 0), Buffer.concat([str(topic), id, Buffer.from(payload, "utf8")]));
mqtt.ts: Remaining Length 7 bits at a time, CONNECT and PUBLISH
  • Remaining Length: 7 bits at a time. The top bit says whether another byte follows, up to 4 bytes, as the specification defines. For example, 128 is encoded as 0x80 0x01. The test suite checks the reference values 127, 128, 16383 and 16384.
  • CONNECT: protocol level 4 (MQTT 3.1.1) with Clean Session set. The example does not use a Will message or authentication.
  • PUBLISH QoS 1: add a two-byte packet id, then wait for PUBACK. If it does not arrive within 500 ms, the send is treated as failed.
  • A message sent with QoS 1 can be duplicated, as the at least once rule of the specification allows, so the receiver should use seq to remove duplicates.
  • TCP is a stream, so there is takePackets, which splits packets by length and keeps an incomplete part for the next round.

The simulated broker in fake-broker.ts accepts CONNECT and replies CONNACK, accepts PUBLISH, stores it in a list and replies PUBACK. It is used to test the sending side without installing anything. It does not check the full specification and should not be used as a stand-in for a real broker.

Step 5: Store-and-forward: when the network drops, data must not be lost

The principle is to always write to the queue first, and then try to drain it. A new message therefore never jumps ahead of an older message that is still waiting. Draining stops the moment a send fails. The message that failed and those after it stay in the queue. When the connection returns, they are sent on in the original order. If the queue is full, the oldest message is dropped and counted in dropped, so that it can be reported. Never drop silently.

store-forward.ts · lines 17–36
  // เข้าคิวก่อนเสมอ แล้วลองระบาย: ข้อความใหม่จึงไม่แซงข้อความเก่าที่ค้างอยู่
  async submit(topic: string, build: (seq: number) => string): Promise<void> {
    const seq = this.nextSeq();
    this.queue.push({ topic, payload: build(seq), seq });
    while (this.queue.length > this.maxQueue) { this.queue.shift(); this.dropped++; }
    await this.flush();
  }

  // ส่งทีละข้อความ หยุดทันทีที่ล้มเหลว (ตัวที่ล้มและตัวหลังจากนั้นยังอยู่ในคิว)
  async flush(): Promise<number> {
    let sent = 0;
    while (this.queue.length) {
      const m = this.queue[0];
      if (!(await this.send(m.topic, m.payload))) break;
      this.queue.shift();
      sent++;
    }
    return sent;
  }
}
store-forward.ts: enqueue first, drain in order, stop on failure

demo.ts cuts the cable at window 11 and reconnects at window 19. In between, messages must accumulate in the queue.

demo.ts · lines 32–41
await link.connect();
const sf = new StoreForward((t, p) => link.publish(t, p));

console.log("\nส่ง MQTT ทุกหน้าต่าง 15 นาที (สายหลุดตั้งแต่หน้าต่างที่ 11 ถึง 18 ต่อใหม่ตอนหน้าต่างที่ 19)");
const DOWN = [10, 17];
for (const [n, w] of windows.entries()) {
  if (n === DOWN[0]) link.drop();
  if (n === DOWN[1] + 1) { await link.connect(); }
  await sf.submit(TOPIC, (seq) => JSON.stringify({ v: 1, seq, ts: new Date(T0 + w.startSec * 1000).toISOString(), windowSec: w.sec, ...MACHINE, ...stripStart(w) }));
  if (n === DOWN[0] || n === DOWN[1] || n === DOWN[1] + 1 || n === windows.length - 1)
demo.ts: cut the cable mid-shift, send through the queue, then reconnect

The queue in the example is in memory. If the gateway restarts or loses power, the pending data is all lost and seq starts counting again. Real work must keep the queue on disk (for example as a JSON Lines file or SQLite) and also save seq to disk, so that the receiver can still detect gaps after a restart.

Actual run: an 8-hour shift, network down for 8 windows

demo.ts generates the simulated data, assigns states, counts parts, summarizes windows, starts the simulated broker at 127.0.0.1 on a random port, and sends everything through the queue.

output.txt
ขอบสัญญาณดิบ 11330 ขอบ -> นับได้ 1122 ชิ้น (ค่าจริงที่ใช้สร้างข้อมูล 1122)

ช่วงสถานะที่จัดได้ (เทียบกับตารางที่ใช้สร้างข้อมูล)
  00:00-00:05  off     300 s
  00:05-00:10  idle    300 s
  00:10-02:00  run    6600 s
  02:00-02:05  idle    300 s
  02:05-04:00  run    6900 s
  04:00-04:30  off    1800 s
  04:30-04:35  idle    300 s
  04:35-07:46  run   11500 s
  07:46-07:50  idle    200 s
  07:50-08:00  off     600 s
  (ตารางจริงมี 10 ช่วง, ที่จัดได้ 10 ช่วง; dip 6 วินาทีที่ 20000 s ถูกกรองออก)

หน้าต่างที่ไม่ได้ run เต็ม 15 นาที หรือมีช่วงหยุดระหว่างชิ้น
  # 1 00:00 run=300 idle=300 off=300 ชิ้น=14 รอบเฉลี่ย=21.66 ช่องว่างยาว=0
  # 9 02:00 run=600 idle=300 off=0 ชิ้น=27 รอบเฉลี่ย=22.14 ช่องว่างยาว=1
  #17 04:00 run=0 idle=0 off=900 ชิ้น=0 รอบเฉลี่ย=null ช่องว่างยาว=0
  #18 04:15 run=0 idle=0 off=900 ชิ้น=0 รอบเฉลี่ย=null ช่องว่างยาว=0
  #19 04:30 run=600 idle=300 off=0 ชิ้น=28 รอบเฉลี่ย=21.95 ช่องว่างยาว=1
  #32 07:45 run=100 idle=200 off=600 ชิ้น=5 รอบเฉลี่ย=21.49 ช่องว่างยาว=0

ส่ง MQTT ทุกหน้าต่าง 15 นาที (สายหลุดตั้งแต่หน้าต่างที่ 11 ถึง 18 ต่อใหม่ตอนหน้าต่างที่ 19)
  หน้าต่าง 11 (02:30): สายหลุด=ใช่  ค้างในคิว=1  broker ได้รวม=10
  หน้าต่าง 18 (04:15): สายหลุด=ใช่  ค้างในคิว=8  broker ได้รวม=10
  หน้าต่าง 19 (04:30): สายหลุด=ไม่  ค้างในคิว=0  broker ได้รวม=19
  หน้าต่าง 32 (07:45): สายหลุด=ไม่  ค้างในคิว=0  broker ได้รวม=32

broker ได้ 32 ข้อความ, seq 1..32, เรียงต่อเนื่องไม่ขาดไม่ซ้ำ: ใช่, ทิ้งเพราะคิวเต็ม 0

ตัวอย่างข้อความที่ broker ได้ (หน้าต่างที่ 1, 11 และ 12)
  btsan-demo/plant1/line2/press07/window
  {"v":1,"seq":1,"ts":"2026-01-05T06:00:00.000Z","windowSec":900,"site":"plant1","line":"line2","machine":"press07","runSec":300,"idleSec":300,"offSec":300,"count":14,"cycleAvgSec":21.66,"cycleMedianSec":21.39,"longGaps":0,"stateAtEnd":"run"}
  btsan-demo/plant1/line2/press07/window
  {"v":1,"seq":11,"ts":"2026-01-05T08:30:00.000Z","windowSec":900,"site":"plant1","line":"line2","machine":"press07","runSec":900,"idleSec":0,"offSec":0,"count":41,"cycleAvgSec":22.19,"cycleMedianSec":22.19,"longGaps":0,"stateAtEnd":"run"}
  btsan-demo/plant1/line2/press07/window
  {"v":1,"seq":12,"ts":"2026-01-05T08:45:00.000Z","windowSec":900,"site":"plant1","line":"line2","machine":"press07","runSec":900,"idleSec":0,"offSec":0,"count":41,"cycleAvgSec":21.9,"cycleMedianSec":21.9,"longGaps":0,"stateAtEnd":"run"}

รวมทั้งกะ: ชิ้น 1122, run 25000 s, idle 1100 s, off 2700 s (รวม 28800 s จาก 28800)
Output from an actual run on 2026-11-21 with node demo.ts (Node 24). Long sample message lines are trimmed here and kept in the full file.

Reading the result item by item

  1. 11,330 raw signal edges gave 1,122 parts counted, matching the number used to generate the data.
  2. 10 state intervals were found, matching the table used to generate the data, and the 6-second current dip at 20,000 seconds was filtered out. So the total run period was not split in half (04:35 to 07:46 is a single run period of 11,500 seconds).
  3. Windows #9 and #19 each have 1 long gap, which is the part between idle periods, so it was not averaged in with normal cycles. Windows #17 and #18 are off for the whole window, so they have no cycle time (null).
  4. The line was down from window 11. During that period the broker had received a total of 10 messages, and the queue grew until it held 8 at window 18.
  5. The connection came back at window 19. The queue drained to 0 and the broker had received a total of 19.
  6. At the end of the shift the broker had 32 messages, seq 1 to 32, in order with none missing and none duplicated, and 0 dropped because of a full queue. This is the number the business cares about, because the chart has no holes even though the network was down for two hours.
  7. Over the whole shift, run was 25,000 s, idle 1,100 s and off 2,700 s, totaling 28,800 s, exactly the length of the shift.

Test suite

retrofit.test.ts has 7 cases and runs with node --test retrofit.test.ts, giving 7 passes. They are: current swinging between the two thresholds does not make the state flicker; a short dip is filtered out and the time moves back to the real start; debounce removes bounce and noise but not real pulses; the queue drains in order after reconnecting; a full queue counts dropped; MQTT encoding (reference values for Remaining Length and incomplete packets); and an end-to-end run through the simulated broker.

From the example to a real machine: electrical safety comes first

  • Clamping a CT onto a motor wire or a main line must be done by a licensed electrician, following the plant's lockout/tagout procedure. Do not open a control cabinet while it is live, and do not let unauthorized people touch it.
  • Choose a CT that suits the motor's current range and has an output that matches the measurement module (for example a current or voltage output that the module supports), following that model's manual. Never leave the secondary terminals open while current flows, as the CT documentation warns.
  • Read the part-count pulse point through an isolation device (for example an optocoupler or a relay), and do not wire it in parallel with the machine's existing circuit without assessing it. Have an electrician check that it does not affect the existing control circuit and safety.
  • Do not take signals from safety-related circuits (for example e-stop or interlock) to use for data collection.
  • If you also want to read from the controller or a meter over Modbus through a gateway, you must check the documentation for that model and get permission from the program's owner. This example does not do this. See the article on Modbus RTU/TCP.
  • Gateway: choose it for the environment (dust, temperature, vibration), not only for the spec on paper, and keep the data collection network separate from the office network.
  • Check the clock: the gateway must sync time (for example via NTP), because the data is summarized in time windows. A drifting clock shifts the windows and makes them impossible to compare with the notebook.
  • Data retention policy: decide how long to keep window data, whether to keep raw data, and who can access it. Production data is often a business secret.

Before trusting the numbers, compare them with the shift lead's notebook for one shift. The goal is not an exact match, but to learn where the difference comes from. This step was described in the earlier survey article about old machines.

Hypothetical examples: applying it to three businesses

Parts stamping plant

Current separates run from idle clearly, because a press draws very different current while waiting and while pressing. The decision to make is how many seconds a short stop must last to be counted, and this must be agreed with the shift lead, because this number changes the total downtime.

Food packaging machine

The part counter matters more than the current, and the debounce must match the real conveyor speed. Check the hygiene rules of the production area before placing any device, and use devices that can be washed and cleaned as the plant requires.

Plant with an unstable network

The highlight is store-and-forward. Keep the queue on disk, and size it to the outage time you are willing to tolerate (for example, with 15-minute windows there are 96 messages per day, so it can hold a very long time). Also have a report when dropped goes above 0, so nobody mistakenly believes the data is complete.

Common mistakes, and a checklist

  • Using a single current threshold to decide run/idle, so the state flickers when the current hovers around the threshold.
  • No minimum time, so every short dip is counted as a stop.
  • Counting every pulse edge without debounce, so the part count is too high.
  • Setting debounce longer than the real pulse width, so parts are lost.
  • Averaging the cycle time including the periods when the machine was stopped, so the cycle time is wrong.
  • Sending MQTT at QoS 0, or not waiting for PUBACK and believing it arrived.
  • An unbounded queue, or dropping messages when the queue is full without counting them.
  • No seq number on the receiving side, so gaps or duplicate messages cannot be detected.
  • Showing missing data as a machine stop, when it should be unknown.
  • Clamping a CT or wiring a signal without a licensed electrician checking it.
  1. Survey the machine, its owner and the permissions before connecting any point, and get a work permit according to the plant's procedure.
  2. Measure the real current when off, idle and run, and measure the real pulse width and bounce before setting thresholds.
  3. state.ts with hysteresis and a minimum time, plus an unknown state when data is missing.
  4. Debounce the pulses, and compare the part count with a hand count over one period.
  5. Summarize into time windows, separating long gaps from normal cycle times.
  6. Use a maintained MQTT client with a real broker, and set QoS 1 and seq.
  7. Keep the queue on disk, report dropped messages, and sync the gateway clock.
  8. Run the test suite every time you change a threshold, and compare with the notebook for at least one shift.

Cautions for the example: the data is simulated and never went through a real machine. There is no Modbus, no authentication or TLS, no keep-alive in the MQTT encoder, no QoS 2, no Last Will. The queue is in memory, and the simulated broker is not a real broker. Use it as a learning model, not as production-ready code.

References

  1. OASIS — MQTT Version 3.1.1 (Remaining Length, QoS 1/PUBACK, CONNECT, Will, Retain) (accessed 2026-11-21)
  2. Eclipse Mosquitto — documentation (open source MQTT server) (accessed 2026-11-21)
  3. MQTT.js — README (client library, MQTT v3.1.1 default, reconnect and queue options) (accessed 2026-11-21)
  4. Node.js — net (TCP sockets as streams) (accessed 2026-11-21)
  5. Node.js — Running TypeScript natively (type stripping) (accessed 2026-11-21)
  6. Wikipedia — Current transformer (split-core type, secondary must not be disconnected from its burden) (accessed 2026-11-21)
  7. Wikipedia — Switch (contact bounce and debouncing) (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