ua_subscription_datachange.c 18 KB

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