tutorial_client_firststeps.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  2. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
  3. /**
  4. * Building a Simple Client
  5. * ------------------------
  6. * You should already have a basic server from the previous tutorials. open62541
  7. * provides both a server- and clientside API, so creating a client is as easy as
  8. * creating a server. Copy the following into a file `myClient.c`: */
  9. #include <stdio.h>
  10. #include "open62541.h"
  11. int main(void) {
  12. UA_Client *client = UA_Client_new(UA_ClientConfig_standard);
  13. UA_StatusCode retval = UA_Client_connect(client, "opc.tcp://localhost:4840");
  14. if(retval != UA_STATUSCODE_GOOD) {
  15. UA_Client_delete(client);
  16. return (int)retval;
  17. }
  18. /* Read the value attribute of the node. UA_Client_readValueAttribute is a
  19. * wrapper for the raw read service available as UA_Client_Service_read. */
  20. UA_Variant value; /* Variants can hold scalar values and arrays of any type */
  21. UA_Variant_init(&value);
  22. /* NodeId of the variable holding the current time */
  23. const UA_NodeId nodeId =
  24. UA_NODEID_NUMERIC(0, UA_NS0ID_SERVER_SERVERSTATUS_CURRENTTIME);
  25. retval = UA_Client_readValueAttribute(client, nodeId, &value);
  26. if(retval == UA_STATUSCODE_GOOD &&
  27. UA_Variant_hasScalarType(&value, &UA_TYPES[UA_TYPES_DATETIME])) {
  28. UA_DateTime raw_date = *(UA_DateTime*)value.data;
  29. UA_String string_date = UA_DateTime_toString(raw_date);
  30. printf("string date is: %.*s\n", (int)string_date.length, string_date.data);
  31. UA_String_deleteMembers(&string_date);
  32. }
  33. /* Clean up */
  34. UA_Variant_deleteMembers(&value);
  35. UA_Client_delete(client); /* Disconnects the client internally */
  36. return UA_STATUSCODE_GOOD;
  37. }
  38. /**
  39. * Compilation is similar to the server example.
  40. *
  41. * .. code-block:: bash
  42. *
  43. * $ gcc -std=c99 open6251.c myClient.c -o myClient
  44. *
  45. * Further tasks
  46. * ^^^^^^^^^^^^^
  47. *
  48. * - Try to connect to some other OPC UA server by changing
  49. * ``opc.tcp://localhost:16664`` to an appropriate address (remember that the
  50. * queried node is contained in any OPC UA server).
  51. *
  52. * - Try to set the value of the variable node (ns=1,i="the.answer") containing
  53. * an ``Int32`` from the example server (which is built in
  54. * :doc:`tutorial_server_firststeps`) using "UA_Client_write" function. The
  55. * example server needs some more modifications, i.e., changing request types.
  56. * The answer can be found in "examples/exampleClient.c". */