ua_subscription_datachange.c 18 KB

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