server.c 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. #include <signal.h>
  6. #include <errno.h> // errno, EINTR
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #define __USE_XOPEN2K
  11. #ifdef UA_MULTITHREADING
  12. # include <pthread.h>
  13. #endif
  14. #ifdef NOT_AMALGATED
  15. # include <time.h>
  16. # include "ua_types.h"
  17. # include "ua_server.h"
  18. # include "logger_stdout.h"
  19. # include "networklayer_tcp.h"
  20. #else
  21. # include "open62541.h"
  22. #endif
  23. /****************************/
  24. /* Server-related variables */
  25. /****************************/
  26. UA_Boolean running = 1;
  27. UA_Logger logger;
  28. /*************************/
  29. /* Read-only data source */
  30. /*************************/
  31. static UA_StatusCode readTimeData(void *handle, UA_Boolean sourceTimeStamp, UA_DataValue *value) {
  32. UA_DateTime *currentTime = UA_DateTime_new();
  33. if(!currentTime)
  34. return UA_STATUSCODE_BADOUTOFMEMORY;
  35. *currentTime = UA_DateTime_now();
  36. value->value.type = &UA_TYPES[UA_TYPES_DATETIME];
  37. value->value.arrayLength = -1;
  38. value->value.data = currentTime;
  39. value->value.arrayDimensionsSize = -1;
  40. value->value.arrayDimensions = NULL;
  41. value->hasValue = UA_TRUE;
  42. if(sourceTimeStamp) {
  43. value->hasSourceTimestamp = UA_TRUE;
  44. value->sourceTimestamp = *currentTime;
  45. }
  46. return UA_STATUSCODE_GOOD;
  47. }
  48. static void releaseTimeData(void *handle, UA_DataValue *value) {
  49. UA_DateTime_delete((UA_DateTime*)value->value.data);
  50. }
  51. /*****************************/
  52. /* Read-only CPU temperature */
  53. /* Only on Linux */
  54. /*****************************/
  55. FILE* temperatureFile = NULL;
  56. static UA_StatusCode readTemperature(void *handle, UA_Boolean sourceTimeStamp, UA_DataValue *value) {
  57. UA_Double* currentTemperature = UA_Double_new();
  58. if(!currentTemperature)
  59. return UA_STATUSCODE_BADOUTOFMEMORY;
  60. fseek(temperatureFile, 0, SEEK_SET);
  61. if(fscanf(temperatureFile, "%lf", currentTemperature) != 1){
  62. UA_LOG_WARNING(logger, UA_LOGGERCATEGORY_USERLAND, "Can not parse temperature");
  63. exit(1);
  64. }
  65. *currentTemperature /= 1000.0;
  66. value->value.type = &UA_TYPES[UA_TYPES_DOUBLE];
  67. value->value.arrayLength = -1;
  68. value->value.data = currentTemperature;
  69. value->value.arrayDimensionsSize = -1;
  70. value->value.arrayDimensions = NULL;
  71. value->hasValue = UA_TRUE;
  72. return UA_STATUSCODE_GOOD;
  73. }
  74. static void releaseTemperature(void *handle, UA_DataValue *value) {
  75. UA_Double_delete((UA_Double*)value->value.data);
  76. }
  77. /*************************/
  78. /* Read-write status led */
  79. /*************************/
  80. #ifdef UA_MULTITHREADING
  81. pthread_rwlock_t writeLock;
  82. #endif
  83. FILE* triggerFile = NULL;
  84. FILE* ledFile = NULL;
  85. UA_Boolean ledStatus = 0;
  86. static UA_StatusCode readLedStatus(void *handle, UA_Boolean sourceTimeStamp, UA_DataValue *value) {
  87. /* In order to reduce blocking time, we could alloc memory for every read
  88. and return a copy of the data. */
  89. #ifdef UA_MULTITHREADING
  90. pthread_rwlock_rdlock(&writeLock);
  91. #endif
  92. value->value.type = &UA_TYPES[UA_TYPES_BOOLEAN];
  93. value->value.arrayLength = -1;
  94. value->value.data = &ledStatus;
  95. value->value.arrayDimensionsSize = -1;
  96. value->value.arrayDimensions = NULL;
  97. value->hasValue = UA_TRUE;
  98. if(sourceTimeStamp) {
  99. value->sourceTimestamp = UA_DateTime_now();
  100. value->hasSourceTimestamp = UA_TRUE;
  101. }
  102. return UA_STATUSCODE_GOOD;
  103. }
  104. static void releaseLedStatus(void *handle, UA_DataValue *value) {
  105. /* If we allocated memory for a specific read, free the content of the
  106. variantdata. */
  107. value->value.arrayLength = -1;
  108. value->value.data = NULL;
  109. #ifdef UA_MULTITHREADING
  110. pthread_rwlock_unlock(&writeLock);
  111. #endif
  112. }
  113. static UA_StatusCode writeLedStatus(void *handle, const UA_Variant *data) {
  114. #ifdef UA_MULTITHREADING
  115. pthread_rwlock_wrlock(&writeLock);
  116. #endif
  117. if(data->data)
  118. ledStatus = *(UA_Boolean*)data->data;
  119. if(triggerFile)
  120. fseek(triggerFile, 0, SEEK_SET);
  121. if(ledFile){
  122. if(ledStatus == 1){
  123. fprintf(ledFile, "%s", "1");
  124. } else {
  125. fprintf(ledFile, "%s", "0");
  126. }
  127. fflush(ledFile);
  128. }
  129. #ifdef UA_MULTITHREADING
  130. pthread_rwlock_unlock(&writeLock);
  131. #endif
  132. return UA_STATUSCODE_GOOD;
  133. }
  134. static void printLedStatus(UA_Server *server, void *data) {
  135. UA_LOG_INFO(logger, UA_LOGGERCATEGORY_SERVER, ledStatus ? "LED is on" : "LED is off");
  136. }
  137. static void stopHandler(int sign) {
  138. printf("Received Ctrl-C\n");
  139. running = 0;
  140. }
  141. static UA_ByteString loadCertificate(void) {
  142. UA_ByteString certificate = UA_STRING_NULL;
  143. FILE *fp = NULL;
  144. //FIXME: a potiential bug of locating the certificate, we need to get the path from the server's config
  145. fp=fopen("localhost.der", "rb");
  146. if(!fp) {
  147. errno = 0; // we read errno also from the tcp layer...
  148. return certificate;
  149. }
  150. fseek(fp, 0, SEEK_END);
  151. certificate.length = ftell(fp);
  152. certificate.data = malloc(certificate.length*sizeof(UA_Byte));
  153. if(!certificate.data)
  154. return certificate;
  155. fseek(fp, 0, SEEK_SET);
  156. if(fread(certificate.data, sizeof(UA_Byte), certificate.length, fp) < (size_t)certificate.length)
  157. UA_ByteString_deleteMembers(&certificate); // error reading the cert
  158. fclose(fp);
  159. return certificate;
  160. }
  161. int main(int argc, char** argv) {
  162. signal(SIGINT, stopHandler); /* catches ctrl-c */
  163. #ifdef UA_MULTITHREADING
  164. pthread_rwlock_init(&writeLock, 0);
  165. #endif
  166. UA_Server *server = UA_Server_new(UA_ServerConfig_standard);
  167. logger = Logger_Stdout_new();
  168. UA_Server_setLogger(server, logger);
  169. UA_ByteString certificate = loadCertificate();
  170. UA_Server_setServerCertificate(server, certificate);
  171. UA_ByteString_deleteMembers(&certificate);
  172. UA_Server_addNetworkLayer(server, ServerNetworkLayerTCP_new(UA_ConnectionConfig_standard, 16664));
  173. UA_UInt16 nsIndex = UA_Server_addNamespace(server, UA_ServerConfig_standard.Application_applicationURI);
  174. // print the status every 2 sec
  175. UA_WorkItem work = {.type = UA_WORKITEMTYPE_METHODCALL,
  176. .work.methodCall = {.method = printLedStatus, .data = NULL} };
  177. UA_Server_addRepeatedWorkItem(server, &work, 20000000, NULL);
  178. // add node with the datetime data source
  179. UA_DataSource dateDataSource = (UA_DataSource)
  180. {.handle = NULL,
  181. .read = readTimeData,
  182. .release = releaseTimeData,
  183. .write = NULL};
  184. const UA_QualifiedName dateName = UA_QUALIFIEDNAME(nsIndex, "current time");
  185. UA_Server_addDataSourceVariableNode(server, dateDataSource, dateName, UA_NODEID_NULL,
  186. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  187. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  188. if(!(temperatureFile = fopen("/sys/class/thermal/thermal_zone0/temp", "r"))){
  189. UA_LOG_WARNING(logger, UA_LOGGERCATEGORY_USERLAND, "[Linux specific] Can not open temperature file, no temperature node will be added");
  190. } else {
  191. // add node with the datetime data source
  192. UA_DataSource temperatureDataSource = (UA_DataSource)
  193. {.handle = NULL,
  194. .read = readTemperature,
  195. .release = releaseTemperature,
  196. .write = NULL};
  197. const UA_QualifiedName ledName = UA_QUALIFIEDNAME(nsIndex, "cpu temperature");
  198. UA_Server_addDataSourceVariableNode(server, temperatureDataSource, ledName, UA_NODEID_NULL,
  199. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  200. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  201. }
  202. if ( !(triggerFile = fopen("/sys/class/leds/led0/trigger", "w"))
  203. || !(ledFile = fopen("/sys/class/leds/led0/brightness", "w"))) {
  204. UA_LOG_WARNING(logger, UA_LOGGERCATEGORY_USERLAND, "[Raspberry Pi specific] Can not open trigger or LED file (try to run server with sudo if on a Raspberry PI)");
  205. UA_LOG_WARNING(logger, UA_LOGGERCATEGORY_USERLAND, "An LED node will be added but no physical LED will be operated");
  206. } else {
  207. //setting led mode to manual
  208. fprintf(triggerFile, "%s", "none");
  209. fflush(triggerFile);
  210. //turning off led initially
  211. fprintf(ledFile, "%s", "1");
  212. fflush(ledFile);
  213. }
  214. // add node with the LED status data source
  215. UA_DataSource ledStatusDataSource = (UA_DataSource)
  216. {.handle = NULL,
  217. .read = readLedStatus,
  218. .release = releaseLedStatus,
  219. .write = writeLedStatus};
  220. const UA_QualifiedName statusName = UA_QUALIFIEDNAME(0, "status LED");
  221. UA_Server_addDataSourceVariableNode(server, ledStatusDataSource, statusName, UA_NODEID_NULL,
  222. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  223. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  224. // add a static variable node to the adresspace
  225. UA_Variant *myIntegerVariant = UA_Variant_new();
  226. UA_Int32 myInteger = 42;
  227. UA_Variant_setScalarCopy(myIntegerVariant, &myInteger, &UA_TYPES[UA_TYPES_INT32]);
  228. const UA_QualifiedName myIntegerName = UA_QUALIFIEDNAME(1, "the answer");
  229. const UA_NodeId myIntegerNodeId = UA_NODEID_STRING(1, "the.answer");
  230. UA_NodeId parentNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER);
  231. UA_NodeId parentReferenceNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES);
  232. UA_Server_addVariableNode(server, myIntegerVariant, myIntegerName,
  233. myIntegerNodeId, parentNodeId, parentReferenceNodeId);
  234. //start server
  235. UA_StatusCode retval = UA_Server_run(server, 1, &running); //blocks until running=false
  236. //ctrl-c received -> clean up
  237. UA_Server_delete(server);
  238. if(temperatureFile)
  239. fclose(temperatureFile);
  240. if(triggerFile){
  241. fseek(triggerFile, 0, SEEK_SET);
  242. //setting led mode to default
  243. fprintf(triggerFile, "%s", "mmc0");
  244. fclose(triggerFile);
  245. }
  246. if(ledFile){
  247. fclose(ledFile);
  248. }
  249. #ifdef UA_MULTITHREADING
  250. pthread_rwlock_destroy(&writeLock);
  251. #endif
  252. return retval;
  253. }