ua_subscription_datachange.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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) Thomas Stalder, Blue Time Concept SA
  8. */
  9. #include "ua_server_internal.h"
  10. #include "ua_subscription.h"
  11. #include "ua_types_encoding_binary.h"
  12. #ifdef UA_ENABLE_SUBSCRIPTIONS /* conditional compilation */
  13. #define UA_VALUENCODING_MAXSTACK 512
  14. void UA_MonitoredItem_init(UA_MonitoredItem *mon, UA_Subscription *sub) {
  15. memset(mon, 0, sizeof(UA_MonitoredItem));
  16. mon->subscription = sub;
  17. TAILQ_INIT(&mon->queue);
  18. }
  19. void UA_MonitoredItem_delete(UA_Server *server, UA_MonitoredItem *monitoredItem) {
  20. if(monitoredItem->monitoredItemType == UA_MONITOREDITEMTYPE_CHANGENOTIFY) {
  21. /* Remove the sampling callback */
  22. UA_MonitoredItem_unregisterSampleCallback(server, monitoredItem);
  23. } else {
  24. /* TODO: Access val data.event */
  25. UA_LOG_ERROR(server->config.logger, UA_LOGCATEGORY_SERVER,
  26. "MonitoredItemTypes other than ChangeNotify are not supported yet");
  27. }
  28. /* Remove the queued notifications if attached to a subscription */
  29. if(monitoredItem->subscription) {
  30. UA_Subscription *sub = monitoredItem->subscription;
  31. UA_Notification *notification, *notification_tmp;
  32. TAILQ_FOREACH_SAFE(notification, &monitoredItem->queue,
  33. listEntry, notification_tmp) {
  34. /* Remove the item from the queues */
  35. TAILQ_REMOVE(&monitoredItem->queue, notification, listEntry);
  36. TAILQ_REMOVE(&sub->notificationQueue, notification, globalEntry);
  37. --sub->notificationQueueSize;
  38. UA_Notification_delete(notification);
  39. }
  40. monitoredItem->queueSize = 0;
  41. }
  42. /* Remove the monitored item */
  43. UA_String_deleteMembers(&monitoredItem->indexRange);
  44. UA_ByteString_deleteMembers(&monitoredItem->lastSampledValue);
  45. UA_Variant_deleteMembers(&monitoredItem->lastValue);
  46. UA_NodeId_deleteMembers(&monitoredItem->monitoredNodeId);
  47. UA_Server_delayedFree(server, monitoredItem);
  48. }
  49. void MonitoredItem_ensureQueueSpace(UA_MonitoredItem *mon) {
  50. if(mon->queueSize <= mon->maxQueueSize)
  51. return;
  52. /* Remove notifications until the queue size is reached */
  53. UA_Subscription *sub = mon->subscription;
  54. while(mon->queueSize > mon->maxQueueSize) {
  55. UA_assert(mon->queueSize >= 2); /* At least two Notifications in the queue */
  56. /* Make sure that the MonitoredItem does not lose its place in the
  57. * global queue when notifications are removed. Otherwise the
  58. * MonitoredItem can "starve" itself by putting new notifications always
  59. * at the end of the global queue and removing the old ones.
  60. *
  61. * - If the oldest notification is removed, put the second oldest
  62. * notification right behind it.
  63. * - If the newest notification is removed, put the new notification
  64. * right behind it. */
  65. UA_Notification *del; /* The notification that will be deleted */
  66. UA_Notification *after_del; /* The notification to keep and move after del */
  67. if(mon->discardOldest) {
  68. /* Remove the oldest */
  69. del = TAILQ_FIRST(&mon->queue);
  70. after_del = TAILQ_NEXT(del, listEntry);
  71. } else {
  72. /* Remove the second newest (to keep the up-to-date notification) */
  73. after_del = TAILQ_LAST(&mon->queue, NotificationQueue);
  74. del = TAILQ_PREV(after_del, NotificationQueue, listEntry);
  75. }
  76. /* Move after_del right after del in the global queue */
  77. TAILQ_REMOVE(&sub->notificationQueue, after_del, globalEntry);
  78. TAILQ_INSERT_AFTER(&sub->notificationQueue, del, after_del, globalEntry);
  79. /* Remove the notification from the queues */
  80. TAILQ_REMOVE(&mon->queue, del, listEntry);
  81. TAILQ_REMOVE(&sub->notificationQueue, del, globalEntry);
  82. --mon->queueSize;
  83. --sub->notificationQueueSize;
  84. /* Free the notification */
  85. UA_Notification_delete(del);
  86. }
  87. if(mon->monitoredItemType == UA_MONITOREDITEMTYPE_CHANGENOTIFY) {
  88. /* Get the element that carries the infobits */
  89. UA_Notification *notification = NULL;
  90. if(mon->discardOldest)
  91. notification = TAILQ_FIRST(&mon->queue);
  92. else
  93. notification = TAILQ_LAST(&mon->queue, NotificationQueue);
  94. UA_assert(notification);
  95. if(mon->maxQueueSize > 1) {
  96. /* Add the infobits either to the newest or the new last entry */
  97. notification->data.value.hasStatus = true;
  98. notification->data.value.status |= (UA_STATUSCODE_INFOTYPE_DATAVALUE |
  99. UA_STATUSCODE_INFOBITS_OVERFLOW);
  100. } else {
  101. /* If the queue size is reduced to one, remove the infobits */
  102. notification->data.value.status &= ~(UA_StatusCode)(UA_STATUSCODE_INFOTYPE_DATAVALUE |
  103. UA_STATUSCODE_INFOBITS_OVERFLOW);
  104. }
  105. }
  106. /* TODO: Infobits for Events? */
  107. }
  108. #define ABS_SUBTRACT_TYPE_INDEPENDENT(a,b) ((a)>(b)?(a)-(b):(b)-(a))
  109. static UA_INLINE UA_Boolean
  110. outOfDeadBand(const void *data1, const void *data2, const size_t index, const UA_DataType *type, const UA_Double deadbandValue) {
  111. if (type == &UA_TYPES[UA_TYPES_SBYTE]) {
  112. if (ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_SByte*)data1)[index], ((const UA_SByte*)data2)[index]) <= deadbandValue)
  113. return false;
  114. } else
  115. if (type == &UA_TYPES[UA_TYPES_BYTE]) {
  116. if (ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_Byte*)data1)[index], ((const UA_Byte*)data2)[index]) <= deadbandValue)
  117. return false;
  118. } else
  119. if (type == &UA_TYPES[UA_TYPES_INT16]) {
  120. if (ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_Int16*)data1)[index], ((const UA_Int16*)data2)[index]) <= deadbandValue)
  121. return false;
  122. } else
  123. if (type == &UA_TYPES[UA_TYPES_UINT16]) {
  124. if (ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_UInt16*)data1)[index], ((const UA_UInt16*)data2)[index]) <= deadbandValue)
  125. return false;
  126. } else
  127. if (type == &UA_TYPES[UA_TYPES_INT32]) {
  128. if (ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_Int32*)data1)[index], ((const UA_Int32*)data2)[index]) <= deadbandValue)
  129. return false;
  130. } else
  131. if (type == &UA_TYPES[UA_TYPES_UINT32]) {
  132. if (ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_UInt32*)data1)[index], ((const UA_UInt32*)data2)[index]) <= deadbandValue)
  133. return false;
  134. } else
  135. if (type == &UA_TYPES[UA_TYPES_INT64]) {
  136. if (ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_Int64*)data1)[index], ((const UA_Int64*)data2)[index]) <= deadbandValue)
  137. return false;
  138. } else
  139. if (type == &UA_TYPES[UA_TYPES_UINT64]) {
  140. if (ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_UInt64*)data1)[index], ((const UA_UInt64*)data2)[index]) <= deadbandValue)
  141. return false;
  142. } else
  143. if (type == &UA_TYPES[UA_TYPES_FLOAT]) {
  144. if (ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_Float*)data1)[index], ((const UA_Float*)data2)[index]) <= deadbandValue)
  145. return false;
  146. } else
  147. if (type == &UA_TYPES[UA_TYPES_DOUBLE]) {
  148. if (ABS_SUBTRACT_TYPE_INDEPENDENT(((const UA_Double*)data1)[index], ((const UA_Double*)data2)[index]) <= deadbandValue)
  149. return false;
  150. }
  151. return true;
  152. }
  153. static UA_INLINE UA_Boolean
  154. updateNeededForFilteredValue(const UA_Variant *value, const UA_Variant *oldValue, const UA_Double deadbandValue) {
  155. if (value->arrayLength != oldValue->arrayLength) {
  156. return true;
  157. }
  158. if (value->type != oldValue->type) {
  159. return true;
  160. }
  161. if (UA_Variant_isScalar(value)) {
  162. return outOfDeadBand(value->data, oldValue->data, 0, value->type, deadbandValue);
  163. } else {
  164. for (size_t i = 0; i < value->arrayLength; ++i) {
  165. if (outOfDeadBand(value->data, oldValue->data, i, value->type, deadbandValue))
  166. return true;
  167. }
  168. }
  169. return false;
  170. }
  171. /* When a change is detected, encoding contains the heap-allocated binary encoded value */
  172. static UA_Boolean
  173. detectValueChangeWithFilter(UA_Server *server, UA_MonitoredItem *mon, UA_DataValue *value,
  174. UA_ByteString *encoding) {
  175. UA_Session *session = &adminSession;
  176. UA_UInt32 subscriptionId = 0;
  177. UA_Subscription *sub = mon->subscription;
  178. if(sub) {
  179. session = sub->session;
  180. subscriptionId = sub->subscriptionId;
  181. }
  182. if(isDataTypeNumeric(value->value.type) &&
  183. (mon->filter.trigger == UA_DATACHANGETRIGGER_STATUSVALUE ||
  184. mon->filter.trigger == UA_DATACHANGETRIGGER_STATUSVALUETIMESTAMP)) {
  185. if(mon->filter.deadbandType == UA_DEADBANDTYPE_ABSOLUTE) {
  186. if(!updateNeededForFilteredValue(&value->value, &mon->lastValue, mon->filter.deadbandValue))
  187. return false;
  188. }
  189. /* else if (mon->filter.deadbandType == UA_DEADBANDTYPE_PERCENT) {
  190. // TODO where do this EURange come from ?
  191. UA_Double deadbandValue = fabs(mon->filter.deadbandValue * (EURange.high-EURange.low));
  192. if (!updateNeededForFilteredValue(value->value, mon->lastValue, deadbandValue))
  193. return false;
  194. }*/
  195. }
  196. /* Stack-allocate some memory for the value encoding. We might heap-allocate
  197. * more memory if needed. This is just enough for scalars and small
  198. * structures. */
  199. UA_STACKARRAY(UA_Byte, stackValueEncoding, UA_VALUENCODING_MAXSTACK);
  200. UA_ByteString valueEncoding;
  201. valueEncoding.data = stackValueEncoding;
  202. valueEncoding.length = UA_VALUENCODING_MAXSTACK;
  203. /* Encode the value */
  204. UA_Byte *bufPos = valueEncoding.data;
  205. const UA_Byte *bufEnd = &valueEncoding.data[valueEncoding.length];
  206. UA_StatusCode retval = UA_encodeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE],
  207. &bufPos, &bufEnd, NULL, NULL);
  208. if(retval == UA_STATUSCODE_BADENCODINGLIMITSEXCEEDED) {
  209. size_t binsize = UA_calcSizeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE]);
  210. if(binsize == 0)
  211. return false;
  212. retval = UA_ByteString_allocBuffer(&valueEncoding, binsize);
  213. if(retval == UA_STATUSCODE_GOOD) {
  214. bufPos = valueEncoding.data;
  215. bufEnd = &valueEncoding.data[valueEncoding.length];
  216. retval = UA_encodeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE],
  217. &bufPos, &bufEnd, NULL, NULL);
  218. }
  219. }
  220. if(retval != UA_STATUSCODE_GOOD) {
  221. UA_LOG_WARNING_SESSION(server->config.logger, session,
  222. "Subscription %u | MonitoredItem %i | "
  223. "Could not encode the value the MonitoredItem with status %s",
  224. subscriptionId, mon->monitoredItemId, UA_StatusCode_name(retval));
  225. return false;
  226. }
  227. /* Has the value changed? */
  228. valueEncoding.length = (uintptr_t)bufPos - (uintptr_t)valueEncoding.data;
  229. UA_Boolean changed = (!mon->lastSampledValue.data ||
  230. !UA_String_equal(&valueEncoding, &mon->lastSampledValue));
  231. /* No change */
  232. if(!changed) {
  233. if(valueEncoding.data != stackValueEncoding)
  234. UA_ByteString_deleteMembers(&valueEncoding);
  235. return false;
  236. }
  237. /* Change detected. Copy encoding on the heap if necessary. */
  238. if(valueEncoding.data == stackValueEncoding) {
  239. retval = UA_ByteString_copy(&valueEncoding, encoding);
  240. if(retval != UA_STATUSCODE_GOOD) {
  241. UA_LOG_WARNING_SESSION(server->config.logger, session,
  242. "Subscription %u | MonitoredItem %i | "
  243. "Detected change, but could not allocate memory for the notification"
  244. "with status %s", subscriptionId, mon->monitoredItemId,
  245. UA_StatusCode_name(retval));
  246. return false;
  247. }
  248. return true;
  249. }
  250. *encoding = valueEncoding;
  251. return true;
  252. }
  253. /* Has this sample changed from the last one? The method may allocate additional
  254. * space for the encoding buffer. Detect the change in encoding->data. */
  255. static UA_Boolean
  256. detectValueChange(UA_Server *server, UA_MonitoredItem *mon,
  257. UA_DataValue value, UA_ByteString *encoding) {
  258. /* Apply Filter */
  259. if(mon->filter.trigger == UA_DATACHANGETRIGGER_STATUS)
  260. value.hasValue = false;
  261. value.hasServerTimestamp = false;
  262. value.hasServerPicoseconds = false;
  263. if(mon->filter.trigger < UA_DATACHANGETRIGGER_STATUSVALUETIMESTAMP) {
  264. value.hasSourceTimestamp = false;
  265. value.hasSourcePicoseconds = false;
  266. }
  267. /* Detect the value change */
  268. return detectValueChangeWithFilter(server, mon, &value, encoding);
  269. }
  270. /* Returns whether the sample was stored in the MonitoredItem */
  271. static UA_Boolean
  272. sampleCallbackWithValue(UA_Server *server, UA_MonitoredItem *monitoredItem,
  273. UA_DataValue *value) {
  274. UA_assert(monitoredItem->monitoredItemType == UA_MONITOREDITEMTYPE_CHANGENOTIFY);
  275. UA_Subscription *sub = monitoredItem->subscription;
  276. /* Contains heap-allocated binary encoding of the value if a change was detected */
  277. UA_ByteString binaryEncoding = UA_BYTESTRING_NULL;
  278. /* Has the value changed? Allocates memory in binaryEncoding if necessary.
  279. * value is edited internally so we make a shallow copy. */
  280. UA_Boolean changed = detectValueChange(server, monitoredItem, *value, &binaryEncoding);
  281. if(!changed)
  282. return false;
  283. UA_Boolean storedValue = false;
  284. if(sub) {
  285. /* Allocate a new notification */
  286. UA_Notification *newNotification = (UA_Notification *)UA_malloc(sizeof(UA_Notification));
  287. if(!newNotification) {
  288. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  289. "Subscription %u | MonitoredItem %i | "
  290. "Item for the publishing queue could not be allocated",
  291. sub->subscriptionId, monitoredItem->monitoredItemId);
  292. UA_ByteString_deleteMembers(&binaryEncoding);
  293. return false;
  294. }
  295. /* <-- Point of no return --> */
  296. newNotification->mon = monitoredItem;
  297. newNotification->data.value = *value; /* Move the value to the notification */
  298. storedValue = true;
  299. /* Add the notification to the end of local and global queue */
  300. TAILQ_INSERT_TAIL(&monitoredItem->queue, newNotification, listEntry);
  301. TAILQ_INSERT_TAIL(&sub->notificationQueue, newNotification, globalEntry);
  302. ++monitoredItem->queueSize;
  303. ++sub->notificationQueueSize;
  304. /* Remove some notifications if the queue is beyond maximum capacity */
  305. MonitoredItem_ensureQueueSpace(monitoredItem);
  306. } else {
  307. /* Call the local callback if not attached to a subscription */
  308. UA_LocalMonitoredItem *localMon = (UA_LocalMonitoredItem*) monitoredItem;
  309. void *nodeContext = NULL;
  310. UA_Server_getNodeContext(server, monitoredItem->monitoredNodeId, &nodeContext);
  311. localMon->callback.dataChangeCallback(server, monitoredItem->monitoredItemId,
  312. localMon->context,
  313. &monitoredItem->monitoredNodeId,
  314. nodeContext, monitoredItem->attributeId,
  315. value);
  316. }
  317. /* Store the encoding for comparison */
  318. UA_ByteString_deleteMembers(&monitoredItem->lastSampledValue);
  319. monitoredItem->lastSampledValue = binaryEncoding;
  320. UA_Variant_deleteMembers(&monitoredItem->lastValue);
  321. UA_Variant_copy(&value->value, &monitoredItem->lastValue);
  322. return storedValue;
  323. }
  324. void
  325. UA_MonitoredItem_sampleCallback(UA_Server *server, UA_MonitoredItem *monitoredItem) {
  326. UA_Session *session = &adminSession;
  327. UA_UInt32 subscriptionId = 0;
  328. UA_Subscription *sub = monitoredItem->subscription;
  329. if(sub) {
  330. session = sub->session;
  331. subscriptionId = sub->subscriptionId;
  332. }
  333. if(monitoredItem->monitoredItemType != UA_MONITOREDITEMTYPE_CHANGENOTIFY) {
  334. UA_LOG_DEBUG_SESSION(server->config.logger, session, "Subscription %u | "
  335. "MonitoredItem %i | Not a data change notification",
  336. subscriptionId, monitoredItem->monitoredItemId);
  337. return;
  338. }
  339. /* Sample the value */
  340. UA_ReadValueId rvid;
  341. UA_ReadValueId_init(&rvid);
  342. rvid.nodeId = monitoredItem->monitoredNodeId;
  343. rvid.attributeId = monitoredItem->attributeId;
  344. rvid.indexRange = monitoredItem->indexRange;
  345. UA_DataValue value = UA_Server_readWithSession(server, session, &rvid, monitoredItem->timestampsToReturn);
  346. /* Operate on the sample */
  347. UA_Boolean storedValue = sampleCallbackWithValue(server, monitoredItem, &value);
  348. /* Delete the sample if it was not stored in the MonitoredItem */
  349. if(!storedValue)
  350. UA_DataValue_deleteMembers(&value);
  351. }
  352. UA_StatusCode
  353. UA_MonitoredItem_registerSampleCallback(UA_Server *server, UA_MonitoredItem *mon) {
  354. if(mon->sampleCallbackIsRegistered)
  355. return UA_STATUSCODE_GOOD;
  356. UA_StatusCode retval =
  357. UA_Server_addRepeatedCallback(server, (UA_ServerCallback)UA_MonitoredItem_sampleCallback,
  358. mon, (UA_UInt32)mon->samplingInterval, &mon->sampleCallbackId);
  359. if(retval == UA_STATUSCODE_GOOD)
  360. mon->sampleCallbackIsRegistered = true;
  361. return retval;
  362. }
  363. UA_StatusCode
  364. UA_MonitoredItem_unregisterSampleCallback(UA_Server *server, UA_MonitoredItem *mon) {
  365. if(!mon->sampleCallbackIsRegistered)
  366. return UA_STATUSCODE_GOOD;
  367. mon->sampleCallbackIsRegistered = false;
  368. return UA_Server_removeRepeatedCallback(server, mon->sampleCallbackId);
  369. }
  370. #endif /* UA_ENABLE_SUBSCRIPTIONS */