server.c 12 KB

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