server.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. UA_StatusCode retval = UA_Variant_setScalarCopy(&value->value, &ledStatus, &UA_TYPES[UA_TYPES_BOOLEAN]);
  107. if(retval != UA_STATUSCODE_GOOD)
  108. return retval;
  109. if(sourceTimeStamp) {
  110. value->sourceTimestamp = UA_DateTime_now();
  111. value->hasSourceTimestamp = UA_TRUE;
  112. }
  113. return UA_STATUSCODE_GOOD;
  114. }
  115. static UA_StatusCode writeLedStatus(void *handle, const UA_Variant *data, const UA_NumericRange *range) {
  116. if(range)
  117. return UA_STATUSCODE_BADINDEXRANGEINVALID;
  118. #ifdef UA_MULTITHREADING
  119. pthread_rwlock_wrlock(&writeLock);
  120. #endif
  121. if(data->data)
  122. ledStatus = *(UA_Boolean*)data->data;
  123. if(triggerFile)
  124. fseek(triggerFile, 0, SEEK_SET);
  125. if(ledFile) {
  126. if(ledStatus == 1)
  127. fprintf(ledFile, "%s", "1");
  128. else
  129. fprintf(ledFile, "%s", "0");
  130. fflush(ledFile);
  131. }
  132. #ifdef UA_MULTITHREADING
  133. pthread_rwlock_unlock(&writeLock);
  134. #endif
  135. return UA_STATUSCODE_GOOD;
  136. }
  137. #ifdef ENABLE_METHODCALLS
  138. static UA_StatusCode getMonitoredItems(const UA_NodeId objectId, const UA_Variant *input, UA_Variant *output, void *handle) {
  139. UA_String tmp = UA_STRING("Hello World");
  140. //UA_Server *theServer = (UA_Server *) handle; // Commented, would result in "unused variable" error
  141. UA_Variant_setScalarCopy(output, &tmp, &UA_TYPES[UA_TYPES_STRING]);
  142. printf("getMonitoredItems was called\n");
  143. return UA_STATUSCODE_GOOD;
  144. }
  145. #endif
  146. static void stopHandler(int sign) {
  147. UA_LOG_INFO(logger, UA_LOGCATEGORY_SERVER, "Received Ctrl-C\n");
  148. running = 0;
  149. }
  150. static UA_ByteString loadCertificate(void) {
  151. UA_ByteString certificate = UA_STRING_NULL;
  152. FILE *fp = NULL;
  153. if(!(fp=fopen("server_cert.der", "rb"))) {
  154. errno = 0; // we read errno also from the tcp layer...
  155. return certificate;
  156. }
  157. fseek(fp, 0, SEEK_END);
  158. certificate.length = ftell(fp);
  159. certificate.data = malloc(certificate.length*sizeof(UA_Byte));
  160. if(!certificate.data){
  161. fclose(fp);
  162. return certificate;
  163. }
  164. fseek(fp, 0, SEEK_SET);
  165. if(fread(certificate.data, sizeof(UA_Byte), certificate.length, fp) < (size_t)certificate.length)
  166. UA_ByteString_deleteMembers(&certificate); // error reading the cert
  167. fclose(fp);
  168. return certificate;
  169. }
  170. UA_StatusCode nodeIter(UA_NodeId childId, UA_Boolean isInverse, UA_NodeId referenceTypeId, void *handle);
  171. UA_StatusCode nodeIter(UA_NodeId childId, UA_Boolean isInverse, UA_NodeId referenceTypeId, void *handle) {
  172. printf("References ns=%d;i=%d using i=%d ", childId.namespaceIndex, childId.identifier.numeric, referenceTypeId.identifier.numeric);
  173. if (isInverse == UA_TRUE) {
  174. printf(" (inverse)");
  175. }
  176. printf("\n");
  177. return UA_STATUSCODE_GOOD;
  178. }
  179. int main(int argc, char** argv) {
  180. signal(SIGINT, stopHandler); /* catches ctrl-c */
  181. #ifdef UA_MULTITHREADING
  182. pthread_rwlock_init(&writeLock, 0);
  183. #endif
  184. UA_Server *server = UA_Server_new(UA_ServerConfig_standard);
  185. logger = Logger_Stdout_new();
  186. UA_Server_setLogger(server, logger);
  187. UA_ByteString certificate = loadCertificate();
  188. UA_Server_setServerCertificate(server, certificate);
  189. UA_ByteString_deleteMembers(&certificate);
  190. UA_Server_addNetworkLayer(server, ServerNetworkLayerTCP_new(UA_ConnectionConfig_standard, 16664));
  191. // add node with the datetime data source
  192. UA_DataSource dateDataSource = (UA_DataSource) {.handle = NULL, .read = readTimeData, .write = NULL};
  193. const UA_QualifiedName dateName = UA_QUALIFIEDNAME(1, "current time");
  194. const UA_LocalizedText dateNameBrowseName = UA_LOCALIZEDTEXT("en_US","current time");
  195. UA_Server_addDataSourceVariableNode(server, UA_NODEID_NULL, dateName, dateNameBrowseName, dateNameBrowseName, 0, 0,
  196. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  197. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  198. dateDataSource,
  199. NULL);
  200. #ifndef _WIN32
  201. //cpu temperature monitoring for linux machines
  202. if((temperatureFile = fopen("/sys/class/thermal/thermal_zone0/temp", "r"))) {
  203. // add node with the data source
  204. UA_DataSource temperatureDataSource = (UA_DataSource) {.handle = NULL, .read = readTemperature, .write = NULL};
  205. const UA_QualifiedName tempName = UA_QUALIFIEDNAME(1, "cpu temperature");
  206. const UA_LocalizedText tempNameBrowseName = UA_LOCALIZEDTEXT("en_US","temperature");
  207. UA_Server_addDataSourceVariableNode(server, UA_NODEID_NULL, tempName, tempNameBrowseName, tempNameBrowseName, 0, 0,
  208. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  209. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  210. temperatureDataSource,
  211. NULL);
  212. }
  213. //LED control for rpi
  214. if(access("/sys/class/leds/led0/trigger", F_OK ) != -1 || access("/sys/class/leds/led0/brightness", F_OK ) != -1) {
  215. if((triggerFile = fopen("/sys/class/leds/led0/trigger", "w")) && (ledFile = fopen("/sys/class/leds/led0/brightness", "w"))) {
  216. //setting led mode to manual
  217. fprintf(triggerFile, "%s", "none");
  218. fflush(triggerFile);
  219. //turning off led initially
  220. fprintf(ledFile, "%s", "1");
  221. fflush(ledFile);
  222. // add node with the LED status data source
  223. UA_DataSource ledStatusDataSource = (UA_DataSource) {.handle = NULL, .read = readLedStatus, .write = writeLedStatus};
  224. const UA_QualifiedName statusName = UA_QUALIFIEDNAME(0, "status LED");
  225. const UA_LocalizedText statusNameBrowseName = UA_LOCALIZEDTEXT("en_US","status LED");
  226. UA_Server_addDataSourceVariableNode(server, UA_NODEID_NULL, statusName, statusNameBrowseName, statusNameBrowseName, 0, 0,
  227. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  228. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  229. ledStatusDataSource,
  230. NULL);
  231. } else {
  232. UA_LOG_WARNING(logger, UA_LOGCATEGORY_USERLAND, "[Raspberry Pi] LED file exist, but I have no access (try to run server with sudo)");
  233. }
  234. }
  235. #endif
  236. // add a static variable node to the adresspace
  237. UA_Variant *myIntegerVariant = UA_Variant_new();
  238. UA_Int32 myInteger = 42;
  239. UA_Variant_setScalarCopy(myIntegerVariant, &myInteger, &UA_TYPES[UA_TYPES_INT32]);
  240. const UA_QualifiedName myIntegerName = UA_QUALIFIEDNAME(1, "the answer");
  241. const UA_NodeId myIntegerNodeId = UA_NODEID_STRING(1, "the.answer");
  242. UA_NodeId parentNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER);
  243. UA_NodeId parentReferenceNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES);
  244. UA_Server_addVariableNode(server, myIntegerNodeId, myIntegerName, UA_LOCALIZEDTEXT("en_US", "the answer"), UA_LOCALIZEDTEXT("en_US", "the answer"), 0, 0,
  245. parentNodeId, parentReferenceNodeId, myIntegerVariant, NULL);
  246. /**************/
  247. /* Demo Nodes */
  248. /**************/
  249. #define DEMOID 50000
  250. UA_Server_addObjectNode(server, UA_NODEID_NUMERIC(1, DEMOID), UA_QUALIFIEDNAME(1, "Demo"), UA_LOCALIZEDTEXT("en_US","Demo"),
  251. UA_LOCALIZEDTEXT("en_US","Demo"), 0, 0, UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  252. UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE), NULL);
  253. #define SCALARID 50001
  254. UA_Server_addObjectNode(server, UA_NODEID_NUMERIC(1, SCALARID), UA_QUALIFIEDNAME(1, "Scalar"), UA_LOCALIZEDTEXT("en_US","Demo"),
  255. UA_LOCALIZEDTEXT("en_US","Demo"), 0, 0, UA_NODEID_NUMERIC(1, DEMOID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  256. UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE), NULL);
  257. #define ARRAYID 50002
  258. UA_Server_addObjectNode(server, UA_NODEID_NUMERIC(1, ARRAYID), UA_QUALIFIEDNAME(1, "Array"), UA_LOCALIZEDTEXT("en_US","Demo"),
  259. UA_LOCALIZEDTEXT("en_US","Demo"), 0, 0, UA_NODEID_NUMERIC(1, DEMOID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  260. UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE), NULL);
  261. #define MATRIXID 50003
  262. UA_Server_addObjectNode(server, UA_NODEID_NUMERIC(1, MATRIXID), UA_QUALIFIEDNAME(1, "Matrix"), UA_LOCALIZEDTEXT("en_US","Demo"),
  263. UA_LOCALIZEDTEXT("en_US","Demo"), 0, 0, UA_NODEID_NUMERIC(1, DEMOID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  264. UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE), NULL);
  265. UA_UInt32 id = 51000; //running id in namespace 0
  266. for(UA_UInt32 type = 0; UA_IS_BUILTIN(type); type++) {
  267. if(type == UA_TYPES_VARIANT || type == UA_TYPES_DIAGNOSTICINFO)
  268. continue;
  269. //add a scalar node for every built-in type
  270. void *value = UA_new(&UA_TYPES[type]);
  271. UA_Variant *variant = UA_Variant_new();
  272. UA_Variant_setScalar(variant, value, &UA_TYPES[type]);
  273. char name[15];
  274. sprintf(name, "%02d", type);
  275. UA_QualifiedName qualifiedName = UA_QUALIFIEDNAME(1, name);
  276. UA_Server_addVariableNode(server, UA_NODEID_NUMERIC(1, ++id), qualifiedName, UA_LOCALIZEDTEXT("en_US",""), UA_LOCALIZEDTEXT("en_US",""), 0, 0,
  277. UA_NODEID_NUMERIC(1, SCALARID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), variant, NULL);
  278. //add an array node for every built-in type
  279. UA_Variant *arrayvar = UA_Variant_new();
  280. UA_Variant_setArray(arrayvar, UA_Array_new(&UA_TYPES[type], 10), 10, &UA_TYPES[type]);
  281. UA_Server_addVariableNode(server, UA_NODEID_NUMERIC(1, ++id), qualifiedName, UA_LOCALIZEDTEXT("en_US",""), UA_LOCALIZEDTEXT("en_US",""), 0, 0,
  282. UA_NODEID_NUMERIC(1, ARRAYID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), arrayvar, NULL);
  283. //add an matrix node for every built-in type
  284. arrayvar = UA_Variant_new();
  285. void* myMultiArray = UA_Array_new(&UA_TYPES[type],9);
  286. arrayvar->arrayDimensions = UA_Array_new(&UA_TYPES[UA_TYPES_INT32],2);
  287. arrayvar->arrayDimensions[0] = 3;
  288. arrayvar->arrayDimensions[1] = 3;
  289. arrayvar->arrayDimensionsSize = 2;
  290. arrayvar->arrayLength = 9;
  291. arrayvar->data = myMultiArray;
  292. arrayvar->type = &UA_TYPES[type];
  293. UA_Server_addVariableNode(server, UA_NODEID_NUMERIC(1, ++id), qualifiedName, UA_LOCALIZEDTEXT("en_US",""), UA_LOCALIZEDTEXT("en_US",""),
  294. 0, 0, UA_NODEID_NUMERIC(1, MATRIXID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), arrayvar, NULL);
  295. }
  296. #ifdef ENABLE_METHODCALLS
  297. UA_Argument inputArguments;
  298. UA_Argument_init(&inputArguments);
  299. inputArguments.arrayDimensionsSize = -1;
  300. inputArguments.arrayDimensions = NULL;
  301. inputArguments.dataType = UA_TYPES[UA_TYPES_STRING].typeId;
  302. inputArguments.description = UA_LOCALIZEDTEXT("en_US", "A String");
  303. inputArguments.name = UA_STRING("Input an integer");
  304. inputArguments.valueRank = -1;
  305. UA_Argument outputArguments;
  306. UA_Argument_init(&outputArguments);
  307. outputArguments.arrayDimensionsSize = -1;
  308. outputArguments.arrayDimensions = NULL;
  309. outputArguments.dataType = UA_TYPES[UA_TYPES_STRING].typeId;
  310. outputArguments.description = UA_LOCALIZEDTEXT("en_US", "A String");
  311. outputArguments.name = UA_STRING("Input an integer");
  312. outputArguments.valueRank = -1;
  313. UA_NodeId methodId; // Retrieve the actual ID if this node if a random id as in UA_NODEID_NUMERIC(1,0) is used
  314. UA_Server_addMethodNode(server, UA_NODEID_NUMERIC(1,62541), UA_QUALIFIEDNAME(1,"ping"), UA_LOCALIZEDTEXT("en_US", "ping"),
  315. UA_LOCALIZEDTEXT("en_US", "Return a single argument as passed by the caller"),
  316. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
  317. 0, 0,
  318. &getMonitoredItems, // Call this method
  319. (void *) server, // Pass our server pointer as a handle to the method
  320. 1, &inputArguments, 1, &outputArguments, &methodId);
  321. #endif
  322. // Example for iterating over all nodes referenced by "Objects":
  323. printf("Nodes connected to 'Objects':\n=============================\n");
  324. UA_Server_forEachChildNodeCall(server, UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), nodeIter, NULL);
  325. // Some easy localization
  326. UA_LocalizedText objectsName = UA_LOCALIZEDTEXT("de_DE", "Objekte");
  327. UA_Server_setAttributeValue(server, UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), UA_ATTRIBUTEID_DISPLAYNAME, (void *) &objectsName);
  328. //start server
  329. UA_StatusCode retval = UA_Server_run(server, 1, &running); //blocks until running=false
  330. //ctrl-c received -> clean up
  331. UA_Server_delete(server);
  332. if(temperatureFile)
  333. fclose(temperatureFile);
  334. if(triggerFile) {
  335. fseek(triggerFile, 0, SEEK_SET);
  336. //setting led mode to default
  337. fprintf(triggerFile, "%s", "mmc0");
  338. fclose(triggerFile);
  339. }
  340. if(ledFile)
  341. fclose(ledFile);
  342. #ifdef UA_MULTITHREADING
  343. pthread_rwlock_destroy(&writeLock);
  344. #endif
  345. return retval;
  346. }