data_changed event
OpcUaSubscription.data_changed is List[Callable[[DataChangeEventArgs], None]]. When data MI changes, the server triggers a push notification, and all callbacks are called sequentially in list order internally.
sub.data_changed.append(callback) # Register
sub.data_changed.remove(callback) # Cancel
sub.data_changed.clear() # Clear
- See the Global Unified Channel
ua.events.any. - For OPC UA alarms / conditional events (protocol events), see Event Subscription.
DataChangeEventArgs
@dataclass
class DataChangeEventArgs:
monitored_item_handle: int = 0
node_id: str = ""
value_string: Optional[str] = None
data_type_name: Optional[str] = None
status: StatusCode = StatusCode.Bad
source_timestamp: Optional[datetime] = None
server_timestamp: Optional[datetime] = None
| Field | Type | Note |
|---|---|---|
| monitored_item_handle | int | Triggered MI Local Handle |
| node_id | str | It's about time MI NodeId |
| value_string | Optional[str] | String representation of the value (synchronously extracted within the Publish callback thread; thread-safe) |
| data_type_name | Optional[str] | Names of built-in data type enumerations (e.g., Double, Int32) |
| status | StatusCode | OpcUaDataValue.status the value of |
| source_timestamp | Optional[datetime] | Data Source Timestamp (UTC) |
| server_timestamp | Optional[datetime] | Server Timestamp (UTC) |
Design Trade-offs
Callback parameters are in flat Python format ( dataclass str + enumeration + datetime), and all fields are extracted at once when the notification arrives. This is thread-safe, but the trade-off is that you cannot access them within the callback OpcUaVariant, so you cannot perform advanced operations.
If the original data is needed OpcUaVariant (e.g., for complex parsing ExtensionObject), use to re-read it synchronously ua.read(e.node_id) within the callback.
Examples
Simple Log
sub.data_changed.append(
lambda e: print(f"{e.node_id} = {e.value_string} ({e.data_type_name}) @ {e.source_timestamp}"))
Write to a file / database
import threading
file_lock = threading.Lock()
def to_csv(e):
ts = e.source_timestamp.isoformat() if e.source_timestamp else ""
with file_lock:
with open("data.csv", "a", encoding="utf-8") as f:
f.write(f"{ts},{e.node_id},{e.value_string}\n")
sub.data_changed.append(to_csv)
source_timestamp is Optional[datetime], the server didn't provide it— None so check for null before using it.
UI Binding (PyQt)
from PyQt5.QtCore import QMetaObject, Qt, Q_ARG
def on_change(e):
# Switch Back to the Thread GUI
QMetaObject.invokeMethod(label, "setText", Qt.QueuedConnection,
Q_ARG(str, e.value_string or ""))
sub.data_changed.append(on_change)
Operations UI in PyQt, Tk, and wxPython must be performed on the main thread; otherwise, the program will crash. PyQt uses QMetaObject.invokeMethod; Tk uses root.after(0, ...); and asyncio uses loop.call_soon_threadsafe.
Thread Model
- Callback at SDK the Publish thread Triggered, not on your main thread
- Within the same notification, callbacks are invoked serially in a fixed order: ① This MI one
callback→ ② All callbacks in the listsub.data_changed→ ③ua.events.anyUnified channel - In the callbackDo not perform long operations — It will delay the subsequent callbacks and the distribution of follow-up notifications; there is no time limit in place here.
- A callback throws an exception and is SDK Swallow it and don't log it, It will not propagate to the main thread—to debug, use try/except and log the error yourself within the callback.
- There is no guarantee that callbacks between multiple subscriptions will run on the same thread, Always lock shared variable data yourself.
Relationship with ua.events.any
from darra_opcua import OpcUaEventCategory
# Method A: Single-subscription tier — The parameter is DataChangeEventArgs
def on_sub(e):
print(f"{e.node_id} = {e.value_string}")
sub.data_changed.append(on_sub)
# Method B: Global Unified Channel (aggregates all subscriptions; the parameter is OpcUaEventEntry)
def on_any(e):
if e.category == OpcUaEventCategory.DataChange:
print(f"[DataChange] {e.source} = {e.message} ({e.status_code.name})")
ua.events.any.append(on_any)
Both events will be triggered for the same data point; choose one to use. Note that the parameter types are different: A is DataChangeEventArgs (value_string / node_id), and B is OpcUaEventEntry (source / message / status_code).