server.c 8.3 KB

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