Layer: L7 Application ยท Build flags: PC_ENABLE_OPCUA
What this example teaches
OPC UA is the dominant industrial interoperability protocol. This opens an OPC UA Binary endpoint on TCP/4840 implementing the type codec, UA-TCP (UACP) framing, the Hello/Acknowledge handshake, the SecureChannel (OpenSecureChannel, SecurityPolicy None), the Session (CreateSession + ActivateSession), and the Read / Write / Browse services - so a real client (UaExpert, open62541, Python asyncua) completes the handshake, opens a secure channel, activates a session, browses the Objects folder, and reads/writes node values. Like Modbus (ModbusTcp), it is just another protocol on its own port, sharing the HTTP server's pool and event loop.
Three resolvers map a tiny address space onto live values. Read returns a value for a node id (false -> BadNodeIdUnknown):
static bool pc_opcua_read(uint16_t ns, uint32_t id, uint32_t attribute, OpcUaVariant *out) {
if (ns != 1 || attribute != OPCUA_ATTR_VALUE) return false;
switch (id) {
case 1: out->type = OpcUaVariantType::OPCUA_VAR_UINT32; out->u32 = millis() / 1000; return true;
case 2: out->type = OpcUaVariantType::OPCUA_VAR_UINT32; out->u32 = ESP.getFreeHeap(); return true;
case 10: out->type = OpcUaVariantType::OPCUA_VAR_UINT32; out->u32 = setpoint; return true;
default: return false;
}
}
Write returns an OPC UA StatusCode - 0 (Good) on success, or a Bad code the client surfaces:
static uint32_t pc_opcua_write(uint16_t ns, uint32_t id, uint32_t attribute, const OpcUaVariant *value) {
if (ns == 1 && id == 10 && attribute == OPCUA_ATTR_VALUE && value->type == OpcUaVariantType::OPCUA_VAR_UINT32) {
setpoint = value->u32; return 0;
}
return (ns == 1 && id == 10) ? OPCUA_STATUS_BAD_NOT_WRITABLE : OPCUA_STATUS_BAD_NODE_ID_UNKNOWN;
}
Browse fills the references under the standard Objects folder (ns=0;i=85) so the variables show up in a client's address-space tree.
Register the handlers, then listen before begin():
pc_opcua_set_read_handler(pc_opcua_read);
pc_opcua_set_write_handler(pc_opcua_write);
pc_opcua_set_browse_handler(pc_opcua_browse);
server.begin(80);
@ PROTO_OPCUA
OPC UA Binary (UA-TCP) server.
Build and run
pio ci --board=esp32dev --project-option="framework=arduino" \
--project-option="build_flags=-DPC_ENABLE_OPCUA=1" \
--lib="." examples/L7-Application/OpcUa/OpcUa.ino
Connect a client to opc.tcp://<ip>:4840 (UaExpert, or python -m asyncua.tools.uals -u opc.tcp://<ip>:4840) and browse/read the Objects folder.
Annotated source
The complete sketch (OpcUa.ino), reproduced verbatim with added explanatory comments:
#define PC_ENABLE_OPCUA 1
static const char *SSID = "YOUR_SSID";
static const char *PASSWORD = "YOUR_PASSWORD";
static uint32_t setpoint = 100;
static bool pc_opcua_read(uint16_t ns, uint32_t id, uint32_t attribute, OpcUaVariant *out)
{
if (ns != 1 || attribute != OPCUA_ATTR_VALUE)
return false;
switch (id)
{
case 1:
out->type = OpcUaVariantType::OPCUA_VAR_UINT32;
out->u32 = millis() / 1000;
return true;
case 2:
out->type = OpcUaVariantType::OPCUA_VAR_UINT32;
out->u32 = ESP.getFreeHeap();
return true;
case 3:
out->type = OpcUaVariantType::OPCUA_VAR_DOUBLE;
out->f64 = 23.5;
return true;
case 10:
out->type = OpcUaVariantType::OPCUA_VAR_UINT32;
out->u32 = setpoint;
return true;
default:
return false;
}
}
static uint32_t pc_opcua_write(uint16_t ns, uint32_t id, uint32_t attribute, const OpcUaVariant *value)
{
if (ns == 1 && id == 10 && attribute == OPCUA_ATTR_VALUE && value->type == OpcUaVariantType::OPCUA_VAR_UINT32)
{
setpoint = value->u32;
return 0;
}
return (ns == 1 && id == 10) ? OPCUA_STATUS_BAD_NOT_WRITABLE : OPCUA_STATUS_BAD_NODE_ID_UNKNOWN;
}
static int32_t pc_opcua_browse(uint16_t ns, uint32_t id, OpcUaReference *out, uint32_t max)
{
if (ns != 0 || id != 85)
return -1;
static const char *names[3] = {"Uptime", "FreeHeap", "Temperature"};
int32_t n = 0;
for (uint32_t i = 0; i < 3 && (uint32_t)n < max; i++, n++)
{
out[n].ref_type_id = OPCUA_REFTYPE_ORGANIZES;
out[n].is_forward = true;
out[n].target_ns = 1;
out[n].target_id = i + 1;
out[n].browse_name_ns = 1;
out[n].browse_name = names[i];
out[n].display_name = names[i];
out[n].node_class = OPCUA_NODECLASS_VARIABLE;
out[n].type_def_id = OPCUA_TYPEDEF_BASE_DATA_VARIABLE;
}
return n;
}
void setup()
{
delay(250);
Serial.print("IP: ");
Serial.printf("IP: %u.%u.%u.%u\n", (unsigned)(ip & 0xFF), (unsigned)((ip >> 8) & 0xFF),
(unsigned)((ip >> 16) & 0xFF), (unsigned)((ip >> 24) & 0xFF));
pc_opcua_set_read_handler(pc_opcua_read);
pc_opcua_set_write_handler(pc_opcua_write);
pc_opcua_set_browse_handler(pc_opcua_browse);
Serial.println("OPC UA endpoint: opc.tcp://<ip>:4840 (handshake + SecureChannel + Session + Read/Write + Browse)");
}
void loop()
{
}
Single-port HTTP server with deterministic, zero-allocation execution.
int32_t listen(uint16_t port, ConnProto proto=ConnProto::PROTO_HTTP)
Register a port to listen on when begin() is called.
void send(uint8_t slot_id, int code, const char *content_type, const char *payload)
Send an HTTP response with a body and close the connection.
int32_t begin(const WebServerConfig *cfg=nullptr)
Initialize all connection slots and open all registered listeners.
void on(const char *path, HttpMethod method, Handler callback)
Register a route handler.
void handle()
Drive the server - call every Arduino loop() iteration.
OPC UA Binary server: handshake + SecureChannel + Session + Read/Write + Browse (PC_ENABLE_OPCUA).
bool init_wifi_physical(const char *, const char *)
Connect to a WiFi access point.
uint32_t pc_net_egress_ip(void)
IPv4 (network byte order) of the current egress interface, or 0 if none.
bool wifi_ready()
True if the WiFi station link is up (associated + an IP is assigned).
Layer 1 (Physical) - link bring-up and live egress-interface reporting.
Layer 7 (Application) - public HTTP routing API.
@ HTTP_GET
Safe, idempotent read.
Fully-parsed HTTP/1.1 request.