server.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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
  44. readTimeData(void *handle, const UA_NodeId nodeId, UA_Boolean sourceTimeStamp,
  45. const UA_NumericRange *range, UA_DataValue *value) {
  46. if(range) {
  47. value->hasStatus = UA_TRUE;
  48. value->status = UA_STATUSCODE_BADINDEXRANGEINVALID;
  49. return UA_STATUSCODE_GOOD;
  50. }
  51. UA_DateTime *currentTime = UA_DateTime_new();
  52. if(!currentTime)
  53. return UA_STATUSCODE_BADOUTOFMEMORY;
  54. *currentTime = UA_DateTime_now();
  55. value->value.type = &UA_TYPES[UA_TYPES_DATETIME];
  56. value->value.arrayLength = -1;
  57. value->value.data = currentTime;
  58. value->hasValue = UA_TRUE;
  59. if(sourceTimeStamp) {
  60. value->hasSourceTimestamp = UA_TRUE;
  61. value->sourceTimestamp = *currentTime;
  62. }
  63. return UA_STATUSCODE_GOOD;
  64. }
  65. /*****************************/
  66. /* Read-only CPU temperature */
  67. /* Only on Linux */
  68. /*****************************/
  69. FILE* temperatureFile = NULL;
  70. static UA_StatusCode
  71. readTemperature(void *handle, const UA_NodeId nodeId, UA_Boolean sourceTimeStamp,
  72. const UA_NumericRange *range, UA_DataValue *value) {
  73. if(range) {
  74. value->hasStatus = UA_TRUE;
  75. value->status = UA_STATUSCODE_BADINDEXRANGEINVALID;
  76. return UA_STATUSCODE_GOOD;
  77. }
  78. UA_Double* currentTemperature = UA_Double_new();
  79. if(!currentTemperature)
  80. return UA_STATUSCODE_BADOUTOFMEMORY;
  81. rewind(temperatureFile);
  82. fflush(temperatureFile);
  83. if(fscanf(temperatureFile, "%lf", currentTemperature) != 1){
  84. UA_LOG_WARNING(logger, UA_LOGCATEGORY_USERLAND, "Can not parse temperature");
  85. exit(1);
  86. }
  87. *currentTemperature /= 1000.0;
  88. value->sourceTimestamp = UA_DateTime_now();
  89. value->hasSourceTimestamp = UA_TRUE;
  90. value->value.type = &UA_TYPES[UA_TYPES_DOUBLE];
  91. value->value.arrayLength = -1;
  92. value->value.data = currentTemperature;
  93. value->value.arrayDimensionsSize = -1;
  94. value->value.arrayDimensions = NULL;
  95. value->hasValue = UA_TRUE;
  96. return UA_STATUSCODE_GOOD;
  97. }
  98. /*************************/
  99. /* Read-write status led */
  100. /*************************/
  101. #ifdef UA_MULTITHREADING
  102. pthread_rwlock_t writeLock;
  103. #endif
  104. FILE* triggerFile = NULL;
  105. FILE* ledFile = NULL;
  106. UA_Boolean ledStatus = 0;
  107. static UA_StatusCode
  108. readLedStatus(void *handle, UA_NodeId nodeid, UA_Boolean sourceTimeStamp,
  109. const UA_NumericRange *range, UA_DataValue *value) {
  110. if(range)
  111. return UA_STATUSCODE_BADINDEXRANGEINVALID;
  112. value->hasValue = UA_TRUE;
  113. UA_StatusCode retval = UA_Variant_setScalarCopy(&value->value, &ledStatus,
  114. &UA_TYPES[UA_TYPES_BOOLEAN]);
  115. if(retval != UA_STATUSCODE_GOOD)
  116. return retval;
  117. if(sourceTimeStamp) {
  118. value->sourceTimestamp = UA_DateTime_now();
  119. value->hasSourceTimestamp = UA_TRUE;
  120. }
  121. return UA_STATUSCODE_GOOD;
  122. }
  123. static UA_StatusCode
  124. writeLedStatus(void *handle, const UA_NodeId nodeid,
  125. const UA_Variant *data, const UA_NumericRange *range) {
  126. if(range)
  127. return UA_STATUSCODE_BADINDEXRANGEINVALID;
  128. #ifdef UA_MULTITHREADING
  129. pthread_rwlock_wrlock(&writeLock);
  130. #endif
  131. if(data->data)
  132. ledStatus = *(UA_Boolean*)data->data;
  133. if(triggerFile)
  134. fseek(triggerFile, 0, SEEK_SET);
  135. if(ledFile) {
  136. if(ledStatus == 1)
  137. fprintf(ledFile, "%s", "1");
  138. else
  139. fprintf(ledFile, "%s", "0");
  140. fflush(ledFile);
  141. }
  142. #ifdef UA_MULTITHREADING
  143. pthread_rwlock_unlock(&writeLock);
  144. #endif
  145. return UA_STATUSCODE_GOOD;
  146. }
  147. #ifdef ENABLE_METHODCALLS
  148. static UA_StatusCode
  149. getMonitoredItems(const UA_NodeId objectId, const UA_Variant *input,
  150. UA_Variant *output, void *handle) {
  151. UA_String tmp = UA_STRING("Hello World");
  152. UA_Variant_setScalarCopy(output, &tmp, &UA_TYPES[UA_TYPES_STRING]);
  153. printf("getMonitoredItems was called\n");
  154. return UA_STATUSCODE_GOOD;
  155. }
  156. #endif
  157. static void stopHandler(int sign) {
  158. UA_LOG_INFO(logger, UA_LOGCATEGORY_SERVER, "Received Ctrl-C\n");
  159. running = 0;
  160. }
  161. static UA_ByteString loadCertificate(void) {
  162. UA_ByteString certificate = UA_STRING_NULL;
  163. FILE *fp = NULL;
  164. if(!(fp=fopen("server_cert.der", "rb"))) {
  165. errno = 0; // we read errno also from the tcp layer...
  166. return certificate;
  167. }
  168. fseek(fp, 0, SEEK_END);
  169. certificate.length = ftell(fp);
  170. certificate.data = malloc(certificate.length*sizeof(UA_Byte));
  171. if(!certificate.data){
  172. fclose(fp);
  173. return certificate;
  174. }
  175. fseek(fp, 0, SEEK_SET);
  176. if(fread(certificate.data, sizeof(UA_Byte), certificate.length, fp) < (size_t)certificate.length)
  177. UA_ByteString_deleteMembers(&certificate); // error reading the cert
  178. fclose(fp);
  179. return certificate;
  180. }
  181. static UA_StatusCode
  182. nodeIter(UA_NodeId childId, UA_Boolean isInverse, UA_NodeId referenceTypeId, void *handle) {
  183. return UA_STATUSCODE_GOOD;
  184. }
  185. int main(int argc, char** argv) {
  186. signal(SIGINT, stopHandler); /* catches ctrl-c */
  187. #ifdef UA_MULTITHREADING
  188. pthread_rwlock_init(&writeLock, 0);
  189. #endif
  190. UA_Server *server = UA_Server_new(UA_ServerConfig_standard);
  191. logger = Logger_Stdout_new();
  192. UA_Server_setLogger(server, logger);
  193. UA_ByteString certificate = loadCertificate();
  194. UA_Server_setServerCertificate(server, certificate);
  195. UA_ByteString_deleteMembers(&certificate);
  196. UA_Server_addNetworkLayer(server, ServerNetworkLayerTCP_new(UA_ConnectionConfig_standard, 16664));
  197. // add node with the datetime data source
  198. UA_DataSource dateDataSource = (UA_DataSource) {.handle = NULL, .read = readTimeData, .write = NULL};
  199. UA_VariableAttributes v_attr;
  200. UA_VariableAttributes_init(&v_attr);
  201. v_attr.description = UA_LOCALIZEDTEXT("en_US","current time");
  202. v_attr.displayName = UA_LOCALIZEDTEXT("en_US","current time");
  203. const UA_QualifiedName dateName = UA_QUALIFIEDNAME(1, "current time");
  204. UA_AddNodesResult res;
  205. res = UA_Server_addDataSourceVariableNode(server, UA_NODEID_NULL,
  206. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  207. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), dateName,
  208. UA_NODEID_NULL, v_attr, dateDataSource);
  209. // Get and reattach the datasource
  210. UA_DataSource dataSourceCopy;
  211. UA_Server_getNodeAttribute_value_dataSource(server, res.addedNodeId, &dataSourceCopy);
  212. if (dataSourceCopy.read != dateDataSource.read)
  213. UA_LOG_WARNING(logger, UA_LOGCATEGORY_USERLAND, "The returned dataSource is not the same as we set?");
  214. else
  215. UA_Server_setNodeAttribute_value_dataSource(server, res.addedNodeId, dataSourceCopy);
  216. #ifndef _WIN32
  217. /* cpu temperature monitoring for linux machines */
  218. if((temperatureFile = fopen("/sys/class/thermal/thermal_zone0/temp", "r"))) {
  219. // add node with the data source
  220. UA_DataSource temperatureDataSource = (UA_DataSource) {
  221. .handle = NULL, .read = readTemperature, .write = NULL};
  222. const UA_QualifiedName tempName = UA_QUALIFIEDNAME(1, "cpu temperature");
  223. UA_VariableAttributes_init(&v_attr);
  224. v_attr.description = UA_LOCALIZEDTEXT("en_US","temperature");
  225. v_attr.displayName = UA_LOCALIZEDTEXT("en_US","temperature");
  226. UA_Server_addDataSourceVariableNode(server, UA_NODEID_NULL,
  227. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  228. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), tempName,
  229. UA_NODEID_NULL, v_attr, temperatureDataSource);
  230. }
  231. /* LED control for rpi */
  232. if(access("/sys/class/leds/led0/trigger", F_OK ) != -1 ||
  233. access("/sys/class/leds/led0/brightness", F_OK ) != -1) {
  234. if((triggerFile = fopen("/sys/class/leds/led0/trigger", "w")) &&
  235. (ledFile = fopen("/sys/class/leds/led0/brightness", "w"))) {
  236. //setting led mode to manual
  237. fprintf(triggerFile, "%s", "none");
  238. fflush(triggerFile);
  239. //turning off led initially
  240. fprintf(ledFile, "%s", "1");
  241. fflush(ledFile);
  242. // add node with the LED status data source
  243. UA_DataSource ledStatusDataSource = (UA_DataSource) {
  244. .handle = NULL, .read = readLedStatus, .write = writeLedStatus};
  245. UA_VariableAttributes_init(&v_attr);
  246. v_attr.description = UA_LOCALIZEDTEXT("en_US","status LED");
  247. v_attr.displayName = UA_LOCALIZEDTEXT("en_US","status LED");
  248. const UA_QualifiedName statusName = UA_QUALIFIEDNAME(0, "status LED");
  249. UA_Server_addDataSourceVariableNode(server, UA_NODEID_NULL,
  250. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  251. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), statusName,
  252. UA_NODEID_NULL, v_attr, ledStatusDataSource);
  253. } else
  254. UA_LOG_WARNING(logger, UA_LOGCATEGORY_USERLAND,
  255. "[Raspberry Pi] LED file exist, but is not accessible (try to run server with sudo)");
  256. }
  257. #endif
  258. // add a static variable node to the adresspace
  259. UA_VariableAttributes myVar;
  260. UA_VariableAttributes_init(&myVar);
  261. myVar.description = UA_LOCALIZEDTEXT("en_US", "the answer");
  262. myVar.displayName = UA_LOCALIZEDTEXT("en_US", "the answer");
  263. UA_Int32 myInteger = 42;
  264. UA_Variant_setScalarCopy(&myVar.value, &myInteger, &UA_TYPES[UA_TYPES_INT32]);
  265. const UA_QualifiedName myIntegerName = UA_QUALIFIEDNAME(1, "the answer");
  266. const UA_NodeId myIntegerNodeId = UA_NODEID_STRING(1, "the.answer");
  267. UA_NodeId parentNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER);
  268. UA_NodeId parentReferenceNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES);
  269. UA_Server_addVariableNode(server, myIntegerNodeId, parentNodeId, parentReferenceNodeId,
  270. myIntegerName, UA_NODEID_NULL, myVar);
  271. UA_Variant_deleteMembers(&myVar.value);
  272. /**************/
  273. /* Demo Nodes */
  274. /**************/
  275. #define DEMOID 50000
  276. UA_ObjectAttributes object_attr;
  277. UA_ObjectAttributes_init(&object_attr);
  278. object_attr.description = UA_LOCALIZEDTEXT("en_US","Demo");
  279. object_attr.displayName = UA_LOCALIZEDTEXT("en_US","Demo");
  280. UA_Server_addObjectNode(server, UA_NODEID_NUMERIC(1, DEMOID),
  281. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  282. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), UA_QUALIFIEDNAME(1, "Demo"),
  283. UA_NODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE), object_attr);
  284. #define SCALARID 50001
  285. object_attr.description = UA_LOCALIZEDTEXT("en_US","Scalar");
  286. object_attr.displayName = UA_LOCALIZEDTEXT("en_US","Scalar");
  287. UA_Server_addObjectNode(server, UA_NODEID_NUMERIC(1, SCALARID),
  288. UA_NODEID_NUMERIC(1, DEMOID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  289. UA_QUALIFIEDNAME(1, "Scalar"),
  290. UA_NODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE), object_attr);
  291. #define ARRAYID 50002
  292. object_attr.description = UA_LOCALIZEDTEXT("en_US","Array");
  293. object_attr.displayName = UA_LOCALIZEDTEXT("en_US","Array");
  294. UA_Server_addObjectNode(server, UA_NODEID_NUMERIC(1, ARRAYID),
  295. UA_NODEID_NUMERIC(1, DEMOID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  296. UA_QUALIFIEDNAME(1, "Array"),
  297. UA_NODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE), object_attr);
  298. #define MATRIXID 50003
  299. object_attr.description = UA_LOCALIZEDTEXT("en_US","Matrix");
  300. object_attr.displayName = UA_LOCALIZEDTEXT("en_US","Matrix");
  301. UA_Server_addObjectNode(server, UA_NODEID_NUMERIC(1, MATRIXID), UA_NODEID_NUMERIC(1, DEMOID),
  302. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), UA_QUALIFIEDNAME(1, "Matrix"),
  303. UA_NODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE), object_attr);
  304. UA_UInt32 id = 51000; // running id in namespace 0
  305. for(UA_UInt32 type = 0; UA_IS_BUILTIN(type); type++) {
  306. if(type == UA_TYPES_VARIANT || type == UA_TYPES_DIAGNOSTICINFO)
  307. continue;
  308. UA_VariableAttributes attr;
  309. UA_VariableAttributes_init(&attr);
  310. char name[15];
  311. sprintf(name, "%02d", type);
  312. attr.displayName = UA_LOCALIZEDTEXT("en_US",name);
  313. UA_QualifiedName qualifiedName = UA_QUALIFIEDNAME(1, name);
  314. /* add a scalar node for every built-in type */
  315. void *value = UA_new(&UA_TYPES[type]);
  316. UA_Variant_setScalar(&attr.value, value, &UA_TYPES[type]);
  317. UA_Server_addVariableNode(server, UA_NODEID_NUMERIC(1, ++id),
  318. UA_NODEID_NUMERIC(1, SCALARID),
  319. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  320. qualifiedName, UA_NODEID_NULL, attr);
  321. UA_Variant_deleteMembers(&attr.value);
  322. /* add an array node for every built-in type */
  323. UA_Variant_setArray(&attr.value, UA_Array_new(&UA_TYPES[type], 10),
  324. 10, &UA_TYPES[type]);
  325. UA_Server_addVariableNode(server, UA_NODEID_NUMERIC(1, ++id),
  326. UA_NODEID_NUMERIC(1, ARRAYID),
  327. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  328. qualifiedName, UA_NODEID_NULL, attr);
  329. UA_Variant_deleteMembers(&attr.value);
  330. /* add an matrix node for every built-in type */
  331. void* myMultiArray = UA_Array_new(&UA_TYPES[type],9);
  332. attr.value.arrayDimensions = UA_Array_new(&UA_TYPES[UA_TYPES_INT32],2);
  333. attr.value.arrayDimensions[0] = 3;
  334. attr.value.arrayDimensions[1] = 3;
  335. attr.value.arrayDimensionsSize = 2;
  336. attr.value.arrayLength = 9;
  337. attr.value.data = myMultiArray;
  338. attr.value.type = &UA_TYPES[type];
  339. UA_Server_addVariableNode(server, UA_NODEID_NUMERIC(1, ++id),
  340. UA_NODEID_NUMERIC(1, MATRIXID),
  341. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  342. qualifiedName, UA_NODEID_NULL, attr);
  343. UA_Variant_deleteMembers(&attr.value);
  344. }
  345. #ifdef ENABLE_METHODCALLS
  346. UA_Argument inputArguments;
  347. UA_Argument_init(&inputArguments);
  348. inputArguments.arrayDimensionsSize = -1;
  349. inputArguments.arrayDimensions = NULL;
  350. inputArguments.dataType = UA_TYPES[UA_TYPES_STRING].typeId;
  351. inputArguments.description = UA_LOCALIZEDTEXT("en_US", "A String");
  352. inputArguments.name = UA_STRING("Input an integer");
  353. inputArguments.valueRank = -1;
  354. UA_Argument outputArguments;
  355. UA_Argument_init(&outputArguments);
  356. outputArguments.arrayDimensionsSize = -1;
  357. outputArguments.arrayDimensions = NULL;
  358. outputArguments.dataType = UA_TYPES[UA_TYPES_STRING].typeId;
  359. outputArguments.description = UA_LOCALIZEDTEXT("en_US", "A String");
  360. outputArguments.name = UA_STRING("Input an integer");
  361. outputArguments.valueRank = -1;
  362. UA_MethodAttributes addmethodattributes;
  363. UA_MethodAttributes_init(&addmethodattributes);
  364. addmethodattributes.description = UA_LOCALIZEDTEXT("en_US", "Return a single argument as passed by the caller");
  365. addmethodattributes.displayName = UA_LOCALIZEDTEXT("en_US", "ping");
  366. addmethodattributes.executable = UA_TRUE;
  367. addmethodattributes.userExecutable = UA_TRUE;
  368. UA_Server_addMethodNode(server, UA_NODEID_NUMERIC(1,62541),
  369. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  370. UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
  371. UA_QUALIFIEDNAME(1,"ping"), addmethodattributes,
  372. &getMonitoredItems, // Call this method
  373. (void *) server, // Pass our server pointer as a handle to the method
  374. 1, &inputArguments, 1, &outputArguments);
  375. #endif
  376. // Example for iterating over all nodes referenced by "Objects":
  377. //printf("Nodes connected to 'Objects':\n=============================\n");
  378. UA_Server_forEachChildNodeCall(server, UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), nodeIter, NULL);
  379. // Some easy localization
  380. UA_LocalizedText objectsName = UA_LOCALIZEDTEXT("de_DE", "Objekte");
  381. UA_Server_setNodeAttribute_displayName(server, UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), objectsName);
  382. //start server
  383. UA_StatusCode retval = UA_Server_run(server, 1, &running); //blocks until running=false
  384. //ctrl-c received -> clean up
  385. UA_Server_delete(server);
  386. if(temperatureFile)
  387. fclose(temperatureFile);
  388. if(triggerFile) {
  389. fseek(triggerFile, 0, SEEK_SET);
  390. //setting led mode to default
  391. fprintf(triggerFile, "%s", "mmc0");
  392. fclose(triggerFile);
  393. }
  394. if(ledFile)
  395. fclose(ledFile);
  396. #ifdef UA_MULTITHREADING
  397. pthread_rwlock_destroy(&writeLock);
  398. #endif
  399. return retval;
  400. }