ua_subscription_datachange.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. *
  5. * Copyright 2017 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  6. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  7. * Copyright 2018 (c) Ari Breitkreuz, fortiss GmbH
  8. * Copyright 2018 (c) Thomas Stalder, Blue Time Concept SA
  9. * Copyright 2018 (c) Fabian Arndt, Root-Core
  10. */
  11. #include "ua_server_internal.h"
  12. #include "ua_subscription.h"
  13. #include "ua_types_encoding_binary.h"
  14. #ifdef UA_ENABLE_SUBSCRIPTIONS /* conditional compilation */
  15. #define UA_VALUENCODING_MAXSTACK 512
  16. #define ABS_SUBTRACT_TYPE_INDEPENDENT(a,b) ((a)>(b)?(a)-(b):(b)-(a))
  17. static UA_Boolean
  18. outOfDeadBand(const void *data1, const void *data2, const size_t index,
  19. const UA_DataType *type, const UA_Double deadbandValue) {
  20. if(type == &UA_TYPES[UA_TYPES_SBYTE]) {
  21. if(ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_SByte*)data1)[index],
  22. ((const UA_SByte*)data2)[index]) <= deadbandValue)
  23. return false;
  24. } else if(type == &UA_TYPES[UA_TYPES_BYTE]) {
  25. if(ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_Byte*)data1)[index],
  26. ((const UA_Byte*)data2)[index]) <= deadbandValue)
  27. return false;
  28. } else if(type == &UA_TYPES[UA_TYPES_INT16]) {
  29. if(ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_Int16*)data1)[index],
  30. ((const UA_Int16*)data2)[index]) <= deadbandValue)
  31. return false;
  32. } else if(type == &UA_TYPES[UA_TYPES_UINT16]) {
  33. if(ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_UInt16*)data1)[index],
  34. ((const UA_UInt16*)data2)[index]) <= deadbandValue)
  35. return false;
  36. } else if(type == &UA_TYPES[UA_TYPES_INT32]) {
  37. if(ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_Int32*)data1)[index],
  38. ((const UA_Int32*)data2)[index]) <= deadbandValue)
  39. return false;
  40. } else if(type == &UA_TYPES[UA_TYPES_UINT32]) {
  41. if(ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_UInt32*)data1)[index],
  42. ((const UA_UInt32*)data2)[index]) <= deadbandValue)
  43. return false;
  44. } else if(type == &UA_TYPES[UA_TYPES_INT64]) {
  45. if(ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_Int64*)data1)[index],
  46. ((const UA_Int64*)data2)[index]) <= deadbandValue)
  47. return false;
  48. } else if(type == &UA_TYPES[UA_TYPES_UINT64]) {
  49. if(ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_UInt64*)data1)[index],
  50. ((const UA_UInt64*)data2)[index]) <= deadbandValue)
  51. return false;
  52. } else if(type == &UA_TYPES[UA_TYPES_FLOAT]) {
  53. if(ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_Float*)data1)[index],
  54. ((const UA_Float*)data2)[index]) <= deadbandValue)
  55. return false;
  56. } else if(type == &UA_TYPES[UA_TYPES_DOUBLE]) {
  57. if(ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_Double*)data1)[index],
  58. ((const UA_Double*)data2)[index]) <= deadbandValue)
  59. return false;
  60. }
  61. return true;
  62. }
  63. static UA_INLINE UA_Boolean
  64. updateNeededForFilteredValue(const UA_Variant *value, const UA_Variant *oldValue,
  65. const UA_Double deadbandValue) {
  66. if(value->arrayLength != oldValue->arrayLength)
  67. return true;
  68. if(value->type != oldValue->type)
  69. return true;
  70. if (UA_Variant_isScalar(value)) {
  71. return outOfDeadBand(value->data, oldValue->data, 0, value->type, deadbandValue);
  72. } else {
  73. for (size_t i = 0; i < value->arrayLength; ++i) {
  74. if (outOfDeadBand(value->data, oldValue->data, i, value->type, deadbandValue))
  75. return true;
  76. }
  77. }
  78. return false;
  79. }
  80. /* When a change is detected, encoding contains the heap-allocated binary encoded value */
  81. static UA_Boolean
  82. detectValueChangeWithFilter(UA_Server *server, UA_Subscription *sub, UA_MonitoredItem *mon,
  83. UA_DataValue *value, UA_ByteString *encoding) {
  84. if(isDataTypeNumeric(value->value.type) &&
  85. (mon->filter.dataChangeFilter.trigger == UA_DATACHANGETRIGGER_STATUSVALUE ||
  86. mon->filter.dataChangeFilter.trigger == UA_DATACHANGETRIGGER_STATUSVALUETIMESTAMP)) {
  87. if(mon->filter.dataChangeFilter.deadbandType == UA_DEADBANDTYPE_ABSOLUTE) {
  88. if(!updateNeededForFilteredValue(&value->value, &mon->lastValue,
  89. mon->filter.dataChangeFilter.deadbandValue))
  90. return false;
  91. }
  92. /* else if (mon->filter.deadbandType == UA_DEADBANDTYPE_PERCENT) {
  93. // TODO where do this EURange come from ?
  94. UA_Double deadbandValue = fabs(mon->filter.deadbandValue * (EURange.high-EURange.low));
  95. if (!updateNeededForFilteredValue(value->value, mon->lastValue, deadbandValue))
  96. return false;
  97. }*/
  98. }
  99. /* Stack-allocate some memory for the value encoding. We might heap-allocate
  100. * more memory if needed. This is just enough for scalars and small
  101. * structures. */
  102. UA_STACKARRAY(UA_Byte, stackValueEncoding, UA_VALUENCODING_MAXSTACK);
  103. UA_ByteString valueEncoding;
  104. valueEncoding.data = stackValueEncoding;
  105. valueEncoding.length = UA_VALUENCODING_MAXSTACK;
  106. /* Encode the value */
  107. UA_Byte *bufPos = valueEncoding.data;
  108. const UA_Byte *bufEnd = &valueEncoding.data[valueEncoding.length];
  109. UA_StatusCode retval = UA_encodeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE],
  110. &bufPos, &bufEnd, NULL, NULL);
  111. if(retval == UA_STATUSCODE_BADENCODINGERROR) {
  112. size_t binsize = UA_calcSizeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE]);
  113. if(binsize == 0)
  114. return false;
  115. if(binsize > UA_VALUENCODING_MAXSTACK) {
  116. retval = UA_ByteString_allocBuffer(&valueEncoding, binsize);
  117. if(retval == UA_STATUSCODE_GOOD) {
  118. bufPos = valueEncoding.data;
  119. bufEnd = &valueEncoding.data[valueEncoding.length];
  120. retval = UA_encodeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE],
  121. &bufPos, &bufEnd, NULL, NULL);
  122. }
  123. }
  124. }
  125. if(retval != UA_STATUSCODE_GOOD) {
  126. UA_LOG_WARNING_SESSION(server->config.logger, sub ? sub->session : &server->adminSession,
  127. "Subscription %u | MonitoredItem %i | "
  128. "Could not encode the value the MonitoredItem with status %s",
  129. sub ? sub->subscriptionId : 0, mon->monitoredItemId,
  130. UA_StatusCode_name(retval));
  131. return false;
  132. }
  133. /* Has the value changed? */
  134. valueEncoding.length = (uintptr_t)bufPos - (uintptr_t)valueEncoding.data;
  135. UA_Boolean changed = (!mon->lastSampledValue.data ||
  136. !UA_String_equal(&valueEncoding, &mon->lastSampledValue));
  137. /* No change */
  138. if(!changed) {
  139. if(valueEncoding.data != stackValueEncoding)
  140. UA_ByteString_deleteMembers(&valueEncoding);
  141. return false;
  142. }
  143. /* Change detected. Copy encoding on the heap if necessary. */
  144. if(valueEncoding.data == stackValueEncoding) {
  145. retval = UA_ByteString_copy(&valueEncoding, encoding);
  146. if(retval != UA_STATUSCODE_GOOD) {
  147. UA_LOG_WARNING_SESSION(server->config.logger, sub ? sub->session : &server->adminSession,
  148. "Subscription %u | MonitoredItem %i | "
  149. "Detected change, but could not allocate memory for the notification"
  150. "with status %s", sub ? sub->subscriptionId : 0,
  151. mon->monitoredItemId, UA_StatusCode_name(retval));
  152. return false;
  153. }
  154. return true;
  155. }
  156. *encoding = valueEncoding;
  157. return true;
  158. }
  159. /* Has this sample changed from the last one? The method may allocate additional
  160. * space for the encoding buffer. Detect the change in encoding->data. */
  161. static UA_Boolean
  162. detectValueChange(UA_Server *server, UA_MonitoredItem *mon,
  163. UA_DataValue value, UA_ByteString *encoding) {
  164. /* Apply Filter */
  165. if(mon->filter.dataChangeFilter.trigger == UA_DATACHANGETRIGGER_STATUS)
  166. value.hasValue = false;
  167. value.hasServerTimestamp = false;
  168. value.hasServerPicoseconds = false;
  169. if(mon->filter.dataChangeFilter.trigger < UA_DATACHANGETRIGGER_STATUSVALUETIMESTAMP) {
  170. value.hasSourceTimestamp = false;
  171. value.hasSourcePicoseconds = false;
  172. }
  173. /* Detect the value change */
  174. return detectValueChangeWithFilter(server, mon->subscription, mon, &value, encoding);
  175. }
  176. /* Returns whether the sample was stored in the MonitoredItem */
  177. static UA_Boolean
  178. sampleCallbackWithValue(UA_Server *server, UA_MonitoredItem *monitoredItem,
  179. UA_DataValue *value) {
  180. UA_assert(monitoredItem->monitoredItemType == UA_MONITOREDITEMTYPE_CHANGENOTIFY);
  181. UA_Subscription *sub = monitoredItem->subscription;
  182. /* Contains heap-allocated binary encoding of the value if a change was detected */
  183. UA_ByteString binValueEncoding = UA_BYTESTRING_NULL;
  184. /* Has the value changed? Allocates memory in binValueEncoding if necessary.
  185. * value is edited internally so we make a shallow copy. */
  186. UA_Boolean changed = detectValueChange(server, monitoredItem, *value, &binValueEncoding);
  187. if(!changed)
  188. return false;
  189. UA_Boolean storedValue = false;
  190. if(sub) {
  191. /* Allocate a new notification */
  192. UA_Notification *newNotification = (UA_Notification *)UA_malloc(sizeof(UA_Notification));
  193. if(!newNotification) {
  194. UA_LOG_WARNING_SESSION(server->config.logger, sub ? sub->session : &server->adminSession,
  195. "Subscription %u | MonitoredItem %i | "
  196. "Item for the publishing queue could not be allocated",
  197. sub->subscriptionId, monitoredItem->monitoredItemId);
  198. UA_ByteString_deleteMembers(&binValueEncoding);
  199. return false;
  200. }
  201. if(value->value.storageType == UA_VARIANT_DATA) {
  202. newNotification->data.value = *value; /* Move the value to the notification */
  203. storedValue = true;
  204. } else { /* => (value->value.storageType == UA_VARIANT_DATA_NODELETE) */
  205. UA_StatusCode retval = UA_DataValue_copy(value, &newNotification->data.value);
  206. if(retval != UA_STATUSCODE_GOOD) {
  207. UA_ByteString_deleteMembers(&binValueEncoding);
  208. UA_free(newNotification);
  209. return false;
  210. }
  211. }
  212. /* <-- Point of no return --> */
  213. /* Enqueue the new notification */
  214. newNotification->mon = monitoredItem;
  215. UA_Notification_enqueue(server, sub, monitoredItem, newNotification);
  216. } else {
  217. /* Call the local callback if not attached to a subscription */
  218. UA_LocalMonitoredItem *localMon = (UA_LocalMonitoredItem*) monitoredItem;
  219. void *nodeContext = NULL;
  220. UA_Server_getNodeContext(server, monitoredItem->monitoredNodeId, &nodeContext);
  221. localMon->callback.dataChangeCallback(server, monitoredItem->monitoredItemId,
  222. localMon->context,
  223. &monitoredItem->monitoredNodeId,
  224. nodeContext, monitoredItem->attributeId,
  225. value);
  226. }
  227. // If someone called UA_Server_deleteMonitoredItem in the user callback,
  228. // then the monitored item will be deleted soon. So, there is no need to
  229. // add the lastValue or lastSampledValue to it.
  230. //
  231. // If we do so, we will leak
  232. // the memory of that values, because UA_Server_deleteMonitoredItem
  233. // already deleted all members and scheduled the monitored item pointer
  234. // for later delete. In the later delete the monitored item will be deleted
  235. // and not the members.
  236. //
  237. // Also in the later delete, all type information is lost and a deleteMember
  238. // is not possible.
  239. //
  240. // We do detect if the monitored item is already defunct.
  241. if (!monitoredItem->sampleCallbackIsRegistered) {
  242. UA_ByteString_deleteMembers(&binValueEncoding);
  243. return storedValue;
  244. }
  245. /* Store the encoding for comparison */
  246. UA_ByteString_deleteMembers(&monitoredItem->lastSampledValue);
  247. monitoredItem->lastSampledValue = binValueEncoding;
  248. /* Store the value for filter comparison (we don't want to decode
  249. * lastSampledValue in every iteration) */
  250. if((monitoredItem->filter.dataChangeFilter.deadbandType == UA_DEADBANDTYPE_PERCENT ||
  251. monitoredItem->filter.dataChangeFilter.deadbandType == UA_DEADBANDTYPE_ABSOLUTE) &&
  252. (monitoredItem->filter.dataChangeFilter.trigger == UA_DATACHANGETRIGGER_STATUSVALUE ||
  253. monitoredItem->filter.dataChangeFilter.trigger == UA_DATACHANGETRIGGER_STATUSVALUETIMESTAMP)) {
  254. UA_Variant_deleteMembers(&monitoredItem->lastValue);
  255. UA_Variant_copy(&value->value, &monitoredItem->lastValue);
  256. /* Don't test the return code here. If this fails, lastValue is empty
  257. * and a notification will be forced for the next deadband comparison. */
  258. }
  259. return storedValue;
  260. }
  261. void
  262. UA_MonitoredItem_sampleCallback(UA_Server *server, UA_MonitoredItem *monitoredItem) {
  263. UA_Subscription *sub = monitoredItem->subscription;
  264. UA_Session *session = &server->adminSession;
  265. if(sub)
  266. session = sub->session;
  267. if(monitoredItem->monitoredItemType != UA_MONITOREDITEMTYPE_CHANGENOTIFY) {
  268. UA_LOG_DEBUG_SESSION(server->config.logger, session, "Subscription %u | "
  269. "MonitoredItem %i | Not a data change notification",
  270. sub ? sub->subscriptionId : 0, monitoredItem->monitoredItemId);
  271. return;
  272. }
  273. /* Get the node */
  274. const UA_Node *node = UA_Nodestore_get(server, &monitoredItem->monitoredNodeId);
  275. /* Sample the value. The sample can still point into the node. */
  276. UA_DataValue value;
  277. UA_DataValue_init(&value);
  278. if(node) {
  279. UA_ReadValueId rvid;
  280. UA_ReadValueId_init(&rvid);
  281. rvid.nodeId = monitoredItem->monitoredNodeId;
  282. rvid.attributeId = monitoredItem->attributeId;
  283. rvid.indexRange = monitoredItem->indexRange;
  284. ReadWithNode(node, server, session, monitoredItem->timestampsToReturn, &rvid, &value);
  285. } else {
  286. value.hasStatus = true;
  287. value.status = UA_STATUSCODE_BADNODEIDUNKNOWN;
  288. }
  289. /* Operate on the sample */
  290. UA_Boolean storedValue = sampleCallbackWithValue(server, monitoredItem, &value);
  291. /* Delete the sample if it was not stored in the MonitoredItem */
  292. if(!storedValue)
  293. UA_DataValue_deleteMembers(&value); /* Does nothing for UA_VARIANT_DATA_NODELETE */
  294. if(node)
  295. UA_Nodestore_release(server, node);
  296. }
  297. #endif /* UA_ENABLE_SUBSCRIPTIONS */