server.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. #ifdef UA_NO_AMALGAMATION
  6. # include <time.h>
  7. # include "ua_types.h"
  8. # include "ua_server.h"
  9. # include "logger_stdout.h"
  10. # include "networklayer_tcp.h"
  11. #else
  12. # include "open62541.h"
  13. #endif
  14. #include <signal.h>
  15. #include <errno.h> // errno, EINTR
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #ifdef _MSC_VER
  20. # include <io.h> //access
  21. #else
  22. # include <unistd.h> //access
  23. #endif
  24. #ifdef UA_MULTITHREADING
  25. # ifdef UA_NO_AMALGAMATION
  26. # ifndef __USE_XOPEN2K
  27. # define __USE_XOPEN2K
  28. # endif
  29. # endif
  30. #include <pthread.h>
  31. #endif
  32. /****************************/
  33. /* Server-related variables */
  34. /****************************/
  35. UA_Boolean running = 1;
  36. UA_Logger logger;
  37. /*************************/
  38. /* Read-only data source */
  39. /*************************/
  40. static UA_StatusCode readTimeData(void *handle, UA_Boolean sourceTimeStamp, const UA_NumericRange *range, UA_DataValue *value) {
  41. if(range) {
  42. value->hasStatus = UA_TRUE;
  43. value->status = UA_STATUSCODE_BADINDEXRANGEINVALID;
  44. return UA_STATUSCODE_GOOD;
  45. }
  46. UA_DateTime *currentTime = UA_DateTime_new();
  47. if(!currentTime)
  48. return UA_STATUSCODE_BADOUTOFMEMORY;
  49. *currentTime = UA_DateTime_now();
  50. value->value.type = &UA_TYPES[UA_TYPES_DATETIME];
  51. value->value.arrayLength = -1;
  52. value->value.data = currentTime;
  53. value->hasValue = UA_TRUE;
  54. if(sourceTimeStamp) {
  55. value->hasSourceTimestamp = UA_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 readTemperature(void *handle, UA_Boolean sourceTimeStamp, const UA_NumericRange *range, UA_DataValue *value) {
  66. if(range) {
  67. value->hasStatus = UA_TRUE;
  68. value->status = UA_STATUSCODE_BADINDEXRANGEINVALID;
  69. return UA_STATUSCODE_GOOD;
  70. }
  71. UA_Double* currentTemperature = UA_Double_new();
  72. if(!currentTemperature)
  73. return UA_STATUSCODE_BADOUTOFMEMORY;
  74. rewind(temperatureFile);
  75. fflush(temperatureFile);
  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 = UA_TRUE;
  83. value->value.type = &UA_TYPES[UA_TYPES_DOUBLE];
  84. value->value.arrayLength = -1;
  85. value->value.data = currentTemperature;
  86. value->value.arrayDimensionsSize = -1;
  87. value->value.arrayDimensions = NULL;
  88. value->hasValue = UA_TRUE;
  89. return UA_STATUSCODE_GOOD;
  90. }
  91. /*************************/
  92. /* Read-write status led */
  93. /*************************/
  94. #ifdef UA_MULTITHREADING
  95. pthread_rwlock_t writeLock;
  96. #endif
  97. FILE* triggerFile = NULL;
  98. FILE* ledFile = NULL;
  99. UA_Boolean ledStatus = 0;
  100. static UA_StatusCode readLedStatus(void *handle, UA_Boolean sourceTimeStamp, const UA_NumericRange *range, UA_DataValue *value) {
  101. if(range)
  102. return UA_STATUSCODE_BADINDEXRANGEINVALID;
  103. UA_StatusCode retval = UA_Variant_setScalarCopy(&value->value, &ledStatus, &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 = UA_TRUE;
  109. }
  110. return UA_STATUSCODE_GOOD;
  111. }
  112. static UA_StatusCode writeLedStatus(void *handle, const UA_Variant *data, const UA_NumericRange *range) {
  113. if(range)
  114. return UA_STATUSCODE_BADINDEXRANGEINVALID;
  115. #ifdef UA_MULTITHREADING
  116. pthread_rwlock_wrlock(&writeLock);
  117. #endif
  118. if(data->data)
  119. ledStatus = *(UA_Boolean*)data->data;
  120. if(triggerFile)
  121. fseek(triggerFile, 0, SEEK_SET);
  122. if(ledFile) {
  123. if(ledStatus == 1)
  124. fprintf(ledFile, "%s", "1");
  125. else
  126. fprintf(ledFile, "%s", "0");
  127. fflush(ledFile);
  128. }
  129. #ifdef UA_MULTITHREADING
  130. pthread_rwlock_unlock(&writeLock);
  131. #endif
  132. return UA_STATUSCODE_GOOD;
  133. }
  134. #ifdef ENABLE_METHODCALLS
  135. static UA_StatusCode getMonitoredItems(const UA_NodeId objectId, const UA_Variant *input, UA_Variant *output) {
  136. UA_String tmp = UA_STRING("Hello World");
  137. UA_Variant_setScalarCopy(output, &tmp, &UA_TYPES[UA_TYPES_STRING]);
  138. printf("getMonitoredItems was called\n");
  139. return UA_STATUSCODE_GOOD;
  140. }
  141. #endif
  142. static void stopHandler(int sign) {
  143. UA_LOG_INFO(logger, UA_LOGCATEGORY_SERVER, "Received Ctrl-C\n");
  144. running = 0;
  145. }
  146. static UA_ByteString loadCertificate(void) {
  147. UA_ByteString certificate = UA_STRING_NULL;
  148. FILE *fp = NULL;
  149. if(!(fp=fopen("server_cert.der", "rb"))) {
  150. errno = 0; // we read errno also from the tcp layer...
  151. return certificate;
  152. }
  153. fseek(fp, 0, SEEK_END);
  154. certificate.length = ftell(fp);
  155. certificate.data = malloc(certificate.length*sizeof(UA_Byte));
  156. if(!certificate.data)
  157. return certificate;
  158. fseek(fp, 0, SEEK_SET);
  159. if(fread(certificate.data, sizeof(UA_Byte), certificate.length, fp) < (size_t)certificate.length)
  160. UA_ByteString_deleteMembers(&certificate); // error reading the cert
  161. fclose(fp);
  162. return certificate;
  163. }
  164. int main(int argc, char** argv) {
  165. signal(SIGINT, stopHandler); /* catches ctrl-c */
  166. #ifdef UA_MULTITHREADING
  167. pthread_rwlock_init(&writeLock, 0);
  168. #endif
  169. UA_Server *server = UA_Server_new(UA_ServerConfig_standard);
  170. logger = Logger_Stdout_new();
  171. UA_Server_setLogger(server, logger);
  172. UA_ByteString certificate = loadCertificate();
  173. UA_Server_setServerCertificate(server, certificate);
  174. UA_ByteString_deleteMembers(&certificate);
  175. UA_Server_addNetworkLayer(server, ServerNetworkLayerTCP_new(UA_ConnectionConfig_standard, 16664));
  176. // add node with the datetime data source
  177. UA_DataSource dateDataSource = (UA_DataSource) {.handle = NULL, .read = readTimeData, .write = NULL};
  178. const UA_QualifiedName dateName = UA_QUALIFIEDNAME(1, "current time");
  179. UA_Server_addDataSourceVariableNode(server, dateDataSource, dateName, UA_NODEID_NULL,
  180. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  181. #ifndef _WIN32
  182. //cpu temperature monitoring for linux machines
  183. if((temperatureFile = fopen("/sys/class/thermal/thermal_zone0/temp", "r"))) {
  184. // add node with the data source
  185. UA_DataSource temperatureDataSource = (UA_DataSource) {.handle = NULL, .read = readTemperature, .write = NULL};
  186. const UA_QualifiedName tempName = UA_QUALIFIEDNAME(1, "cpu temperature");
  187. UA_Server_addDataSourceVariableNode(server, temperatureDataSource, tempName, UA_NODEID_NULL,
  188. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  189. }
  190. //LED control for rpi
  191. if(access("/sys/class/leds/led0/trigger", F_OK ) != -1 || access("/sys/class/leds/led0/brightness", F_OK ) != -1) {
  192. if((triggerFile = fopen("/sys/class/leds/led0/trigger", "w")) && (ledFile = fopen("/sys/class/leds/led0/brightness", "w"))) {
  193. //setting led mode to manual
  194. fprintf(triggerFile, "%s", "none");
  195. fflush(triggerFile);
  196. //turning off led initially
  197. fprintf(ledFile, "%s", "1");
  198. fflush(ledFile);
  199. // add node with the LED status data source
  200. UA_DataSource ledStatusDataSource = (UA_DataSource) {.handle = NULL, .read = readLedStatus, .write = writeLedStatus};
  201. const UA_QualifiedName statusName = UA_QUALIFIEDNAME(0, "status LED");
  202. UA_Server_addDataSourceVariableNode(server, ledStatusDataSource, statusName, UA_NODEID_NULL,
  203. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  204. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  205. } else {
  206. UA_LOG_WARNING(logger, UA_LOGCATEGORY_USERLAND, "[Raspberry Pi] LED file exist, but I have no access (try to run server with sudo)");
  207. }
  208. }
  209. #endif
  210. // add a static variable node to the adresspace
  211. UA_Variant *myIntegerVariant = UA_Variant_new();
  212. UA_Int32 myInteger = 42;
  213. UA_Variant_setScalarCopy(myIntegerVariant, &myInteger, &UA_TYPES[UA_TYPES_INT32]);
  214. const UA_QualifiedName myIntegerName = UA_QUALIFIEDNAME(1, "the answer");
  215. const UA_NodeId myIntegerNodeId = UA_NODEID_STRING(1, "the.answer");
  216. UA_NodeId parentNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER);
  217. UA_NodeId parentReferenceNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES);
  218. UA_Server_addVariableNode(server, myIntegerVariant, myIntegerName,
  219. myIntegerNodeId, parentNodeId, parentReferenceNodeId);
  220. /**************/
  221. /* Demo Nodes */
  222. /**************/
  223. #define DEMOID 50000
  224. UA_Server_addObjectNode(server,UA_QUALIFIEDNAME(1, "Demo"), UA_NODEID_NUMERIC(1, DEMOID), UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  225. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), UA_NODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE));
  226. #define SCALARID 50001
  227. UA_Server_addObjectNode(server,UA_QUALIFIEDNAME(1, "Scalar"), UA_NODEID_NUMERIC(1, SCALARID), UA_NODEID_NUMERIC(1, DEMOID),
  228. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), UA_NODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE));
  229. #define ARRAYID 50002
  230. UA_Server_addObjectNode(server,UA_QUALIFIEDNAME(1, "Array"), UA_NODEID_NUMERIC(1, ARRAYID), UA_NODEID_NUMERIC(1, DEMOID),
  231. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), UA_NODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE));
  232. #define MATRIXID 50003
  233. UA_Server_addObjectNode(server,UA_QUALIFIEDNAME(1, "Matrix"), UA_NODEID_NUMERIC(1, MATRIXID), UA_NODEID_NUMERIC(1, DEMOID),
  234. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), UA_NODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE));
  235. UA_UInt32 id = 51000; //running id in namespace 0
  236. for(UA_UInt32 type = 0; UA_IS_BUILTIN(type); type++) {
  237. if(type == UA_TYPES_VARIANT || type == UA_TYPES_DIAGNOSTICINFO)
  238. continue;
  239. //add a scalar node for every built-in type
  240. void *value = UA_new(&UA_TYPES[type]);
  241. UA_Variant *variant = UA_Variant_new();
  242. UA_Variant_setScalar(variant, value, &UA_TYPES[type]);
  243. char name[15];
  244. sprintf(name, "%02d", type);
  245. UA_QualifiedName qualifiedName = UA_QUALIFIEDNAME(1, name);
  246. UA_Server_addVariableNode(server, variant, qualifiedName, UA_NODEID_NUMERIC(1, ++id),
  247. UA_NODEID_NUMERIC(1, SCALARID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  248. //add an array node for every built-in type
  249. UA_Variant *arrayvar = UA_Variant_new();
  250. UA_Variant_setArray(arrayvar, UA_Array_new(&UA_TYPES[type], 10), 10, &UA_TYPES[type]);
  251. UA_Server_addVariableNode(server, arrayvar, qualifiedName, UA_NODEID_NUMERIC(1, ++id),
  252. UA_NODEID_NUMERIC(1, ARRAYID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  253. //add an matrix node for every built-in type
  254. arrayvar = UA_Variant_new();
  255. void* myMultiArray = UA_Array_new(&UA_TYPES[type],9);
  256. arrayvar->arrayDimensions = UA_Array_new(&UA_TYPES[UA_TYPES_INT32],2);
  257. arrayvar->arrayDimensions[0] = 3;
  258. arrayvar->arrayDimensions[1] = 3;
  259. arrayvar->arrayDimensionsSize = 2;
  260. arrayvar->arrayLength = 9;
  261. arrayvar->data = myMultiArray;
  262. arrayvar->type = &UA_TYPES[type];
  263. UA_Server_addVariableNode(server, arrayvar, qualifiedName, UA_NODEID_NUMERIC(1, ++id),
  264. UA_NODEID_NUMERIC(1, MATRIXID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  265. }
  266. #ifdef ENABLE_METHODCALLS
  267. UA_Argument inputArguments;
  268. UA_Argument_init(&inputArguments);
  269. inputArguments.arrayDimensionsSize = -1;
  270. inputArguments.arrayDimensions = NULL;
  271. inputArguments.dataType = UA_TYPES[UA_TYPES_STRING].typeId;
  272. inputArguments.description = UA_LOCALIZEDTEXT("en_US", "A String");
  273. inputArguments.name = UA_STRING("Input an integer");
  274. inputArguments.valueRank = -1;
  275. UA_Argument outputArguments;
  276. UA_Argument_init(&outputArguments);
  277. outputArguments.arrayDimensionsSize = -1;
  278. outputArguments.arrayDimensions = NULL;
  279. outputArguments.dataType = UA_TYPES[UA_TYPES_STRING].typeId;
  280. outputArguments.description = UA_LOCALIZEDTEXT("en_US", "A String");
  281. outputArguments.name = UA_STRING("Input an integer");
  282. outputArguments.valueRank = -1;
  283. UA_Server_addMethodNode(server, UA_QUALIFIEDNAME(1,"ping"), UA_NODEID_NUMERIC(1,62541),
  284. UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES),
  285. &getMonitoredItems, 1, &inputArguments, 1, &outputArguments);
  286. #endif
  287. //start server
  288. UA_StatusCode retval = UA_Server_run(server, 1, &running); //blocks until running=false
  289. //ctrl-c received -> clean up
  290. UA_Server_delete(server);
  291. if(temperatureFile)
  292. fclose(temperatureFile);
  293. if(triggerFile) {
  294. fseek(triggerFile, 0, SEEK_SET);
  295. //setting led mode to default
  296. fprintf(triggerFile, "%s", "mmc0");
  297. fclose(triggerFile);
  298. }
  299. if(ledFile)
  300. fclose(ledFile);
  301. #ifdef UA_MULTITHREADING
  302. pthread_rwlock_destroy(&writeLock);
  303. #endif
  304. return retval;
  305. }