ua_subscription_datachange.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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_WARNING_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. LIST_REMOVE(monitoredItem, listEntry);
  55. UA_String_deleteMembers(&monitoredItem->indexRange);
  56. UA_ByteString_deleteMembers(&monitoredItem->lastSampledValue);
  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. /* Errors are returned as no change detected */
  128. static UA_Boolean
  129. detectValueChangeWithFilter(UA_MonitoredItem *mon, UA_DataValue *value,
  130. UA_ByteString *encoding) {
  131. /* Encode the data for comparison */
  132. size_t binsize = UA_calcSizeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE]);
  133. if(binsize == 0)
  134. return false;
  135. /* Allocate buffer on the heap if necessary */
  136. if(binsize > UA_VALUENCODING_MAXSTACK &&
  137. UA_ByteString_allocBuffer(encoding, binsize) != UA_STATUSCODE_GOOD)
  138. return false;
  139. /* Encode the value */
  140. UA_Byte *bufPos = encoding->data;
  141. const UA_Byte *bufEnd = &encoding->data[encoding->length];
  142. UA_StatusCode retval = UA_encodeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE],
  143. &bufPos, &bufEnd, NULL, NULL);
  144. if(retval != UA_STATUSCODE_GOOD)
  145. return false;
  146. /* The value has changed */
  147. encoding->length = (uintptr_t)bufPos - (uintptr_t)encoding->data;
  148. return !mon->lastSampledValue.data || !UA_String_equal(encoding, &mon->lastSampledValue);
  149. }
  150. /* Has this sample changed from the last one? The method may allocate additional
  151. * space for the encoding buffer. Detect the change in encoding->data. */
  152. static UA_Boolean
  153. detectValueChange(UA_MonitoredItem *mon, UA_DataValue *value, UA_ByteString *encoding) {
  154. /* Apply Filter */
  155. UA_Boolean hasValue = value->hasValue;
  156. if(mon->trigger == UA_DATACHANGETRIGGER_STATUS)
  157. value->hasValue = false;
  158. UA_Boolean hasServerTimestamp = value->hasServerTimestamp;
  159. UA_Boolean hasServerPicoseconds = value->hasServerPicoseconds;
  160. value->hasServerTimestamp = false;
  161. value->hasServerPicoseconds = false;
  162. UA_Boolean hasSourceTimestamp = value->hasSourceTimestamp;
  163. UA_Boolean hasSourcePicoseconds = value->hasSourcePicoseconds;
  164. if(mon->trigger < UA_DATACHANGETRIGGER_STATUSVALUETIMESTAMP) {
  165. value->hasSourceTimestamp = false;
  166. value->hasSourcePicoseconds = false;
  167. }
  168. /* Detect the Value Change */
  169. UA_Boolean res = detectValueChangeWithFilter(mon, value, encoding);
  170. /* Reset the filter */
  171. value->hasValue = hasValue;
  172. value->hasServerTimestamp = hasServerTimestamp;
  173. value->hasServerPicoseconds = hasServerPicoseconds;
  174. value->hasSourceTimestamp = hasSourceTimestamp;
  175. value->hasSourcePicoseconds = hasSourcePicoseconds;
  176. return res;
  177. }
  178. /* Returns whether a new sample was created */
  179. static UA_Boolean
  180. sampleCallbackWithValue(UA_Server *server, UA_Subscription *sub,
  181. UA_MonitoredItem *monitoredItem,
  182. UA_DataValue *value,
  183. UA_ByteString *valueEncoding) {
  184. UA_assert(monitoredItem->monitoredItemType == UA_MONITOREDITEMTYPE_CHANGENOTIFY);
  185. /* Store the pointer to the stack-allocated bytestring to see if a heap-allocation
  186. * was necessary */
  187. UA_Byte *stackValueEncoding = valueEncoding->data;
  188. /* Has the value changed? */
  189. UA_Boolean changed = detectValueChange(monitoredItem, value, valueEncoding);
  190. if(!changed)
  191. return false;
  192. /* Allocate the entry for the publish queue */
  193. UA_Notification *newNotification =
  194. (UA_Notification *)UA_malloc(sizeof(UA_Notification));
  195. if(!newNotification) {
  196. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  197. "Subscription %u | MonitoredItem %i | "
  198. "Item for the publishing queue could not be allocated",
  199. sub->subscriptionId, monitoredItem->monitoredItemId);
  200. return false;
  201. }
  202. /* Copy valueEncoding on the heap for the next comparison (if not already done) */
  203. if(valueEncoding->data == stackValueEncoding) {
  204. UA_ByteString cbs;
  205. if(UA_ByteString_copy(valueEncoding, &cbs) != UA_STATUSCODE_GOOD) {
  206. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  207. "Subscription %u | MonitoredItem %i | "
  208. "ByteString to compare values could not be created",
  209. sub->subscriptionId, monitoredItem->monitoredItemId);
  210. UA_free(newNotification);
  211. return false;
  212. }
  213. *valueEncoding = cbs;
  214. }
  215. /* Prepare the newQueueItem */
  216. if(value->hasValue && value->value.storageType == UA_VARIANT_DATA_NODELETE) {
  217. /* Make a deep copy of the value */
  218. UA_StatusCode retval = UA_DataValue_copy(value, &newNotification->data.value);
  219. if(retval != UA_STATUSCODE_GOOD) {
  220. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  221. "Subscription %u | MonitoredItem %i | "
  222. "Item for the publishing queue could not be prepared",
  223. sub->subscriptionId, monitoredItem->monitoredItemId);
  224. UA_free(newNotification);
  225. return false;
  226. }
  227. } else {
  228. newNotification->data.value = *value; /* Just copy the value and do not release it */
  229. }
  230. /* <-- Point of no return --> */
  231. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  232. "Subscription %u | MonitoredItem %u | Sampled a new value",
  233. sub->subscriptionId, monitoredItem->monitoredItemId);
  234. newNotification->mon = monitoredItem;
  235. /* Replace the encoding for comparison */
  236. UA_ByteString_deleteMembers(&monitoredItem->lastSampledValue);
  237. monitoredItem->lastSampledValue = *valueEncoding;
  238. /* Add the notification to the end of local and global queue */
  239. TAILQ_INSERT_TAIL(&monitoredItem->queue, newNotification, listEntry);
  240. TAILQ_INSERT_TAIL(&sub->notificationQueue, newNotification, globalEntry);
  241. ++monitoredItem->queueSize;
  242. ++sub->notificationQueueSize;
  243. /* Remove some notifications if the queue is beyond maximum capacity */
  244. MonitoredItem_ensureQueueSpace(monitoredItem);
  245. return true;
  246. }
  247. void
  248. UA_MonitoredItem_SampleCallback(UA_Server *server,
  249. UA_MonitoredItem *monitoredItem) {
  250. UA_Subscription *sub = monitoredItem->subscription;
  251. if(monitoredItem->monitoredItemType != UA_MONITOREDITEMTYPE_CHANGENOTIFY) {
  252. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  253. "Subscription %u | MonitoredItem %i | "
  254. "Not a data change notification",
  255. sub->subscriptionId, monitoredItem->monitoredItemId);
  256. return;
  257. }
  258. /* Read the value */
  259. UA_ReadValueId rvid;
  260. UA_ReadValueId_init(&rvid);
  261. rvid.nodeId = monitoredItem->monitoredNodeId;
  262. rvid.attributeId = monitoredItem->attributeId;
  263. rvid.indexRange = monitoredItem->indexRange;
  264. UA_DataValue value =
  265. UA_Server_readWithSession(server, sub->session,
  266. &rvid, monitoredItem->timestampsToReturn);
  267. /* Stack-allocate some memory for the value encoding. We might heap-allocate
  268. * more memory if needed. This is just enough for scalars and small
  269. * structures. */
  270. UA_STACKARRAY(UA_Byte, stackValueEncoding, UA_VALUENCODING_MAXSTACK);
  271. UA_ByteString valueEncoding;
  272. valueEncoding.data = stackValueEncoding;
  273. valueEncoding.length = UA_VALUENCODING_MAXSTACK;
  274. /* Create a sample and compare with the last value */
  275. UA_Boolean newNotification = sampleCallbackWithValue(server, sub, monitoredItem,
  276. &value, &valueEncoding);
  277. /* Clean up */
  278. if(!newNotification) {
  279. if(valueEncoding.data != stackValueEncoding)
  280. UA_ByteString_deleteMembers(&valueEncoding);
  281. UA_DataValue_deleteMembers(&value);
  282. }
  283. }
  284. UA_StatusCode
  285. MonitoredItem_registerSampleCallback(UA_Server *server, UA_MonitoredItem *mon) {
  286. if(mon->sampleCallbackIsRegistered)
  287. return UA_STATUSCODE_GOOD;
  288. UA_StatusCode retval =
  289. UA_Server_addRepeatedCallback(server, (UA_ServerCallback)UA_MonitoredItem_SampleCallback,
  290. mon, (UA_UInt32)mon->samplingInterval, &mon->sampleCallbackId);
  291. if(retval == UA_STATUSCODE_GOOD)
  292. mon->sampleCallbackIsRegistered = true;
  293. return retval;
  294. }
  295. UA_StatusCode
  296. MonitoredItem_unregisterSampleCallback(UA_Server *server, UA_MonitoredItem *mon) {
  297. if(!mon->sampleCallbackIsRegistered)
  298. return UA_STATUSCODE_GOOD;
  299. mon->sampleCallbackIsRegistered = false;
  300. return UA_Server_removeRepeatedCallback(server, mon->sampleCallbackId);
  301. }
  302. #endif /* UA_ENABLE_SUBSCRIPTIONS */