matlab/matlab-agentic-toolkit / skills-catalog/test-and-measurement/matlab-build-industrial-hmi
matlab-build-industrial-hmi
VerifiedBuild industrial-grade SCADA/HMI dashboards in MATLAB following industrial-HMI conventions (ISA-101-aligned): gray-field philosophy, alarms at source, write safeguards, fixed-range trends, drill-down layout. Produces a real App Designer app (.mlapp, or plain-text .m+.xml on R2026b+) by handing serialization to the matlab-build-app skill when available, and falls back to a programmatic .m app otherwise. Use when wrapping OPC UA / Modbus / MQTT / OSI PI / PI AF monitoring scripts into a live operator app, building plant overviews, designing operator dashboards, or any time a user asks for a "SCADA dashboard", "HMI", "plant dashboard", "operator screen", or "industrial monitoring app" in MATLAB. Trigger on: SCADA, HMI, industrial dashboard, plant overview, operator screen, uigauge, uilamp, alarm banner, gray-field, ISA-101, OPC UA dashboard, setpoint, write safeguards, alarm visualization, OSIsoft PI, AVEVA PI, PI Server, PI Data Archive, PI AF, PI Asset Framework, piclient, afclient.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 21.6 KB |
| assets/design-report-schema.json | config | 9.9 KB |
| assets/designReportReadback.m | other | 12.5 KB |
| assets/hmi-spec-template.md | markdown | 18.4 KB |
| manifest.yaml | config | 1.7 KB |
| references/alarm-patterns.md | markdown | 10.9 KB |
| references/app-designer-gotchas.md | markdown | 9.0 KB |
| references/app-designer-handoff.md | markdown | 17.7 KB |
| references/color-and-layout-rules.md | markdown | 16.3 KB |
| references/common-mistakes.md | markdown | 49.6 KB |
| references/key-functions.md | markdown | 4.1 KB |
| references/known-schema-patterns.md | markdown | 4.1 KB |
| references/pi-af-cheatsheet.md | markdown | 16.7 KB |
| references/protocol-cheatsheet.md | markdown | 19.1 KB |
| references/server-agnostic-discovery.md | markdown | 8.4 KB |
| references/trend-config-reference.md | markdown | 10.9 KB |
| references/widget-selection-flowchart.md | markdown | 6.6 KB |
| references/write-safeguards-reference.md | markdown | 9.2 KB |
references/protocol-cheatsheet.md
View on GitHub# Protocol Cheatsheet — OPC UA, Modbus, MQTT
Use this when wrapping a script generated by **OPC UA Explorer**, **Modbus Explorer**, or any MQTT publish/subscribe demo into an HMI. Each protocol has its own read/write API shape, and the most common HMI bugs come from copying the API surface wrong — not from the HMI conventions themselves.
If you only have time to read one section, read the **Don't get this wrong** box for the protocol you're wrapping.
## Decision rule
| User has a script from… | Pattern |
|---|---|
| OPC UA Explorer (`opcua(…)`, `findNodeById`, `subscribe`) | §OPC UA below; preserve the explorer's node identifiers, do **not** rename nodes in the HMI |
| Modbus Explorer (`modbus('tcpip',…)`, `read(m,'coils'/'holdingregs',…)`) | §Modbus below; classify each register as coil → lamp, holding → gauge |
| MQTT publish/subscribe (`mqttclient(…)`, `subscribe(c, topic, Callback=…)`) | §MQTT below; one trend line per subscribed topic |
| OSI / AVEVA PI Data Archive (`piclient(…)`, `tags`, `read`) or PI AF (`afclient(…)`, `getRootElements`, `getAttributes`) | See `references/pi-af-cheatsheet.md` — separate file because PI has no `subscribe()` (polling-timer like Modbus) and AF browsing is hierarchical (drill-down). **Never** replace these with `NET.addAssembly('OSIsoft.AFSDK')` calls. |
## OPC UA
### Callback shape — pick the right one before writing the subscribe call
Two callback signatures are valid, depending on whether you're writing the `subscribe()` call yourself or pasting a callback from the **OPC UA Explorer** app's generated script.
| Source of the script | Callback signature | `notification.Node` / `notification.Data` |
|---|---|---|
| You're writing the `subscribe` call yourself | `cb(sub, notification)` — **2 args** | scalar struct (single change per call) |
| The `subscribe` call came from the OPC UA Explorer app's generated script | `cb(subObj, notification, ~)` — **3 args** (vectorized) | struct array (one entry per node that changed in the cycle) |
**When in doubt, write the subscribe call yourself with the 2-arg shape.** Only switch to the 3-arg vectorized shape when you're literally pasting the Explorer-generated `dataChangeCallback`. Mixing the two — 3-arg signature with 2-arg server output, or vice versa — is the most common "subscription succeeds, callback never fires / errors" cause. Two failure modes flow from getting this wrong (both in `common-mistakes.md` #17): a 2-arg `@(src, evt)` for an Explorer script throws *"Too many input arguments"*, and reading the Explorer's `notification` as a scalar updates only the first node.
In both shapes, `notification.Node` and `notification.Data` are *struct arrays*, not scalars. Even when only one node changes, indexing as `notification.Node(i)` and `notification.Data(i)` works for the 1-element case — there's no need to special-case it.
### Don't get this wrong
- **Store the subscription handle on a property.** `app.Subscription = subscribe(...)`, never `sub = subscribe(...)`. A local variable is GC'd at function exit and the listener detaches silently. See `app-designer-gotchas.md`.
- **Use the server's actual node names** from `notification.Node(i).Name`. Never invent labels like "Tank-level / Temperature / Pressure" when the server's namespace says `Sinusoid`, `Square`, `Constant`. The HMI must mirror the source script's identifiers so an operator can cross-reference with the OPC UA server.
### 2-arg callback shape (preferred when you control the subscribe call)
This is the shape to use unless you're pasting an Explorer-generated callback. `notification.Node` and `notification.Data` are *struct arrays* (parallel — one entry per changed node) even when only one node changed:
```matlab
function onDataChange(app, ~, notification)
% notification.Node : struct array — one per changed node
% fields: Name, Identifier, NamespaceIndex, NodeClass
% notification.Data : struct array (parallel) — one per changed node
% fields: Value, Timestamp, Quality
nodes = notification.Node;
data = notification.Data;
elapsed = seconds(datetime('now') - app.StartTime);
for i = 1:numel(nodes)
name = char(nodes(i).Name);
val = data(i).Value;
w = app.Widgets(strcmp({app.Widgets.Key}, name));
if isempty(w), continue; end
w.Display.Value = val;
if ~isempty(w.Trace)
addpoints(w.Trace, elapsed, double(val));
end
updateAlarmState(app, name, val);
end
drawnow limitrate;
end
```
The `for i = 1:numel(nodes)` indexing pattern works equally well for the common 1-node-changed case and the multi-node burst case — no special-casing needed.
Wire it with the publishing interval set **explicitly** to the rate the screen needs (seconds; the default is 1). Stating it records the intended rate in the code and is required for any rate other than 1 s:
```matlab
app.Subscription = subscribe(app.UAClient, nodes, ...
@(sub, notification) onDataChange(app, sub, notification), ...
PublishInterval = 1); % ~1 Hz; 0.5 for 2 Hz
```
### Vectorized callback shape (matches Explorer-generated scripts)
```matlab
function onDataChange(app, ~, notification, ~)
% notification is itself a struct array — one entry per node that changed.
nodes = [notification(:).Node];
data = [notification(:).Data];
names = string({nodes(:).Name});
vals = [data(:).Value];
elapsed = seconds(datetime('now') - app.StartTime);
for i = 1:numel(names)
w = app.Widgets(strcmp({app.Widgets.Key}, char(names(i))));
if isempty(w), continue; end
w.Display.Value = vals(i);
if ~isempty(w.Trace)
addpoints(w.Trace, elapsed, double(vals(i)));
end
updateAlarmState(app, char(names(i)), vals(i));
end
drawnow limitrate;
end
```
### Resolving Explorer-script identifiers to widget keys
The Explorer's `findNodeById(uaClient.Namespace, namespaceIndex, identifier)` returns a node. Read `.Name` from each resolved node and use that as the widget key — this preserves the server's naming and survives namespace reshuffles:
```matlab
namespaceIndex = [3, 3, 3]; % from the generated script
identifier = [1001, 1006, 1005];
nodes = arrayfun(@(i) findNodeByName_or_findById(uaClient.Namespace, ...
namespaceIndex(i), identifier(i)), 1:numel(identifier));
nodeNames = string({nodes.Name}); % e.g. ["Constant", "Square", "Sinusoid"]
% Now build one widget per resolved name. Never relabel.
```
### Writability inferred from the node, not assumed
Use `AccessLevelCurrent` (release-aware shape — see `app-designer-gotchas.md`). A node that the Explorer wrote in its sample (`% writeValue(uaClient,node,"50")`) is the strongest signal that it's writable; promote that node to a setpoint spinner with a confirm dialog (Pattern 5 in SKILL.md).
### Method nodes (`invoke`)
Some OPC UA servers expose **method nodes** for operator-triggered actions: reset a counter, start a sequence, run a calibration, acknowledge a server-side latch. In an HMI, these become buttons — but treat invocation with the same safeguards as a write: confirm before, flash on success/failure, range/type hints on the inputs.
#### Discover the method's signature *before* building the input UI
Don't hard-code the number or types of arguments. Inspect the method node:
```matlab
methodNode = findNodeById(client.Namespace, 6, 'MyMethod');
numIn = methodNode.NumInputs; % e.g. 2
inTypes = methodNode.InputTypes; % e.g. {'String','Double'}
% Method may also have outputs:
numOut = methodNode.NumOutputs;
outTypes = methodNode.OutputTypes;
```
The HMI builds one input field per `inTypes{i}`, with the type name in the `Tooltip` and `Placeholder` so the operator knows what's expected. Dispatch to a numeric vs string field by inspecting the type name.
#### Construction pattern — typed input row + invoke button
```matlab
function buildInvokePanel(app, parent, methodNode)
inTypes = methodNode.InputTypes;
numIn = methodNode.NumInputs;
gl = uigridlayout(parent, [1 numIn + 1], ...
'BackgroundColor', [0.86 0.86 0.86]);
app.MyMethodNode = methodNode;
app.MyMethodFields = gobjects(1, numIn);
for i = 1:numIn
typeName = inTypes{i};
if any(strcmpi(typeName, {'Double','Single','Int32','UInt32','Int16','UInt16'}))
f = uieditfield(gl, 'numeric', ...
'Tooltip', sprintf('Argument %d (%s)', i, typeName), ...
'Placeholder', typeName);
else
f = uieditfield(gl, 'text', ...
'Tooltip', sprintf('Argument %d (%s)', i, typeName), ...
'Placeholder', typeName);
end
app.MyMethodFields(i) = f;
end
app.InvokeButton = uibutton(gl, ...
'Text', 'Invoke MyMethod', ...
'ButtonPushedFcn', @(~,~) onInvokeMyMethod(app));
end
```
#### Invoke with confirm dialog (treat method invocation as a write)
```matlab
function onInvokeMyMethod(app)
% Coerce each field per InputTypes — string for 'String', double for numeric.
inTypes = app.MyMethodNode.InputTypes;
args = cell(1, numel(inTypes));
for i = 1:numel(inTypes)
v = app.MyMethodFields(i).Value;
switch lower(inTypes{i})
case 'string'
args{i} = string(v);
otherwise
args{i} = double(v);
end
end
msg = sprintf('Invoke %s with:\n%s', app.MyMethodNode.Name, ...
strjoin(arrayfun(@(k) sprintf(' arg %d: %s', k, ...
string(args{k})), 1:numel(args), 'UniformOutput', false), newline));
sel = uiconfirm(app.UIFigure, msg, 'Confirm Invoke', ...
'Options', {'Invoke','Cancel'}, ...
'DefaultOption', 'Cancel', ...
'CancelOption', 'Cancel', ...
'Icon', 'warning');
if sel ~= "Invoke"
return
end
try
outputs = invoke(app.UAClient, app.MyMethodNode, args{:});
flashFeedback(app.InvokeButton, [0.7 1 0.7]);
if ~isempty(outputs)
app.InvokeStatusLabel.Text = sprintf('Returned: %s', ...
strjoin(string(outputs), ', '));
end
catch ME
flashFeedback(app.InvokeButton, [1 0.7 0.7]);
uialert(app.UIFigure, ME.message, 'Invoke failed');
end
end
```
`invoke` returns method outputs as a cell array (or empty when the method has no outputs). Display them in a status label adjacent to the button if the method's `NumOutputs > 0`. The `flashFeedback` helper is the same one used for `writeValue` — see `references/write-safeguards-reference.md`.
## Modbus
### Don't get this wrong
- The `write()` argument order is **easy to flip**. The supported signature is:
```matlab
write(m, target, address, values, serverId, 'precision')
```
`serverId` is **before** `'precision'`. Putting precision in slot 5 produces:
> Expected input number 5, serverId, to be one of these types: double, single, uint8, uint16, ...
This is the most common Modbus HMI write bug — the spinner and confirm dialog are correct but the actual `write` call fails. **Always use the 6-argument form** when you have a non-default `serverId`, or fall back to the 4-argument form `write(m, target, address, values)` when `serverId` is 1 (default).
- `read()`'s 6-argument form is `read(m, target, address, count, serverId, precisions)` where `count` may be a vector when `precisions` is a cell array — see the explorer-generated `read(m, 'holdingregs', 1, [1, 1], serverId, {'uint16', 'uint32'})`. Mirror that shape.
- Modbus has **no subscription mechanism**; live updates use a polling `timer` (`BusyMode='drop'`, `ExecutionMode='fixedSpacing'`). This is the one place the SKILL.md "subscribe by default" rule does not apply, because there's no `subscribe()` to call.
### Coils → lamps, holding registers → gauges
| Register type | MATLAB read | Widget |
|---|---|---|
| Coil (1-bit) | `read(m, 'coils', addr, count, serverId)` | `uilamp` (binary) |
| Discrete input (1-bit) | `read(m, 'inputs', addr, count, serverId)` | `uilamp` (binary, read-only) |
| Holding register (16-bit) | `read(m, 'holdingregs', addr, count, serverId, 'uint16')` | `uigauge` if range known, else `uieditfield('numeric','Editable',false)` |
| Input register (16-bit) | `read(m, 'inputregs', addr, count, serverId)` | `uigauge` (read-only) |
Holding registers can also be written (`write(m, 'holdingregs', …)`), so the writable ones get a setpoint spinner. Coils can be written too (`write(m, 'coils', addr, [0|1], serverId)`) — bind those to a `uistatebutton` + confirm.
### Working write callback (correct argument order)
```matlab
function sendWrite(app)
addr = app.WriteAddrSpinner.Value;
newVal = app.WriteSpinner.Value;
msg = sprintf(['Write Holding Register:\n\n' ...
' address: %d\n value: %d\n range: 0 - 65535'], addr, newVal);
sel = uiconfirm(app.UIFigure, msg, 'Confirm Write', ...
'Options', {'Apply','Cancel'}, ...
'DefaultOption', 'Cancel', 'CancelOption', 'Cancel', 'Icon', 'warning');
if sel == "Apply"
try
% CORRECT: serverId before 'precision'
write(app.ModbusClient, 'holdingregs', addr, newVal, ...
app.ServerId, 'uint16');
flashFeedback(app.WriteSpinner, [0.7 1 0.7]);
catch ME
flashFeedback(app.WriteSpinner, [1 0.7 0.7]);
uialert(app.UIFigure, ME.message, 'Write Failed');
end
end
end
```
### Polling pattern for Modbus live updates
Ordering matters in `startupFcn`: **lay out and `drawnow` first, construct the client second,
start the timer third.** `modbus('tcpip', host, port)` against an unreachable host blocks
**~21 s** before throwing, and `'Timeout'` does not shorten it (it bounds per-transaction
response waiting, not the OS-level TCP connect: measured 21.5 s at the default, 21.1 s at
`Timeout=1`, 21.1 s at `Timeout=0.5`). The same block applies to `opcua`/`connect`, `mqttclient`,
`piclient` and `afclient`. Connect before the first `drawnow` and the operator gets a frozen MATLAB
with no window for 21 s, then on failure no window at all:
```matlab
% startupFcn, after createComponents has laid out the gray-field screen:
app.CommsLamp.Color = [0.5 0.5 0.5]; % gray = not yet connected
app.AlarmBanner.Text = "Connecting to " + host + "…";
drawnow % screen is up BEFORE the blocking call
try
app.Client = modbus('tcpip', host, port);
app.CommsLamp.Color = [0.4 0.6 1.0]; % blue = comms up, never green
app.AlarmBanner.Text = "SYSTEM NORMAL";
catch ME
app.AlarmBanner.Text = "No connection: " + ME.message;
return % leave the screen up, writes disabled
end
```
```matlab
% Then, with a live client:
app.PollTimer = timer( ...
'ExecutionMode', 'fixedSpacing', ...
'BusyMode', 'drop', ...
'Period', 1, ...
'TimerFcn', @(~,~) pollModbus(app));
start(app.PollTimer);
```
The `BusyMode='drop'` is mandatory — without it, slow Modbus responses queue up timer callbacks and the UI stalls.
## MQTT
### Don't get this wrong
- `subscribe(c, topic, Callback=@cb)` — the callback is a **name-value pair**, not a positional argument. Forgetting `Callback=` registers the subscription but the message stays buffered (`read(c)` works, but live updates never fire).
- The callback signature is `cb(topic, message)` where `message` is a **string**. Numeric payloads must be parsed (`str2double`, `jsondecode`, etc.). The MQTT layer has no schema — it's bytes on the wire.
- Subscribe **before** any messages are expected. If you subscribe after the broker has already sent retained messages, you'll get the latest retained value (good), but missed in-flight messages are gone (no replay).
- Publish via `write(c, topic, message)` — `message` must be a `string` or `char`. Numeric setpoints go through `string(value)` or `jsonencode(struct(…))`.
### Live trend wired to a subscription callback
```matlab
% Construction (in createComponents) — one trace per subscribed topic
ax = uiaxes(parent, 'XLim', [0 300], 'YLim', [0 100]);
xlabel(ax, 'Time (s)'); ylabel(ax, 'Value'); grid(ax, 'on');
trace = animatedline(ax, 'MaximumNumPoints', 300, ...
'Color', [0 0 0], 'LineWidth', 1.2);
app.Topics(end+1) = struct('Name', topic, 'Trace', trace, ...
'Display', readout, 'StartTime', datetime('now'));
% Subscribe — Callback is a name-value pair
subscribe(app.MqttClient, topic, ...
Callback = @(t, m) onMessage(app, t, m), ...
QualityOfService = 1);
```
```matlab
function onMessage(app, topic, message)
idx = find(strcmp({app.Topics.Name}, topic), 1);
if isempty(idx), return; end
val = str2double(message); % adjust per payload schema
if isnan(val), return; end % non-numeric payload — skip trend
elapsed = seconds(datetime('now') - app.Topics(idx).StartTime);
addpoints(app.Topics(idx).Trace, elapsed, val);
app.Topics(idx).Display.Value = val;
drawnow limitrate;
end
```
### Why the live chart is the most common MQTT bug
A common observation in MQTT HMI evaluations: the dashboard layout is correct, the connect/subscribe/publish buttons all work, but the trend stays flat on the first attempt. The two failure modes for "subscribed but no trend" are:
1. The callback was registered as a **positional argument** (`subscribe(c, topic, @cb)` instead of `Callback=@cb`). The subscription succeeds but the callback is never invoked.
2. The callback fires but `str2double` returns `NaN` (because the broker is sending JSON or comma-separated values), the `NaN` gets passed to `addpoints`, and the trace renders nothing without erroring.
Both are silent. Sanity-check by logging `topic` and `message` to the command window before plotting.
### JSON payloads
When the broker publishes JSON like `{"temp": 72.5, "ts": "2026-06-08T10:15:00Z"}`:
```matlab
function onMessage(app, topic, message)
try
s = jsondecode(message);
catch
return % malformed JSON
end
if ~isfield(s, 'temp'), return; end
elapsed = seconds(datetime('now') - app.StartTime);
addpoints(app.TempTrace, elapsed, s.temp);
drawnow limitrate;
end
```
Don't infer schema from the topic name; always check `isfield` before reaching into `s`.
## Cross-references
- Pattern 6 in SKILL.md — OPC UA `subscribe()` over `timer`. The Modbus exception (no subscription, must poll) is documented above; the same exception applies to PI / PI AF.
- `references/pi-af-cheatsheet.md` — OSI / AVEVA PI Data Archive (`piclient`) and PI AF (`afclient`). Use these clients, never direct AFSDK `.NET` calls.
- `references/widget-selection-flowchart.md` — once payload type is decoded, widget selection is the same across protocols.
- `references/write-safeguards-reference.md` — the confirm/range/feedback pattern is identical for `writeValue()` (OPC UA), `write(m, …)` (Modbus), `write(c, …)` (MQTT), and `write(piClient, tag, val, TimeInstance=…)` (PI). Only the API call inside the `try` block differs.
- `references/app-designer-gotchas.md` — `Subscription` cleanup, listener-leak gotcha, struct-property defaults.
----
Copyright 2026 The MathWorks, Inc.
----
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation). | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK). | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |