ua_subscription_datachange.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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) Julius Pfrommer, Fraunhofer IOSB
  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
  61. MonitoredItem_ensureQueueSpace(UA_MonitoredItem *mon) {
  62. UA_Boolean valueDiscarded = false;
  63. UA_Subscription *sub = mon->subscription;
  64. /* Remove notifications until the queue size is reached */
  65. while(mon->queueSize > mon->maxQueueSize) {
  66. /* maxQueuesize is at least 1 */
  67. UA_assert(mon->queueSize >= 2);
  68. /* Get the item to remove. New items are added to the end */
  69. UA_Notification *notification = NULL;
  70. if(mon->discardOldest) {
  71. /* Remove the oldest */
  72. notification = TAILQ_FIRST(&mon->queue);
  73. } else {
  74. /* Keep the newest, remove the second-newest */
  75. notification = TAILQ_LAST(&mon->queue, NotificationQueue);
  76. notification = TAILQ_PREV(notification, NotificationQueue, listEntry);
  77. }
  78. UA_assert(notification);
  79. /* Remove the item */
  80. TAILQ_REMOVE(&mon->queue, notification, listEntry);
  81. TAILQ_REMOVE(&sub->notificationQueue, notification, globalEntry);
  82. --mon->queueSize;
  83. --sub->notificationQueueSize;
  84. /* Free the notification */
  85. if(mon->monitoredItemType == UA_MONITOREDITEMTYPE_CHANGENOTIFY) {
  86. UA_DataValue_deleteMembers(&notification->data.value);
  87. } else {
  88. /* TODO: event implemantation */
  89. }
  90. /* Work around a false positive in clang analyzer */
  91. #ifndef __clang_analyzer__
  92. UA_free(notification);
  93. #endif
  94. valueDiscarded = true;
  95. }
  96. if(!valueDiscarded)
  97. return;
  98. if(mon->monitoredItemType == UA_MONITOREDITEMTYPE_CHANGENOTIFY) {
  99. /* Get the element that carries the infobits */
  100. UA_Notification *notification = NULL;
  101. if(mon->discardOldest)
  102. notification = TAILQ_FIRST(&mon->queue);
  103. else
  104. notification = TAILQ_LAST(&mon->queue, NotificationQueue);
  105. UA_assert(notification);
  106. if(mon->maxQueueSize > 1) {
  107. /* Add the infobits either to the newest or the new last entry */
  108. notification->data.value.hasStatus = true;
  109. notification->data.value.status |= (UA_STATUSCODE_INFOTYPE_DATAVALUE |
  110. UA_STATUSCODE_INFOBITS_OVERFLOW);
  111. } else {
  112. /* If the queue size is reduced to one, remove the infobits */
  113. notification->data.value.status &= ~(UA_StatusCode)(UA_STATUSCODE_INFOTYPE_DATAVALUE |
  114. UA_STATUSCODE_INFOBITS_OVERFLOW);
  115. }
  116. }
  117. /* TODO: Infobits for Events? */
  118. }
  119. /* Errors are returned as no change detected */
  120. static UA_Boolean
  121. detectValueChangeWithFilter(UA_MonitoredItem *mon, UA_DataValue *value,
  122. UA_ByteString *encoding) {
  123. /* Encode the data for comparison */
  124. size_t binsize = UA_calcSizeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE]);
  125. if(binsize == 0)
  126. return false;
  127. /* Allocate buffer on the heap if necessary */
  128. if(binsize > UA_VALUENCODING_MAXSTACK &&
  129. UA_ByteString_allocBuffer(encoding, binsize) != UA_STATUSCODE_GOOD)
  130. return false;
  131. /* Encode the value */
  132. UA_Byte *bufPos = encoding->data;
  133. const UA_Byte *bufEnd = &encoding->data[encoding->length];
  134. UA_StatusCode retval = UA_encodeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE],
  135. &bufPos, &bufEnd, NULL, NULL);
  136. if(retval != UA_STATUSCODE_GOOD)
  137. return false;
  138. /* The value has changed */
  139. encoding->length = (uintptr_t)bufPos - (uintptr_t)encoding->data;
  140. return !mon->lastSampledValue.data || !UA_String_equal(encoding, &mon->lastSampledValue);
  141. }
  142. /* Has this sample changed from the last one? The method may allocate additional
  143. * space for the encoding buffer. Detect the change in encoding->data. */
  144. static UA_Boolean
  145. detectValueChange(UA_MonitoredItem *mon, UA_DataValue *value, UA_ByteString *encoding) {
  146. /* Apply Filter */
  147. UA_Boolean hasValue = value->hasValue;
  148. if(mon->trigger == UA_DATACHANGETRIGGER_STATUS)
  149. value->hasValue = false;
  150. UA_Boolean hasServerTimestamp = value->hasServerTimestamp;
  151. UA_Boolean hasServerPicoseconds = value->hasServerPicoseconds;
  152. value->hasServerTimestamp = false;
  153. value->hasServerPicoseconds = false;
  154. UA_Boolean hasSourceTimestamp = value->hasSourceTimestamp;
  155. UA_Boolean hasSourcePicoseconds = value->hasSourcePicoseconds;
  156. if(mon->trigger < UA_DATACHANGETRIGGER_STATUSVALUETIMESTAMP) {
  157. value->hasSourceTimestamp = false;
  158. value->hasSourcePicoseconds = false;
  159. }
  160. /* Detect the Value Change */
  161. UA_Boolean res = detectValueChangeWithFilter(mon, value, encoding);
  162. /* Reset the filter */
  163. value->hasValue = hasValue;
  164. value->hasServerTimestamp = hasServerTimestamp;
  165. value->hasServerPicoseconds = hasServerPicoseconds;
  166. value->hasSourceTimestamp = hasSourceTimestamp;
  167. value->hasSourcePicoseconds = hasSourcePicoseconds;
  168. return res;
  169. }
  170. /* Returns whether a new sample was created */
  171. static UA_Boolean
  172. sampleCallbackWithValue(UA_Server *server, UA_Subscription *sub,
  173. UA_MonitoredItem *monitoredItem,
  174. UA_DataValue *value,
  175. UA_ByteString *valueEncoding) {
  176. UA_assert(monitoredItem->monitoredItemType == UA_MONITOREDITEMTYPE_CHANGENOTIFY);
  177. /* Store the pointer to the stack-allocated bytestring to see if a heap-allocation
  178. * was necessary */
  179. UA_Byte *stackValueEncoding = valueEncoding->data;
  180. /* Has the value changed? */
  181. UA_Boolean changed = detectValueChange(monitoredItem, value, valueEncoding);
  182. if(!changed)
  183. return false;
  184. /* Allocate the entry for the publish queue */
  185. UA_Notification *newNotification =
  186. (UA_Notification *)UA_malloc(sizeof(UA_Notification));
  187. if(!newNotification) {
  188. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  189. "Subscription %u | MonitoredItem %i | "
  190. "Item for the publishing queue could not be allocated",
  191. sub->subscriptionId, monitoredItem->monitoredItemId);
  192. return false;
  193. }
  194. /* Copy valueEncoding on the heap for the next comparison (if not already done) */
  195. if(valueEncoding->data == stackValueEncoding) {
  196. UA_ByteString cbs;
  197. if(UA_ByteString_copy(valueEncoding, &cbs) != UA_STATUSCODE_GOOD) {
  198. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  199. "Subscription %u | MonitoredItem %i | "
  200. "ByteString to compare values could not be created",
  201. sub->subscriptionId, monitoredItem->monitoredItemId);
  202. UA_free(newNotification);
  203. return false;
  204. }
  205. *valueEncoding = cbs;
  206. }
  207. /* Prepare the newQueueItem */
  208. if(value->hasValue && value->value.storageType == UA_VARIANT_DATA_NODELETE) {
  209. /* Make a deep copy of the value */
  210. UA_StatusCode retval = UA_DataValue_copy(value, &newNotification->data.value);
  211. if(retval != UA_STATUSCODE_GOOD) {
  212. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  213. "Subscription %u | MonitoredItem %i | "
  214. "Item for the publishing queue could not be prepared",
  215. sub->subscriptionId, monitoredItem->monitoredItemId);
  216. UA_free(newNotification);
  217. return false;
  218. }
  219. } else {
  220. newNotification->data.value = *value; /* Just copy the value and do not release it */
  221. }
  222. /* <-- Point of no return --> */
  223. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  224. "Subscription %u | MonitoredItem %u | Sampled a new value",
  225. sub->subscriptionId, monitoredItem->monitoredItemId);
  226. newNotification->mon = monitoredItem;
  227. /* Replace the encoding for comparison */
  228. UA_ByteString_deleteMembers(&monitoredItem->lastSampledValue);
  229. monitoredItem->lastSampledValue = *valueEncoding;
  230. /* Add the sample to the queue for publication */
  231. TAILQ_INSERT_TAIL(&monitoredItem->queue, newNotification, listEntry);
  232. TAILQ_INSERT_TAIL(&sub->notificationQueue, newNotification, globalEntry);
  233. ++monitoredItem->queueSize;
  234. ++sub->notificationQueueSize;
  235. /* Remove entries from the queue if required and add the sample to the global queue */
  236. MonitoredItem_ensureQueueSpace(monitoredItem);
  237. return true;
  238. }
  239. void
  240. UA_MonitoredItem_SampleCallback(UA_Server *server,
  241. UA_MonitoredItem *monitoredItem) {
  242. UA_Subscription *sub = monitoredItem->subscription;
  243. if(monitoredItem->monitoredItemType != UA_MONITOREDITEMTYPE_CHANGENOTIFY) {
  244. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  245. "Subscription %u | MonitoredItem %i | "
  246. "Not a data change notification",
  247. sub->subscriptionId, monitoredItem->monitoredItemId);
  248. return;
  249. }
  250. /* Read the value */
  251. UA_ReadValueId rvid;
  252. UA_ReadValueId_init(&rvid);
  253. rvid.nodeId = monitoredItem->monitoredNodeId;
  254. rvid.attributeId = monitoredItem->attributeId;
  255. rvid.indexRange = monitoredItem->indexRange;
  256. UA_DataValue value =
  257. UA_Server_readWithSession(server, sub->session,
  258. &rvid, monitoredItem->timestampsToReturn);
  259. /* Stack-allocate some memory for the value encoding. We might heap-allocate
  260. * more memory if needed. This is just enough for scalars and small
  261. * structures. */
  262. UA_Byte *stackValueEncoding = (UA_Byte *)UA_alloca(UA_VALUENCODING_MAXSTACK);
  263. UA_ByteString valueEncoding;
  264. valueEncoding.data = stackValueEncoding;
  265. valueEncoding.length = UA_VALUENCODING_MAXSTACK;
  266. /* Create a sample and compare with the last value */
  267. UA_Boolean newNotification = sampleCallbackWithValue(server, sub, monitoredItem,
  268. &value, &valueEncoding);
  269. /* Clean up */
  270. if(!newNotification) {
  271. if(valueEncoding.data != stackValueEncoding)
  272. UA_ByteString_deleteMembers(&valueEncoding);
  273. UA_DataValue_deleteMembers(&value);
  274. }
  275. }
  276. UA_StatusCode
  277. MonitoredItem_registerSampleCallback(UA_Server *server, UA_MonitoredItem *mon) {
  278. if(mon->sampleCallbackIsRegistered)
  279. return UA_STATUSCODE_GOOD;
  280. UA_StatusCode retval =
  281. UA_Server_addRepeatedCallback(server, (UA_ServerCallback)UA_MonitoredItem_SampleCallback,
  282. mon, (UA_UInt32)mon->samplingInterval, &mon->sampleCallbackId);
  283. if(retval == UA_STATUSCODE_GOOD)
  284. mon->sampleCallbackIsRegistered = true;
  285. return retval;
  286. }
  287. UA_StatusCode
  288. MonitoredItem_unregisterSampleCallback(UA_Server *server, UA_MonitoredItem *mon) {
  289. if(!mon->sampleCallbackIsRegistered)
  290. return UA_STATUSCODE_GOOD;
  291. mon->sampleCallbackIsRegistered = false;
  292. return UA_Server_removeRepeatedCallback(server, mon->sampleCallbackId);
  293. }
  294. #endif /* UA_ENABLE_SUBSCRIPTIONS */