How-to
Publish one MQTT event when a PLC bit rises
Short answer
Publish on the transition, not the level. Retain the previous valid sample of the PLC Boolean and publish one MQTT event only when the pair reads false then true. An acquisition cycle cannot see a pulse shorter than itself, so latch short pulses in the PLC and reset the latch after the event publishes, and make the consumer tolerant of duplicate deliveries.
On this page
Publish on the transition, not the level. On the box that polls the PLC, retain the previous valid sample of the Boolean and send one MQTT message only when the pair reads false, then true — one rising edge produces exactly one event, however long the bit stays high. Two numbers decide whether that works: the tag's acquisition cycle, 1 s in this deployment, and how long the PLC holds the bit true. A cycle of that length cannot catch a shorter true period, so a one-scan pulse must be latched in the PLC and reset after the event publishes. The message itself is copied field-for-field from the publisher the consumer already accepts. This path is operational event data, never a safety function.
Where the event logic runs #
The PLC owns the Boolean, but it does not build or send the MQTT message. The edge box polls the bit over OPC UA, decides whether a rising edge occurred, and publishes one message to the broker; the IoT gateway already forwarding telemetry carries the event the rest of the way over the same broker path. That split — acquisition, transition detection and publishing on one box between the PLC and the broker — is the architecture of bridging OPC UA PLC data to MQTT with an edge PC. Moving the publish into the PLC instead is the trade covered in PLC MQTT direct publishing versus an IoT gateway; for one bit with a fixed message contract, the gateway route leaves the PLC program untouched.
The logic is small enough to run on the gateway you already have. When the project gets its own box instead, a fanless mini PC in the cabinet does the polling, detection and publishing.
Publish on the pair, not the level #
If the script publishes whenever the tag reads true, a bit held high through a production order emits one message per acquisition cycle — one message per poll. Edge detection fixes that: keep the previous valid sample and publish only on the false-to-true pair.
previous : Boolean := not initialized
every acquisition cycle:
current : Boolean := read the PLC tag
quality := the tag's communication status
if quality is good:
if previous is initialized
and previous = false
and current = true:
publish one event
previous := current
previous, current and quality are illustrative names for the retained sample, the fresh reading and the tag status; map them to the tag and script variables your gateway exposes. Initialize previous from the first valid reading, never from an assumed false: a box that starts while the bit is already true would otherwise manufacture a phantom event. Bad-quality readings leave previous untouched, so a communication dropout cannot fabricate a transition either.
Step-by-step: one rising edge, one event #
- In the PLC and its OPC UA server, expose the machine event as a single Boolean and record its node address.
- On the edge box, create a tag mapped to that node, Boolean-compatible, with the acquisition cycle this deployment uses.
- Initialize the retained previous sample from the first valid reading, and treat that reading as state, not as an event.
- Every cycle, read the value and the quality, apply the pair test, and update the retained sample only from good readings.
- Build the payload in the existing message contract.
- Publish to the broker topic the existing subscriber listens on.
- Run the acceptance tests in the last section before the event drives anything downstream.
Catching a production-start bit on the acquisition cycle #
Inputs:
- Acquisition cycle: the polling interval this project sets for the tag; the bit is read once per cycle.
- Bit behavior, held case: the bit stays true for as long as the machine condition lasts; assumed to persist well beyond one cycle because it represents an ongoing state.
- Bit behavior, pulse case: the PLC sets and resets the bit within one program scan, so the true period lasts milliseconds.
Rule in words: the edge box samples at instants exactly one cycle apart, and a true period is detected only if at least one instant falls inside it. The longest stretch containing no instant is the gap between two consecutive instants.
Arithmetic:
- Sampling instants fall at t = 0 s, 1 s, 2 s, 3 s.
- A true period of 1.00 s cannot fit inside a 1.00 s gap, so every placement of it contains a sampling instant: detection is guaranteed at 1.00 s and above.
- A true period of 0.99 s can fit: true from t = 0.005 s to t = 0.995 s contains no instant and is never read.
- Latch hold time: twice the cycle, which guarantees a sample and still survives one bad-quality poll.
Result: the guaranteed-detection threshold of this deployment is 1.00 s of continuous true time, and the committed latch hold is two cycles.
Decision: a held bit that stays true for at least one full cycle is read directly — no PLC change. Any bit true for less than that, which includes every one-scan pulse, gets latched in the PLC: set on the event, reset by the edge logic once the event is published. The set-and-reset structure is the same one behind latching two level inputs for pump start and stop control — the event sets the bit and only the acknowledgment resets it.
Copy the message the consumer already parses #
The existing C# publisher defines the wire contract, so copy its serialized output, not its class design. Capture one accepted message from the working publisher, or from a broker trace, before writing anything. Match the field names and capitalization exactly — Text, PO, Passage and Length in the current message — with PO as a string and Passage and Length as integers. Match the timestamp the same way: the working code derives it from DateTimeOffset.Now, so its serialized format and offset handling are part of the contract.
Two fields need a decision rather than a copy. MACHINE_ID is the first argument the working call passes to PublishAsync; confirm from the trace whether it selects the MQTT topic or rides inside the payload as a routing field, because the two fail differently at the consumer. TypePayload is the other: the button-driven event sends eTypePayload.UserInteraction, one of the MachineWarning, MachineError, MachineMessage and UserInteraction values the consumer already handles, so the automated production start should also send one of those four, in the same serialized form — name or number — the current publisher emits. The existing event carries Text = "Start PO"; keep that value unless the consumer is updated with it.
Duplicates, restarts and recovery #
A retried publish can deliver the same event twice; at-least-once delivery makes that expected behavior, not a fault. The consumer either keys on an event identifier added to the payload, such as a per-bit counter, or tolerates duplicate content when the contract is frozen.
Restarts are where events are won or lost. With a plain held bit, initializing the retained sample from the first valid reading suppresses phantoms — and also swallows any transition that occurred while the box was off. With the latched event bit from the worked example, initialize the retained sample to false instead, and reset the PLC latch after each publish: a restart while the latch is still set then re-sends the event once, which the duplicate handling above absorbs.
Prove it before the event drives anything #
Attach a test subscriber to the same topic before changing anything downstream, force the bit through both states, and check:
| Test | Action | Expected result |
|---|---|---|
| Single event | Force false to true and hold true through at least three acquisition cycles | Exactly one message |
| Re-arm | Return to false, then true again | A second message, and only then |
| Restart | Start the edge box with the bit already true | No message from initialization |
| Dropout | Break the PLC link mid-test and restore it | No phantom message; a transition that occurred during the gap publishes once on recovery |
One rising edge, one message, every time — that is the whole acceptance criterion.
Questions asked
Why does my gateway publish the same event every cycle while the PLC bit stays high?
Because the logic publishes on the level, not the transition. Retain the previous valid sample and publish only when the pair reads false then true; one rising edge then produces exactly one message. A second message should appear only after the bit returns to false and rises again.
Can the read cycle miss a PLC pulse?
Yes. The tag is sampled once per cycle, so any true period shorter than the cycle can fall entirely between two samples and is never seen. Latch short pulses in the PLC and reset the latch after the event publishes. Shortening the acquisition cycle only lowers the threshold; it does not remove the limit.
What should happen when the PLC connection drops and comes back?
Never update the retained sample from a bad-quality read. On recovery, the first good reading is compared against the last good one, so a bit that went true during the outage publishes then: a delayed real event, not a phantom. Even with no dropout, detection lags the transition by up to one acquisition cycle, so the payload timestamp reflects publish time, not the instant the bit rose.
How do I stop duplicate events when a publish is retried?
Not at the protocol alone. At-least-once delivery (QoS 1) redelivers by design, and exactly-once (QoS 2) cannot stop your own logic from publishing again after a restart. Add a per-bit counter to the payload only if the consumer contract supports an extra field, and key the consumer on it so a second copy updates rather than appends.