server.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /*
  2. * This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  3. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information.
  4. */
  5. //to compile with single file releases:
  6. // * single-threaded: gcc -std=c99 server.c open62541.c -o server
  7. // * multi-threaded: gcc -std=c99 server.c open62541.c -o server -lurcu-cds -lurcu -lurcu-common -lpthread
  8. #ifdef UA_NO_AMALGAMATION
  9. # include <time.h>
  10. # include "ua_types.h"
  11. # include "ua_server.h"
  12. # include "logger_stdout.h"
  13. # include "networklayer_tcp.h"
  14. #else
  15. # include "open62541.h"
  16. #endif
  17. #include <signal.h>
  18. #include <errno.h> // errno, EINTR
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #ifdef _MSC_VER
  23. # include <io.h> //access
  24. #else
  25. # include <unistd.h> //access
  26. #endif
  27. #ifdef UA_MULTITHREADING
  28. # ifdef UA_NO_AMALGAMATION
  29. # ifndef __USE_XOPEN2K
  30. # define __USE_XOPEN2K
  31. # endif
  32. # endif
  33. #include <pthread.h>
  34. #endif
  35. /****************************/
  36. /* Server-related variables */
  37. /****************************/
  38. UA_Boolean running = 1;
  39. UA_Logger logger;
  40. /*************************/
  41. /* Read-only data source */
  42. /*************************/
  43. static UA_StatusCode readTimeData(void *handle, UA_Boolean sourceTimeStamp, const UA_NumericRange *range, UA_DataValue *value) {
  44. if(range) {
  45. value->hasStatus = UA_TRUE;
  46. value->status = UA_STATUSCODE_BADINDEXRANGEINVALID;
  47. return UA_STATUSCODE_GOOD;
  48. }
  49. UA_DateTime *currentTime = UA_DateTime_new();
  50. if(!currentTime)
  51. return UA_STATUSCODE_BADOUTOFMEMORY;
  52. *currentTime = UA_DateTime_now();
  53. value->value.type = &UA_TYPES[UA_TYPES_DATETIME];
  54. value->value.arrayLength = -1;
  55. value->value.data = currentTime;
  56. value->hasValue = UA_TRUE;
  57. if(sourceTimeStamp) {
  58. value->hasSourceTimestamp = UA_TRUE;
  59. value->sourceTimestamp = *currentTime;
  60. }
  61. return UA_STATUSCODE_GOOD;
  62. }
  63. /*****************************/
  64. /* Read-only CPU temperature */
  65. /* Only on Linux */
  66. /*****************************/
  67. FILE* temperatureFile = NULL;
  68. static UA_StatusCode readTemperature(void *handle, UA_Boolean sourceTimeStamp, const UA_NumericRange *range, UA_DataValue *value) {
  69. if(range) {
  70. value->hasStatus = UA_TRUE;
  71. value->status = UA_STATUSCODE_BADINDEXRANGEINVALID;
  72. return UA_STATUSCODE_GOOD;
  73. }
  74. UA_Double* currentTemperature = UA_Double_new();
  75. if(!currentTemperature)
  76. return UA_STATUSCODE_BADOUTOFMEMORY;
  77. rewind(temperatureFile);
  78. fflush(temperatureFile);
  79. if(fscanf(temperatureFile, "%lf", currentTemperature) != 1){
  80. UA_LOG_WARNING(logger, UA_LOGCATEGORY_USERLAND, "Can not parse temperature");
  81. exit(1);
  82. }
  83. *currentTemperature /= 1000.0;
  84. value->sourceTimestamp = UA_DateTime_now();
  85. value->hasSourceTimestamp = UA_TRUE;
  86. value->value.type = &UA_TYPES[UA_TYPES_DOUBLE];
  87. value->value.arrayLength = -1;
  88. value->value.data = currentTemperature;
  89. value->value.arrayDimensionsSize = -1;
  90. value->value.arrayDimensions = NULL;
  91. value->hasValue = UA_TRUE;
  92. return UA_STATUSCODE_GOOD;
  93. }
  94. /*************************/
  95. /* Read-write status led */
  96. /*************************/
  97. #ifdef UA_MULTITHREADING
  98. pthread_rwlock_t writeLock;
  99. #endif
  100. FILE* triggerFile = NULL;
  101. FILE* ledFile = NULL;
  102. UA_Boolean ledStatus = 0;
  103. static UA_StatusCode readLedStatus(void *handle, UA_Boolean sourceTimeStamp, const UA_NumericRange *range, UA_DataValue *value) {
  104. if(range)
  105. return UA_STATUSCODE_BADINDEXRANGEINVALID;
  106. value->hasValue = UA_TRUE;
  107. UA_StatusCode retval = UA_Variant_setScalarCopy(&value->value, &ledStatus, &UA_TYPES[UA_TYPES_BOOLEAN]);
  108. if(retval != UA_STATUSCODE_GOOD)
  109. return retval;
  110. if(sourceTimeStamp) {
  111. value->sourceTimestamp = UA_DateTime_now();
  112. value->hasSourceTimestamp = UA_TRUE;
  113. }
  114. return UA_STATUSCODE_GOOD;
  115. }
  116. static UA_StatusCode writeLedStatus(void *handle, const UA_Variant *data, const UA_NumericRange *range) {
  117. if(range)
  118. return UA_STATUSCODE_BADINDEXRANGEINVALID;
  119. #ifdef UA_MULTITHREADING
  120. pthread_rwlock_wrlock(&writeLock);
  121. #endif
  122. if(data->data)
  123. ledStatus = *(UA_Boolean*)data->data;
  124. if(triggerFile)
  125. fseek(triggerFile, 0, SEEK_SET);
  126. if(ledFile) {
  127. if(ledStatus == 1)
  128. fprintf(ledFile, "%s", "1");
  129. else
  130. fprintf(ledFile, "%s", "0");
  131. fflush(ledFile);
  132. }
  133. #ifdef UA_MULTITHREADING
  134. pthread_rwlock_unlock(&writeLock);
  135. #endif
  136. return UA_STATUSCODE_GOOD;
  137. }
  138. #ifdef ENABLE_METHODCALLS
  139. static UA_StatusCode getMonitoredItems(const UA_NodeId objectId, const UA_Variant *input, UA_Variant *output, void *handle) {
  140. UA_String tmp = UA_STRING("Hello World");
  141. //UA_Server *theServer = (UA_Server *) handle; // Commented, would result in "unused variable" error
  142. UA_Variant_setScalarCopy(output, &tmp, &UA_TYPES[UA_TYPES_STRING]);
  143. printf("getMonitoredItems was called\n");
  144. return UA_STATUSCODE_GOOD;
  145. }
  146. #endif
  147. static void stopHandler(int sign) {
  148. UA_LOG_INFO(logger, UA_LOGCATEGORY_SERVER, "Received Ctrl-C\n");
  149. running = 0;
  150. }
  151. static UA_ByteString loadCertificate(void) {
  152. UA_ByteString certificate = UA_STRING_NULL;
  153. FILE *fp = NULL;
  154. if(!(fp=fopen("server_cert.der", "rb"))) {
  155. errno = 0; // we read errno also from the tcp layer...
  156. return certificate;
  157. }
  158. fseek(fp, 0, SEEK_END);
  159. certificate.length = ftell(fp);
  160. certificate.data = malloc(certificate.length*sizeof(UA_Byte));
  161. if(!certificate.data){
  162. fclose(fp);
  163. return certificate;
  164. }
  165. fseek(fp, 0, SEEK_SET);
  166. if(fread(certificate.data, sizeof(UA_Byte), certificate.length, fp) < (size_t)certificate.length)
  167. UA_ByteString_deleteMembers(&certificate); // error reading the cert
  168. fclose(fp);
  169. return certificate;
  170. }
  171. UA_StatusCode nodeIter(UA_NodeId childId, UA_Boolean isInverse, UA_NodeId referenceTypeId, void *handle);
  172. UA_StatusCode nodeIter(UA_NodeId childId, UA_Boolean isInverse, UA_NodeId referenceTypeId, void *handle) {
  173. /*printf("References ns=%d;i=%d using i=%d ", childId.namespaceIndex, childId.identifier.numeric, referenceTypeId.identifier.numeric);
  174. if (isInverse == UA_TRUE) {
  175. printf(" (inverse)");
  176. }
  177. printf("\n");*/
  178. return UA_STATUSCODE_GOOD;
  179. }
  180. int main(int argc, char** argv) {
  181. signal(SIGINT, stopHandler); /* catches ctrl-c */
  182. #ifdef UA_MULTITHREADING
  183. pthread_rwlock_init(&writeLock, 0);
  184. #endif
  185. UA_Server *server = UA_Server_new(UA_ServerConfig_standard);
  186. logger = Logger_Stdout_new();
  187. UA_Server_setLogger(server, logger);
  188. UA_ByteString certificate = loadCertificate();
  189. UA_Server_setServerCertificate(server, certificate);
  190. UA_ByteString_deleteMembers(&certificate);
  191. UA_Server_addNetworkLayer(server, ServerNetworkLayerTCP_new(UA_ConnectionConfig_standard, 16664));
  192. // add node with the datetime data source
  193. UA_NodeId nodeId_currentTime;
  194. UA_DataSource dateDataSource = (UA_DataSource) {.handle = NULL, .read = readTimeData, .write = NULL};
  195. const UA_QualifiedName dateName = UA_QUALIFIEDNAME(1, "current time");
  196. const UA_LocalizedText dateNameBrowseName = UA_LOCALIZEDTEXT("en_US","current time");
  197. UA_Server_addDataSourceVariableNode(server, UA_NODEID_NULL, dateName, dateNameBrowseName, dateNameBrowseName, 0, 0,
  198. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  199. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  200. dateDataSource,
  201. &nodeId_currentTime);
  202. // Get and reattach the datasource
  203. UA_DataSource *dataSourceCopy = NULL;
  204. UA_Server_getAttribute_DataSource(server, nodeId_currentTime, &dataSourceCopy);
  205. if (dataSourceCopy == NULL)
  206. UA_LOG_WARNING(logger, UA_LOGCATEGORY_USERLAND, "The returned dataSource is invalid");
  207. else if (dataSourceCopy->read != dateDataSource.read)
  208. UA_LOG_WARNING(logger, UA_LOGCATEGORY_USERLAND, "The returned dataSource is not the same as we set?");
  209. else
  210. UA_Server_setAttribute_DataSource(server, nodeId_currentTime, dataSourceCopy);
  211. free(dataSourceCopy);
  212. #ifndef _WIN32
  213. //cpu temperature monitoring for linux machines
  214. if((temperatureFile = fopen("/sys/class/thermal/thermal_zone0/temp", "r"))) {
  215. // add node with the data source
  216. UA_DataSource temperatureDataSource = (UA_DataSource) {.handle = NULL, .read = readTemperature, .write = NULL};
  217. const UA_QualifiedName tempName = UA_QUALIFIEDNAME(1, "cpu temperature");
  218. const UA_LocalizedText tempNameBrowseName = UA_LOCALIZEDTEXT("en_US","temperature");
  219. UA_Server_addDataSourceVariableNode(server, UA_NODEID_NULL, tempName, tempNameBrowseName, tempNameBrowseName, 0, 0,
  220. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  221. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  222. temperatureDataSource,
  223. NULL);
  224. }
  225. //LED control for rpi
  226. if(access("/sys/class/leds/led0/trigger", F_OK ) != -1 || access("/sys/class/leds/led0/brightness", F_OK ) != -1) {
  227. if((triggerFile = fopen("/sys/class/leds/led0/trigger", "w")) && (ledFile = fopen("/sys/class/leds/led0/brightness", "w"))) {
  228. //setting led mode to manual
  229. fprintf(triggerFile, "%s", "none");
  230. fflush(triggerFile);
  231. //turning off led initially
  232. fprintf(ledFile, "%s", "1");
  233. fflush(ledFile);
  234. // add node with the LED status data source
  235. UA_DataSource ledStatusDataSource = (UA_DataSource) {.handle = NULL, .read = readLedStatus, .write = writeLedStatus};
  236. const UA_QualifiedName statusName = UA_QUALIFIEDNAME(0, "status LED");
  237. const UA_LocalizedText statusNameBrowseName = UA_LOCALIZEDTEXT("en_US","status LED");
  238. UA_Server_addDataSourceVariableNode(server, UA_NODEID_NULL, statusName, statusNameBrowseName, statusNameBrowseName, 0, 0,
  239. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  240. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  241. ledStatusDataSource,
  242. NULL);
  243. } else {
  244. UA_LOG_WARNING(logger, UA_LOGCATEGORY_USERLAND, "[Raspberry Pi] LED file exist, but I have no access (try to run server with sudo)");
  245. }
  246. }
  247. #endif
  248. // add a static variable node to the adresspace
  249. UA_Variant *myIntegerVariant = UA_Variant_new();
  250. UA_Int32 myInteger = 42;
  251. UA_Variant_setScalarCopy(myIntegerVariant, &myInteger, &UA_TYPES[UA_TYPES_INT32]);
  252. const UA_QualifiedName myIntegerName = UA_QUALIFIEDNAME(1, "the answer");
  253. const UA_NodeId myIntegerNodeId = UA_NODEID_STRING(1, "the.answer");
  254. UA_NodeId parentNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER);
  255. UA_NodeId parentReferenceNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES);
  256. UA_Server_addVariableNode(server, myIntegerNodeId, myIntegerName, UA_LOCALIZEDTEXT("en_US", "the answer"), UA_LOCALIZEDTEXT("en_US", "the answer"), 0, 0,
  257. parentNodeId, parentReferenceNodeId, myIntegerVariant, NULL);
  258. /**************/
  259. /* Demo Nodes */
  260. /**************/
  261. #define DEMOID 50000
  262. UA_Server_addObjectNode(server, UA_NODEID_NUMERIC(1, DEMOID), UA_QUALIFIEDNAME(1, "Demo"), UA_LOCALIZEDTEXT("en_US","Demo"),
  263. UA_LOCALIZEDTEXT("en_US","Demo"), 0, 0, UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  264. UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE), NULL);
  265. #define SCALARID 50001
  266. UA_Server_addObjectNode(server, UA_NODEID_NUMERIC(1, SCALARID), UA_QUALIFIEDNAME(1, "Scalar"), UA_LOCALIZEDTEXT("en_US","Scalar"),
  267. UA_LOCALIZEDTEXT("en_US","Scalar"), 0, 0, UA_NODEID_NUMERIC(1, DEMOID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  268. UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE), NULL);
  269. #define ARRAYID 50002
  270. UA_Server_addObjectNode(server, UA_NODEID_NUMERIC(1, ARRAYID), UA_QUALIFIEDNAME(1, "Array"), UA_LOCALIZEDTEXT("en_US","Array"),
  271. UA_LOCALIZEDTEXT("en_US","Array"), 0, 0, UA_NODEID_NUMERIC(1, DEMOID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  272. UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE), NULL);
  273. #define MATRIXID 50003
  274. UA_Server_addObjectNode(server, UA_NODEID_NUMERIC(1, MATRIXID), UA_QUALIFIEDNAME(1, "Matrix"), UA_LOCALIZEDTEXT("en_US","Matrix"),
  275. UA_LOCALIZEDTEXT("en_US","Matrix"), 0, 0, UA_NODEID_NUMERIC(1, DEMOID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  276. UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE), NULL);
  277. UA_UInt32 id = 51000; //running id in namespace 0
  278. for(UA_UInt32 type = 0; UA_IS_BUILTIN(type); type++) {
  279. if(type == UA_TYPES_VARIANT || type == UA_TYPES_DIAGNOSTICINFO)
  280. continue;
  281. //add a scalar node for every built-in type
  282. void *value = UA_new(&UA_TYPES[type]);
  283. UA_Variant *variant = UA_Variant_new();
  284. UA_Variant_setScalar(variant, value, &UA_TYPES[type]);
  285. char name[15];
  286. sprintf(name, "%02d", type);
  287. UA_QualifiedName qualifiedName = UA_QUALIFIEDNAME(1, name);
  288. UA_Server_addVariableNode(server, UA_NODEID_NUMERIC(1, ++id), qualifiedName, UA_LOCALIZEDTEXT("en_US",name), UA_LOCALIZEDTEXT("en_US",name), 0, 0,
  289. UA_NODEID_NUMERIC(1, SCALARID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), variant, NULL);
  290. //add an array node for every built-in type
  291. UA_Variant *arrayvar = UA_Variant_new();
  292. UA_Variant_setArray(arrayvar, UA_Array_new(&UA_TYPES[type], 10), 10, &UA_TYPES[type]);
  293. UA_Server_addVariableNode(server, UA_NODEID_NUMERIC(1, ++id), qualifiedName, UA_LOCALIZEDTEXT("en_US",name), UA_LOCALIZEDTEXT("en_US",name), 0, 0,
  294. UA_NODEID_NUMERIC(1, ARRAYID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), arrayvar, NULL);
  295. //add an matrix node for every built-in type
  296. arrayvar = UA_Variant_new();
  297. void* myMultiArray = UA_Array_new(&UA_TYPES[type],9);
  298. arrayvar->arrayDimensions = UA_Array_new(&UA_TYPES[UA_TYPES_INT32],2);
  299. arrayvar->arrayDimensions[0] = 3;
  300. arrayvar->arrayDimensions[1] = 3;
  301. arrayvar->arrayDimensionsSize = 2;
  302. arrayvar->arrayLength = 9;
  303. arrayvar->data = myMultiArray;
  304. arrayvar->type = &UA_TYPES[type];
  305. UA_Server_addVariableNode(server, UA_NODEID_NUMERIC(1, ++id), qualifiedName, UA_LOCALIZEDTEXT("en_US",""), UA_LOCALIZEDTEXT("en_US",""),
  306. 0, 0, UA_NODEID_NUMERIC(1, MATRIXID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), arrayvar, NULL);
  307. }
  308. #ifdef ENABLE_METHODCALLS
  309. UA_Argument inputArguments;
  310. UA_Argument_init(&inputArguments);
  311. inputArguments.arrayDimensionsSize = -1;
  312. inputArguments.arrayDimensions = NULL;
  313. inputArguments.dataType = UA_TYPES[UA_TYPES_STRING].typeId;
  314. inputArguments.description = UA_LOCALIZEDTEXT("en_US", "A String");
  315. inputArguments.name = UA_STRING("Input an integer");
  316. inputArguments.valueRank = -1;
  317. UA_Argument outputArguments;
  318. UA_Argument_init(&outputArguments);
  319. outputArguments.arrayDimensionsSize = -1;
  320. outputArguments.arrayDimensions = NULL;
  321. outputArguments.dataType = UA_TYPES[UA_TYPES_STRING].typeId;
  322. outputArguments.description = UA_LOCALIZEDTEXT("en_US", "A String");
  323. outputArguments.name = UA_STRING("Input an integer");
  324. outputArguments.valueRank = -1;
  325. UA_NodeId methodId; // Retrieve the actual ID if this node if a random id as in UA_NODEID_NUMERIC(1,0) is used
  326. UA_Server_addMethodNode(server, UA_NODEID_NUMERIC(1,62541), UA_QUALIFIEDNAME(1,"ping"), UA_LOCALIZEDTEXT("en_US", "ping"),
  327. UA_LOCALIZEDTEXT("en_US", "Return a single argument as passed by the caller"),
  328. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
  329. 0, 0,
  330. &getMonitoredItems, // Call this method
  331. (void *) server, // Pass our server pointer as a handle to the method
  332. 1, &inputArguments, 1, &outputArguments, &methodId);
  333. // Dettach the method from the methodNode
  334. UA_Server_setAttribute_method(server, UA_NODEID_NUMERIC(1,62541), NULL, NULL);
  335. // Reaettach the method from the methodNode
  336. UA_Server_setAttribute_method(server, UA_NODEID_NUMERIC(1,62541), &getMonitoredItems, (void *) server);
  337. #endif
  338. // Example for iterating over all nodes referenced by "Objects":
  339. //printf("Nodes connected to 'Objects':\n=============================\n");
  340. UA_Server_forEachChildNodeCall(server, UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), nodeIter, NULL);
  341. // Some easy localization
  342. UA_LocalizedText objectsName = UA_LOCALIZEDTEXT("de_DE", "Objekte");
  343. UA_Server_setAttribute_displayName(server, UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), &objectsName);
  344. //start server
  345. UA_StatusCode retval = UA_Server_run(server, 1, &running); //blocks until running=false
  346. //ctrl-c received -> clean up
  347. UA_Server_delete(server);
  348. if(temperatureFile)
  349. fclose(temperatureFile);
  350. if(triggerFile) {
  351. fseek(triggerFile, 0, SEEK_SET);
  352. //setting led mode to default
  353. fprintf(triggerFile, "%s", "mmc0");
  354. fclose(triggerFile);
  355. }
  356. if(ledFile)
  357. fclose(ledFile);
  358. #ifdef UA_MULTITHREADING
  359. pthread_rwlock_destroy(&writeLock);
  360. #endif
  361. return retval;
  362. }