server.c 18 KB

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