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