server.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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 potential 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. static UA_StatusCode UA_Double_encodeBinary(UA_Double const *src, UA_ByteString *dst,
  188. size_t* offset) {
  189. if ((UA_Int32) (*offset + sizeof(UA_Double)) > dst->length)
  190. return UA_STATUSCODE_BADENCODINGERROR;
  191. /* ARM7TDMI Half Little Endian Byte order for Double 3 2 1 0 7 6 5 4 */
  192. UA_Byte srcDouble[sizeof(UA_Double)];
  193. memcpy(&srcDouble,src,sizeof(UA_Double));
  194. dst->data[(*offset)++] = srcDouble[4];
  195. dst->data[(*offset)++] = srcDouble[5];
  196. dst->data[(*offset)++] = srcDouble[6];
  197. dst->data[(*offset)++] = srcDouble[7];
  198. dst->data[(*offset)++] = srcDouble[0];
  199. dst->data[(*offset)++] = srcDouble[1];
  200. dst->data[(*offset)++] = srcDouble[2];
  201. dst->data[(*offset)++] = srcDouble[3];
  202. return UA_STATUSCODE_GOOD;
  203. }
  204. int main(int argc, char** argv) {
  205. signal(SIGINT, stopHandler); /* catches ctrl-c */
  206. #ifdef UA_MULTITHREADING
  207. pthread_rwlock_init(&writeLock, 0);
  208. #endif
  209. UA_Server *server = UA_Server_new(UA_ServerConfig_standard);
  210. logger = Logger_Stdout_new();
  211. UA_Server_setLogger(server, logger);
  212. UA_ByteString certificate = loadCertificate();
  213. UA_Server_setServerCertificate(server, certificate);
  214. UA_ByteString_deleteMembers(&certificate);
  215. UA_Server_addNetworkLayer(server, ServerNetworkLayerTCP_new(UA_ConnectionConfig_standard, 16664));
  216. // add node with the datetime data source
  217. UA_DataSource dateDataSource = (UA_DataSource)
  218. {.handle = NULL,
  219. .read = readTimeData,
  220. .release = releaseTimeData,
  221. .write = NULL};
  222. const UA_QualifiedName dateName = UA_QUALIFIEDNAME(1, "current time");
  223. UA_Server_addDataSourceVariableNode(server, dateDataSource, dateName, UA_NODEID_NULL,
  224. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  225. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  226. #ifndef _WIN32
  227. //cpu temperature monitoring for linux machines
  228. if((temperatureFile = fopen("/sys/class/thermal/thermal_zone0/temp", "r"))){
  229. // add node with the data source
  230. UA_DataSource temperatureDataSource = (UA_DataSource)
  231. {.handle = NULL,
  232. .read = readTemperature,
  233. .release = releaseTemperature,
  234. .write = NULL};
  235. const UA_QualifiedName tempName = UA_QUALIFIEDNAME(1, "cpu temperature");
  236. UA_Server_addDataSourceVariableNode(server, temperatureDataSource, tempName, UA_NODEID_NULL,
  237. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  238. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  239. }
  240. //LED control for rpi
  241. if( access("/sys/class/leds/led0/trigger", F_OK ) != -1
  242. || access("/sys/class/leds/led0/brightness", F_OK ) != -1){
  243. if ( (triggerFile = fopen("/sys/class/leds/led0/trigger", "w"))
  244. && (ledFile = fopen("/sys/class/leds/led0/brightness", "w"))) {
  245. //setting led mode to manual
  246. fprintf(triggerFile, "%s", "none");
  247. fflush(triggerFile);
  248. //turning off led initially
  249. fprintf(ledFile, "%s", "1");
  250. fflush(ledFile);
  251. // add node with the LED status data source
  252. UA_DataSource ledStatusDataSource = (UA_DataSource)
  253. {.handle = NULL,
  254. .read = readLedStatus,
  255. .release = releaseLedStatus,
  256. .write = writeLedStatus};
  257. const UA_QualifiedName statusName = UA_QUALIFIEDNAME(0, "status LED");
  258. UA_Server_addDataSourceVariableNode(server, ledStatusDataSource, statusName, UA_NODEID_NULL,
  259. UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER),
  260. UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  261. }else{
  262. UA_LOG_WARNING(logger, UA_LOGCATEGORY_USERLAND, "[Raspberry Pi] LED file exist, but I have no access (try to run server with sudo)");
  263. }
  264. }
  265. #endif
  266. // add a static variable node to the adresspace
  267. UA_Variant *myIntegerVariant = UA_Variant_new();
  268. UA_Int32 myInteger = 42;
  269. UA_Variant_setScalarCopy(myIntegerVariant, &myInteger, &UA_TYPES[UA_TYPES_INT32]);
  270. const UA_QualifiedName myIntegerName = UA_QUALIFIEDNAME(1, "the answer");
  271. const UA_NodeId myIntegerNodeId = UA_NODEID_STRING(1, "the.answer");
  272. UA_NodeId parentNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER);
  273. UA_NodeId parentReferenceNodeId = UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES);
  274. UA_Server_addVariableNode(server, myIntegerVariant, myIntegerName,
  275. myIntegerNodeId, parentNodeId, parentReferenceNodeId);
  276. /**************/
  277. /* Demo Nodes */
  278. /**************/
  279. #define DEMOID 50000
  280. 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));
  281. #define SCALARID 50001
  282. 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));
  283. #define ARRAYID 50002
  284. 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));
  285. UA_UInt32 id = 51000; //running id in namespace 0
  286. for(UA_UInt32 type = 0; UA_IS_BUILTIN(type); type++) {
  287. if(type == UA_TYPES_VARIANT || type == UA_TYPES_DIAGNOSTICINFO)
  288. continue;
  289. //add a scalar node for every built-in type
  290. void *value = UA_new(&UA_TYPES[type]);
  291. UA_Variant *variant = UA_Variant_new();
  292. UA_Variant_setScalar(variant, value, &UA_TYPES[type]);
  293. char name[15];
  294. sprintf(name, "%02d", type);
  295. UA_QualifiedName myIntegerName = UA_QUALIFIEDNAME(1, name);
  296. UA_Server_addVariableNode(server, variant, myIntegerName, UA_NODEID_NUMERIC(1, ++id),
  297. UA_NODEID_NUMERIC(1, SCALARID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  298. //add an array node for every built-in type
  299. UA_Variant *arrayvar = UA_Variant_new();
  300. UA_Variant_setArray(arrayvar, UA_Array_new(&UA_TYPES[type], 10), 10, &UA_TYPES[type]);
  301. UA_Server_addVariableNode(server, arrayvar, myIntegerName, UA_NODEID_NUMERIC(1, ++id),
  302. UA_NODEID_NUMERIC(1, ARRAYID), UA_NODEID_NUMERIC(0, UA_NS0ID_ORGANIZES));
  303. }
  304. //start server
  305. UA_StatusCode retval = UA_Server_run(server, 1, &running); //blocks until running=false
  306. //ctrl-c received -> clean up
  307. UA_Server_delete(server);
  308. if(temperatureFile)
  309. fclose(temperatureFile);
  310. if(triggerFile){
  311. fseek(triggerFile, 0, SEEK_SET);
  312. //setting led mode to default
  313. fprintf(triggerFile, "%s", "mmc0");
  314. fclose(triggerFile);
  315. }
  316. if(ledFile){
  317. fclose(ledFile);
  318. }
  319. #ifdef UA_MULTITHREADING
  320. pthread_rwlock_destroy(&writeLock);
  321. #endif
  322. return retval;
  323. }