ua_subscription_datachange.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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_INLINE 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_MonitoredItem *mon, UA_DataValue *value,
  83. UA_ByteString *encoding) {
  84. UA_Session *session = &server->adminSession;
  85. UA_UInt32 subscriptionId = 0;
  86. UA_Subscription *sub = mon->subscription;
  87. if(sub) {
  88. session = sub->session;
  89. subscriptionId = sub->subscriptionId;
  90. }
  91. if(isDataTypeNumeric(value->value.type) &&
  92. (mon->filter.dataChangeFilter.trigger == UA_DATACHANGETRIGGER_STATUSVALUE ||
  93. mon->filter.dataChangeFilter.trigger == UA_DATACHANGETRIGGER_STATUSVALUETIMESTAMP)) {
  94. if(mon->filter.dataChangeFilter.deadbandType == UA_DEADBANDTYPE_ABSOLUTE) {
  95. if(!updateNeededForFilteredValue(&value->value, &mon->lastValue,
  96. mon->filter.dataChangeFilter.deadbandValue))
  97. return false;
  98. }
  99. /* else if (mon->filter.deadbandType == UA_DEADBANDTYPE_PERCENT) {
  100. // TODO where do this EURange come from ?
  101. UA_Double deadbandValue = fabs(mon->filter.deadbandValue * (EURange.high-EURange.low));
  102. if (!updateNeededForFilteredValue(value->value, mon->lastValue, deadbandValue))
  103. return false;
  104. }*/
  105. }
  106. /* Stack-allocate some memory for the value encoding. We might heap-allocate
  107. * more memory if needed. This is just enough for scalars and small
  108. * structures. */
  109. UA_STACKARRAY(UA_Byte, stackValueEncoding, UA_VALUENCODING_MAXSTACK);
  110. UA_ByteString valueEncoding;
  111. valueEncoding.data = stackValueEncoding;
  112. valueEncoding.length = UA_VALUENCODING_MAXSTACK;
  113. /* Encode the value */
  114. UA_Byte *bufPos = valueEncoding.data;
  115. const UA_Byte *bufEnd = &valueEncoding.data[valueEncoding.length];
  116. UA_StatusCode retval = UA_encodeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE],
  117. &bufPos, &bufEnd, NULL, NULL);
  118. if(retval == UA_STATUSCODE_BADENCODINGERROR) {
  119. size_t binsize = UA_calcSizeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE]);
  120. if(binsize == 0)
  121. return false;
  122. if(binsize > UA_VALUENCODING_MAXSTACK) {
  123. retval = UA_ByteString_allocBuffer(&valueEncoding, binsize);
  124. if(retval == UA_STATUSCODE_GOOD) {
  125. bufPos = valueEncoding.data;
  126. bufEnd = &valueEncoding.data[valueEncoding.length];
  127. retval = UA_encodeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE],
  128. &bufPos, &bufEnd, NULL, NULL);
  129. }
  130. }
  131. }
  132. if(retval != UA_STATUSCODE_GOOD) {
  133. UA_LOG_WARNING_SESSION(server->config.logger, session,
  134. "Subscription %u | MonitoredItem %i | "
  135. "Could not encode the value the MonitoredItem with status %s",
  136. subscriptionId, mon->monitoredItemId, UA_StatusCode_name(retval));
  137. return false;
  138. }
  139. /* Has the value changed? */
  140. valueEncoding.length = (uintptr_t)bufPos - (uintptr_t)valueEncoding.data;
  141. UA_Boolean changed = (!mon->lastSampledValue.data ||
  142. !UA_String_equal(&valueEncoding, &mon->lastSampledValue));
  143. /* No change */
  144. if(!changed) {
  145. if(valueEncoding.data != stackValueEncoding)
  146. UA_ByteString_deleteMembers(&valueEncoding);
  147. return false;
  148. }
  149. /* Change detected. Copy encoding on the heap if necessary. */
  150. if(valueEncoding.data == stackValueEncoding) {
  151. retval = UA_ByteString_copy(&valueEncoding, encoding);
  152. if(retval != UA_STATUSCODE_GOOD) {
  153. UA_LOG_WARNING_SESSION(server->config.logger, session,
  154. "Subscription %u | MonitoredItem %i | "
  155. "Detected change, but could not allocate memory for the notification"
  156. "with status %s", subscriptionId, mon->monitoredItemId,
  157. UA_StatusCode_name(retval));
  158. return false;
  159. }
  160. return true;
  161. }
  162. *encoding = valueEncoding;
  163. return true;
  164. }
  165. /* Has this sample changed from the last one? The method may allocate additional
  166. * space for the encoding buffer. Detect the change in encoding->data. */
  167. static UA_Boolean
  168. detectValueChange(UA_Server *server, UA_MonitoredItem *mon,
  169. UA_DataValue value, UA_ByteString *encoding) {
  170. /* Apply Filter */
  171. if(mon->filter.dataChangeFilter.trigger == UA_DATACHANGETRIGGER_STATUS)
  172. value.hasValue = false;
  173. value.hasServerTimestamp = false;
  174. value.hasServerPicoseconds = false;
  175. if(mon->filter.dataChangeFilter.trigger < UA_DATACHANGETRIGGER_STATUSVALUETIMESTAMP) {
  176. value.hasSourceTimestamp = false;
  177. value.hasSourcePicoseconds = false;
  178. }
  179. /* Detect the value change */
  180. return detectValueChangeWithFilter(server, mon, &value, encoding);
  181. }
  182. /* Returns whether the sample was stored in the MonitoredItem */
  183. static UA_Boolean
  184. sampleCallbackWithValue(UA_Server *server, UA_MonitoredItem *monitoredItem,
  185. UA_DataValue *value) {
  186. UA_assert(monitoredItem->monitoredItemType == UA_MONITOREDITEMTYPE_CHANGENOTIFY);
  187. UA_Subscription *sub = monitoredItem->subscription;
  188. /* Contains heap-allocated binary encoding of the value if a change was detected */
  189. UA_ByteString binaryEncoding = UA_BYTESTRING_NULL;
  190. /* Has the value changed? Allocates memory in binaryEncoding if necessary.
  191. * value is edited internally so we make a shallow copy. */
  192. UA_Boolean changed = detectValueChange(server, monitoredItem, *value, &binaryEncoding);
  193. if(!changed)
  194. return false;
  195. UA_Boolean storedValue = false;
  196. if(sub) {
  197. /* Allocate a new notification */
  198. UA_Notification *newNotification = (UA_Notification *)UA_malloc(sizeof(UA_Notification));
  199. if(!newNotification) {
  200. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  201. "Subscription %u | MonitoredItem %i | "
  202. "Item for the publishing queue could not be allocated",
  203. sub->subscriptionId, monitoredItem->monitoredItemId);
  204. UA_ByteString_deleteMembers(&binaryEncoding);
  205. return false;
  206. }
  207. /* <-- Point of no return --> */
  208. newNotification->mon = monitoredItem;
  209. newNotification->data.value = *value; /* Move the value to the notification */
  210. storedValue = true;
  211. /* Enqueue the new notification */
  212. UA_Notification_enqueue(server, sub, monitoredItem, newNotification);
  213. } else {
  214. /* Call the local callback if not attached to a subscription */
  215. UA_LocalMonitoredItem *localMon = (UA_LocalMonitoredItem*) monitoredItem;
  216. void *nodeContext = NULL;
  217. UA_Server_getNodeContext(server, monitoredItem->monitoredNodeId, &nodeContext);
  218. localMon->callback.dataChangeCallback(server, monitoredItem->monitoredItemId,
  219. localMon->context,
  220. &monitoredItem->monitoredNodeId,
  221. nodeContext, monitoredItem->attributeId,
  222. value);
  223. }
  224. // If someone called UA_Server_deleteMonitoredItem in the user callback,
  225. // then the monitored item will be deleted soon. So, there is no need to
  226. // add the lastValue or lastSampledValue to it.
  227. //
  228. // If we do so, we will leak
  229. // the memory of that values, because UA_Server_deleteMonitoredItem
  230. // already deleted all members and scheduled the monitored item pointer
  231. // for later delete. In the later delete the monitored item will be deleted
  232. // and not the members.
  233. //
  234. // Also in the later delete, all type information is lost and a deleteMember
  235. // is not possible.
  236. //
  237. // We do detect if the monitored item is already defunct.
  238. if (!monitoredItem->sampleCallbackIsRegistered) {
  239. UA_ByteString_deleteMembers(&binaryEncoding);
  240. return storedValue;
  241. }
  242. /* Store the encoding for comparison */
  243. UA_ByteString_deleteMembers(&monitoredItem->lastSampledValue);
  244. monitoredItem->lastSampledValue = binaryEncoding;
  245. UA_Variant_deleteMembers(&monitoredItem->lastValue);
  246. UA_Variant_copy(&value->value, &monitoredItem->lastValue);
  247. return storedValue;
  248. }
  249. void
  250. UA_MonitoredItem_sampleCallback(UA_Server *server, UA_MonitoredItem *monitoredItem) {
  251. UA_Session *session = &server->adminSession;
  252. UA_UInt32 subscriptionId = 0;
  253. UA_Subscription *sub = monitoredItem->subscription;
  254. if(sub) {
  255. session = sub->session;
  256. subscriptionId = sub->subscriptionId;
  257. }
  258. if(monitoredItem->monitoredItemType != UA_MONITOREDITEMTYPE_CHANGENOTIFY) {
  259. UA_LOG_DEBUG_SESSION(server->config.logger, session, "Subscription %u | "
  260. "MonitoredItem %i | Not a data change notification",
  261. subscriptionId, monitoredItem->monitoredItemId);
  262. return;
  263. }
  264. /* Sample the value */
  265. UA_ReadValueId rvid;
  266. UA_ReadValueId_init(&rvid);
  267. rvid.nodeId = monitoredItem->monitoredNodeId;
  268. rvid.attributeId = monitoredItem->attributeId;
  269. rvid.indexRange = monitoredItem->indexRange;
  270. UA_DataValue value = UA_Server_readWithSession(server, session, &rvid,
  271. monitoredItem->timestampsToReturn);
  272. /* Operate on the sample */
  273. UA_Boolean storedValue = sampleCallbackWithValue(server, monitoredItem, &value);
  274. /* Delete the sample if it was not stored in the MonitoredItem */
  275. if(!storedValue)
  276. UA_DataValue_deleteMembers(&value);
  277. }
  278. #endif /* UA_ENABLE_SUBSCRIPTIONS */