ua_subscription_datachange.c 18 KB

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