server.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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_AMALGAMATE
  6. # include "open62541.h"
  7. #else
  8. # include <time.h>
  9. # include "ua_types.h"
  10. # include "ua_server.h"
  11. # include "logger_stdout.h"
  12. # include "networklayer_tcp.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. #define __USE_XOPEN2K
  25. #ifdef UA_MULTITHREADING
  26. # include <pthread.h>
  27. #endif
  28. /****************************/
  29. /* Server-related variables */
  30. /****************************/
  31. UA_Boolean running = 1;
  32. UA_Logger logger;
  33. /*************************/
  34. /* Read-only data source */
  35. /*************************/
  36. static UA_StatusCode readTimeData(void *handle, UA_Boolean sourceTimeStamp, const UA_NumericRange *range, UA_DataValue *value) {
  37. if(range) {
  38. value->hasStatus = UA_TRUE;
  39. value->status = UA_STATUSCODE_BADINDEXRANGEINVALID;
  40. return UA_STATUSCODE_GOOD;
  41. }
  42. UA_DateTime *currentTime = UA_DateTime_new();
  43. if(!currentTime)
  44. return UA_STATUSCODE_BADOUTOFMEMORY;
  45. *currentTime = UA_DateTime_now();
  46. value->value.type = &UA_TYPES[UA_TYPES_DATETIME];
  47. value->value.arrayLength = -1;
  48. value->value.data = currentTime;
  49. value->hasValue = UA_TRUE;
  50. if(sourceTimeStamp) {
  51. value->hasSourceTimestamp = UA_TRUE;
  52. value->sourceTimestamp = *currentTime;
  53. }
  54. return UA_STATUSCODE_GOOD;
  55. }
  56. /*****************************/
  57. /* Read-only CPU temperature */
  58. /* Only on Linux */
  59. /*****************************/
  60. FILE* temperatureFile = NULL;
  61. static UA_StatusCode readTemperature(void *handle, UA_Boolean sourceTimeStamp, const UA_NumericRange *range, UA_DataValue *value) {
  62. if(range) {
  63. value->hasStatus = UA_TRUE;
  64. value->status = UA_STATUSCODE_BADINDEXRANGEINVALID;
  65. return UA_STATUSCODE_GOOD;
  66. }
  67. UA_Double* currentTemperature = UA_Double_new();
  68. if(!currentTemperature)
  69. return UA_STATUSCODE_BADOUTOFMEMORY;
  70. fseek(temperatureFile, 0, SEEK_SET);
  71. if(fscanf(temperatureFile, "%lf", currentTemperature) != 1){
  72. UA_LOG_WARNING(logger, UA_LOGCATEGORY_USERLAND, "Can not parse temperature");
  73. exit(1);
  74. }
  75. *currentTemperature /= 1000.0;
  76. value->value.type = &UA_TYPES[UA_TYPES_DOUBLE];
  77. value->value.arrayLength = -1;
  78. value->value.data = currentTemperature;
  79. value->value.arrayDimensionsSize = -1;
  80. value->value.arrayDimensions = NULL;
  81. value->hasValue = UA_TRUE;
  82. return UA_STATUSCODE_GOOD;
  83. }
  84. /*************************/
  85. /* Read-write status led */
  86. /*************************/
  87. #ifdef UA_MULTITHREADING
  88. pthread_rwlock_t writeLock;
  89. #endif
  90. FILE* triggerFile = NULL;
  91. FILE* ledFile = NULL;
  92. UA_Boolean ledStatus = 0;
  93. static UA_StatusCode readLedStatus(void *handle, UA_Boolean sourceTimeStamp, const UA_NumericRange *range, UA_DataValue *value) {
  94. if(range)
  95. return UA_STATUSCODE_BADINDEXRANGEINVALID;
  96. UA_StatusCode retval = UA_Variant_setScalarCopy(&value->value, &ledStatus, &UA_TYPES[UA_TYPES_BOOLEAN]);
  97. if(retval != UA_STATUSCODE_GOOD)
  98. return retval;
  99. if(sourceTimeStamp) {
  100. value->sourceTimestamp = UA_DateTime_now();
  101. value->hasSourceTimestamp = UA_TRUE;
  102. }
  103. return UA_STATUSCODE_GOOD;
  104. }
  105. static UA_StatusCode writeLedStatus(void *handle, const UA_Variant *data, const UA_NumericRange *range) {
  106. if(range)
  107. return UA_STATUSCODE_BADINDEXRANGEINVALID;
  108. #ifdef UA_MULTITHREADING
  109. pthread_rwlock_wrlock(&writeLock);
  110. #endif
  111. if(data->data)
  112. ledStatus = *(UA_Boolean*)data->data;
  113. if(triggerFile)
  114. fseek(triggerFile, 0, SEEK_SET);
  115. if(ledFile) {
  116. if(ledStatus == 1)
  117. fprintf(ledFile, "%s", "1");
  118. else
  119. fprintf(ledFile, "%s", "0");
  120. fflush(ledFile);
  121. }
  122. #ifdef UA_MULTITHREADING
  123. pthread_rwlock_unlock(&writeLock);
  124. #endif
  125. return UA_STATUSCODE_GOOD;
  126. }
  127. static void stopHandler(int sign) {
  128. UA_LOG_INFO(logger, UA_LOGCATEGORY_SERVER, "Received Ctrl-C\n");
  129. running = 0;
  130. }
  131. static UA_ByteString loadCertificate(void) {
  132. UA_ByteString certificate = UA_STRING_NULL;
  133. FILE *fp = NULL;
  134. if(!(fp=fopen("server_cert.der", "rb"))) {
  135. errno = 0; // we read errno also from the tcp layer...
  136. return certificate;
  137. }
  138. fseek(fp, 0, SEEK_END);
  139. certificate.length = ftell(fp);
  140. certificate.data = malloc(certificate.length*sizeof(UA_Byte));
  141. if(!certificate.data)
  142. return certificate;
  143. fseek(fp, 0, SEEK_SET);
  144. if(fread(certificate.data, sizeof(UA_Byte), certificate.length, fp) < (size_t)certificate.length)
  145. UA_ByteString_deleteMembers(&certificate); // error reading the cert
  146. fclose(fp);
  147. return certificate;
  148. }
  149. int main(int argc, char** argv) {
  150. signal(SIGINT, stopHandler); /* catches ctrl-c */
  151. #ifdef UA_MULTITHREADING
  152. pthread_rwlock_init(&writeLock, 0);
  153. #endif
  154. UA_Server *server = UA_Server_new(UA_ServerConfig_standard);
  155. logger = Logger_Stdout_new();
  156. UA_Server_setLogger(server, logger);
  157. UA_ByteString certificate = loadCertificate();
  158. UA_Server_setServerCertificate(server, certificate);
  159. UA_ByteString_deleteMembers(&certificate);
  160. UA_Server_addNetworkLayer(server, ServerNetworkLayerTCP_new(UA_ConnectionConfig_standard, 16664));
  161. // add node with the datetime data source
  162. UA_DataSource dateDataSource = (UA_DataSource) {.handle = NULL, .read = readTimeData, .write = NULL};
  163. const UA_QualifiedName dateName = UA_QUALIFIEDNAME(1, "current time");
  164. UA_Server_addDataSourceVariableNode(server, dateDataSource, dateName, UA_NODEID_NULL,
  165. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  166. #ifndef _WIN32
  167. //cpu temperature monitoring for linux machines
  168. if((temperatureFile = fopen("/sys/class/thermal/thermal_zone0/temp", "r"))) {
  169. // add node with the data source
  170. UA_DataSource temperatureDataSource = (UA_DataSource) {.handle = NULL, .read = readTemperature, .write = NULL};
  171. const UA_QualifiedName tempName = UA_QUALIFIEDNAME(1, "cpu temperature");
  172. UA_Server_addDataSourceVariableNode(server, temperatureDataSource, tempName, UA_NODEID_NULL,
  173. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  174. }
  175. //LED control for rpi
  176. if(access("/sys/class/leds/led0/trigger", F_OK ) != -1 || access("/sys/class/leds/led0/brightness", F_OK ) != -1) {
  177. if((triggerFile = fopen("/sys/class/leds/led0/trigger", "w")) && (ledFile = fopen("/sys/class/leds/led0/brightness", "w"))) {
  178. //setting led mode to manual
  179. fprintf(triggerFile, "%s", "none");
  180. fflush(triggerFile);
  181. //turning off led initially
  182. fprintf(ledFile, "%s", "1");
  183. fflush(ledFile);
  184. // add node with the LED status data source
  185. UA_DataSource ledStatusDataSource = (UA_DataSource) {.handle = NULL, .read = readLedStatus, .write = writeLedStatus};
  186. const UA_QualifiedName statusName = UA_QUALIFIEDNAME(0, "status LED");
  187. UA_Server_addDataSourceVariableNode(server, ledStatusDataSource, statusName, UA_NODEID_NULL,
  188. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  189. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  190. } else {
  191. UA_LOG_WARNING(logger, UA_LOGCATEGORY_USERLAND, "[Raspberry Pi] LED file exist, but I have no access (try to run server with sudo)");
  192. }
  193. }
  194. #endif
  195. // add a static variable node to the adresspace
  196. UA_Variant *myIntegerVariant = UA_Variant_new();
  197. UA_Int32 myInteger = 42;
  198. UA_Variant_setScalarCopy(myIntegerVariant, &myInteger, &UA_TYPES[UA_TYPES_INT32]);
  199. const UA_QualifiedName myIntegerName = UA_QUALIFIEDNAME(1, "the answer");
  200. const UA_NodeId myIntegerNodeId = UA_NODEID_STRING(1, "the.answer");
  201. UA_NodeId parentNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER);
  202. UA_NodeId parentReferenceNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES);
  203. UA_Server_addVariableNode(server, myIntegerVariant, myIntegerName,
  204. myIntegerNodeId, parentNodeId, parentReferenceNodeId);
  205. /**************/
  206. /* Demo Nodes */
  207. /**************/
  208. #define DEMOID 50000
  209. UA_Server_addObjectNode(server,UA_QUALIFIEDNAME(1, "Demo"), UA_NODEID_NUMERIC(1, DEMOID), UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  210. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), UA_NODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE));
  211. #define SCALARID 50001
  212. UA_Server_addObjectNode(server,UA_QUALIFIEDNAME(1, "Scalar"), UA_NODEID_NUMERIC(1, SCALARID), UA_NODEID_NUMERIC(1, DEMOID),
  213. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), UA_NODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE));
  214. #define ARRAYID 50002
  215. UA_Server_addObjectNode(server,UA_QUALIFIEDNAME(1, "Array"), UA_NODEID_NUMERIC(1, ARRAYID), UA_NODEID_NUMERIC(1, DEMOID),
  216. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES), UA_NODEID_NUMERIC(0, UA_NS0ID_FOLDERTYPE));
  217. UA_UInt32 id = 51000; //running id in namespace 0
  218. for(UA_UInt32 type = 0; UA_IS_BUILTIN(type); type++) {
  219. if(type == UA_TYPES_VARIANT || type == UA_TYPES_DIAGNOSTICINFO)
  220. continue;
  221. //add a scalar node for every built-in type
  222. void *value = UA_new(&UA_TYPES[type]);
  223. UA_Variant *variant = UA_Variant_new();
  224. UA_Variant_setScalar(variant, value, &UA_TYPES[type]);
  225. char name[15];
  226. sprintf(name, "%02d", type);
  227. UA_QualifiedName myIntegerName = UA_QUALIFIEDNAME(1, name);
  228. UA_Server_addVariableNode(server, variant, myIntegerName, UA_NODEID_NUMERIC(1, ++id),
  229. UA_NODEID_NUMERIC(1, SCALARID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  230. //add an array node for every built-in type
  231. UA_Variant *arrayvar = UA_Variant_new();
  232. UA_Variant_setArray(arrayvar, UA_Array_new(&UA_TYPES[type], 10), 10, &UA_TYPES[type]);
  233. UA_Server_addVariableNode(server, arrayvar, myIntegerName, UA_NODEID_NUMERIC(1, ++id),
  234. UA_NODEID_NUMERIC(1, ARRAYID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  235. }
  236. //start server
  237. UA_StatusCode retval = UA_Server_run(server, 1, &running); //blocks until running=false
  238. //ctrl-c received -> clean up
  239. UA_Server_delete(server);
  240. if(temperatureFile)
  241. fclose(temperatureFile);
  242. if(triggerFile) {
  243. fseek(triggerFile, 0, SEEK_SET);
  244. //setting led mode to default
  245. fprintf(triggerFile, "%s", "mmc0");
  246. fclose(triggerFile);
  247. }
  248. if(ledFile)
  249. fclose(ledFile);
  250. #ifdef UA_MULTITHREADING
  251. pthread_rwlock_destroy(&writeLock);
  252. #endif
  253. return retval;
  254. }