以下是一个简单的示例,展示了如何将上述接口封装在一个类中:
#include <open62541/client.h>
class OPCUAClient {
public:
OPCUAClient() {
client = UA_Client_new();
subscriptionId = 0;
}
~OPCUAClient() {
if (client) {
UA_Client_delete(client);
}
}
bool connect(const char* url) {
UA_StatusCode status = UA_Client_connect(client, url);
return status == UA_STATUSCODE_GOOD;
}
bool disconnect() {
UA_Client_disconnect(client);
return true;
}
bool readValueAttribute(UA_NodeId nodeId, void* value) {
UA_ReadValueId readValueId;
readValueId.nodeId = nodeId;
readValueId.attributeId = UA_ATTRIBUTEID_VALUE;
UA_ReadRequest request;
request.nodesToRead = &readValueId;
request.nodesToReadSize = 1;
UA_ReadResponse response = UA_Client_Service_read(client, request);
if (response.responseHeader.serviceResult == UA_STATUSCODE_GOOD &&
response.resultsSize > 0 && response.results[0].hasValue &&
response.results[0].value.hasValue)
{
*(static_cast<UA_Int32*>(value)) = *static_cast<const UA_Int32*>(response.results[0].value.data);
return true;
}
return false;
}
bool writeValueAttribute(UA_NodeId nodeId, const void* value) {
// TODO: Implement the logic to write a value attribute
return false;
}
// Add more member functions for other APIs
private:
UA_Client* client;
uint32_t subscriptionId;
};
int main() {
OPCUAClient client;
// Connect to the OPC UA server
if (client.connect("opc.tcp://localhost:4840")) {
// Read value attribute
UA_NodeId nodeId = UA_NODEID_NUMERIC(1, 1001);
UA_Int32 value;
if (client.readValueAttribute(nodeId, &value)) {
// Do something with the value
printf("Value: %d\n", value);
} else {
printf("Failed to read value attribute.\n");
}
// Disconnect from the OPC UA server
client.disconnect();
} else {
printf("Failed to connect to OPC UA server.\n");
}
return 0;
}
请注意,上述代码仅为示例,并未完整实现所有接口的封装逻辑。具体的实现取决于你所使用的 OPC UA 客户端库和需求。
内容由零声教学AI助手提供,问题来源于学员提问




