opcuaServer.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 <stdio.h>
  6. #include <stdlib.h>
  7. #ifndef WIN32
  8. #include <sys/mman.h>
  9. #include <sys/wait.h>
  10. #include <unistd.h>
  11. #include <sys/time.h>
  12. #else
  13. #include "winsock2.h"
  14. #endif
  15. #include <sys/types.h>
  16. #include <fcntl.h>
  17. #include <signal.h>
  18. #include <errno.h> // errno, EINTR
  19. #include "ua_server.h"
  20. #include "logger_stdout.h"
  21. #include "networklayer_tcp.h"
  22. UA_Boolean running = UA_TRUE;
  23. void stopHandler(int sign) {
  24. running = UA_FALSE;
  25. }
  26. void serverCallback(UA_Server *server) {
  27. // printf("does whatever servers do\n");
  28. }
  29. UA_ByteString loadCertificate() {
  30. UA_ByteString certificate = UA_STRING_NULL;
  31. FILE *fp = UA_NULL;
  32. //FIXME: a potiential bug of locating the certificate, we need to get the path from the server's config
  33. fp=fopen("localhost.der", "rb");
  34. if(!fp) {
  35. errno = 0; // otherwise we think sth went wrong on the tcp socket level
  36. return certificate;
  37. }
  38. fseek(fp, 0, SEEK_END);
  39. certificate.length = ftell(fp);
  40. certificate.data = malloc(certificate.length*sizeof(UA_Byte));
  41. fseek(fp, 0, SEEK_SET);
  42. if(fread(certificate.data, sizeof(UA_Byte), certificate.length, fp) < (size_t)certificate.length)
  43. UA_ByteString_deleteMembers(&certificate); // error reading the cert
  44. fclose(fp);
  45. return certificate;
  46. }
  47. int main(int argc, char** argv) {
  48. signal(SIGINT, stopHandler); /* catches ctrl-c */
  49. UA_Server server;
  50. UA_String endpointUrl;
  51. UA_String_copycstring("no endpoint url",&endpointUrl);
  52. UA_Server_init(&server, &endpointUrl);
  53. Logger_Stdout_init(&server.logger);
  54. server.serverCertificate = loadCertificate();
  55. #define PORT 16664
  56. NetworklayerTCP* nl;
  57. NetworklayerTCP_new(&nl, UA_ConnectionConfig_standard, PORT);
  58. printf("Server started, connect to to opc.tcp://127.0.0.1:%i\n", PORT);
  59. struct timeval callback_interval = {1, 0}; // 1 second
  60. UA_Int32 retval = NetworkLayerTCP_run(nl, &server, callback_interval,
  61. serverCallback, &running);
  62. NetworklayerTCP_delete(nl);
  63. UA_Server_deleteMembers(&server);
  64. UA_String_deleteMembers(&endpointUrl);
  65. return retval == UA_SUCCESS ? 0 : retval;
  66. }