EventFilter
Visão geral
OPC UA Part 4 §7.18 EventFilter:
- select_clauses — Quais campos devem ser selecionados?
- where_clause — Critérios de filtragem (ainda não implementados; deixe em branco)
SimpleAttributeOperand Campos: type_definition_id / browse_path / attribute_id / index_range.
Session::SubscribeEvents(std::string const& node_id = "", Subscription* existing = nullptr) não tem parâmetro EventFilter; os campos a serem selecionados são os 4 fixos SelectClause: Severity / Message / SourceName / Time.
No lado do C++, atualmente não dá para mudar quais campos são capturados, nem para definir WhereClause. Para personalizar o filtro é preciso usar a camada de conveniência em C DarraUa_EventSubscription_SubscribeWithFilter(sub, object_node_id, filter, cb, ctx, &out_mi); se for passado um filtro NULL, voltam esses 4 campos padrão.
API
namespace darra::opcua {
/// SimpleAttributeOperand (Part 4 §7.4.4.5)
struct SimpleAttributeOperand {
std::string type_definition_id; // Tipo de evento NodeId, como "i=2041"; vazio = curinga BaseEventType
std::vector<std::string> browse_path; // Por exemplo, ["Severity"] / ["EnabledState","Id"]; vazio = todo o conjunto
AttributeId attribute_id = AttributeId::Value;
std::string index_range; // NumericRange Sequência; Vazio = Todos
};
/// EventFilter (Part 4 §7.18)
struct EventFilter {
std::vector<SimpleAttributeOperand> select_clauses;
std::string where_clause; // V1 Não realizado, deixar em branco
};
}
Ambos são campos da estrutura, sem métodos. O SDK exige C++17; o exemplo usa inicialização por posição (não escreva a inicialização especificada .field =, pois isso é do C++20).
Exemplo de código
#include <darra/opcua/client.hpp>
#include <darra/opcua/event_filter.hpp>
#include <iostream>
using namespace darra::opcua;
Session s("opc.tcp://localhost:4840");
s.Connect();
Subscription sub = s.CreateSubscription(500.0);
// 1) Criar um tipo de filtro (no momento, só é possível criá-lo; não é possível importá-lo SubscribeEvents)
EventFilter filter;
filter.select_clauses = {
SimpleAttributeOperand{ "i=2041", {"EventId"} },
SimpleAttributeOperand{ "i=2041", {"EventType"} },
SimpleAttributeOperand{ "i=2041", {"SourceName"} },
SimpleAttributeOperand{ "i=2041", {"Time"} },
SimpleAttributeOperand{ "i=2041", {"Message"} },
SimpleAttributeOperand{ "i=2041", {"Severity"} },
SimpleAttributeOperand{ "i=2782", {"ConditionId"} },
SimpleAttributeOperand{ "i=2915", {"ActiveState", "Id"} },
};
// 2) Assinatura efetiva — possui apenas dois parâmetros, sem filtro
EventSubscription ev = s.SubscribeEvents("i=2253", &sub);
// 3) A função de retorno recebe 5 campos com nomes fixos, e não a matriz `fields[]`
ev.on_event() = [](EventArrivedEventArgs const& e) {
std::cout << "sev=" << e.severity << " " << e.message
<< " src=" << e.source_name << "\n";
};
Referência rápida de campos
Parâmetros de retorno de chamada EventArrivedEventArgs sãoCampo de nome, não é um fields[] array, nem possui os AsBoolean() métodos de acesso AsByteString() / AsDateTime() / AsUInt16() / :
| campo | Tipo | Explicação |
|---|---|---|
| severity | uint16_t | Gravidade 1-1000 |
| message | std::string | LocalizedText.text |
| source_name | std::string | |
| time | int64_t | FileTime(UTC 100ns since 1601) |
| event_type | std::string | Atualmente, heng é uma string vazia(SelectClauses não incluído EventType) |
A seguir, apresentamos a tabela padrão OPC UA do campo BaseEventType / ConditionType, para referência;Atualmente, não é possível SDK capturar os campos além desses 4:
| EventType | BrowsePath | Significado | É possível prendê-lo neste momento? |
|---|---|---|---|
| BaseEventType (i=2041) | {"Severity"} | Gravidade 1-1000 | Pode (fixo SelectClause) |
| BaseEventType | {"Message"} | Texto da notícia | Pode (fixo SelectClause) |
| BaseEventType | {"SourceName"} | Nome da fonte | Pode (fixo SelectClause) |
| BaseEventType | {"Time"} | Hora do evento | Pode (fixo SelectClause) |
| BaseEventType | {"EventId"} | ID exclusivo do evento | Não pode |
| BaseEventType | {"EventType"} | Tipo de evento NodeId | Não pode |
| ConditionType (i=2782) | {"ConditionId"} | Condições NodeId | Não pode |
| AcknowledgeableConditionType (i=2881) | {"AckedState", "Id"} | bool se é Ack | Não pode |
| AlarmConditionType (i=2915) | {"ActiveState", "Id"} | bool: está ativado? | Não pode |
Descrição da implementação
- São sempre extraídos 4 campos SelectClause:Severity / Message / SourceName / Time, não são 5 — considere 4
where_clauseNão realizado, deixar em branco- Não conseguir identificar EventId / , o que afeta ConditionIddiretamente Alarme e confirmação de
Acknowledge/Confirm/AddComment(eles precisamevent_id) — consulte a explicação sobre a lacuna de competências nessa página
Melhores práticas
- Para personalizar campos/filtros, use a camada C
DarraUa_EventSubscription_SubscribeWithFilter - As chamadas de retorno são executadas de forma síncrona na thread de publicação, e as tarefas de recuperação são encaminhadas para a fila
Comparação entre idiomas
| item | C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|---|
| EventFilter | EventFilter | EventFilter | EventFilterDef.Filter | EventFilter | EventFilter | DarraUa_EventFilter |
| SimpleAttributeOperand | SimpleAttributeOperand | SimpleAttributeOperand | EventFilterDef.Operand | SimpleAttributeOperand | SimpleAttributeOperand | DarraUa_SimpleAttributeOperand |
| Assinatura de eventos com filtro | subscribe(..., filter) | subscribe(..., filter) | subscribe(..., Filter) | Nenhum | subscribe(..., filter) | DarraUa_EventSubscription_SubscribeWithFilter |
Os nomes dos tipos em Java são diferentes: Sim EventFilterDef.Filter / EventFilterDef.Operand(EventFilterDef.java), Não EventFilter / SimpleAttributeOperand. O C++ é a única linguagem que não possui um “ponto de entrada de assinatura de eventos com filtro”.