opcuaServer.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 "server/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. NetworklayerTCP* nl;
  56. NetworklayerTCP_new(&nl, UA_ConnectionConfig_standard, 16664);
  57. struct timeval callback_interval = {1, 0}; // 1 second
  58. UA_Int32 retval = NetworkLayerTCP_run(nl, &server, callback_interval,
  59. serverCallback, &running);
  60. NetworklayerTCP_delete(nl);
  61. UA_Server_deleteMembers(&server);
  62. return retval == UA_SUCCESS ? 0 : retval;
  63. }