Custom objects and methods
Goal
Extend the Function node server with custom objects and methods in the address space.
Where to add the code
Place the following additions right after you create the namespace in your Function node. This keeps the example aligned with the basic server tutorial.
Example: add a custom object
// Add a custom object under the Objects folder
const device = namespace.addObject({
organizedBy: "ObjectsFolder",
browseName: "Device001"
});
// Add a few variables to the object
const serialNumber = namespace.addVariable({
componentOf: device,
browseName: "SerialNumber",
dataType: "String"
});
const temperature = namespace.addVariable({
componentOf: device,
browseName: "Temperature",
dataType: "Double"
});
// Set initial values (and update later with new messages)
serialNumber.setValueFromSource({ dataType: opcua.DataType.String, value: "SN-001" });
temperature.setValueFromSource({ dataType: opcua.DataType.Double, value: msg.value || 20.0 });
Example: add a method
const method = namespace.addMethod(device, {
browseName: "Reset",
inputArguments: [],
outputArguments: []
});
method.bindMethod((inputArguments, context, callback) => {
// Do your reset logic here
const callMethodResult = {
statusCode: opcua.StatusCodes.Good,
outputArguments: []
};
callback(null, callMethodResult);
});
Test the method
Use any OPC UA client to call Device001.Reset. You should receive a Good status code.
Next step
Continue with user authentication.
Further reading
For more tips and examples, see the Sterfive book node-opcua by example.