ua_pubsub.c 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152
  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 (c) 2017-2018 Fraunhofer IOSB (Author: Andreas Ebner)
  6. * Copyright (c) 2019 Fraunhofer IOSB (Author: Julius Pfrommer)
  7. * Copyright (c) 2019 Kalycito Infotech Private Limited
  8. */
  9. #include "server/ua_server_internal.h"
  10. #ifdef UA_ENABLE_PUBSUB /* conditional compilation */
  11. #include "ua_pubsub.h"
  12. #ifdef UA_ENABLE_PUBSUB_INFORMATIONMODEL
  13. #include "ua_pubsub_ns0.h"
  14. #endif
  15. #ifdef UA_ENABLE_PUBSUB_DELTAFRAMES
  16. #include "ua_types_encoding_binary.h"
  17. #endif
  18. #define UA_MAX_STACKBUF 512 /* Max size of network messages on the stack */
  19. #define UA_MAX_SIZENAME 64 /* Max size of Qualified Name of Subscribed Variable */
  20. /* Forward declaration */
  21. static void
  22. UA_WriterGroup_deleteMembers(UA_Server *server, UA_WriterGroup *writerGroup);
  23. static void
  24. UA_DataSetField_deleteMembers(UA_DataSetField *field);
  25. /**********************************************/
  26. /* Connection */
  27. /**********************************************/
  28. UA_StatusCode
  29. UA_PubSubConnectionConfig_copy(const UA_PubSubConnectionConfig *src,
  30. UA_PubSubConnectionConfig *dst) {
  31. UA_StatusCode retVal = UA_STATUSCODE_GOOD;
  32. memcpy(dst, src, sizeof(UA_PubSubConnectionConfig));
  33. retVal |= UA_String_copy(&src->name, &dst->name);
  34. retVal |= UA_Variant_copy(&src->address, &dst->address);
  35. retVal |= UA_String_copy(&src->transportProfileUri, &dst->transportProfileUri);
  36. retVal |= UA_Variant_copy(&src->connectionTransportSettings, &dst->connectionTransportSettings);
  37. if(src->connectionPropertiesSize > 0){
  38. dst->connectionProperties = (UA_KeyValuePair *)
  39. UA_calloc(src->connectionPropertiesSize, sizeof(UA_KeyValuePair));
  40. if(!dst->connectionProperties){
  41. return UA_STATUSCODE_BADOUTOFMEMORY;
  42. }
  43. for(size_t i = 0; i < src->connectionPropertiesSize; i++){
  44. retVal |= UA_QualifiedName_copy(&src->connectionProperties[i].key,
  45. &dst->connectionProperties[i].key);
  46. retVal |= UA_Variant_copy(&src->connectionProperties[i].value,
  47. &dst->connectionProperties[i].value);
  48. }
  49. }
  50. return retVal;
  51. }
  52. UA_StatusCode
  53. UA_Server_getPubSubConnectionConfig(UA_Server *server, const UA_NodeId connection,
  54. UA_PubSubConnectionConfig *config) {
  55. if(!config)
  56. return UA_STATUSCODE_BADINVALIDARGUMENT;
  57. UA_PubSubConnection *currentPubSubConnection =
  58. UA_PubSubConnection_findConnectionbyId(server, connection);
  59. if(!currentPubSubConnection)
  60. return UA_STATUSCODE_BADNOTFOUND;
  61. UA_PubSubConnectionConfig tmpPubSubConnectionConfig;
  62. //deep copy of the actual config
  63. UA_PubSubConnectionConfig_copy(currentPubSubConnection->config, &tmpPubSubConnectionConfig);
  64. *config = tmpPubSubConnectionConfig;
  65. return UA_STATUSCODE_GOOD;
  66. }
  67. UA_PubSubConnection *
  68. UA_PubSubConnection_findConnectionbyId(UA_Server *server, UA_NodeId connectionIdentifier) {
  69. for(size_t i = 0; i < server->pubSubManager.connectionsSize; i++){
  70. if(UA_NodeId_equal(&connectionIdentifier, &server->pubSubManager.connections[i].identifier)){
  71. return &server->pubSubManager.connections[i];
  72. }
  73. }
  74. return NULL;
  75. }
  76. void
  77. UA_PubSubConnectionConfig_deleteMembers(UA_PubSubConnectionConfig *connectionConfig) {
  78. UA_String_deleteMembers(&connectionConfig->name);
  79. UA_String_deleteMembers(&connectionConfig->transportProfileUri);
  80. UA_Variant_deleteMembers(&connectionConfig->connectionTransportSettings);
  81. UA_Variant_deleteMembers(&connectionConfig->address);
  82. for(size_t i = 0; i < connectionConfig->connectionPropertiesSize; i++){
  83. UA_QualifiedName_deleteMembers(&connectionConfig->connectionProperties[i].key);
  84. UA_Variant_deleteMembers(&connectionConfig->connectionProperties[i].value);
  85. }
  86. UA_free(connectionConfig->connectionProperties);
  87. }
  88. void
  89. UA_PubSubConnection_deleteMembers(UA_Server *server, UA_PubSubConnection *connection) {
  90. //delete connection config
  91. UA_PubSubConnectionConfig_deleteMembers(connection->config);
  92. //remove contained WriterGroups
  93. UA_WriterGroup *writerGroup, *tmpWriterGroup;
  94. LIST_FOREACH_SAFE(writerGroup, &connection->writerGroups, listEntry, tmpWriterGroup){
  95. UA_Server_removeWriterGroup(server, writerGroup->identifier);
  96. }
  97. /* remove contained ReaderGroups */
  98. UA_ReaderGroup *readerGroups, *tmpReaderGroup;
  99. LIST_FOREACH_SAFE(readerGroups, &connection->readerGroups, listEntry, tmpReaderGroup){
  100. UA_Server_removeReaderGroup(server, readerGroups->identifier);
  101. }
  102. UA_NodeId_deleteMembers(&connection->identifier);
  103. if(connection->channel){
  104. connection->channel->close(connection->channel);
  105. }
  106. UA_free(connection->config);
  107. }
  108. UA_StatusCode
  109. UA_Server_addWriterGroup(UA_Server *server, const UA_NodeId connection,
  110. const UA_WriterGroupConfig *writerGroupConfig,
  111. UA_NodeId *writerGroupIdentifier) {
  112. UA_StatusCode retVal = UA_STATUSCODE_GOOD;
  113. if(!writerGroupConfig)
  114. return UA_STATUSCODE_BADINVALIDARGUMENT;
  115. //search the connection by the given connectionIdentifier
  116. UA_PubSubConnection *currentConnectionContext =
  117. UA_PubSubConnection_findConnectionbyId(server, connection);
  118. if(!currentConnectionContext)
  119. return UA_STATUSCODE_BADNOTFOUND;
  120. //allocate memory for new WriterGroup
  121. UA_WriterGroup *newWriterGroup = (UA_WriterGroup *) UA_calloc(1, sizeof(UA_WriterGroup));
  122. if(!newWriterGroup)
  123. return UA_STATUSCODE_BADOUTOFMEMORY;
  124. newWriterGroup->linkedConnection = currentConnectionContext->identifier;
  125. UA_PubSubManager_generateUniqueNodeId(server, &newWriterGroup->identifier);
  126. if(writerGroupIdentifier){
  127. UA_NodeId_copy(&newWriterGroup->identifier, writerGroupIdentifier);
  128. }
  129. //deep copy of the config
  130. UA_WriterGroupConfig tmpWriterGroupConfig;
  131. retVal |= UA_WriterGroupConfig_copy(writerGroupConfig, &tmpWriterGroupConfig);
  132. if(!tmpWriterGroupConfig.messageSettings.content.decoded.type) {
  133. UA_UadpWriterGroupMessageDataType *wgm = UA_UadpWriterGroupMessageDataType_new();
  134. tmpWriterGroupConfig.messageSettings.content.decoded.data = wgm;
  135. tmpWriterGroupConfig.messageSettings.content.decoded.type =
  136. &UA_TYPES[UA_TYPES_UADPWRITERGROUPMESSAGEDATATYPE];
  137. tmpWriterGroupConfig.messageSettings.encoding = UA_EXTENSIONOBJECT_DECODED;
  138. }
  139. newWriterGroup->config = tmpWriterGroupConfig;
  140. retVal |= UA_WriterGroup_addPublishCallback(server, newWriterGroup);
  141. LIST_INSERT_HEAD(&currentConnectionContext->writerGroups, newWriterGroup, listEntry);
  142. #ifdef UA_ENABLE_PUBSUB_INFORMATIONMODEL
  143. addWriterGroupRepresentation(server, newWriterGroup);
  144. #endif
  145. return retVal;
  146. }
  147. UA_StatusCode
  148. UA_Server_removeWriterGroup(UA_Server *server, const UA_NodeId writerGroup){
  149. UA_WriterGroup *wg = UA_WriterGroup_findWGbyId(server, writerGroup);
  150. if(!wg)
  151. return UA_STATUSCODE_BADNOTFOUND;
  152. UA_PubSubConnection *connection =
  153. UA_PubSubConnection_findConnectionbyId(server, wg->linkedConnection);
  154. if(!connection)
  155. return UA_STATUSCODE_BADNOTFOUND;
  156. //unregister the publish callback
  157. UA_PubSubManager_removeRepeatedPubSubCallback(server, wg->publishCallbackId);
  158. #ifdef UA_ENABLE_PUBSUB_INFORMATIONMODEL
  159. removeGroupRepresentation(server, wg);
  160. #endif
  161. UA_WriterGroup_deleteMembers(server, wg);
  162. LIST_REMOVE(wg, listEntry);
  163. UA_free(wg);
  164. return UA_STATUSCODE_GOOD;
  165. }
  166. /**********************************************/
  167. /* ReaderGroup */
  168. /**********************************************/
  169. /**
  170. * Add ReaderGroup to connection.
  171. *
  172. * @param server
  173. * @param connectionIdentifier
  174. * @param readerGroupConfiguration
  175. * @param readerGroupIdentifier
  176. * @return UA_STATUSCODE_GOOD on success
  177. */
  178. UA_StatusCode
  179. UA_Server_addReaderGroup(UA_Server *server, UA_NodeId connectionIdentifier,
  180. const UA_ReaderGroupConfig *readerGroupConfig,
  181. UA_NodeId *readerGroupIdentifier) {
  182. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  183. UA_ReaderGroupConfig tmpReaderGroupConfig;
  184. /* Search the connection by the given connectionIdentifier */
  185. if(!readerGroupConfig) {
  186. return UA_STATUSCODE_BADINVALIDARGUMENT;
  187. }
  188. /* Search the connection by the given connectionIdentifier */
  189. UA_PubSubConnection *currentConnectionContext = UA_PubSubConnection_findConnectionbyId(server, connectionIdentifier);
  190. if(!currentConnectionContext) {
  191. return UA_STATUSCODE_BADNOTFOUND;
  192. }
  193. /* Allocate memory for new reader group */
  194. UA_ReaderGroup *newGroup = (UA_ReaderGroup *)UA_calloc(1, sizeof(UA_ReaderGroup));
  195. if(!newGroup) {
  196. return UA_STATUSCODE_BADOUTOFMEMORY;
  197. }
  198. /* Generate nodeid for the readergroup identifier */
  199. newGroup->linkedConnection = currentConnectionContext->identifier;
  200. UA_PubSubManager_generateUniqueNodeId(server, &newGroup->identifier);
  201. if(readerGroupIdentifier) {
  202. UA_NodeId_copy(&newGroup->identifier, readerGroupIdentifier);
  203. }
  204. /* Deep copy of the config */
  205. retval |= UA_ReaderGroupConfig_copy(readerGroupConfig, &tmpReaderGroupConfig);
  206. newGroup->config = tmpReaderGroupConfig;
  207. retval |= UA_ReaderGroup_addSubscribeCallback(server, newGroup);
  208. LIST_INSERT_HEAD(&currentConnectionContext->readerGroups, newGroup, listEntry);
  209. currentConnectionContext->readerGroupsSize++;
  210. #ifdef UA_ENABLE_PUBSUB_INFORMATIONMODEL
  211. addReaderGroupRepresentation(server, newGroup);
  212. #endif
  213. return retval;
  214. }
  215. /**
  216. * Remove ReaderGroup from connection and delete contained readers.
  217. *
  218. * @param server
  219. * @param groupIdentifier
  220. * @return UA_STATUSCODE_GOOD on success
  221. */
  222. UA_StatusCode
  223. UA_Server_removeReaderGroup(UA_Server *server, UA_NodeId groupIdentifier) {
  224. UA_ReaderGroup* readerGroup = UA_ReaderGroup_findRGbyId(server, groupIdentifier);
  225. if(readerGroup == NULL) {
  226. return UA_STATUSCODE_BADNOTFOUND;
  227. }
  228. /* Search the connection to which the given readergroup is connected to */
  229. UA_PubSubConnection *connection = UA_PubSubConnection_findConnectionbyId(server, readerGroup->linkedConnection);
  230. if(connection == NULL) {
  231. return UA_STATUSCODE_BADNOTFOUND;
  232. }
  233. /* Unregister subscribe callback */
  234. UA_PubSubManager_removeRepeatedPubSubCallback(server, readerGroup->subscribeCallbackId);
  235. #ifdef UA_ENABLE_PUBSUB_INFORMATIONMODEL
  236. /* To Do:RemoveGroupRepresentation(server, &readerGroup->identifier) */
  237. #endif
  238. /* UA_Server_ReaderGroup_delete also removes itself from the list */
  239. UA_Server_ReaderGroup_delete(server, readerGroup);
  240. /* Remove readerGroup from Connection */
  241. LIST_REMOVE(readerGroup, listEntry);
  242. UA_free(readerGroup);
  243. return UA_STATUSCODE_GOOD;
  244. }
  245. /**
  246. * To Do:
  247. * Update ReaderGroup configuration.
  248. *
  249. * @param server
  250. * @param readerGroupIdentifier
  251. * @param readerGroupConfiguration
  252. * @return UA_STATUSCODE_GOOD on success
  253. */
  254. UA_StatusCode
  255. UA_Server_ReaderGroup_updateConfig(UA_Server *server, UA_NodeId readerGroupIdentifier,
  256. const UA_ReaderGroupConfig *config) {
  257. return UA_STATUSCODE_BADNOTIMPLEMENTED;
  258. }
  259. /**
  260. * Get ReaderGroup configuration.
  261. *
  262. * @param server
  263. * @param groupIdentifier
  264. * @param readerGroupConfiguration
  265. * @return UA_STATUSCODE_GOOD on success
  266. */
  267. UA_StatusCode
  268. UA_Server_ReaderGroup_getConfig(UA_Server *server, UA_NodeId readerGroupIdentifier,
  269. UA_ReaderGroupConfig *config) {
  270. if(!config) {
  271. return UA_STATUSCODE_BADINVALIDARGUMENT;
  272. }
  273. /* Identify the readergroup through the readerGroupIdentifier */
  274. UA_ReaderGroup *currentReaderGroup = UA_ReaderGroup_findRGbyId(server, readerGroupIdentifier);
  275. if(!currentReaderGroup) {
  276. return UA_STATUSCODE_BADNOTFOUND;
  277. }
  278. UA_ReaderGroupConfig tmpReaderGroupConfig;
  279. /* deep copy of the actual config */
  280. UA_ReaderGroupConfig_copy(&currentReaderGroup->config, &tmpReaderGroupConfig);
  281. *config = tmpReaderGroupConfig;
  282. return UA_STATUSCODE_GOOD;
  283. }
  284. /* To Do UA_ReaderGroupConfig delete */
  285. /**
  286. * Delete ReaderGroup.
  287. *
  288. * @param server
  289. * @param groupIdentifier
  290. */
  291. void UA_Server_ReaderGroup_delete(UA_Server* server, UA_ReaderGroup *readerGroup) {
  292. /* To Do Call UA_ReaderGroupConfig_delete */
  293. UA_DataSetReader *dataSetReader, *tmpDataSetReader;
  294. LIST_FOREACH_SAFE(dataSetReader, &readerGroup->readers, listEntry, tmpDataSetReader) {
  295. UA_DataSetReader_delete(server, dataSetReader);
  296. }
  297. UA_PubSubConnection* pConn = UA_PubSubConnection_findConnectionbyId(server, readerGroup->linkedConnection);
  298. if(pConn != NULL) {
  299. pConn->readerGroupsSize--;
  300. }
  301. /* Delete ReaderGroup and its members */
  302. UA_String_deleteMembers(&readerGroup->config.name);
  303. UA_NodeId_deleteMembers(&readerGroup->linkedConnection);
  304. UA_NodeId_deleteMembers(&readerGroup->identifier);
  305. }
  306. /**
  307. * Copy ReaderGroup configuration.
  308. *
  309. * @param source
  310. * @param destination
  311. * @return UA_STATUSCODE_GOOD on success
  312. */
  313. UA_StatusCode
  314. UA_ReaderGroupConfig_copy(const UA_ReaderGroupConfig *src,
  315. UA_ReaderGroupConfig *dst) {
  316. UA_String_copy(&src->name, &dst->name);
  317. /* Currently simple memcpy only */
  318. memcpy(&dst->securityParameters, &src->securityParameters, sizeof(UA_PubSubSecurityParameters));
  319. return UA_STATUSCODE_GOOD;
  320. }
  321. static UA_DataSetReader *
  322. getReaderFromIdentifier(UA_Server *server, UA_NetworkMessage *pMsg, UA_PubSubConnection *pConnection) {
  323. if(pConnection->readerGroupsSize == 1) {
  324. if(LIST_FIRST(&pConnection->readerGroups)->readersCount == 1) {
  325. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER, "only 1 DataSetReader available. This one will be used.");
  326. return LIST_FIRST(&LIST_FIRST(&pConnection->readerGroups)->readers);
  327. }
  328. }
  329. if(!pMsg->publisherIdEnabled)
  330. return NULL;
  331. UA_ReaderGroup* readerGroup;
  332. LIST_FOREACH(readerGroup, &pConnection->readerGroups, listEntry) {
  333. UA_DataSetReader *tmpReader;
  334. LIST_FOREACH(tmpReader, &readerGroup->readers, listEntry) {
  335. switch (pMsg->publisherIdType) {
  336. case UA_PUBLISHERDATATYPE_BYTE:
  337. if(tmpReader->config.publisherId.type == &UA_TYPES[UA_TYPES_BYTE] &&
  338. pMsg->publisherIdType == UA_PUBLISHERDATATYPE_BYTE &&
  339. pMsg->publisherId.publisherIdByte == *(UA_Byte*)tmpReader->config.publisherId.data) {
  340. return tmpReader;
  341. }
  342. break;
  343. case UA_PUBLISHERDATATYPE_UINT16:
  344. if(tmpReader->config.publisherId.type == &UA_TYPES[UA_TYPES_UINT16] &&
  345. pMsg->publisherIdType == UA_PUBLISHERDATATYPE_UINT16 &&
  346. pMsg->publisherId.publisherIdUInt16 == *(UA_UInt16*)tmpReader->config.publisherId.data) {
  347. return tmpReader;
  348. }
  349. break;
  350. case UA_PUBLISHERDATATYPE_UINT32:
  351. if(tmpReader->config.publisherId.type == &UA_TYPES[UA_TYPES_UINT32] &&
  352. pMsg->publisherIdType == UA_PUBLISHERDATATYPE_UINT32 &&
  353. pMsg->publisherId.publisherIdUInt32 == *(UA_UInt32*)tmpReader->config.publisherId.data) {
  354. return tmpReader;
  355. }
  356. break;
  357. case UA_PUBLISHERDATATYPE_UINT64:
  358. if(tmpReader->config.publisherId.type == &UA_TYPES[UA_TYPES_UINT64] &&
  359. pMsg->publisherIdType == UA_PUBLISHERDATATYPE_UINT64 &&
  360. pMsg->publisherId.publisherIdUInt64 == *(UA_UInt64*)tmpReader->config.publisherId.data) {
  361. return tmpReader;
  362. }
  363. break;
  364. case UA_PUBLISHERDATATYPE_STRING:
  365. if(tmpReader->config.publisherId.type == &UA_TYPES[UA_TYPES_STRING] &&
  366. pMsg->publisherIdType == UA_PUBLISHERDATATYPE_STRING &&
  367. UA_String_equal(&pMsg->publisherId.publisherIdString, (UA_String*)tmpReader->config.publisherId.data)) {
  368. return tmpReader;
  369. }
  370. break;
  371. default:
  372. return NULL;
  373. }
  374. }
  375. }
  376. return NULL;
  377. }
  378. /**
  379. * Process NetworkMessage.
  380. *
  381. * @param server
  382. * @param networkmessage
  383. * @return UA_STATUSCODE_GOOD on success
  384. */
  385. UA_StatusCode
  386. UA_Server_processNetworkMessage(UA_Server *server, UA_NetworkMessage *pMsg,
  387. UA_PubSubConnection *pConnection) {
  388. if(!pMsg || !pConnection)
  389. return UA_STATUSCODE_BADINVALIDARGUMENT;
  390. /* To Do The condition with dataSetWriterIdAvailable and WriterGroupIdAvailable to be handled
  391. * when pMsg->groupHeaderEnabled, pMsg->dataSetClassIdEnabled, pMsg->payloadHeaderEnabled
  392. * Here some filtering is possible */
  393. UA_DataSetReader* dataSetReaderErg = getReaderFromIdentifier(server, pMsg, pConnection);
  394. /* No Reader with the specified id found */
  395. if(!dataSetReaderErg) {
  396. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER, "No DataSetReader found with PublisherId");
  397. return UA_STATUSCODE_BADNOTFOUND; /* TODO: Check the return code */
  398. }
  399. UA_LOG_DEBUG(&server->config.logger, UA_LOGCATEGORY_SERVER, "DataSetReader found with PublisherId");
  400. UA_Byte anzDataSets = 1;
  401. if(pMsg->payloadHeaderEnabled)
  402. anzDataSets = pMsg->payloadHeader.dataSetPayloadHeader.count;
  403. for(UA_Byte iterator = 0; iterator < anzDataSets; iterator++) {
  404. UA_LOG_DEBUG(&server->config.logger, UA_LOGCATEGORY_SERVER, "Process Msg with DataSetReader!");
  405. UA_Server_DataSetReader_process(server, dataSetReaderErg, &pMsg->payload.dataSetPayload.dataSetMessages[iterator]);
  406. }
  407. /* To Do the condition with dataSetWriterId and WriterGroupId
  408. * else condition for dataSetWriterIdAvailable and writerGroupIdAvailable) */
  409. return UA_STATUSCODE_GOOD;
  410. }
  411. /**
  412. * Find ReaderGroup with its identifier.
  413. *
  414. * @param server
  415. * @param groupIdentifier
  416. * @return the ReaderGroup or NULL if not found
  417. */
  418. UA_ReaderGroup * UA_ReaderGroup_findRGbyId(UA_Server *server, UA_NodeId identifier) {
  419. for (size_t iteratorConn = 0; iteratorConn < server->pubSubManager.connectionsSize; iteratorConn++) {
  420. UA_ReaderGroup* readerGroup = NULL;
  421. LIST_FOREACH(readerGroup, &server->pubSubManager.connections[iteratorConn].readerGroups, listEntry) {
  422. if(UA_NodeId_equal(&identifier, &readerGroup->identifier)) {
  423. return readerGroup;
  424. }
  425. }
  426. }
  427. return NULL;
  428. }
  429. /**
  430. * Find a DataSetReader with its identifier
  431. *
  432. * @param server
  433. * @param identifier
  434. * @return the DataSetReader or NULL if not found
  435. */
  436. UA_DataSetReader *UA_ReaderGroup_findDSRbyId(UA_Server *server, UA_NodeId identifier) {
  437. for (size_t iteratorConn = 0; iteratorConn < server->pubSubManager.connectionsSize; iteratorConn++) {
  438. UA_ReaderGroup* readerGroup = NULL;
  439. LIST_FOREACH(readerGroup, &server->pubSubManager.connections[iteratorConn].readerGroups, listEntry) {
  440. UA_DataSetReader *tmpReader;
  441. LIST_FOREACH(tmpReader, &readerGroup->readers, listEntry) {
  442. if(UA_NodeId_equal(&tmpReader->identifier, &identifier)) {
  443. return tmpReader;
  444. }
  445. }
  446. }
  447. }
  448. return NULL;
  449. }
  450. /**********************************************/
  451. /* DataSetReader */
  452. /**********************************************/
  453. /**
  454. * Add a DataSetReader to ReaderGroup
  455. *
  456. * @param server
  457. * @param readerGroupIdentifier
  458. * @param dataSetReaderConfig
  459. * @param readerIdentifier
  460. * @return UA_STATUSCODE_GOOD on success
  461. */
  462. UA_StatusCode
  463. UA_Server_addDataSetReader(UA_Server *server, UA_NodeId readerGroupIdentifier,
  464. const UA_DataSetReaderConfig *dataSetReaderConfig,
  465. UA_NodeId *readerIdentifier) {
  466. /* Search the reader group by the given readerGroupIdentifier */
  467. UA_ReaderGroup *readerGroup = UA_ReaderGroup_findRGbyId(server, readerGroupIdentifier);
  468. if(!dataSetReaderConfig) {
  469. return UA_STATUSCODE_BADNOTFOUND;
  470. }
  471. if(readerGroup == NULL) {
  472. return UA_STATUSCODE_BADNOTFOUND;
  473. }
  474. /* Allocate memory for new DataSetReader */
  475. UA_DataSetReader *newDataSetReader = (UA_DataSetReader *)UA_calloc(1, sizeof(UA_DataSetReader));
  476. /* Copy the config into the new dataSetReader */
  477. UA_DataSetReaderConfig_copy(dataSetReaderConfig, &newDataSetReader->config);
  478. newDataSetReader->linkedReaderGroup = readerGroup->identifier;
  479. UA_PubSubManager_generateUniqueNodeId(server, &newDataSetReader->identifier);
  480. if(readerIdentifier != NULL) {
  481. UA_NodeId_copy(&newDataSetReader->identifier, readerIdentifier);
  482. }
  483. /* Add the new reader to the group */
  484. LIST_INSERT_HEAD(&readerGroup->readers, newDataSetReader, listEntry);
  485. readerGroup->readersCount++;
  486. #ifdef UA_ENABLE_PUBSUB_INFORMATIONMODEL
  487. addDataSetReaderRepresentation(server, newDataSetReader);
  488. #endif
  489. return UA_STATUSCODE_GOOD;
  490. }
  491. /**
  492. * Remove a DataSetReader from ReaderGroup
  493. *
  494. * @param server
  495. * @param readerGroupIdentifier
  496. * @return UA_STATUSCODE_GOOD on success
  497. */
  498. UA_StatusCode
  499. UA_Server_removeDataSetReader(UA_Server *server, UA_NodeId readerIdentifier) {
  500. /* Remove datasetreader given by the identifier */
  501. UA_DataSetReader *dataSetReader = UA_ReaderGroup_findDSRbyId(server, readerIdentifier);
  502. if(!dataSetReader) {
  503. return UA_STATUSCODE_BADNOTFOUND;
  504. }
  505. #ifdef UA_ENABLE_PUBSUB_INFORMATIONMODEL
  506. removeDataSetReaderRepresentation(server, dataSetReader);
  507. #endif
  508. UA_DataSetReader_delete(server, dataSetReader);
  509. return UA_STATUSCODE_GOOD;
  510. }
  511. /**
  512. * Update the config of the DataSetReader.
  513. *
  514. * @param server
  515. * @param dataSetReaderIdentifier
  516. * @param readerGroupIdentifier
  517. * @param config
  518. * @return UA_STATUSCODE_GOOD on success
  519. */
  520. UA_StatusCode
  521. UA_Server_DataSetReader_updateConfig(UA_Server *server, UA_NodeId dataSetReaderIdentifier, UA_NodeId readerGroupIdentifier,
  522. const UA_DataSetReaderConfig *config) {
  523. if(config == NULL) {
  524. return UA_STATUSCODE_BADINVALIDARGUMENT;
  525. }
  526. UA_DataSetReader *currentDataSetReader = UA_ReaderGroup_findDSRbyId(server, dataSetReaderIdentifier);
  527. UA_ReaderGroup *currentReaderGroup = UA_ReaderGroup_findRGbyId(server, readerGroupIdentifier);
  528. if(!currentDataSetReader) {
  529. return UA_STATUSCODE_BADNOTFOUND;
  530. }
  531. /* The update functionality will be extended during the next PubSub batches.
  532. * Currently is only a change of the publishing interval possible. */
  533. if(currentDataSetReader->config.writerGroupId != config->writerGroupId) {
  534. UA_PubSubManager_removeRepeatedPubSubCallback(server, currentReaderGroup->subscribeCallbackId);
  535. currentDataSetReader->config.writerGroupId = config->writerGroupId;
  536. UA_ReaderGroup_subscribeCallback(server, currentReaderGroup);
  537. }
  538. else {
  539. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  540. "No or unsupported ReaderGroup update.");
  541. }
  542. return UA_STATUSCODE_GOOD;
  543. }
  544. /**
  545. * Get the current config of the UA_DataSetReader.
  546. *
  547. * @param server
  548. * @param dataSetReaderIdentifier
  549. * @param config
  550. * @return UA_STATUSCODE_GOOD on success
  551. */
  552. UA_StatusCode
  553. UA_Server_DataSetReader_getConfig(UA_Server *server, UA_NodeId dataSetReaderIdentifier,
  554. UA_DataSetReaderConfig *config) {
  555. if(!config) {
  556. return UA_STATUSCODE_BADINVALIDARGUMENT;
  557. }
  558. UA_DataSetReader *currentDataSetReader = UA_ReaderGroup_findDSRbyId(server, dataSetReaderIdentifier);
  559. if(!currentDataSetReader) {
  560. return UA_STATUSCODE_BADNOTFOUND;
  561. }
  562. UA_DataSetReaderConfig tmpReaderConfig;
  563. /* Deep copy of the actual config */
  564. UA_DataSetReaderConfig_copy(&currentDataSetReader->config, &tmpReaderConfig);
  565. *config = tmpReaderConfig;
  566. return UA_STATUSCODE_GOOD;
  567. }
  568. /**
  569. * This Method is used to initially set the SubscribedDataSet to TargetVariablesType and to create the list of target Variables of a SubscribedDataSetType.
  570. *
  571. * @param server
  572. * @param dataSetReaderIdentifier
  573. * @param targetVariables
  574. * @return UA_STATUSCODE_GOOD on success
  575. */
  576. UA_StatusCode
  577. UA_Server_DataSetReader_createTargetVariables(UA_Server *server, UA_NodeId dataSetReaderIdentifier, UA_TargetVariablesDataType *targetVariables) {
  578. UA_StatusCode retval = UA_STATUSCODE_BADUNEXPECTEDERROR;
  579. UA_DataSetReader* pDS = UA_ReaderGroup_findDSRbyId(server, dataSetReaderIdentifier);
  580. if(pDS == NULL) {
  581. return UA_STATUSCODE_BADINVALIDARGUMENT;
  582. }
  583. if(pDS->subscribedDataSetTarget.targetVariablesSize > 0) {
  584. UA_TargetVariablesDataType_deleteMembers(&pDS->subscribedDataSetTarget);
  585. pDS->subscribedDataSetTarget.targetVariablesSize = 0;
  586. pDS->subscribedDataSetTarget.targetVariables = NULL;
  587. }
  588. /* Set subscribed dataset to TargetVariableType */
  589. pDS->subscribedDataSetType = UA_PUBSUB_SDS_TARGET;
  590. retval = UA_TargetVariablesDataType_copy(targetVariables, &pDS->subscribedDataSetTarget);
  591. return retval;
  592. }
  593. /**
  594. * Adds Subscribed Variables from the DataSetMetaData for the given DataSet into the given parent node
  595. * and creates the corresponding data in the targetVariables of the DataSetReader
  596. *
  597. * @param server
  598. * @param parentNode
  599. * @param dataSetReaderIdentifier
  600. * @return UA_STATUSCODE_GOOD on success
  601. */
  602. UA_StatusCode UA_Server_DataSetReader_addTargetVariables(UA_Server *server, UA_NodeId *parentNode, UA_NodeId dataSetReaderIdentifier, UA_SubscribedDataSetEnumType sdsType) {
  603. if((server == NULL) || (parentNode == NULL)) {
  604. return UA_STATUSCODE_BADINVALIDARGUMENT;
  605. }
  606. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  607. UA_DataSetReader* pDataSetReader = UA_ReaderGroup_findDSRbyId(server, dataSetReaderIdentifier);
  608. if(pDataSetReader == NULL) {
  609. return UA_STATUSCODE_BADINVALIDARGUMENT;
  610. }
  611. UA_TargetVariablesDataType targetVars;
  612. targetVars.targetVariablesSize = pDataSetReader->config.dataSetMetaData.fieldsSize;
  613. targetVars.targetVariables = (UA_FieldTargetDataType *)UA_calloc(targetVars.targetVariablesSize, sizeof(UA_FieldTargetDataType));
  614. for (size_t iteratorField = 0; iteratorField < pDataSetReader->config.dataSetMetaData.fieldsSize; iteratorField++) {
  615. UA_VariableAttributes vAttr = UA_VariableAttributes_default;
  616. vAttr.valueRank = pDataSetReader->config.dataSetMetaData.fields[iteratorField].valueRank;
  617. if(pDataSetReader->config.dataSetMetaData.fields[iteratorField].arrayDimensionsSize > 0) {
  618. retval = UA_Array_copy(pDataSetReader->config.dataSetMetaData.fields[iteratorField].arrayDimensions, pDataSetReader->config.dataSetMetaData.fields[iteratorField].arrayDimensionsSize, (void**)&vAttr.arrayDimensions, &UA_TYPES[UA_TYPES_UINT32]);
  619. if(retval == UA_STATUSCODE_GOOD) {
  620. vAttr.arrayDimensionsSize = pDataSetReader->config.dataSetMetaData.fields[iteratorField].arrayDimensionsSize;
  621. }
  622. }
  623. vAttr.dataType = pDataSetReader->config.dataSetMetaData.fields[iteratorField].dataType;
  624. vAttr.accessLevel = UA_ACCESSLEVELMASK_READ;
  625. UA_LocalizedText_copy(&pDataSetReader->config.dataSetMetaData.fields[iteratorField].description, &vAttr.description);
  626. UA_QualifiedName qn;
  627. UA_QualifiedName_init(&qn);
  628. char szTmpName[UA_MAX_SIZENAME];
  629. if(pDataSetReader->config.dataSetMetaData.fields[iteratorField].name.length > 0) {
  630. UA_UInt16 slen = UA_MAX_SIZENAME -1;
  631. vAttr.displayName.locale = UA_STRING("en-US");
  632. vAttr.displayName.text = pDataSetReader->config.dataSetMetaData.fields[iteratorField].name;
  633. if(pDataSetReader->config.dataSetMetaData.fields[iteratorField].name.length < slen) {
  634. slen = (UA_UInt16)pDataSetReader->config.dataSetMetaData.fields[iteratorField].name.length;
  635. UA_snprintf(szTmpName, sizeof(szTmpName), "%.*s", (int)slen, (const char*)pDataSetReader->config.dataSetMetaData.fields[iteratorField].name.data);
  636. }
  637. szTmpName[slen] = '\0';
  638. qn = UA_QUALIFIEDNAME(1, szTmpName);
  639. }
  640. else {
  641. strcpy(szTmpName, "SubscribedVariable");
  642. vAttr.displayName = UA_LOCALIZEDTEXT("en-US", szTmpName);
  643. qn = UA_QUALIFIEDNAME(1, "SubscribedVariable");
  644. }
  645. /* Add variable to the given parent node */
  646. UA_NodeId newNode;
  647. retval = UA_Server_addVariableNode(server, UA_NODEID_NULL, *parentNode,
  648. UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT), qn,
  649. UA_NODEID_NUMERIC(0, UA_NS0ID_BASEDATAVARIABLETYPE), vAttr, NULL, &newNode);
  650. if(retval == UA_STATUSCODE_GOOD) {
  651. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_USERLAND, "addVariableNode %s succeeded", szTmpName);
  652. }
  653. else {
  654. UA_LOG_ERROR(&server->config.logger, UA_LOGCATEGORY_USERLAND, "addVariableNode: error 0x%x", retval);
  655. }
  656. UA_FieldTargetDataType_init(&targetVars.targetVariables[iteratorField]);
  657. targetVars.targetVariables[iteratorField].attributeId = UA_ATTRIBUTEID_VALUE;
  658. UA_NodeId_copy(&newNode, &targetVars.targetVariables[iteratorField].targetNodeId);
  659. UA_NodeId_deleteMembers(&newNode);
  660. if(vAttr.arrayDimensionsSize > 0) {
  661. UA_Array_delete(vAttr.arrayDimensions, vAttr.arrayDimensionsSize, &UA_TYPES[UA_TYPES_UINT32]);
  662. }
  663. }
  664. if(sdsType == UA_PUBSUB_SDS_TARGET) {
  665. retval = UA_Server_DataSetReader_createTargetVariables(server, pDataSetReader->identifier, &targetVars);
  666. }
  667. UA_TargetVariablesDataType_deleteMembers(&targetVars);
  668. return retval;
  669. }
  670. /**
  671. * Process a NetworkMessage with a DataSetReader.
  672. *
  673. * @param server
  674. * @param dataSetReader
  675. * @param dataSetMsg
  676. */
  677. void UA_Server_DataSetReader_process(UA_Server *server, UA_DataSetReader *dataSetReader, UA_DataSetMessage* dataSetMsg) {
  678. if((dataSetReader == NULL) || (dataSetMsg == NULL) || (server == NULL)) {
  679. return;
  680. }
  681. if(!dataSetMsg->header.dataSetMessageValid) {
  682. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER, "DataSetMessage is discarded: message is not valid");
  683. /* To Do check ConfigurationVersion*/
  684. /*if(dataSetMsg->header.configVersionMajorVersionEnabled)
  685. * {
  686. * if(dataSetMsg->header.configVersionMajorVersion != dataSetReader->config.dataSetMetaData.configurationVersion.majorVersion)
  687. * {
  688. * UA_LOG_WARNING(server->config.logger, UA_LOGCATEGORY_SERVER, "DataSetMessage is discarded: ConfigurationVersion MajorVersion does not match");
  689. * return;
  690. * }
  691. } */
  692. }
  693. else {
  694. if(dataSetMsg->header.dataSetMessageType == UA_DATASETMESSAGE_DATAKEYFRAME) {
  695. if(dataSetMsg->header.fieldEncoding != UA_FIELDENCODING_RAWDATA) {
  696. size_t anzFields = dataSetMsg->data.keyFrameData.fieldCount;
  697. if(dataSetReader->config.dataSetMetaData.fieldsSize < anzFields) {
  698. anzFields = dataSetReader->config.dataSetMetaData.fieldsSize;
  699. }
  700. if(dataSetReader->subscribedDataSetTarget.targetVariablesSize < anzFields) {
  701. anzFields = dataSetReader->subscribedDataSetTarget.targetVariablesSize;
  702. }
  703. UA_StatusCode retVal = UA_STATUSCODE_GOOD;
  704. for (UA_UInt16 iteratorField = 0; iteratorField < anzFields; iteratorField++) {
  705. if(dataSetMsg->data.keyFrameData.dataSetFields[iteratorField].hasValue) {
  706. if(dataSetReader->subscribedDataSetTarget.targetVariables[iteratorField].attributeId == UA_ATTRIBUTEID_VALUE) {
  707. retVal = UA_Server_writeValue(server, dataSetReader->subscribedDataSetTarget.targetVariables[iteratorField].targetNodeId, dataSetMsg->data.keyFrameData.dataSetFields[iteratorField].value);
  708. if(retVal != UA_STATUSCODE_GOOD) {
  709. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER, "Error Write Value KF %u: 0x%x", iteratorField, retVal);
  710. }
  711. }
  712. else {
  713. UA_WriteValue writeVal;
  714. UA_WriteValue_init(&writeVal);
  715. writeVal.attributeId = dataSetReader->subscribedDataSetTarget.targetVariables[iteratorField].attributeId;
  716. writeVal.indexRange = dataSetReader->subscribedDataSetTarget.targetVariables[iteratorField].receiverIndexRange;
  717. writeVal.nodeId = dataSetReader->subscribedDataSetTarget.targetVariables[iteratorField].targetNodeId;
  718. UA_DataValue_copy(&dataSetMsg->data.keyFrameData.dataSetFields[iteratorField], &writeVal.value);
  719. retVal = UA_Server_write(server, &writeVal);
  720. if(retVal != UA_STATUSCODE_GOOD) {
  721. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER, "Error Write KF %u: 0x%x", iteratorField, retVal);
  722. }
  723. }
  724. }
  725. }
  726. }
  727. }
  728. }
  729. }
  730. /**
  731. * Copy the config of the DataSetReader.
  732. *
  733. * @param src
  734. * @param dst
  735. * @return UA_STATUSCODE_GOOD on success
  736. */
  737. UA_StatusCode
  738. UA_DataSetReaderConfig_copy(const UA_DataSetReaderConfig *src,
  739. UA_DataSetReaderConfig *dst) {
  740. memset(dst, 0, sizeof(UA_DataSetReaderConfig));
  741. UA_StatusCode retVal = UA_String_copy(&src->name, &dst->name);
  742. if(retVal != UA_STATUSCODE_GOOD) {
  743. return retVal;
  744. }
  745. retVal = UA_Variant_copy(&src->publisherId, &dst->publisherId);
  746. if(retVal != UA_STATUSCODE_GOOD) {
  747. return retVal;
  748. }
  749. dst->writerGroupId = src->writerGroupId;
  750. dst->dataSetWriterId = src->dataSetWriterId;
  751. retVal = UA_DataSetMetaDataType_copy(&src->dataSetMetaData, &dst->dataSetMetaData);
  752. if(retVal != UA_STATUSCODE_GOOD) {
  753. return retVal;
  754. }
  755. dst->dataSetFieldContentMask = src->dataSetFieldContentMask;
  756. dst->messageReceiveTimeout = src->messageReceiveTimeout;
  757. /* Currently memcpy is used to copy the securityParameters */
  758. memcpy(&dst->securityParameters, &src->securityParameters, sizeof(UA_PubSubSecurityParameters));
  759. retVal = UA_UadpDataSetReaderMessageDataType_copy(&src->messageSettings, &dst->messageSettings);
  760. if(retVal != UA_STATUSCODE_GOOD) {
  761. return retVal;
  762. }
  763. return UA_STATUSCODE_GOOD;
  764. }
  765. /**
  766. * Delete the DataSetReader.
  767. *
  768. * @param server
  769. * @param dataSetReader
  770. */
  771. void UA_DataSetReader_delete(UA_Server *server, UA_DataSetReader *dataSetReader) {
  772. /* Delete DataSetReader config */
  773. UA_String_deleteMembers(&dataSetReader->config.name);
  774. UA_Variant_deleteMembers(&dataSetReader->config.publisherId);
  775. UA_DataSetMetaDataType_deleteMembers(&dataSetReader->config.dataSetMetaData);
  776. UA_UadpDataSetReaderMessageDataType_deleteMembers(&dataSetReader->config.messageSettings);
  777. UA_TargetVariablesDataType_deleteMembers(&dataSetReader->subscribedDataSetTarget);
  778. /* Delete DataSetReader */
  779. UA_ReaderGroup* pGroup = UA_ReaderGroup_findRGbyId(server, dataSetReader->linkedReaderGroup);
  780. if(pGroup != NULL) {
  781. pGroup->readersCount--;
  782. }
  783. UA_NodeId_deleteMembers(&dataSetReader->identifier);
  784. UA_NodeId_deleteMembers(&dataSetReader->linkedReaderGroup);
  785. /* Remove DataSetReader from group */
  786. LIST_REMOVE(dataSetReader, listEntry);
  787. /* Free memory allocated for DataSetReader */
  788. UA_free(dataSetReader);
  789. }
  790. /**********************************************/
  791. /* PublishedDataSet */
  792. /**********************************************/
  793. UA_StatusCode
  794. UA_PublishedDataSetConfig_copy(const UA_PublishedDataSetConfig *src,
  795. UA_PublishedDataSetConfig *dst) {
  796. UA_StatusCode retVal = UA_STATUSCODE_GOOD;
  797. memcpy(dst, src, sizeof(UA_PublishedDataSetConfig));
  798. retVal |= UA_String_copy(&src->name, &dst->name);
  799. switch(src->publishedDataSetType){
  800. case UA_PUBSUB_DATASET_PUBLISHEDITEMS:
  801. //no additional items
  802. break;
  803. case UA_PUBSUB_DATASET_PUBLISHEDITEMS_TEMPLATE:
  804. if(src->config.itemsTemplate.variablesToAddSize > 0){
  805. dst->config.itemsTemplate.variablesToAdd = (UA_PublishedVariableDataType *) UA_calloc(
  806. src->config.itemsTemplate.variablesToAddSize, sizeof(UA_PublishedVariableDataType));
  807. }
  808. for(size_t i = 0; i < src->config.itemsTemplate.variablesToAddSize; i++){
  809. retVal |= UA_PublishedVariableDataType_copy(&src->config.itemsTemplate.variablesToAdd[i],
  810. &dst->config.itemsTemplate.variablesToAdd[i]);
  811. }
  812. retVal |= UA_DataSetMetaDataType_copy(&src->config.itemsTemplate.metaData,
  813. &dst->config.itemsTemplate.metaData);
  814. break;
  815. default:
  816. return UA_STATUSCODE_BADINVALIDARGUMENT;
  817. }
  818. return retVal;
  819. }
  820. UA_StatusCode
  821. UA_Server_getPublishedDataSetConfig(UA_Server *server, const UA_NodeId pds,
  822. UA_PublishedDataSetConfig *config){
  823. if(!config)
  824. return UA_STATUSCODE_BADINVALIDARGUMENT;
  825. UA_PublishedDataSet *currentPublishedDataSet = UA_PublishedDataSet_findPDSbyId(server, pds);
  826. if(!currentPublishedDataSet)
  827. return UA_STATUSCODE_BADNOTFOUND;
  828. UA_PublishedDataSetConfig tmpPublishedDataSetConfig;
  829. //deep copy of the actual config
  830. UA_PublishedDataSetConfig_copy(&currentPublishedDataSet->config, &tmpPublishedDataSetConfig);
  831. *config = tmpPublishedDataSetConfig;
  832. return UA_STATUSCODE_GOOD;
  833. }
  834. UA_PublishedDataSet *
  835. UA_PublishedDataSet_findPDSbyId(UA_Server *server, UA_NodeId identifier){
  836. for(size_t i = 0; i < server->pubSubManager.publishedDataSetsSize; i++){
  837. if(UA_NodeId_equal(&server->pubSubManager.publishedDataSets[i].identifier, &identifier)){
  838. return &server->pubSubManager.publishedDataSets[i];
  839. }
  840. }
  841. return NULL;
  842. }
  843. void
  844. UA_PublishedDataSetConfig_deleteMembers(UA_PublishedDataSetConfig *pdsConfig){
  845. //delete pds config
  846. UA_String_deleteMembers(&pdsConfig->name);
  847. switch (pdsConfig->publishedDataSetType){
  848. case UA_PUBSUB_DATASET_PUBLISHEDITEMS:
  849. //no additional items
  850. break;
  851. case UA_PUBSUB_DATASET_PUBLISHEDITEMS_TEMPLATE:
  852. if(pdsConfig->config.itemsTemplate.variablesToAddSize > 0){
  853. for(size_t i = 0; i < pdsConfig->config.itemsTemplate.variablesToAddSize; i++){
  854. UA_PublishedVariableDataType_deleteMembers(&pdsConfig->config.itemsTemplate.variablesToAdd[i]);
  855. }
  856. UA_free(pdsConfig->config.itemsTemplate.variablesToAdd);
  857. }
  858. UA_DataSetMetaDataType_deleteMembers(&pdsConfig->config.itemsTemplate.metaData);
  859. break;
  860. default:
  861. break;
  862. }
  863. }
  864. void
  865. UA_PublishedDataSet_deleteMembers(UA_Server *server, UA_PublishedDataSet *publishedDataSet){
  866. UA_PublishedDataSetConfig_deleteMembers(&publishedDataSet->config);
  867. //delete PDS
  868. UA_DataSetMetaDataType_deleteMembers(&publishedDataSet->dataSetMetaData);
  869. UA_DataSetField *field, *tmpField;
  870. LIST_FOREACH_SAFE(field, &publishedDataSet->fields, listEntry, tmpField) {
  871. UA_Server_removeDataSetField(server, field->identifier);
  872. }
  873. UA_NodeId_deleteMembers(&publishedDataSet->identifier);
  874. }
  875. UA_DataSetFieldResult
  876. UA_Server_addDataSetField(UA_Server *server, const UA_NodeId publishedDataSet,
  877. const UA_DataSetFieldConfig *fieldConfig,
  878. UA_NodeId *fieldIdentifier) {
  879. UA_StatusCode retVal = UA_STATUSCODE_GOOD;
  880. UA_DataSetFieldResult result = {UA_STATUSCODE_BADINVALIDARGUMENT, {0, 0}};
  881. if(!fieldConfig)
  882. return result;
  883. UA_PublishedDataSet *currentDataSet = UA_PublishedDataSet_findPDSbyId(server, publishedDataSet);
  884. if(currentDataSet == NULL){
  885. result.result = UA_STATUSCODE_BADNOTFOUND;
  886. return result;
  887. }
  888. if(currentDataSet->config.publishedDataSetType != UA_PUBSUB_DATASET_PUBLISHEDITEMS){
  889. result.result = UA_STATUSCODE_BADNOTIMPLEMENTED;
  890. return result;
  891. }
  892. UA_DataSetField *newField = (UA_DataSetField *) UA_calloc(1, sizeof(UA_DataSetField));
  893. if(!newField){
  894. result.result = UA_STATUSCODE_BADINTERNALERROR;
  895. return result;
  896. }
  897. UA_DataSetFieldConfig tmpFieldConfig;
  898. retVal |= UA_DataSetFieldConfig_copy(fieldConfig, &tmpFieldConfig);
  899. newField->config = tmpFieldConfig;
  900. UA_PubSubManager_generateUniqueNodeId(server, &newField->identifier);
  901. if(fieldIdentifier != NULL){
  902. UA_NodeId_copy(&newField->identifier, fieldIdentifier);
  903. }
  904. newField->publishedDataSet = currentDataSet->identifier;
  905. //update major version of parent published data set
  906. currentDataSet->dataSetMetaData.configurationVersion.majorVersion = UA_PubSubConfigurationVersionTimeDifference();
  907. LIST_INSERT_HEAD(&currentDataSet->fields, newField, listEntry);
  908. if(newField->config.field.variable.promotedField)
  909. currentDataSet->promotedFieldsCount++;
  910. currentDataSet->fieldSize++;
  911. result.result = retVal;
  912. result.configurationVersion.majorVersion = currentDataSet->dataSetMetaData.configurationVersion.majorVersion;
  913. result.configurationVersion.minorVersion = currentDataSet->dataSetMetaData.configurationVersion.minorVersion;
  914. return result;
  915. }
  916. UA_DataSetFieldResult
  917. UA_Server_removeDataSetField(UA_Server *server, const UA_NodeId dsf) {
  918. UA_DataSetField *currentField = UA_DataSetField_findDSFbyId(server, dsf);
  919. UA_DataSetFieldResult result = {UA_STATUSCODE_BADNOTFOUND, {0, 0}};
  920. if(!currentField)
  921. return result;
  922. UA_PublishedDataSet *parentPublishedDataSet =
  923. UA_PublishedDataSet_findPDSbyId(server, currentField->publishedDataSet);
  924. if(!parentPublishedDataSet)
  925. return result;
  926. parentPublishedDataSet->fieldSize--;
  927. if(currentField->config.field.variable.promotedField)
  928. parentPublishedDataSet->promotedFieldsCount--;
  929. /* update major version of PublishedDataSet */
  930. parentPublishedDataSet->dataSetMetaData.configurationVersion.majorVersion =
  931. UA_PubSubConfigurationVersionTimeDifference();
  932. UA_DataSetField_deleteMembers(currentField);
  933. LIST_REMOVE(currentField, listEntry);
  934. UA_free(currentField);
  935. result.result = UA_STATUSCODE_GOOD;
  936. result.configurationVersion.majorVersion = parentPublishedDataSet->dataSetMetaData.configurationVersion.majorVersion;
  937. result.configurationVersion.minorVersion = parentPublishedDataSet->dataSetMetaData.configurationVersion.minorVersion;
  938. return result;
  939. }
  940. /**********************************************/
  941. /* DataSetWriter */
  942. /**********************************************/
  943. UA_StatusCode
  944. UA_DataSetWriterConfig_copy(const UA_DataSetWriterConfig *src,
  945. UA_DataSetWriterConfig *dst){
  946. UA_StatusCode retVal = UA_STATUSCODE_GOOD;
  947. memcpy(dst, src, sizeof(UA_DataSetWriterConfig));
  948. retVal |= UA_String_copy(&src->name, &dst->name);
  949. retVal |= UA_String_copy(&src->dataSetName, &dst->dataSetName);
  950. retVal |= UA_ExtensionObject_copy(&src->messageSettings, &dst->messageSettings);
  951. dst->dataSetWriterProperties = (UA_KeyValuePair *)
  952. UA_calloc(src->dataSetWriterPropertiesSize, sizeof(UA_KeyValuePair));
  953. if(!dst->dataSetWriterProperties)
  954. return UA_STATUSCODE_BADOUTOFMEMORY;
  955. for(size_t i = 0; i < src->dataSetWriterPropertiesSize; i++){
  956. retVal |= UA_KeyValuePair_copy(&src->dataSetWriterProperties[i], &dst->dataSetWriterProperties[i]);
  957. }
  958. return retVal;
  959. }
  960. UA_StatusCode
  961. UA_Server_getDataSetWriterConfig(UA_Server *server, const UA_NodeId dsw,
  962. UA_DataSetWriterConfig *config){
  963. UA_StatusCode retVal = UA_STATUSCODE_GOOD;
  964. if(!config)
  965. return UA_STATUSCODE_BADINVALIDARGUMENT;
  966. UA_DataSetWriter *currentDataSetWriter = UA_DataSetWriter_findDSWbyId(server, dsw);
  967. if(!currentDataSetWriter)
  968. return UA_STATUSCODE_BADNOTFOUND;
  969. UA_DataSetWriterConfig tmpWriterConfig;
  970. //deep copy of the actual config
  971. retVal |= UA_DataSetWriterConfig_copy(&currentDataSetWriter->config, &tmpWriterConfig);
  972. *config = tmpWriterConfig;
  973. return retVal;
  974. }
  975. UA_DataSetWriter *
  976. UA_DataSetWriter_findDSWbyId(UA_Server *server, UA_NodeId identifier) {
  977. for(size_t i = 0; i < server->pubSubManager.connectionsSize; i++){
  978. UA_WriterGroup *tmpWriterGroup;
  979. LIST_FOREACH(tmpWriterGroup, &server->pubSubManager.connections[i].writerGroups, listEntry){
  980. UA_DataSetWriter *tmpWriter;
  981. LIST_FOREACH(tmpWriter, &tmpWriterGroup->writers, listEntry){
  982. if(UA_NodeId_equal(&tmpWriter->identifier, &identifier)){
  983. return tmpWriter;
  984. }
  985. }
  986. }
  987. }
  988. return NULL;
  989. }
  990. void
  991. UA_DataSetWriterConfig_deleteMembers(UA_DataSetWriterConfig *pdsConfig) {
  992. UA_String_deleteMembers(&pdsConfig->name);
  993. UA_String_deleteMembers(&pdsConfig->dataSetName);
  994. for(size_t i = 0; i < pdsConfig->dataSetWriterPropertiesSize; i++){
  995. UA_KeyValuePair_deleteMembers(&pdsConfig->dataSetWriterProperties[i]);
  996. }
  997. UA_free(pdsConfig->dataSetWriterProperties);
  998. UA_ExtensionObject_deleteMembers(&pdsConfig->messageSettings);
  999. }
  1000. static void
  1001. UA_DataSetWriter_deleteMembers(UA_Server *server, UA_DataSetWriter *dataSetWriter) {
  1002. UA_DataSetWriterConfig_deleteMembers(&dataSetWriter->config);
  1003. //delete DataSetWriter
  1004. UA_NodeId_deleteMembers(&dataSetWriter->identifier);
  1005. UA_NodeId_deleteMembers(&dataSetWriter->linkedWriterGroup);
  1006. UA_NodeId_deleteMembers(&dataSetWriter->connectedDataSet);
  1007. #ifdef UA_ENABLE_PUBSUB_DELTAFRAMES
  1008. //delete lastSamples store
  1009. for(size_t i = 0; i < dataSetWriter->lastSamplesCount; i++) {
  1010. UA_DataValue_deleteMembers(&dataSetWriter->lastSamples[i].value);
  1011. }
  1012. UA_free(dataSetWriter->lastSamples);
  1013. dataSetWriter->lastSamples = NULL;
  1014. dataSetWriter->lastSamplesCount = 0;
  1015. #endif
  1016. }
  1017. /**********************************************/
  1018. /* WriterGroup */
  1019. /**********************************************/
  1020. UA_StatusCode
  1021. UA_WriterGroupConfig_copy(const UA_WriterGroupConfig *src,
  1022. UA_WriterGroupConfig *dst){
  1023. UA_StatusCode retVal = UA_STATUSCODE_GOOD;
  1024. memcpy(dst, src, sizeof(UA_WriterGroupConfig));
  1025. retVal |= UA_String_copy(&src->name, &dst->name);
  1026. retVal |= UA_ExtensionObject_copy(&src->transportSettings, &dst->transportSettings);
  1027. retVal |= UA_ExtensionObject_copy(&src->messageSettings, &dst->messageSettings);
  1028. dst->groupProperties = (UA_KeyValuePair *) UA_calloc(src->groupPropertiesSize, sizeof(UA_KeyValuePair));
  1029. if(!dst->groupProperties)
  1030. return UA_STATUSCODE_BADOUTOFMEMORY;
  1031. for(size_t i = 0; i < src->groupPropertiesSize; i++){
  1032. retVal |= UA_KeyValuePair_copy(&src->groupProperties[i], &dst->groupProperties[i]);
  1033. }
  1034. return retVal;
  1035. }
  1036. UA_StatusCode
  1037. UA_Server_getWriterGroupConfig(UA_Server *server, const UA_NodeId writerGroup,
  1038. UA_WriterGroupConfig *config){
  1039. UA_StatusCode retVal = UA_STATUSCODE_GOOD;
  1040. if(!config)
  1041. return UA_STATUSCODE_BADINVALIDARGUMENT;
  1042. UA_WriterGroup *currentWriterGroup = UA_WriterGroup_findWGbyId(server, writerGroup);
  1043. if(!currentWriterGroup){
  1044. return UA_STATUSCODE_BADNOTFOUND;
  1045. }
  1046. UA_WriterGroupConfig tmpWriterGroupConfig;
  1047. //deep copy of the actual config
  1048. retVal |= UA_WriterGroupConfig_copy(&currentWriterGroup->config, &tmpWriterGroupConfig);
  1049. *config = tmpWriterGroupConfig;
  1050. return retVal;
  1051. }
  1052. UA_StatusCode
  1053. UA_Server_updateWriterGroupConfig(UA_Server *server, UA_NodeId writerGroupIdentifier,
  1054. const UA_WriterGroupConfig *config){
  1055. if(!config)
  1056. return UA_STATUSCODE_BADINVALIDARGUMENT;
  1057. UA_WriterGroup *currentWriterGroup = UA_WriterGroup_findWGbyId(server, writerGroupIdentifier);
  1058. if(!currentWriterGroup)
  1059. return UA_STATUSCODE_BADNOTFOUND;
  1060. //The update functionality will be extended during the next PubSub batches.
  1061. //Currently is only a change of the publishing interval possible.
  1062. if(currentWriterGroup->config.maxEncapsulatedDataSetMessageCount != config->maxEncapsulatedDataSetMessageCount){
  1063. currentWriterGroup->config.maxEncapsulatedDataSetMessageCount = config->maxEncapsulatedDataSetMessageCount;
  1064. if(currentWriterGroup->config.messageSettings.encoding == UA_EXTENSIONOBJECT_ENCODED_NOBODY) {
  1065. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  1066. "MaxEncapsulatedDataSetMessag need enabled 'PayloadHeader' within the message settings.");
  1067. }
  1068. }
  1069. if(currentWriterGroup->config.publishingInterval != config->publishingInterval) {
  1070. UA_PubSubManager_removeRepeatedPubSubCallback(server, currentWriterGroup->publishCallbackId);
  1071. currentWriterGroup->config.publishingInterval = config->publishingInterval;
  1072. UA_WriterGroup_addPublishCallback(server, currentWriterGroup);
  1073. }
  1074. if(currentWriterGroup->config.priority != config->priority) {
  1075. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  1076. "No or unsupported WriterGroup update.");
  1077. }
  1078. return UA_STATUSCODE_GOOD;
  1079. }
  1080. UA_WriterGroup *
  1081. UA_WriterGroup_findWGbyId(UA_Server *server, UA_NodeId identifier){
  1082. for(size_t i = 0; i < server->pubSubManager.connectionsSize; i++){
  1083. UA_WriterGroup *tmpWriterGroup;
  1084. LIST_FOREACH(tmpWriterGroup, &server->pubSubManager.connections[i].writerGroups, listEntry) {
  1085. if(UA_NodeId_equal(&identifier, &tmpWriterGroup->identifier)){
  1086. return tmpWriterGroup;
  1087. }
  1088. }
  1089. }
  1090. return NULL;
  1091. }
  1092. void
  1093. UA_WriterGroupConfig_deleteMembers(UA_WriterGroupConfig *writerGroupConfig){
  1094. //delete writerGroup config
  1095. UA_String_deleteMembers(&writerGroupConfig->name);
  1096. UA_ExtensionObject_deleteMembers(&writerGroupConfig->transportSettings);
  1097. UA_ExtensionObject_deleteMembers(&writerGroupConfig->messageSettings);
  1098. for(size_t i = 0; i < writerGroupConfig->groupPropertiesSize; i++){
  1099. UA_KeyValuePair_deleteMembers(&writerGroupConfig->groupProperties[i]);
  1100. }
  1101. UA_free(writerGroupConfig->groupProperties);
  1102. }
  1103. static void
  1104. UA_WriterGroup_deleteMembers(UA_Server *server, UA_WriterGroup *writerGroup) {
  1105. UA_WriterGroupConfig_deleteMembers(&writerGroup->config);
  1106. //delete WriterGroup
  1107. //delete all writers. Therefore removeDataSetWriter is called from PublishedDataSet
  1108. UA_DataSetWriter *dataSetWriter, *tmpDataSetWriter;
  1109. LIST_FOREACH_SAFE(dataSetWriter, &writerGroup->writers, listEntry, tmpDataSetWriter){
  1110. UA_Server_removeDataSetWriter(server, dataSetWriter->identifier);
  1111. }
  1112. UA_NodeId_deleteMembers(&writerGroup->linkedConnection);
  1113. UA_NodeId_deleteMembers(&writerGroup->identifier);
  1114. }
  1115. UA_StatusCode
  1116. UA_Server_addDataSetWriter(UA_Server *server,
  1117. const UA_NodeId writerGroup, const UA_NodeId dataSet,
  1118. const UA_DataSetWriterConfig *dataSetWriterConfig,
  1119. UA_NodeId *writerIdentifier) {
  1120. UA_StatusCode retVal = UA_STATUSCODE_GOOD;
  1121. if(!dataSetWriterConfig)
  1122. return UA_STATUSCODE_BADINVALIDARGUMENT;
  1123. UA_PublishedDataSet *currentDataSetContext = UA_PublishedDataSet_findPDSbyId(server, dataSet);
  1124. if(!currentDataSetContext)
  1125. return UA_STATUSCODE_BADNOTFOUND;
  1126. UA_WriterGroup *wg = UA_WriterGroup_findWGbyId(server, writerGroup);
  1127. if(!wg)
  1128. return UA_STATUSCODE_BADNOTFOUND;
  1129. UA_DataSetWriter *newDataSetWriter = (UA_DataSetWriter *) UA_calloc(1, sizeof(UA_DataSetWriter));
  1130. if(!newDataSetWriter)
  1131. return UA_STATUSCODE_BADOUTOFMEMORY;
  1132. //copy the config into the new dataSetWriter
  1133. UA_DataSetWriterConfig tmpDataSetWriterConfig;
  1134. retVal |= UA_DataSetWriterConfig_copy(dataSetWriterConfig, &tmpDataSetWriterConfig);
  1135. newDataSetWriter->config = tmpDataSetWriterConfig;
  1136. //save the current version of the connected PublishedDataSet
  1137. newDataSetWriter->connectedDataSetVersion = currentDataSetContext->dataSetMetaData.configurationVersion;
  1138. #ifdef UA_ENABLE_PUBSUB_DELTAFRAMES
  1139. //initialize the queue for the last values
  1140. newDataSetWriter->lastSamples = (UA_DataSetWriterSample * )
  1141. UA_calloc(currentDataSetContext->fieldSize, sizeof(UA_DataSetWriterSample));
  1142. if(!newDataSetWriter->lastSamples) {
  1143. UA_DataSetWriterConfig_deleteMembers(&newDataSetWriter->config);
  1144. UA_free(newDataSetWriter);
  1145. return UA_STATUSCODE_BADOUTOFMEMORY;
  1146. }
  1147. newDataSetWriter->lastSamplesCount = currentDataSetContext->fieldSize;
  1148. #endif
  1149. //connect PublishedDataSet with DataSetWriter
  1150. newDataSetWriter->connectedDataSet = currentDataSetContext->identifier;
  1151. newDataSetWriter->linkedWriterGroup = wg->identifier;
  1152. UA_PubSubManager_generateUniqueNodeId(server, &newDataSetWriter->identifier);
  1153. if(writerIdentifier != NULL)
  1154. UA_NodeId_copy(&newDataSetWriter->identifier, writerIdentifier);
  1155. //add the new writer to the group
  1156. LIST_INSERT_HEAD(&wg->writers, newDataSetWriter, listEntry);
  1157. wg->writersCount++;
  1158. #ifdef UA_ENABLE_PUBSUB_INFORMATIONMODEL
  1159. addDataSetWriterRepresentation(server, newDataSetWriter);
  1160. #endif
  1161. return retVal;
  1162. }
  1163. UA_StatusCode
  1164. UA_Server_removeDataSetWriter(UA_Server *server, const UA_NodeId dsw){
  1165. UA_DataSetWriter *dataSetWriter = UA_DataSetWriter_findDSWbyId(server, dsw);
  1166. if(!dataSetWriter)
  1167. return UA_STATUSCODE_BADNOTFOUND;
  1168. UA_WriterGroup *linkedWriterGroup = UA_WriterGroup_findWGbyId(server, dataSetWriter->linkedWriterGroup);
  1169. if(!linkedWriterGroup)
  1170. return UA_STATUSCODE_BADNOTFOUND;
  1171. linkedWriterGroup->writersCount--;
  1172. #ifdef UA_ENABLE_PUBSUB_INFORMATIONMODEL
  1173. removeDataSetWriterRepresentation(server, dataSetWriter);
  1174. #endif
  1175. //remove DataSetWriter from group
  1176. UA_DataSetWriter_deleteMembers(server, dataSetWriter);
  1177. LIST_REMOVE(dataSetWriter, listEntry);
  1178. UA_free(dataSetWriter);
  1179. return UA_STATUSCODE_GOOD;
  1180. }
  1181. /**********************************************/
  1182. /* DataSetField */
  1183. /**********************************************/
  1184. UA_StatusCode
  1185. UA_DataSetFieldConfig_copy(const UA_DataSetFieldConfig *src, UA_DataSetFieldConfig *dst){
  1186. memcpy(dst, src, sizeof(UA_DataSetFieldConfig));
  1187. if(src->dataSetFieldType == UA_PUBSUB_DATASETFIELD_VARIABLE) {
  1188. UA_String_copy(&src->field.variable.fieldNameAlias, &dst->field.variable.fieldNameAlias);
  1189. UA_PublishedVariableDataType_copy(&src->field.variable.publishParameters,
  1190. &dst->field.variable.publishParameters);
  1191. } else {
  1192. return UA_STATUSCODE_BADNOTSUPPORTED;
  1193. }
  1194. return UA_STATUSCODE_GOOD;
  1195. }
  1196. UA_StatusCode
  1197. UA_Server_getDataSetFieldConfig(UA_Server *server, const UA_NodeId dsf,
  1198. UA_DataSetFieldConfig *config) {
  1199. UA_StatusCode retVal = UA_STATUSCODE_GOOD;
  1200. if(!config)
  1201. return UA_STATUSCODE_BADINVALIDARGUMENT;
  1202. UA_DataSetField *currentDataSetField = UA_DataSetField_findDSFbyId(server, dsf);
  1203. if(!currentDataSetField)
  1204. return UA_STATUSCODE_BADNOTFOUND;
  1205. UA_DataSetFieldConfig tmpFieldConfig;
  1206. //deep copy of the actual config
  1207. retVal |= UA_DataSetFieldConfig_copy(&currentDataSetField->config, &tmpFieldConfig);
  1208. *config = tmpFieldConfig;
  1209. return retVal;
  1210. }
  1211. UA_DataSetField *
  1212. UA_DataSetField_findDSFbyId(UA_Server *server, UA_NodeId identifier) {
  1213. for(size_t i = 0; i < server->pubSubManager.publishedDataSetsSize; i++){
  1214. UA_DataSetField *tmpField;
  1215. LIST_FOREACH(tmpField, &server->pubSubManager.publishedDataSets[i].fields, listEntry){
  1216. if(UA_NodeId_equal(&tmpField->identifier, &identifier)){
  1217. return tmpField;
  1218. }
  1219. }
  1220. }
  1221. return NULL;
  1222. }
  1223. void
  1224. UA_DataSetFieldConfig_deleteMembers(UA_DataSetFieldConfig *dataSetFieldConfig){
  1225. if(dataSetFieldConfig->dataSetFieldType == UA_PUBSUB_DATASETFIELD_VARIABLE){
  1226. UA_String_deleteMembers(&dataSetFieldConfig->field.variable.fieldNameAlias);
  1227. UA_PublishedVariableDataType_deleteMembers(&dataSetFieldConfig->field.variable.publishParameters);
  1228. }
  1229. }
  1230. static void
  1231. UA_DataSetField_deleteMembers(UA_DataSetField *field) {
  1232. UA_DataSetFieldConfig_deleteMembers(&field->config);
  1233. //delete DataSetField
  1234. UA_NodeId_deleteMembers(&field->identifier);
  1235. UA_NodeId_deleteMembers(&field->publishedDataSet);
  1236. UA_FieldMetaData_deleteMembers(&field->fieldMetaData);
  1237. }
  1238. /*********************************************************/
  1239. /* PublishValues handling */
  1240. /*********************************************************/
  1241. /**
  1242. * Compare two variants. Internally used for value change detection.
  1243. *
  1244. * @return true if the value has changed
  1245. */
  1246. #ifdef UA_ENABLE_PUBSUB_DELTAFRAMES
  1247. static UA_Boolean
  1248. valueChangedVariant(UA_Variant *oldValue, UA_Variant *newValue){
  1249. if(! (oldValue && newValue))
  1250. return false;
  1251. UA_ByteString *oldValueEncoding = UA_ByteString_new(), *newValueEncoding = UA_ByteString_new();
  1252. size_t oldValueEncodingSize, newValueEncodingSize;
  1253. oldValueEncodingSize = UA_calcSizeBinary(oldValue, &UA_TYPES[UA_TYPES_VARIANT]);
  1254. newValueEncodingSize = UA_calcSizeBinary(newValue, &UA_TYPES[UA_TYPES_VARIANT]);
  1255. if((oldValueEncodingSize == 0) || (newValueEncodingSize == 0))
  1256. return false;
  1257. if(oldValueEncodingSize != newValueEncodingSize)
  1258. return true;
  1259. if(UA_ByteString_allocBuffer(oldValueEncoding, oldValueEncodingSize) != UA_STATUSCODE_GOOD)
  1260. return false;
  1261. if(UA_ByteString_allocBuffer(newValueEncoding, newValueEncodingSize) != UA_STATUSCODE_GOOD)
  1262. return false;
  1263. UA_Byte *bufPosOldValue = oldValueEncoding->data;
  1264. const UA_Byte *bufEndOldValue = &oldValueEncoding->data[oldValueEncoding->length];
  1265. UA_Byte *bufPosNewValue = newValueEncoding->data;
  1266. const UA_Byte *bufEndNewValue = &newValueEncoding->data[newValueEncoding->length];
  1267. if(UA_encodeBinary(oldValue, &UA_TYPES[UA_TYPES_VARIANT],
  1268. &bufPosOldValue, &bufEndOldValue, NULL, NULL) != UA_STATUSCODE_GOOD){
  1269. return false;
  1270. }
  1271. if(UA_encodeBinary(newValue, &UA_TYPES[UA_TYPES_VARIANT],
  1272. &bufPosNewValue, &bufEndNewValue, NULL, NULL) != UA_STATUSCODE_GOOD){
  1273. return false;
  1274. }
  1275. oldValueEncoding->length = (uintptr_t)bufPosOldValue - (uintptr_t)oldValueEncoding->data;
  1276. newValueEncoding->length = (uintptr_t)bufPosNewValue - (uintptr_t)newValueEncoding->data;
  1277. UA_Boolean compareResult = !UA_ByteString_equal(oldValueEncoding, newValueEncoding);
  1278. UA_ByteString_delete(oldValueEncoding);
  1279. UA_ByteString_delete(newValueEncoding);
  1280. return compareResult;
  1281. }
  1282. #endif
  1283. /**
  1284. * Obtain the latest value for a specific DataSetField. This method is currently
  1285. * called inside the DataSetMessage generation process.
  1286. */
  1287. static void
  1288. UA_PubSubDataSetField_sampleValue(UA_Server *server, UA_DataSetField *field,
  1289. UA_DataValue *value) {
  1290. /* Read the value */
  1291. UA_ReadValueId rvid;
  1292. UA_ReadValueId_init(&rvid);
  1293. rvid.nodeId = field->config.field.variable.publishParameters.publishedVariable;
  1294. rvid.attributeId = field->config.field.variable.publishParameters.attributeId;
  1295. rvid.indexRange = field->config.field.variable.publishParameters.indexRange;
  1296. *value = UA_Server_read(server, &rvid, UA_TIMESTAMPSTORETURN_BOTH);
  1297. }
  1298. static UA_StatusCode
  1299. UA_PubSubDataSetWriter_generateKeyFrameMessage(UA_Server *server, UA_DataSetMessage *dataSetMessage,
  1300. UA_DataSetWriter *dataSetWriter) {
  1301. UA_PublishedDataSet *currentDataSet =
  1302. UA_PublishedDataSet_findPDSbyId(server, dataSetWriter->connectedDataSet);
  1303. if(!currentDataSet)
  1304. return UA_STATUSCODE_BADNOTFOUND;
  1305. /* Prepare DataSetMessageContent */
  1306. dataSetMessage->header.dataSetMessageValid = true;
  1307. dataSetMessage->header.dataSetMessageType = UA_DATASETMESSAGE_DATAKEYFRAME;
  1308. dataSetMessage->data.keyFrameData.fieldCount = currentDataSet->fieldSize;
  1309. dataSetMessage->data.keyFrameData.dataSetFields = (UA_DataValue *)
  1310. UA_Array_new(currentDataSet->fieldSize, &UA_TYPES[UA_TYPES_DATAVALUE]);
  1311. if(!dataSetMessage->data.keyFrameData.dataSetFields)
  1312. return UA_STATUSCODE_BADOUTOFMEMORY;
  1313. #ifdef UA_ENABLE_JSON_ENCODING
  1314. /* json: insert fieldnames used as json keys */
  1315. dataSetMessage->data.keyFrameData.fieldNames =
  1316. (UA_String *)UA_Array_new(currentDataSet->fieldSize, &UA_TYPES[UA_TYPES_STRING]);
  1317. if(!dataSetMessage->data.keyFrameData.fieldNames)
  1318. return UA_STATUSCODE_BADOUTOFMEMORY;
  1319. #endif
  1320. /* Loop over the fields */
  1321. size_t counter = 0;
  1322. UA_DataSetField *dsf;
  1323. LIST_FOREACH(dsf, &currentDataSet->fields, listEntry) {
  1324. #ifdef UA_ENABLE_JSON_ENCODING
  1325. /* json: store the fieldNameAlias*/
  1326. UA_String_copy(&dsf->config.field.variable.fieldNameAlias,
  1327. &dataSetMessage->data.keyFrameData.fieldNames[counter]);
  1328. #endif
  1329. /* Sample the value */
  1330. UA_DataValue *dfv = &dataSetMessage->data.keyFrameData.dataSetFields[counter];
  1331. UA_PubSubDataSetField_sampleValue(server, dsf, dfv);
  1332. /* Deactivate statuscode? */
  1333. if(((u64)dataSetWriter->config.dataSetFieldContentMask & (u64)UA_DATASETFIELDCONTENTMASK_STATUSCODE) == 0)
  1334. dfv->hasStatus = false;
  1335. /* Deactivate timestamps */
  1336. if(((u64)dataSetWriter->config.dataSetFieldContentMask &
  1337. (u64)UA_DATASETFIELDCONTENTMASK_SOURCETIMESTAMP) == 0)
  1338. dfv->hasSourceTimestamp = false;
  1339. if(((u64)dataSetWriter->config.dataSetFieldContentMask &
  1340. (u64)UA_DATASETFIELDCONTENTMASK_SOURCEPICOSECONDS) == 0)
  1341. dfv->hasSourcePicoseconds = false;
  1342. if(((u64)dataSetWriter->config.dataSetFieldContentMask &
  1343. (u64)UA_DATASETFIELDCONTENTMASK_SERVERTIMESTAMP) == 0)
  1344. dfv->hasServerTimestamp = false;
  1345. if(((u64)dataSetWriter->config.dataSetFieldContentMask &
  1346. (u64)UA_DATASETFIELDCONTENTMASK_SERVERPICOSECONDS) == 0)
  1347. dfv->hasServerPicoseconds = false;
  1348. #ifdef UA_ENABLE_PUBSUB_DELTAFRAMES
  1349. /* Update lastValue store */
  1350. UA_DataValue_deleteMembers(&dataSetWriter->lastSamples[counter].value);
  1351. UA_DataValue_copy(dfv, &dataSetWriter->lastSamples[counter].value);
  1352. #endif
  1353. counter++;
  1354. }
  1355. return UA_STATUSCODE_GOOD;
  1356. }
  1357. #ifdef UA_ENABLE_PUBSUB_DELTAFRAMES
  1358. static UA_StatusCode
  1359. UA_PubSubDataSetWriter_generateDeltaFrameMessage(UA_Server *server,
  1360. UA_DataSetMessage *dataSetMessage,
  1361. UA_DataSetWriter *dataSetWriter) {
  1362. UA_PublishedDataSet *currentDataSet =
  1363. UA_PublishedDataSet_findPDSbyId(server, dataSetWriter->connectedDataSet);
  1364. if(!currentDataSet)
  1365. return UA_STATUSCODE_BADNOTFOUND;
  1366. /* Prepare DataSetMessageContent */
  1367. memset(dataSetMessage, 0, sizeof(UA_DataSetMessage));
  1368. dataSetMessage->header.dataSetMessageValid = true;
  1369. dataSetMessage->header.dataSetMessageType = UA_DATASETMESSAGE_DATADELTAFRAME;
  1370. UA_DataSetField *dsf;
  1371. size_t counter = 0;
  1372. LIST_FOREACH(dsf, &currentDataSet->fields, listEntry) {
  1373. /* Sample the value */
  1374. UA_DataValue value;
  1375. UA_DataValue_init(&value);
  1376. UA_PubSubDataSetField_sampleValue(server, dsf, &value);
  1377. /* Check if the value has changed */
  1378. if(valueChangedVariant(&dataSetWriter->lastSamples[counter].value.value, &value.value)) {
  1379. /* increase fieldCount for current delta message */
  1380. dataSetMessage->data.deltaFrameData.fieldCount++;
  1381. dataSetWriter->lastSamples[counter].valueChanged = true;
  1382. /* Update last stored sample */
  1383. UA_DataValue_deleteMembers(&dataSetWriter->lastSamples[counter].value);
  1384. dataSetWriter->lastSamples[counter].value = value;
  1385. } else {
  1386. UA_DataValue_deleteMembers(&value);
  1387. dataSetWriter->lastSamples[counter].valueChanged = false;
  1388. }
  1389. counter++;
  1390. }
  1391. /* Allocate DeltaFrameFields */
  1392. UA_DataSetMessage_DeltaFrameField *deltaFields = (UA_DataSetMessage_DeltaFrameField *)
  1393. UA_calloc(dataSetMessage->data.deltaFrameData.fieldCount, sizeof(UA_DataSetMessage_DeltaFrameField));
  1394. if(!deltaFields)
  1395. return UA_STATUSCODE_BADOUTOFMEMORY;
  1396. dataSetMessage->data.deltaFrameData.deltaFrameFields = deltaFields;
  1397. size_t currentDeltaField = 0;
  1398. for(size_t i = 0; i < currentDataSet->fieldSize; i++) {
  1399. if(!dataSetWriter->lastSamples[i].valueChanged)
  1400. continue;
  1401. UA_DataSetMessage_DeltaFrameField *dff = &deltaFields[currentDeltaField];
  1402. dff->fieldIndex = (UA_UInt16) i;
  1403. UA_DataValue_copy(&dataSetWriter->lastSamples[i].value, &dff->fieldValue);
  1404. dataSetWriter->lastSamples[i].valueChanged = false;
  1405. /* Deactivate statuscode? */
  1406. if(((u64)dataSetWriter->config.dataSetFieldContentMask & (u64)UA_DATASETFIELDCONTENTMASK_STATUSCODE) == 0)
  1407. dff->fieldValue.hasStatus = false;
  1408. /* Deactivate timestamps? */
  1409. if(((u64)dataSetWriter->config.dataSetFieldContentMask & (u64)UA_DATASETFIELDCONTENTMASK_SOURCETIMESTAMP) == 0)
  1410. dff->fieldValue.hasSourceTimestamp = false;
  1411. if(((u64)dataSetWriter->config.dataSetFieldContentMask & (u64)UA_DATASETFIELDCONTENTMASK_SOURCEPICOSECONDS) == 0)
  1412. dff->fieldValue.hasServerPicoseconds = false;
  1413. if(((u64)dataSetWriter->config.dataSetFieldContentMask & (u64)UA_DATASETFIELDCONTENTMASK_SERVERTIMESTAMP) == 0)
  1414. dff->fieldValue.hasServerTimestamp = false;
  1415. if(((u64)dataSetWriter->config.dataSetFieldContentMask & (u64)UA_DATASETFIELDCONTENTMASK_SERVERPICOSECONDS) == 0)
  1416. dff->fieldValue.hasServerPicoseconds = false;
  1417. currentDeltaField++;
  1418. }
  1419. return UA_STATUSCODE_GOOD;
  1420. }
  1421. #endif
  1422. /**
  1423. * Generate a DataSetMessage for the given writer.
  1424. *
  1425. * @param dataSetWriter ptr to corresponding writer
  1426. * @return ptr to generated DataSetMessage
  1427. */
  1428. static UA_StatusCode
  1429. UA_DataSetWriter_generateDataSetMessage(UA_Server *server, UA_DataSetMessage *dataSetMessage,
  1430. UA_DataSetWriter *dataSetWriter) {
  1431. UA_PublishedDataSet *currentDataSet =
  1432. UA_PublishedDataSet_findPDSbyId(server, dataSetWriter->connectedDataSet);
  1433. if(!currentDataSet)
  1434. return UA_STATUSCODE_BADNOTFOUND;
  1435. /* Reset the message */
  1436. memset(dataSetMessage, 0, sizeof(UA_DataSetMessage));
  1437. /* store messageType to switch between json or uadp (default) */
  1438. UA_UInt16 messageType = UA_TYPES_UADPDATASETWRITERMESSAGEDATATYPE;
  1439. UA_JsonDataSetWriterMessageDataType *jsonDataSetWriterMessageDataType = NULL;
  1440. /* The configuration Flags are included
  1441. * inside the std. defined UA_UadpDataSetWriterMessageDataType */
  1442. UA_UadpDataSetWriterMessageDataType defaultUadpConfiguration;
  1443. UA_UadpDataSetWriterMessageDataType *dataSetWriterMessageDataType = NULL;
  1444. if((dataSetWriter->config.messageSettings.encoding == UA_EXTENSIONOBJECT_DECODED ||
  1445. dataSetWriter->config.messageSettings.encoding == UA_EXTENSIONOBJECT_DECODED_NODELETE) &&
  1446. (dataSetWriter->config.messageSettings.content.decoded.type ==
  1447. &UA_TYPES[UA_TYPES_UADPDATASETWRITERMESSAGEDATATYPE])) {
  1448. dataSetWriterMessageDataType = (UA_UadpDataSetWriterMessageDataType *)
  1449. dataSetWriter->config.messageSettings.content.decoded.data;
  1450. /* type is UADP */
  1451. messageType = UA_TYPES_UADPDATASETWRITERMESSAGEDATATYPE;
  1452. } else if((dataSetWriter->config.messageSettings.encoding == UA_EXTENSIONOBJECT_DECODED ||
  1453. dataSetWriter->config.messageSettings.encoding == UA_EXTENSIONOBJECT_DECODED_NODELETE) &&
  1454. (dataSetWriter->config.messageSettings.content.decoded.type ==
  1455. &UA_TYPES[UA_TYPES_JSONDATASETWRITERMESSAGEDATATYPE])) {
  1456. jsonDataSetWriterMessageDataType = (UA_JsonDataSetWriterMessageDataType *)
  1457. dataSetWriter->config.messageSettings.content.decoded.data;
  1458. /* type is JSON */
  1459. messageType = UA_TYPES_JSONDATASETWRITERMESSAGEDATATYPE;
  1460. } else {
  1461. /* create default flag configuration if no
  1462. * UadpDataSetWriterMessageDataType was passed in */
  1463. memset(&defaultUadpConfiguration, 0, sizeof(UA_UadpDataSetWriterMessageDataType));
  1464. defaultUadpConfiguration.dataSetMessageContentMask = (UA_UadpDataSetMessageContentMask)
  1465. ((u64)UA_UADPDATASETMESSAGECONTENTMASK_TIMESTAMP | (u64)UA_UADPDATASETMESSAGECONTENTMASK_MAJORVERSION |
  1466. (u64)UA_UADPDATASETMESSAGECONTENTMASK_MINORVERSION);
  1467. dataSetWriterMessageDataType = &defaultUadpConfiguration;
  1468. }
  1469. /* Sanity-test the configuration */
  1470. if(dataSetWriterMessageDataType &&
  1471. (dataSetWriterMessageDataType->networkMessageNumber != 0 ||
  1472. dataSetWriterMessageDataType->dataSetOffset != 0 ||
  1473. dataSetWriterMessageDataType->configuredSize != 0)) {
  1474. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  1475. "Static DSM configuration not supported. Using defaults");
  1476. dataSetWriterMessageDataType->networkMessageNumber = 0;
  1477. dataSetWriterMessageDataType->dataSetOffset = 0;
  1478. dataSetWriterMessageDataType->configuredSize = 0;
  1479. }
  1480. /* The field encoding depends on the flags inside the writer config.
  1481. * TODO: This can be moved to the encoding layer. */
  1482. if(dataSetWriter->config.dataSetFieldContentMask & (u64)UA_DATASETFIELDCONTENTMASK_RAWDATA
  1483. ) {
  1484. dataSetMessage->header.fieldEncoding = UA_FIELDENCODING_RAWDATA;
  1485. } else if((u64)dataSetWriter->config.dataSetFieldContentMask &
  1486. ((u64)UA_DATASETFIELDCONTENTMASK_SOURCETIMESTAMP | (u64)UA_DATASETFIELDCONTENTMASK_SERVERPICOSECONDS |
  1487. (u64)UA_DATASETFIELDCONTENTMASK_SOURCEPICOSECONDS | (u64)UA_DATASETFIELDCONTENTMASK_STATUSCODE)) {
  1488. dataSetMessage->header.fieldEncoding = UA_FIELDENCODING_DATAVALUE;
  1489. } else {
  1490. dataSetMessage->header.fieldEncoding = UA_FIELDENCODING_VARIANT;
  1491. }
  1492. if(messageType == UA_TYPES_UADPDATASETWRITERMESSAGEDATATYPE) {
  1493. /* Std: 'The DataSetMessageContentMask defines the flags for the content of the DataSetMessage header.' */
  1494. if((u64)dataSetWriterMessageDataType->dataSetMessageContentMask &
  1495. (u64)UA_UADPDATASETMESSAGECONTENTMASK_MAJORVERSION) {
  1496. dataSetMessage->header.configVersionMajorVersionEnabled = true;
  1497. dataSetMessage->header.configVersionMajorVersion =
  1498. currentDataSet->dataSetMetaData.configurationVersion.majorVersion;
  1499. }
  1500. if((u64)dataSetWriterMessageDataType->dataSetMessageContentMask &
  1501. (u64)UA_UADPDATASETMESSAGECONTENTMASK_MINORVERSION) {
  1502. dataSetMessage->header.configVersionMinorVersionEnabled = true;
  1503. dataSetMessage->header.configVersionMinorVersion =
  1504. currentDataSet->dataSetMetaData.configurationVersion.minorVersion;
  1505. }
  1506. if((u64)dataSetWriterMessageDataType->dataSetMessageContentMask &
  1507. (u64)UA_UADPDATASETMESSAGECONTENTMASK_SEQUENCENUMBER) {
  1508. dataSetMessage->header.dataSetMessageSequenceNrEnabled = true;
  1509. dataSetMessage->header.dataSetMessageSequenceNr =
  1510. dataSetWriter->actualDataSetMessageSequenceCount;
  1511. }
  1512. if((u64)dataSetWriterMessageDataType->dataSetMessageContentMask &
  1513. (u64)UA_UADPDATASETMESSAGECONTENTMASK_TIMESTAMP) {
  1514. dataSetMessage->header.timestampEnabled = true;
  1515. dataSetMessage->header.timestamp = UA_DateTime_now();
  1516. }
  1517. /* TODO: Picoseconds resolution not supported atm */
  1518. if((u64)dataSetWriterMessageDataType->dataSetMessageContentMask &
  1519. (u64)UA_UADPDATASETMESSAGECONTENTMASK_PICOSECONDS) {
  1520. dataSetMessage->header.picoSecondsIncluded = false;
  1521. }
  1522. /* TODO: Statuscode not supported yet */
  1523. if((u64)dataSetWriterMessageDataType->dataSetMessageContentMask &
  1524. (u64)UA_UADPDATASETMESSAGECONTENTMASK_STATUS) {
  1525. dataSetMessage->header.statusEnabled = false;
  1526. }
  1527. } else if(messageType == UA_TYPES_JSONDATASETWRITERMESSAGEDATATYPE) {
  1528. if((u64)jsonDataSetWriterMessageDataType->dataSetMessageContentMask &
  1529. (u64)UA_JSONDATASETMESSAGECONTENTMASK_METADATAVERSION) {
  1530. dataSetMessage->header.configVersionMajorVersionEnabled = true;
  1531. dataSetMessage->header.configVersionMajorVersion =
  1532. currentDataSet->dataSetMetaData.configurationVersion.majorVersion;
  1533. }
  1534. if((u64)jsonDataSetWriterMessageDataType->dataSetMessageContentMask &
  1535. (u64)UA_JSONDATASETMESSAGECONTENTMASK_METADATAVERSION) {
  1536. dataSetMessage->header.configVersionMinorVersionEnabled = true;
  1537. dataSetMessage->header.configVersionMinorVersion =
  1538. currentDataSet->dataSetMetaData.configurationVersion.minorVersion;
  1539. }
  1540. if((u64)jsonDataSetWriterMessageDataType->dataSetMessageContentMask &
  1541. (u64)UA_JSONDATASETMESSAGECONTENTMASK_SEQUENCENUMBER) {
  1542. dataSetMessage->header.dataSetMessageSequenceNrEnabled = true;
  1543. dataSetMessage->header.dataSetMessageSequenceNr =
  1544. dataSetWriter->actualDataSetMessageSequenceCount;
  1545. }
  1546. if((u64)jsonDataSetWriterMessageDataType->dataSetMessageContentMask &
  1547. (u64)UA_JSONDATASETMESSAGECONTENTMASK_TIMESTAMP) {
  1548. dataSetMessage->header.timestampEnabled = true;
  1549. dataSetMessage->header.timestamp = UA_DateTime_now();
  1550. }
  1551. /* TODO: Statuscode not supported yet */
  1552. if((u64)jsonDataSetWriterMessageDataType->dataSetMessageContentMask &
  1553. (u64)UA_JSONDATASETMESSAGECONTENTMASK_STATUS) {
  1554. dataSetMessage->header.statusEnabled = false;
  1555. }
  1556. }
  1557. /* Set the sequence count. Automatically rolls over to zero */
  1558. dataSetWriter->actualDataSetMessageSequenceCount++;
  1559. /* JSON does not differ between deltaframes and keyframes, only keyframes are currently used. */
  1560. if(messageType != UA_TYPES_JSONDATASETWRITERMESSAGEDATATYPE){
  1561. #ifdef UA_ENABLE_PUBSUB_DELTAFRAMES
  1562. /* Check if the PublishedDataSet version has changed -> if yes flush the lastValue store and send a KeyFrame */
  1563. if(dataSetWriter->connectedDataSetVersion.majorVersion != currentDataSet->dataSetMetaData.configurationVersion.majorVersion ||
  1564. dataSetWriter->connectedDataSetVersion.minorVersion != currentDataSet->dataSetMetaData.configurationVersion.minorVersion) {
  1565. /* Remove old samples */
  1566. for(size_t i = 0; i < dataSetWriter->lastSamplesCount; i++)
  1567. UA_DataValue_deleteMembers(&dataSetWriter->lastSamples[i].value);
  1568. /* Realloc pds dependent memory */
  1569. dataSetWriter->lastSamplesCount = currentDataSet->fieldSize;
  1570. UA_DataSetWriterSample *newSamplesArray = (UA_DataSetWriterSample * )
  1571. UA_realloc(dataSetWriter->lastSamples, sizeof(UA_DataSetWriterSample) * dataSetWriter->lastSamplesCount);
  1572. if(!newSamplesArray)
  1573. return UA_STATUSCODE_BADOUTOFMEMORY;
  1574. dataSetWriter->lastSamples = newSamplesArray;
  1575. memset(dataSetWriter->lastSamples, 0, sizeof(UA_DataSetWriterSample) * dataSetWriter->lastSamplesCount);
  1576. dataSetWriter->connectedDataSetVersion = currentDataSet->dataSetMetaData.configurationVersion;
  1577. UA_PubSubDataSetWriter_generateKeyFrameMessage(server, dataSetMessage, dataSetWriter);
  1578. dataSetWriter->deltaFrameCounter = 0;
  1579. return UA_STATUSCODE_GOOD;
  1580. }
  1581. /* The standard defines: if a PDS contains only one fields no delta messages
  1582. * should be generated because they need more memory than a keyframe with 1
  1583. * field. */
  1584. if(currentDataSet->fieldSize > 1 && dataSetWriter->deltaFrameCounter > 0 &&
  1585. dataSetWriter->deltaFrameCounter <= dataSetWriter->config.keyFrameCount) {
  1586. UA_PubSubDataSetWriter_generateDeltaFrameMessage(server, dataSetMessage, dataSetWriter);
  1587. dataSetWriter->deltaFrameCounter++;
  1588. return UA_STATUSCODE_GOOD;
  1589. }
  1590. dataSetWriter->deltaFrameCounter = 1;
  1591. #endif
  1592. }
  1593. UA_PubSubDataSetWriter_generateKeyFrameMessage(server, dataSetMessage, dataSetWriter);
  1594. return UA_STATUSCODE_GOOD;
  1595. }
  1596. static UA_StatusCode
  1597. sendNetworkMessageJson(UA_PubSubConnection *connection, UA_DataSetMessage *dsm,
  1598. UA_UInt16 *writerIds, UA_Byte dsmCount, UA_ExtensionObject *transportSettings) {
  1599. UA_StatusCode retval = UA_STATUSCODE_BADNOTSUPPORTED;
  1600. #ifdef UA_ENABLE_JSON_ENCODING
  1601. UA_NetworkMessage nm;
  1602. memset(&nm, 0, sizeof(UA_NetworkMessage));
  1603. nm.version = 1;
  1604. nm.networkMessageType = UA_NETWORKMESSAGE_DATASET;
  1605. nm.payloadHeaderEnabled = true;
  1606. nm.payloadHeader.dataSetPayloadHeader.count = dsmCount;
  1607. nm.payloadHeader.dataSetPayloadHeader.dataSetWriterIds = writerIds;
  1608. nm.payload.dataSetPayload.dataSetMessages = dsm;
  1609. /* Allocate the buffer. Allocate on the stack if the buffer is small. */
  1610. UA_ByteString buf;
  1611. size_t msgSize = UA_NetworkMessage_calcSizeJson(&nm, NULL, 0, NULL, 0, true);
  1612. size_t stackSize = 1;
  1613. if(msgSize <= UA_MAX_STACKBUF)
  1614. stackSize = msgSize;
  1615. UA_STACKARRAY(UA_Byte, stackBuf, stackSize);
  1616. buf.data = stackBuf;
  1617. buf.length = msgSize;
  1618. if(msgSize > UA_MAX_STACKBUF) {
  1619. retval = UA_ByteString_allocBuffer(&buf, msgSize);
  1620. if(retval != UA_STATUSCODE_GOOD)
  1621. return retval;
  1622. }
  1623. /* Encode the message */
  1624. UA_Byte *bufPos = buf.data;
  1625. memset(bufPos, 0, msgSize);
  1626. const UA_Byte *bufEnd = &buf.data[buf.length];
  1627. retval = UA_NetworkMessage_encodeJson(&nm, &bufPos, &bufEnd, NULL, 0, NULL, 0, true);
  1628. if(retval != UA_STATUSCODE_GOOD) {
  1629. if(msgSize > UA_MAX_STACKBUF)
  1630. UA_ByteString_deleteMembers(&buf);
  1631. return retval;
  1632. }
  1633. /* Send the prepared messages */
  1634. retval = connection->channel->send(connection->channel, transportSettings, &buf);
  1635. if(msgSize > UA_MAX_STACKBUF)
  1636. UA_ByteString_deleteMembers(&buf);
  1637. #endif
  1638. return retval;
  1639. }
  1640. static UA_StatusCode
  1641. sendNetworkMessage(UA_PubSubConnection *connection, UA_WriterGroup *wg,
  1642. UA_DataSetMessage *dsm, UA_UInt16 *writerIds, UA_Byte dsmCount,
  1643. UA_ExtensionObject *messageSettings,
  1644. UA_ExtensionObject *transportSettings) {
  1645. if(messageSettings->content.decoded.type !=
  1646. &UA_TYPES[UA_TYPES_UADPWRITERGROUPMESSAGEDATATYPE])
  1647. return UA_STATUSCODE_BADINTERNALERROR;
  1648. UA_UadpWriterGroupMessageDataType *wgm = (UA_UadpWriterGroupMessageDataType*)
  1649. messageSettings->content.decoded.data;
  1650. UA_NetworkMessage nm;
  1651. memset(&nm, 0, sizeof(UA_NetworkMessage));
  1652. nm.publisherIdEnabled =
  1653. ((u64)wgm->networkMessageContentMask & (u64)UA_UADPNETWORKMESSAGECONTENTMASK_PUBLISHERID) != 0;
  1654. nm.groupHeaderEnabled =
  1655. ((u64)wgm->networkMessageContentMask & (u64)UA_UADPNETWORKMESSAGECONTENTMASK_GROUPHEADER) != 0;
  1656. nm.groupHeader.writerGroupIdEnabled =
  1657. ((u64)wgm->networkMessageContentMask & (u64)UA_UADPNETWORKMESSAGECONTENTMASK_WRITERGROUPID) != 0;
  1658. nm.groupHeader.groupVersionEnabled =
  1659. ((u64)wgm->networkMessageContentMask & (u64)UA_UADPNETWORKMESSAGECONTENTMASK_GROUPVERSION) != 0;
  1660. nm.groupHeader.networkMessageNumberEnabled =
  1661. ((u64)wgm->networkMessageContentMask & (u64)UA_UADPNETWORKMESSAGECONTENTMASK_NETWORKMESSAGENUMBER) != 0;
  1662. nm.groupHeader.sequenceNumberEnabled =
  1663. ((u64)wgm->networkMessageContentMask & (u64)UA_UADPNETWORKMESSAGECONTENTMASK_SEQUENCENUMBER) != 0;
  1664. nm.payloadHeaderEnabled =
  1665. ((u64)wgm->networkMessageContentMask & (u64)UA_UADPNETWORKMESSAGECONTENTMASK_PAYLOADHEADER) != 0;
  1666. nm.timestampEnabled =
  1667. ((u64)wgm->networkMessageContentMask & (u64)UA_UADPNETWORKMESSAGECONTENTMASK_TIMESTAMP) != 0;
  1668. nm.picosecondsEnabled =
  1669. ((u64)wgm->networkMessageContentMask & (u64)UA_UADPNETWORKMESSAGECONTENTMASK_PICOSECONDS) != 0;
  1670. nm.dataSetClassIdEnabled =
  1671. ((u64)wgm->networkMessageContentMask & (u64)UA_UADPNETWORKMESSAGECONTENTMASK_DATASETCLASSID) != 0;
  1672. nm.promotedFieldsEnabled =
  1673. ((u64)wgm->networkMessageContentMask & (u64)UA_UADPNETWORKMESSAGECONTENTMASK_PROMOTEDFIELDS) != 0;
  1674. nm.version = 1;
  1675. nm.networkMessageType = UA_NETWORKMESSAGE_DATASET;
  1676. if(connection->config->publisherIdType == UA_PUBSUB_PUBLISHERID_NUMERIC) {
  1677. nm.publisherIdType = UA_PUBLISHERDATATYPE_UINT16;
  1678. nm.publisherId.publisherIdUInt32 = connection->config->publisherId.numeric;
  1679. } else if(connection->config->publisherIdType == UA_PUBSUB_PUBLISHERID_STRING){
  1680. nm.publisherIdType = UA_PUBLISHERDATATYPE_STRING;
  1681. nm.publisherId.publisherIdString = connection->config->publisherId.string;
  1682. }
  1683. /* Compute the length of the dsm separately for the header */
  1684. UA_STACKARRAY(UA_UInt16, dsmLengths, dsmCount);
  1685. for(UA_Byte i = 0; i < dsmCount; i++)
  1686. dsmLengths[i] = (UA_UInt16)UA_DataSetMessage_calcSizeBinary(&dsm[i]);
  1687. nm.payloadHeader.dataSetPayloadHeader.count = dsmCount;
  1688. nm.payloadHeader.dataSetPayloadHeader.dataSetWriterIds = writerIds;
  1689. nm.groupHeader.writerGroupId = wg->config.writerGroupId;
  1690. nm.groupHeader.networkMessageNumber = 1;
  1691. nm.payload.dataSetPayload.sizes = dsmLengths;
  1692. nm.payload.dataSetPayload.dataSetMessages = dsm;
  1693. /* Allocate the buffer. Allocate on the stack if the buffer is small. */
  1694. UA_ByteString buf;
  1695. size_t msgSize = UA_NetworkMessage_calcSizeBinary(&nm);
  1696. size_t stackSize = 1;
  1697. if(msgSize <= UA_MAX_STACKBUF)
  1698. stackSize = msgSize;
  1699. UA_STACKARRAY(UA_Byte, stackBuf, stackSize);
  1700. buf.data = stackBuf;
  1701. buf.length = msgSize;
  1702. UA_StatusCode retval;
  1703. if(msgSize > UA_MAX_STACKBUF) {
  1704. retval = UA_ByteString_allocBuffer(&buf, msgSize);
  1705. if(retval != UA_STATUSCODE_GOOD)
  1706. return retval;
  1707. }
  1708. /* Encode the message */
  1709. UA_Byte *bufPos = buf.data;
  1710. memset(bufPos, 0, msgSize);
  1711. const UA_Byte *bufEnd = &buf.data[buf.length];
  1712. retval = UA_NetworkMessage_encodeBinary(&nm, &bufPos, bufEnd);
  1713. if(retval != UA_STATUSCODE_GOOD) {
  1714. if(msgSize > UA_MAX_STACKBUF)
  1715. UA_ByteString_deleteMembers(&buf);
  1716. return retval;
  1717. }
  1718. /* Send the prepared messages */
  1719. retval = connection->channel->send(connection->channel, transportSettings, &buf);
  1720. if(msgSize > UA_MAX_STACKBUF)
  1721. UA_ByteString_deleteMembers(&buf);
  1722. return retval;
  1723. }
  1724. /* This callback triggers the collection and publish of NetworkMessages and the
  1725. * contained DataSetMessages. */
  1726. void
  1727. UA_WriterGroup_publishCallback(UA_Server *server, UA_WriterGroup *writerGroup) {
  1728. UA_LOG_DEBUG(&server->config.logger, UA_LOGCATEGORY_SERVER, "Publish Callback");
  1729. if(!writerGroup) {
  1730. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  1731. "Publish failed. WriterGroup not found");
  1732. return;
  1733. }
  1734. /* Nothing to do? */
  1735. if(writerGroup->writersCount <= 0)
  1736. return;
  1737. /* Binary or Json encoding? */
  1738. if(writerGroup->config.encodingMimeType != UA_PUBSUB_ENCODING_UADP &&
  1739. writerGroup->config.encodingMimeType != UA_PUBSUB_ENCODING_JSON) {
  1740. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  1741. "Publish failed: Unknown encoding type.");
  1742. return;
  1743. }
  1744. /* Find the connection associated with the writer */
  1745. UA_PubSubConnection *connection =
  1746. UA_PubSubConnection_findConnectionbyId(server, writerGroup->linkedConnection);
  1747. if(!connection) {
  1748. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  1749. "Publish failed. PubSubConnection invalid.");
  1750. return;
  1751. }
  1752. /* How many DSM can be sent in one NM? */
  1753. UA_Byte maxDSM = (UA_Byte)writerGroup->config.maxEncapsulatedDataSetMessageCount;
  1754. if(writerGroup->config.maxEncapsulatedDataSetMessageCount > UA_BYTE_MAX)
  1755. maxDSM = UA_BYTE_MAX;
  1756. /* If the maxEncapsulatedDataSetMessageCount is set to 0->1 */
  1757. if(maxDSM == 0)
  1758. maxDSM = 1;
  1759. /* It is possible to put several DataSetMessages into one NetworkMessage.
  1760. * But only if they do not contain promoted fields. NM with only DSM are
  1761. * sent out right away. The others are kept in a buffer for "batching". */
  1762. size_t dsmCount = 0;
  1763. UA_DataSetWriter *dsw;
  1764. UA_STACKARRAY(UA_UInt16, dsWriterIds, writerGroup->writersCount);
  1765. UA_STACKARRAY(UA_DataSetMessage, dsmStore, writerGroup->writersCount);
  1766. LIST_FOREACH(dsw, &writerGroup->writers, listEntry) {
  1767. /* Find the dataset */
  1768. UA_PublishedDataSet *pds =
  1769. UA_PublishedDataSet_findPDSbyId(server, dsw->connectedDataSet);
  1770. if(!pds) {
  1771. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  1772. "PubSub Publish: PublishedDataSet not found");
  1773. continue;
  1774. }
  1775. /* Generate the DSM */
  1776. UA_StatusCode res =
  1777. UA_DataSetWriter_generateDataSetMessage(server, &dsmStore[dsmCount], dsw);
  1778. if(res != UA_STATUSCODE_GOOD) {
  1779. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  1780. "PubSub Publish: DataSetMessage creation failed");
  1781. continue;
  1782. }
  1783. /* Send right away if there is only this DSM in a NM. If promoted fields
  1784. * are contained in the PublishedDataSet, then this DSM must go into a
  1785. * dedicated NM as well. */
  1786. if(pds->promotedFieldsCount > 0 || maxDSM == 1) {
  1787. if(writerGroup->config.encodingMimeType == UA_PUBSUB_ENCODING_UADP){
  1788. res = sendNetworkMessage(connection, writerGroup, &dsmStore[dsmCount],
  1789. &dsw->config.dataSetWriterId, 1,
  1790. &writerGroup->config.messageSettings,
  1791. &writerGroup->config.transportSettings);
  1792. }else if(writerGroup->config.encodingMimeType == UA_PUBSUB_ENCODING_JSON){
  1793. res = sendNetworkMessageJson(connection, &dsmStore[dsmCount],
  1794. &dsw->config.dataSetWriterId, 1, &writerGroup->config.transportSettings);
  1795. }
  1796. if(res != UA_STATUSCODE_GOOD)
  1797. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  1798. "PubSub Publish: Could not send a NetworkMessage");
  1799. UA_DataSetMessage_free(&dsmStore[dsmCount]);
  1800. continue;
  1801. }
  1802. dsWriterIds[dsmCount] = dsw->config.dataSetWriterId;
  1803. dsmCount++;
  1804. }
  1805. /* Send the NetworkMessages with batched DataSetMessages */
  1806. size_t nmCount = (dsmCount / maxDSM) + ((dsmCount % maxDSM) == 0 ? 0 : 1);
  1807. for(UA_UInt32 i = 0; i < nmCount; i++) {
  1808. UA_Byte nmDsmCount = maxDSM;
  1809. if(i == nmCount - 1 && (dsmCount % maxDSM))
  1810. nmDsmCount = (UA_Byte)dsmCount % maxDSM;
  1811. UA_StatusCode res3 = UA_STATUSCODE_GOOD;
  1812. if(writerGroup->config.encodingMimeType == UA_PUBSUB_ENCODING_UADP){
  1813. res3 = sendNetworkMessage(connection, writerGroup, &dsmStore[i * maxDSM],
  1814. &dsWriterIds[i * maxDSM], nmDsmCount,
  1815. &writerGroup->config.messageSettings,
  1816. &writerGroup->config.transportSettings);
  1817. }else if(writerGroup->config.encodingMimeType == UA_PUBSUB_ENCODING_JSON){
  1818. res3 = sendNetworkMessageJson(connection, &dsmStore[i * maxDSM],
  1819. &dsWriterIds[i * maxDSM], nmDsmCount, &writerGroup->config.transportSettings);
  1820. }
  1821. if(res3 != UA_STATUSCODE_GOOD)
  1822. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER,
  1823. "PubSub Publish: Sending a NetworkMessage failed");
  1824. }
  1825. /* Clean up DSM */
  1826. for(size_t i = 0; i < dsmCount; i++)
  1827. UA_DataSetMessage_free(&dsmStore[i]);
  1828. }
  1829. /* Add new publishCallback. The first execution is triggered directly after
  1830. * creation. */
  1831. UA_StatusCode
  1832. UA_WriterGroup_addPublishCallback(UA_Server *server, UA_WriterGroup *writerGroup) {
  1833. UA_StatusCode retval =
  1834. UA_PubSubManager_addRepeatedCallback(server,
  1835. (UA_ServerCallback) UA_WriterGroup_publishCallback,
  1836. writerGroup, writerGroup->config.publishingInterval,
  1837. &writerGroup->publishCallbackId);
  1838. if(retval == UA_STATUSCODE_GOOD)
  1839. writerGroup->publishCallbackIsRegistered = true;
  1840. /* Run once after creation */
  1841. UA_WriterGroup_publishCallback(server, writerGroup);
  1842. return retval;
  1843. }
  1844. /* This callback triggers the collection and reception of NetworkMessages and the
  1845. * contained DataSetMessages. */
  1846. void UA_ReaderGroup_subscribeCallback(UA_Server *server, UA_ReaderGroup *readerGroup) {
  1847. UA_PubSubConnection *connection = UA_PubSubConnection_findConnectionbyId(server, readerGroup->linkedConnection);
  1848. UA_ByteString buffer;
  1849. if(UA_ByteString_allocBuffer(&buffer, 512) != UA_STATUSCODE_GOOD) {
  1850. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_SERVER, "Message buffer alloc failed!");
  1851. return;
  1852. }
  1853. connection->channel->receive(connection->channel, &buffer, NULL, 300000);
  1854. if(buffer.length > 0) {
  1855. UA_LOG_INFO(&server->config.logger, UA_LOGCATEGORY_USERLAND, "Message received:");
  1856. UA_NetworkMessage currentNetworkMessage;
  1857. memset(&currentNetworkMessage, 0, sizeof(UA_NetworkMessage));
  1858. size_t currentPosition = 0;
  1859. UA_NetworkMessage_decodeBinary(&buffer, &currentPosition, &currentNetworkMessage);
  1860. UA_Server_processNetworkMessage(server, &currentNetworkMessage, connection);
  1861. UA_NetworkMessage_deleteMembers(&currentNetworkMessage);
  1862. }
  1863. UA_ByteString_deleteMembers(&buffer);
  1864. }
  1865. /* Add new subscribeCallback. The first execution is triggered directly after
  1866. * creation. */
  1867. UA_StatusCode
  1868. UA_ReaderGroup_addSubscribeCallback(UA_Server *server, UA_ReaderGroup *readerGroup) {
  1869. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  1870. UA_PubSubConnection *connection = UA_PubSubConnection_findConnectionbyId(server, readerGroup->linkedConnection);
  1871. if(connection != NULL) {
  1872. retval = connection->channel->regist(connection->channel, NULL, NULL);
  1873. if(retval == UA_STATUSCODE_GOOD) {
  1874. retval = UA_PubSubManager_addRepeatedCallback(server,
  1875. (UA_ServerCallback) UA_ReaderGroup_subscribeCallback,
  1876. readerGroup, 5,
  1877. &readerGroup->subscribeCallbackId);
  1878. }
  1879. else {
  1880. UA_LOG_WARNING(&server->config.logger, UA_LOGCATEGORY_SERVER, "register channel failed: 0x%x!", retval);
  1881. }
  1882. }
  1883. if(retval == UA_STATUSCODE_GOOD) {
  1884. readerGroup->subscribeCallbackIsRegistered = true;
  1885. }
  1886. /* Run once after creation */
  1887. UA_ReaderGroup_subscribeCallback(server, readerGroup);
  1888. return retval;
  1889. }
  1890. #endif /* UA_ENABLE_PUBSUB */