Suscripción a eventos (C)
OPC UA Eventos (Alarmas y condiciones) mediante suscripción DarraUa_Subscription_AddEventItem. Esto es OPC UA Eventos del protocolo, y el de SDK DataChange Llamada de retorno No es lo mismo.
DarraUa_Subscription_AddEventItem— eventos de protocolo OPC UA (alarma / condición, empujados por el servidor, esta sección)DarraUa_OnDataChange— cambio de datos del MI (cambió el valor de la variable)DarraUa_OnSubscriptionState— estado interno de la suscripción de la SDK (sin relación con el protocolo)
El API de eventos está en un archivo de cabecera independiente:
#include <opcua/opcua_event.h>
API
OPCUA_API DarraUa_Status OPCUA_CALL DarraUa_Subscription_AddEventItem(
DarraUa_SubscriptionHandle sub,
const char* object_node_id_str, /* NULL = "i=2253" Server */
DarraUa_OnEvent cb,
void* user_context,
DarraUa_MonitoredItemHandle* out_mi);
| Parámetros | Por defecto | Explicación |
|---|---|---|
| object_node_id_str | NULL → i=2253 (Server) | El nodo de origen del evento debe tener el atributo EventNotifier (12) |
| cb | — | Llamada de retorno de evento |
| out_mi | — | Salida de la función, nuevo MI identificador |
Carga del evento
typedef struct {
uint16_t severity; /* 1-1000 */
const char* message; /* LocalizedText.text, UTF-8 */
const char* source_name; /* UTF-8 */
DarraUa_DateTime time; /* UTC 100ns since 1601 */
const char* event_type; /* NodeId Cadena de caracteres, posiblemente NULL */
} DarraUa_Event;
| Campo | Significado |
|---|---|
| severity | 1-1000; cuanto mayor sea el valor, más grave es el caso |
| message | Mensaje legible para las personas |
| source_name | Nombre del objeto origen del evento desencadenante |
| time | Marca de tiempo del incidente (servidor) |
| event_type | Tipo de evento NodeId, por ejemplo, "i=2041" (BaseEventType) |
Ciclo de vida: ev Los punteros solo son válidos para llamadas de retorno internas; lo mismo ocurre con los campos de cadena. Si desea conservarlos, strdup o cópielos en su propio búfer.
Nivel de gravedad
- 1-249 — Low
- 250-499 — Medium
- 500-749 — High
- 750-1000 — HighHigh
Firma de la llamada de retorno del evento
typedef void (*DarraUa_OnEvent)(
DarraUa_SubscriptionHandle sub,
DarraUa_MonitoredItemHandle mi,
const DarraUa_Event* ev,
void* user_context);
Integrado EventFilter
La SDK usa fijamente 4 SimpleAttributeOperand (campos estándar de BaseEventType):
| Índice | Campo |
|---|---|
| 0 | Severity (UInt16) |
| 1 | Message (LocalizedText) |
| 2 | SourceName (String) |
| 3 | Time (DateTime) |
whereClause = Vacío, es decir, se notifican todos los eventos. Aplicable a la gran mayoría de los servidores.
Cuando sea necesario personalizar la condición SelectClause / where, utilice DarraUa_EventSubscription_SubscribeWithFilter
(véase EventFilter), y tanto este como el creado AddEventItem por son del mismo tipo de evento MI.
Ejemplo completo
#include <opcua/opcua.h>
#include <opcua/opcua_event.h>
#include <stdio.h>
#if defined(_WIN32)
# include <windows.h>
# define OPCUA_SLEEP_MS(ms) Sleep(ms)
#else
# include <unistd.h>
# define OPCUA_SLEEP_MS(ms) usleep((ms) * 1000)
#endif
static int g_event_count = 0;
static const char* severity_label(uint16_t s)
{
if (s == 0) return "None";
if (s < 250) return "Low";
if (s < 500) return "Medium";
if (s < 750) return "High";
return "HighHigh";
}
static void on_event(DarraUa_SubscriptionHandle sub,
DarraUa_MonitoredItemHandle mi,
const DarraUa_Event* ev, void* ctx)
{
(void)sub; (void)mi; (void)ctx;
if (!ev) return;
g_event_count++;
printf("[event #%d] sev=%u (%s) src=\"%s\" type=\"%s\" time=%lld msg=\"%s\"\n",
g_event_count,
(unsigned)ev->severity, severity_label(ev->severity),
ev->source_name ? ev->source_name : "",
ev->event_type ? ev->event_type : "",
(long long)ev->time,
ev->message ? ev->message : "");
}
int main(int argc, char** argv)
{
const char* endpoint = (argc >= 2) ? argv[1] : "opc.tcp://localhost:4840";
DarraUa_Initialize();
DarraUa_SessionConfig cfg;
DarraUa_SessionConfig_Init(&cfg);
cfg.endpoint_url = endpoint;
cfg.security_policy_uri = "http://opcfoundation.org/UA/SecurityPolicy#None";
DarraUa_SessionHandle h = UA_INVALID_SESSION_HANDLE;
DarraUa_Session_Create(&cfg, &h);
DarraUa_Session_Connect(h);
DarraUa_SubscriptionConfig sc;
DarraUa_SubscriptionConfig_Init(&sc);
sc.publishing_interval_ms = 500.0;
DarraUa_SubscriptionHandle sub = UA_INVALID_SUBSCRIPTION_HANDLE;
DarraUa_Subscription_Create(h, &sc, &sub);
/* Añadir un evento en el servidor (i=2253) MI */
DarraUa_MonitoredItemHandle ev_mi = UA_INVALID_MONITORED_ITEM_HANDLE;
DarraUa_Status st = DarraUa_Subscription_AddEventItem(
sub, "i=2253", on_event, NULL, &ev_mi);
if (!UA_STATUS_IS_GOOD(st)) {
fprintf(stderr, "AddEventItem failed: %s\n", DarraUa_StatusName(st));
}
/* Bombear durante 10 segundos */
for (int i = 0; i < 20; ++i) {
OPCUA_SLEEP_MS(500);
DarraUa_Session_Publish(h, 2000);
}
printf("Total events received: %d\n", g_event_count);
DarraUa_Subscription_Delete(sub);
DarraUa_Session_Disconnect(h);
DarraUa_Session_Close(h);
DarraUa_Shutdown();
return 0;
}
Reutilizar una suscripción existente
Los eventos se MI pueden asociar a una suscripción de datos existente y compartir publishingInterval:
DarraUa_SubscriptionHandle sub = /* Suscripciones a datos existentes */;
DarraUa_MonitoredItemHandle data_mi = UA_INVALID_MONITORED_ITEM_HANDLE;
DarraUa_MonitoredItemHandle ev_mi = UA_INVALID_MONITORED_ITEM_HANDLE;
DarraUa_Subscription_AddNode(sub, "ns=2;s=Counter", UA_ATTR_VALUE,
-1.0, on_change, NULL, &data_mi); /* Datos MI */
DarraUa_Subscription_AddEventItem(sub, "i=2253",
on_event, NULL, &ev_mi); /* Suceso MI */
out_mi Se debe pasar un puntero válido (no puede ser NULL) — SDK se escribirá en el identificador MI recién asignado.
EventNotifier
Solo los nodos cuyo atributo EventNotifier (12) sea distinto de 0 pueden generar eventos. Por defecto, Server(i=2253) es un EventNotifier. La capacidad de un nodo personalizado para actuar como fuente de eventos depende de la implementación del servidor.
Operaciones de alarma (Confirmar)
Al recibir un evento de tipo AlarmConditionType, el operador suele tener que confirmarlo (Acknowledge). A través de DarraUa_Session_Call Método de confirmación del nodo de alarma:
/* condition_id Es el nodo de condición que activa la alarma NodeId */
DarraUa_NodeId obj_id, mtd_id;
/* Análisis de condition_id y condition_id + «.Acknowledge» en la estructura NodeId , omitido */
DarraUa_Variant* args[2] = { /* eventId */, /* comment */ };
DarraUa_Variant* outs = NULL;
uint32_t out_n = 0;
DarraUa_Status method_st = 0;
DarraUa_Session_Call(h, &obj_id, &mtd_id,
(const DarraUa_Variant* const*)args, 2, &outs, &out_n, &method_st);
Plantilla para guardar cadenas de caracteres
Los campos dentro de las funciones de devolución de llamada tienen un ciclo de vida corto, y quiero conservar el evento:
typedef struct {
uint16_t severity;
char* message;
char* source_name;
DarraUa_DateTime time;
} SavedEvent;
static SavedEvent* g_events = NULL;
static int g_n = 0, g_cap = 0;
static char* dup_or_null(const char* s)
{
if (!s) return NULL;
char* out = (char*)malloc(strlen(s) + 1);
if (out) strcpy(out, s);
return out;
}
static void on_event_save(DarraUa_SubscriptionHandle s, DarraUa_MonitoredItemHandle m,
const DarraUa_Event* ev, void* ctx)
{
(void)s; (void)m; (void)ctx;
if (!ev) return;
if (g_n == g_cap) {
g_cap = g_cap ? g_cap * 2 : 16;
g_events = (SavedEvent*)realloc(g_events, g_cap * sizeof(SavedEvent));
}
SavedEvent* dst = &g_events[g_n++];
dst->severity = ev->severity;
dst->message = dup_or_null(ev->message);
dst->source_name = dup_or_null(ev->source_name);
dst->time = ev->time;
}