ua_subscription.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. #include "ua_subscription.h"
  2. #include "ua_server_internal.h"
  3. #include "ua_types_encoding_binary.h"
  4. #include "ua_services.h"
  5. #include "ua_nodestore.h"
  6. #ifdef UA_ENABLE_SUBSCRIPTIONS /* conditional compilation */
  7. #define UA_VALUENCODING_MAXSTACK 512
  8. /*****************/
  9. /* MonitoredItem */
  10. /*****************/
  11. UA_MonitoredItem * UA_MonitoredItem_new() {
  12. UA_MonitoredItem *new = UA_malloc(sizeof(UA_MonitoredItem));
  13. new->subscription = NULL;
  14. new->currentQueueSize = 0;
  15. new->maxQueueSize = 0;
  16. new->monitoredItemType = UA_MONITOREDITEMTYPE_CHANGENOTIFY; /* currently hardcoded */
  17. new->timestampsToReturn = UA_TIMESTAMPSTORETURN_SOURCE;
  18. UA_String_init(&new->indexRange);
  19. TAILQ_INIT(&new->queue);
  20. UA_NodeId_init(&new->monitoredNodeId);
  21. new->lastSampledValue = UA_BYTESTRING_NULL;
  22. memset(&new->sampleJobGuid, 0, sizeof(UA_Guid));
  23. new->sampleJobIsRegistered = false;
  24. new->itemId = 0;
  25. return new;
  26. }
  27. void MonitoredItem_delete(UA_Server *server, UA_MonitoredItem *monitoredItem) {
  28. MonitoredItem_unregisterSampleJob(server, monitoredItem);
  29. /* clear the queued samples */
  30. MonitoredItem_queuedValue *val, *val_tmp;
  31. TAILQ_FOREACH_SAFE(val, &monitoredItem->queue, listEntry, val_tmp) {
  32. TAILQ_REMOVE(&monitoredItem->queue, val, listEntry);
  33. UA_DataValue_deleteMembers(&val->value);
  34. UA_free(val);
  35. }
  36. monitoredItem->currentQueueSize = 0;
  37. LIST_REMOVE(monitoredItem, listEntry);
  38. UA_String_deleteMembers(&monitoredItem->indexRange);
  39. UA_ByteString_deleteMembers(&monitoredItem->lastSampledValue);
  40. UA_NodeId_deleteMembers(&monitoredItem->monitoredNodeId);
  41. UA_free(monitoredItem);
  42. }
  43. static void
  44. ensureSpaceInMonitoredItemQueue(UA_MonitoredItem *mon) {
  45. if(mon->currentQueueSize < mon->maxQueueSize)
  46. return;
  47. MonitoredItem_queuedValue *queueItem;
  48. if(mon->discardOldest)
  49. queueItem = TAILQ_FIRST(&mon->queue);
  50. else
  51. queueItem = TAILQ_LAST(&mon->queue, QueueOfQueueDataValues);
  52. UA_assert(queueItem); /* When the currentQueueSize > 0, then there is an item */
  53. TAILQ_REMOVE(&mon->queue, queueItem, listEntry);
  54. UA_DataValue_deleteMembers(&queueItem->value);
  55. UA_free(queueItem);
  56. --mon->currentQueueSize;
  57. }
  58. /* Has this sample changed from the last one? The method may allocate additional
  59. * space for the encoding buffer. Detect the change in encoding->data. */
  60. static UA_StatusCode
  61. detectValueChange(UA_MonitoredItem *mon, UA_DataValue *value,
  62. UA_ByteString *encoding, UA_Boolean *changed) {
  63. /* Apply Filter */
  64. UA_Boolean hasValue = value->hasValue;
  65. if(mon->trigger == UA_DATACHANGETRIGGER_STATUS)
  66. value->hasValue = false;
  67. UA_Boolean hasServerTimestamp = value->hasServerTimestamp;
  68. UA_Boolean hasServerPicoseconds = value->hasServerPicoseconds;
  69. value->hasServerTimestamp = false;
  70. value->hasServerPicoseconds = false;
  71. UA_Boolean hasSourceTimestamp = value->hasSourceTimestamp;
  72. UA_Boolean hasSourcePicoseconds = value->hasSourcePicoseconds;
  73. if(mon->trigger < UA_DATACHANGETRIGGER_STATUSVALUETIMESTAMP) {
  74. value->hasSourceTimestamp = false;
  75. value->hasSourcePicoseconds = false;
  76. }
  77. /* Encode the data for comparison */
  78. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  79. size_t binsize = UA_calcSizeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE]);
  80. if(binsize == 0) {
  81. retval = UA_STATUSCODE_BADINTERNALERROR;
  82. goto cleanup;
  83. }
  84. /* Allocate buffer on the heap if necessary */
  85. if(binsize > UA_VALUENCODING_MAXSTACK &&
  86. UA_ByteString_allocBuffer(encoding, binsize) != UA_STATUSCODE_GOOD) {
  87. retval = UA_STATUSCODE_BADOUTOFMEMORY;
  88. goto cleanup;
  89. }
  90. /* Encode the value */
  91. size_t encodingOffset = 0;
  92. retval = UA_encodeBinary(value, &UA_TYPES[UA_TYPES_DATAVALUE],
  93. NULL, NULL, encoding, &encodingOffset);
  94. if(retval != UA_STATUSCODE_GOOD)
  95. goto cleanup;
  96. /* The value has changed */
  97. encoding->length = encodingOffset;
  98. if(!mon->lastSampledValue.data || !UA_String_equal(encoding, &mon->lastSampledValue))
  99. *changed = true;
  100. cleanup:
  101. /* Reset the filter */
  102. value->hasValue = hasValue;
  103. value->hasServerTimestamp = hasServerTimestamp;
  104. value->hasServerPicoseconds = hasServerPicoseconds;
  105. value->hasSourceTimestamp = hasSourceTimestamp;
  106. value->hasSourcePicoseconds = hasSourcePicoseconds;
  107. return retval;
  108. }
  109. void UA_MoniteredItem_SampleCallback(UA_Server *server, UA_MonitoredItem *monitoredItem) {
  110. UA_Subscription *sub = monitoredItem->subscription;
  111. if(monitoredItem->monitoredItemType != UA_MONITOREDITEMTYPE_CHANGENOTIFY) {
  112. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  113. "Subscription %u | MonitoredItem %i | "
  114. "Not a data change notification",
  115. sub->subscriptionID, monitoredItem->itemId);
  116. return;
  117. }
  118. /* Adjust timestampstoreturn to get source timestamp for triggering */
  119. UA_TimestampsToReturn ts = monitoredItem->timestampsToReturn;
  120. if(ts == UA_TIMESTAMPSTORETURN_SERVER)
  121. ts = UA_TIMESTAMPSTORETURN_BOTH;
  122. else if(ts == UA_TIMESTAMPSTORETURN_NEITHER)
  123. ts = UA_TIMESTAMPSTORETURN_SOURCE;
  124. /* Read the value */
  125. UA_ReadValueId rvid;
  126. UA_ReadValueId_init(&rvid);
  127. rvid.nodeId = monitoredItem->monitoredNodeId;
  128. rvid.attributeId = monitoredItem->attributeID;
  129. rvid.indexRange = monitoredItem->indexRange;
  130. UA_DataValue value;
  131. UA_DataValue_init(&value);
  132. Service_Read_single(server, sub->session, ts, &rvid, &value);
  133. /* Stack-allocate some memory for the value encoding */
  134. UA_Byte *stackValueEncoding = UA_alloca(UA_VALUENCODING_MAXSTACK);
  135. UA_ByteString valueEncoding;
  136. valueEncoding.data = stackValueEncoding;
  137. valueEncoding.length = UA_VALUENCODING_MAXSTACK;
  138. /* Has the value changed? */
  139. UA_Boolean changed = false;
  140. UA_StatusCode retval = detectValueChange(monitoredItem, &value,
  141. &valueEncoding, &changed);
  142. if(!changed || retval != UA_STATUSCODE_GOOD)
  143. goto cleanup;
  144. /* Allocate the entry for the publish queue */
  145. MonitoredItem_queuedValue *newQueueItem = UA_malloc(sizeof(MonitoredItem_queuedValue));
  146. if(!newQueueItem) {
  147. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  148. "Subscription %u | MonitoredItem %i | "
  149. "Item for the publishing queue could not be allocated",
  150. sub->subscriptionID, monitoredItem->itemId);
  151. goto cleanup;
  152. }
  153. /* Copy valueEncoding on the heap for the next comparison (if not already done) */
  154. if(valueEncoding.data == stackValueEncoding) {
  155. UA_ByteString cbs;
  156. if(UA_ByteString_copy(&valueEncoding, &cbs) != UA_STATUSCODE_GOOD) {
  157. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  158. "Subscription %u | MonitoredItem %i | "
  159. "ByteString to compare values could not be created",
  160. sub->subscriptionID, monitoredItem->itemId);
  161. UA_free(newQueueItem);
  162. goto cleanup;
  163. }
  164. valueEncoding = cbs;
  165. }
  166. /* Prepare the newQueueItem */
  167. if(value.hasValue && value.value.storageType == UA_VARIANT_DATA_NODELETE) {
  168. if(UA_DataValue_copy(&value, &newQueueItem->value) != UA_STATUSCODE_GOOD) {
  169. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  170. "Subscription %u | MonitoredItem %i | "
  171. "Item for the publishing queue could not be prepared",
  172. sub->subscriptionID, monitoredItem->itemId);
  173. UA_free(newQueueItem);
  174. goto cleanup;
  175. }
  176. } else {
  177. newQueueItem->value = value;
  178. }
  179. newQueueItem->clientHandle = monitoredItem->clientHandle;
  180. /* <-- Point of no return --> */
  181. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  182. "Subscription %u | MonitoredItem %u | Sampled a new value",
  183. sub->subscriptionID, monitoredItem->itemId);
  184. /* Replace the encoding for comparison */
  185. UA_ByteString_deleteMembers(&monitoredItem->lastSampledValue);
  186. monitoredItem->lastSampledValue = valueEncoding;
  187. /* Add the sample to the queue for publication */
  188. ensureSpaceInMonitoredItemQueue(monitoredItem);
  189. TAILQ_INSERT_TAIL(&monitoredItem->queue, newQueueItem, listEntry);
  190. ++monitoredItem->currentQueueSize;
  191. return;
  192. cleanup:
  193. if(valueEncoding.data != stackValueEncoding)
  194. UA_ByteString_deleteMembers(&valueEncoding);
  195. UA_DataValue_deleteMembers(&value);
  196. }
  197. UA_StatusCode
  198. MonitoredItem_registerSampleJob(UA_Server *server, UA_MonitoredItem *mon) {
  199. UA_Job job;
  200. job.type = UA_JOBTYPE_METHODCALL;
  201. job.job.methodCall.method = (UA_ServerCallback)UA_MoniteredItem_SampleCallback;
  202. job.job.methodCall.data = mon;
  203. UA_StatusCode retval = UA_Server_addRepeatedJob(server, job,
  204. (UA_UInt32)mon->samplingInterval,
  205. &mon->sampleJobGuid);
  206. if(retval == UA_STATUSCODE_GOOD)
  207. mon->sampleJobIsRegistered = true;
  208. return retval;
  209. }
  210. UA_StatusCode MonitoredItem_unregisterSampleJob(UA_Server *server, UA_MonitoredItem *mon) {
  211. if(!mon->sampleJobIsRegistered)
  212. return UA_STATUSCODE_GOOD;
  213. mon->sampleJobIsRegistered = false;
  214. return UA_Server_removeRepeatedJob(server, mon->sampleJobGuid);
  215. }
  216. /****************/
  217. /* Subscription */
  218. /****************/
  219. UA_Subscription * UA_Subscription_new(UA_Session *session, UA_UInt32 subscriptionID) {
  220. UA_Subscription *new = UA_malloc(sizeof(UA_Subscription));
  221. if(!new)
  222. return NULL;
  223. new->session = session;
  224. new->subscriptionID = subscriptionID;
  225. new->sequenceNumber = 0;
  226. new->maxKeepAliveCount = 0;
  227. new->publishingEnabled = false;
  228. memset(&new->publishJobGuid, 0, sizeof(UA_Guid));
  229. new->publishJobIsRegistered = false;
  230. new->currentKeepAliveCount = 0;
  231. new->currentLifetimeCount = 0;
  232. new->lastMonitoredItemId = 0;
  233. new->state = UA_SUBSCRIPTIONSTATE_NORMAL; /* The first publish response is sent immediately */
  234. LIST_INIT(&new->monitoredItems);
  235. TAILQ_INIT(&new->retransmissionQueue);
  236. new->retransmissionQueueSize = 0;
  237. return new;
  238. }
  239. void UA_Subscription_deleteMembers(UA_Subscription *subscription, UA_Server *server) {
  240. Subscription_unregisterPublishJob(server, subscription);
  241. /* Delete monitored Items */
  242. UA_MonitoredItem *mon, *tmp_mon;
  243. LIST_FOREACH_SAFE(mon, &subscription->monitoredItems, listEntry, tmp_mon) {
  244. LIST_REMOVE(mon, listEntry);
  245. MonitoredItem_delete(server, mon);
  246. }
  247. /* Delete Retransmission Queue */
  248. UA_NotificationMessageEntry *nme, *nme_tmp;
  249. TAILQ_FOREACH_SAFE(nme, &subscription->retransmissionQueue, listEntry, nme_tmp) {
  250. TAILQ_REMOVE(&subscription->retransmissionQueue, nme, listEntry);
  251. UA_NotificationMessage_deleteMembers(&nme->message);
  252. UA_free(nme);
  253. }
  254. subscription->retransmissionQueueSize = 0;
  255. }
  256. UA_MonitoredItem *
  257. UA_Subscription_getMonitoredItem(UA_Subscription *sub, UA_UInt32 monitoredItemID) {
  258. UA_MonitoredItem *mon;
  259. LIST_FOREACH(mon, &sub->monitoredItems, listEntry) {
  260. if(mon->itemId == monitoredItemID)
  261. break;
  262. }
  263. return mon;
  264. }
  265. UA_StatusCode
  266. UA_Subscription_deleteMonitoredItem(UA_Server *server, UA_Subscription *sub,
  267. UA_UInt32 monitoredItemID) {
  268. UA_MonitoredItem *mon;
  269. LIST_FOREACH(mon, &sub->monitoredItems, listEntry) {
  270. if(mon->itemId == monitoredItemID) {
  271. LIST_REMOVE(mon, listEntry);
  272. MonitoredItem_delete(server, mon);
  273. return UA_STATUSCODE_GOOD;
  274. }
  275. }
  276. return UA_STATUSCODE_BADMONITOREDITEMIDINVALID;
  277. }
  278. static size_t
  279. countQueuedNotifications(UA_Subscription *sub, UA_Boolean *moreNotifications) {
  280. size_t notifications = 0;
  281. if(sub->publishingEnabled) {
  282. UA_MonitoredItem *mon;
  283. LIST_FOREACH(mon, &sub->monitoredItems, listEntry) {
  284. MonitoredItem_queuedValue *qv;
  285. TAILQ_FOREACH(qv, &mon->queue, listEntry) {
  286. if(notifications >= sub->notificationsPerPublish) {
  287. *moreNotifications = true;
  288. break;
  289. }
  290. ++notifications;
  291. }
  292. }
  293. }
  294. return notifications;
  295. }
  296. static void
  297. UA_Subscription_addRetransmissionMessage(UA_Server *server, UA_Subscription *sub,
  298. UA_NotificationMessageEntry *entry) {
  299. /* Release the oldest entry if there is not enough space */
  300. if(server->config.maxRetransmissionQueueSize > 0 &&
  301. sub->retransmissionQueueSize >= server->config.maxRetransmissionQueueSize) {
  302. UA_NotificationMessageEntry *lastentry =
  303. TAILQ_LAST(&sub->retransmissionQueue, UA_ListOfNotificationMessages);
  304. TAILQ_REMOVE(&sub->retransmissionQueue, lastentry, listEntry);
  305. --sub->retransmissionQueueSize;
  306. UA_NotificationMessage_deleteMembers(&lastentry->message);
  307. UA_free(lastentry);
  308. }
  309. /* Add entry */
  310. TAILQ_INSERT_HEAD(&sub->retransmissionQueue, entry, listEntry);
  311. ++sub->retransmissionQueueSize;
  312. }
  313. UA_StatusCode
  314. UA_Subscription_removeRetransmissionMessage(UA_Subscription *sub, UA_UInt32 sequenceNumber) {
  315. UA_NotificationMessageEntry *entry, *entry_tmp;
  316. TAILQ_FOREACH_SAFE(entry, &sub->retransmissionQueue, listEntry, entry_tmp) {
  317. if(entry->message.sequenceNumber != sequenceNumber)
  318. continue;
  319. TAILQ_REMOVE(&sub->retransmissionQueue, entry, listEntry);
  320. --sub->retransmissionQueueSize;
  321. UA_NotificationMessage_deleteMembers(&entry->message);
  322. UA_free(entry);
  323. return UA_STATUSCODE_GOOD;
  324. }
  325. return UA_STATUSCODE_BADSEQUENCENUMBERUNKNOWN;
  326. }
  327. static UA_StatusCode
  328. prepareNotificationMessage(UA_Subscription *sub, UA_NotificationMessage *message,
  329. size_t notifications) {
  330. /* Array of ExtensionObject to hold different kinds of notifications
  331. (currently only DataChangeNotifications) */
  332. message->notificationData = UA_Array_new(1, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]);
  333. if(!message->notificationData)
  334. return UA_STATUSCODE_BADOUTOFMEMORY;
  335. message->notificationDataSize = 1;
  336. /* Allocate Notification */
  337. UA_DataChangeNotification *dcn = UA_DataChangeNotification_new();
  338. if(!dcn)
  339. goto cleanup;
  340. UA_ExtensionObject *data = message->notificationData;
  341. data->encoding = UA_EXTENSIONOBJECT_DECODED;
  342. data->content.decoded.data = dcn;
  343. data->content.decoded.type = &UA_TYPES[UA_TYPES_DATACHANGENOTIFICATION];
  344. /* Allocate array of notifications */
  345. dcn->monitoredItems =
  346. UA_Array_new(notifications, &UA_TYPES[UA_TYPES_MONITOREDITEMNOTIFICATION]);
  347. if(!dcn->monitoredItems)
  348. goto cleanup;
  349. dcn->monitoredItemsSize = notifications;
  350. /* Move notifications into the response .. the point of no return */
  351. size_t l = 0;
  352. UA_MonitoredItem *mon;
  353. LIST_FOREACH(mon, &sub->monitoredItems, listEntry) {
  354. MonitoredItem_queuedValue *qv, *qv_tmp;
  355. TAILQ_FOREACH_SAFE(qv, &mon->queue, listEntry, qv_tmp) {
  356. if(l >= notifications)
  357. return UA_STATUSCODE_GOOD;
  358. UA_MonitoredItemNotification *min = &dcn->monitoredItems[l];
  359. min->clientHandle = qv->clientHandle;
  360. min->value = qv->value;
  361. TAILQ_REMOVE(&mon->queue, qv, listEntry);
  362. UA_free(qv);
  363. --mon->currentQueueSize;
  364. ++l;
  365. }
  366. }
  367. return UA_STATUSCODE_GOOD;
  368. cleanup:
  369. UA_NotificationMessage_deleteMembers(message);
  370. return UA_STATUSCODE_BADOUTOFMEMORY;
  371. }
  372. void UA_Subscription_publishCallback(UA_Server *server, UA_Subscription *sub) {
  373. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session, "Subscription %u | "
  374. "Publish Callback", sub->subscriptionID);
  375. /* Count the available notifications */
  376. UA_Boolean moreNotifications = false;
  377. size_t notifications = countQueuedNotifications(sub, &moreNotifications);
  378. /* Return if nothing to do */
  379. if(notifications == 0) {
  380. ++sub->currentKeepAliveCount;
  381. if(sub->currentKeepAliveCount < sub->maxKeepAliveCount)
  382. return;
  383. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  384. "Subscription %u | Sending a KeepAlive",
  385. sub->subscriptionID)
  386. }
  387. /* Check if the securechannel is valid */
  388. UA_SecureChannel *channel = sub->session->channel;
  389. if(!channel)
  390. return;
  391. /* Dequeue a response */
  392. UA_PublishResponseEntry *pre = SIMPLEQ_FIRST(&sub->session->responseQueue);
  393. /* Cannot publish without a response */
  394. if(!pre) {
  395. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  396. "Subscription %u | Cannot send a publish response "
  397. "since the publish queue is empty", sub->subscriptionID)
  398. if(sub->state != UA_SUBSCRIPTIONSTATE_LATE) {
  399. sub->state = UA_SUBSCRIPTIONSTATE_LATE;
  400. } else {
  401. ++sub->currentLifetimeCount;
  402. if(sub->currentLifetimeCount > sub->lifeTimeCount) {
  403. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session, "Subscription %u | "
  404. "End of lifetime for subscription", sub->subscriptionID);
  405. UA_Session_deleteSubscription(server, sub->session, sub->subscriptionID);
  406. }
  407. }
  408. return;
  409. }
  410. UA_PublishResponse *response = &pre->response;
  411. UA_NotificationMessage *message = &response->notificationMessage;
  412. UA_NotificationMessageEntry *retransmission = NULL;
  413. if(notifications > 0) {
  414. /* Allocate the retransmission entry */
  415. retransmission = malloc(sizeof(UA_NotificationMessageEntry));
  416. if(!retransmission) {
  417. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  418. "Subscription %u | Could not allocate memory "
  419. "for retransmission", sub->subscriptionID);
  420. return;
  421. }
  422. /* Prepare the response */
  423. UA_StatusCode retval =
  424. prepareNotificationMessage(sub, message, notifications);
  425. if(retval != UA_STATUSCODE_GOOD) {
  426. UA_LOG_WARNING_SESSION(server->config.logger, sub->session,
  427. "Subscription %u | Could not prepare the "
  428. "notification message", sub->subscriptionID);
  429. UA_free(retransmission);
  430. return;
  431. }
  432. }
  433. /* <-- The point of no return --> */
  434. /* Remove the response from the response queue */
  435. SIMPLEQ_REMOVE_HEAD(&sub->session->responseQueue, listEntry);
  436. /* Set up the response */
  437. response->responseHeader.timestamp = UA_DateTime_now();
  438. response->subscriptionId = sub->subscriptionID;
  439. response->moreNotifications = moreNotifications;
  440. message->publishTime = response->responseHeader.timestamp;
  441. if(notifications == 0) {
  442. /* Send sequence number for the next notification */
  443. message->sequenceNumber = sub->sequenceNumber + 1;
  444. } else {
  445. /* Increase the sequence number */
  446. message->sequenceNumber = ++sub->sequenceNumber;
  447. /* Put the notification message into the retransmission queue. This needs to
  448. * be done here, so that the message itself is included in the available
  449. * sequence numbers for acknowledgement. */
  450. retransmission->message = response->notificationMessage;
  451. UA_Subscription_addRetransmissionMessage(server, sub, retransmission);
  452. }
  453. /* Get the available sequence numbers from the retransmission queue */
  454. size_t available = sub->retransmissionQueueSize;
  455. if(available > 0) {
  456. response->availableSequenceNumbers = UA_alloca(available * sizeof(UA_UInt32));
  457. response->availableSequenceNumbersSize = available;
  458. size_t i = 0;
  459. UA_NotificationMessageEntry *nme;
  460. TAILQ_FOREACH(nme, &sub->retransmissionQueue, listEntry) {
  461. response->availableSequenceNumbers[i] = nme->message.sequenceNumber;
  462. ++i;
  463. }
  464. }
  465. /* Send the response */
  466. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  467. "Subscription %u | Sending out a publish response with %u "
  468. "notifications", sub->subscriptionID, (UA_UInt32)notifications);
  469. UA_SecureChannel_sendBinaryMessage(sub->session->channel, pre->requestId, response,
  470. &UA_TYPES[UA_TYPES_PUBLISHRESPONSE]);
  471. /* Reset subscription state to normal. */
  472. sub->state = UA_SUBSCRIPTIONSTATE_NORMAL;
  473. sub->currentKeepAliveCount = 0;
  474. sub->currentLifetimeCount = 0;
  475. /* Free the response */
  476. UA_Array_delete(response->results, response->resultsSize,
  477. &UA_TYPES[UA_TYPES_UINT32]);
  478. UA_free(pre); /* no need for UA_PublishResponse_deleteMembers */
  479. /* Repeat if there are more notifications to send */
  480. if(moreNotifications)
  481. UA_Subscription_publishCallback(server, sub);
  482. }
  483. UA_StatusCode
  484. Subscription_registerPublishJob(UA_Server *server, UA_Subscription *sub) {
  485. if(sub->publishJobIsRegistered)
  486. return UA_STATUSCODE_GOOD;
  487. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  488. "Subscription %u | Register subscription publishing callback",
  489. sub->subscriptionID);
  490. UA_Job job;
  491. job.type = UA_JOBTYPE_METHODCALL;
  492. job.job.methodCall.method = (UA_ServerCallback)UA_Subscription_publishCallback;
  493. job.job.methodCall.data = sub;
  494. UA_StatusCode retval =
  495. UA_Server_addRepeatedJob(server, job, (UA_UInt32)sub->publishingInterval,
  496. &sub->publishJobGuid);
  497. if(retval == UA_STATUSCODE_GOOD)
  498. sub->publishJobIsRegistered = true;
  499. return retval;
  500. }
  501. UA_StatusCode
  502. Subscription_unregisterPublishJob(UA_Server *server, UA_Subscription *sub) {
  503. if(!sub->publishJobIsRegistered)
  504. return UA_STATUSCODE_GOOD;
  505. UA_LOG_DEBUG_SESSION(server->config.logger, sub->session,
  506. "Subscription %u | Unregister subscription publishing callback",
  507. sub->subscriptionID);
  508. sub->publishJobIsRegistered = false;
  509. return UA_Server_removeRepeatedJob(server, sub->publishJobGuid);
  510. }
  511. /* When the session has publish requests stored but the last subscription is
  512. deleted... Send out empty responses */
  513. void
  514. UA_Subscription_answerPublishRequestsNoSubscription(UA_Server *server, UA_NodeId *sessionToken) {
  515. /* Get session */
  516. UA_Session *session = UA_SessionManager_getSession(&server->sessionManager, sessionToken);
  517. UA_NodeId_delete(sessionToken);
  518. /* No session or there are remaining subscriptions */
  519. if(!session || LIST_FIRST(&session->serverSubscriptions))
  520. return;
  521. /* Send a response for every queued request */
  522. UA_PublishResponseEntry *pre;
  523. while((pre = SIMPLEQ_FIRST(&session->responseQueue))) {
  524. SIMPLEQ_REMOVE_HEAD(&session->responseQueue, listEntry);
  525. UA_PublishResponse *response = &pre->response;
  526. response->responseHeader.serviceResult = UA_STATUSCODE_BADNOSUBSCRIPTION;
  527. response->responseHeader.timestamp = UA_DateTime_now();
  528. UA_SecureChannel_sendBinaryMessage(session->channel, pre->requestId, response,
  529. &UA_TYPES[UA_TYPES_PUBLISHRESPONSE]);
  530. UA_PublishResponse_deleteMembers(response);
  531. UA_free(pre);
  532. }
  533. }
  534. #endif /* UA_ENABLE_SUBSCRIPTIONS */