C/C++ - IP Connection – Tinkerforge

- Getting Started
  - Primer
  - Tutorials
  - FAQ
- Hardware
  - Bricks
  - Bricklets
  - Master Extensions
  - Power Supplies
  - Accessories
  - Timeline
- Software
  - Brick Daemon (brickd)
  - Brick Viewer (brickv)
  - API Bindings
    - C/C++
      - Requirements
      - Installation
      - Testing an Example
      - API Reference and Examples
        - IP Connection
          - Examples
            - Enumerate
            - Authenticate
          - API
            - Basic Functions
            - Callback Configuration Functions
            - Callbacks
        - Bricks
        - Bricklets
    - C/C++ (iOS)
    - C#
    - C# (Windows Phone)
    - Delphi/Lazarus
    - Java
    - Java (Android)
    - JavaScript
    - LabVIEW
    - Mathematica
    - MATLAB/Octave
    - Perl
    - PHP
    - Python
    - Ruby
    - Shell
    - Visual Basic .NET
  - Firmwares and Plugins
  - Device Identifier
  - Source Code and Bug Tracking
  - Programming Interface
- Starter Kits
  - Weather Station
  - Hardware Hacking
  - Server Room Monitoring
  - Blinkenlights
  - Internet of Things
  - Camera Slider
- Embedded Boards
  - Raspberry Pi
- Specifications
  - Technical Data
  - TCP/IP Protocol
  - Modbus Protocol
  - Wireshark Dissector

# C/C++ - IP Connection

This is the description of the C/C++ API bindings for the IP Connection. The IP Connection manages the communication between the API bindings and the Brick Daemon or a WIFI/Ethernet Extension. Before Bricks and Bricklets can be controlled using their API an IP Connection has to be created and its TCP/IP connection has to be established.

An installation guide for the C/C++ API bindings is part of their general description.

## Examples

The example code below is Public Domain (CC0 1.0).

### Enumerate

Download (example_enumerate.c)

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58

    #include <stdio.h>

    #include "ip_connection.h"

    #define HOST "localhost"
    #define PORT 4223

    // Print incoming enumeration information
    void cb_enumerate(const char *uid, const char *connected_uid,
                      char position, uint8_t hardware_version[3],
                      uint8_t firmware_version[3], uint16_t device_identifier,
                      uint8_t enumeration_type, void *user_data) {
        (void)user_data;

        printf("UID:               %s\n", uid);
        printf("Enumeration Type:  %d\n", enumeration_type);

        if(enumeration_type == IPCON_ENUMERATION_TYPE_DISCONNECTED) {
            printf("\n");
            return;
        }

        printf("Connected UID:     %s\n", connected_uid);
        printf("Position:          %c\n", position);
        printf("Hardware Version:  %d.%d.%d\n", hardware_version[0],
                                                hardware_version[1],
                                                hardware_version[2]);
        printf("Firmware Version:  %d.%d.%d\n", firmware_version[0],
                                                firmware_version[1],
                                                firmware_version[2]);
        printf("Device Identifier: %d\n", device_identifier);
        printf("\n");
    }

    int main() {
        // Create IP Connection
        IPConnection ipcon;
        ipcon_create(&ipcon);

        // Connect to brickd
        if(ipcon_connect(&ipcon, HOST, PORT) < 0) {
            fprintf(stderr, "Could not connect to brickd\n");
            exit(1);
        }

        // Register enumeration callback to "cb_enumerate"
        ipcon_register_callback(&ipcon,
                                IPCON_CALLBACK_ENUMERATE,
                                (void *)cb_enumerate,
                                NULL);

        // Trigger enumerate
        ipcon_enumerate(&ipcon);

        printf("Press key to exit\n");
        getchar();
        ipcon_destroy(&ipcon); // Calls ipcon_disconnect internally
    }

### Authenticate

Download (example_authenticate.c)

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68

    #include <stdio.h>

    #include "ip_connection.h"

    #define HOST "localhost"
    #define PORT 4223
    #define SECRET "My Authentication Secret!"

    // Authenticate each time the connection got (re-)established
    void cb_connected(uint8_t connect_reason, void *user_data) {
        IPConnection *ipcon = (IPConnection *)user_data;

        switch(connect_reason) {
        case IPCON_CONNECT_REASON_REQUEST:        printf("Connected by request\n"); break;
        case IPCON_CONNECT_REASON_AUTO_RECONNECT: printf("Auto-Reconnected\n"); break;
        }

        // Authenticate first...
        if (ipcon_authenticate(ipcon, SECRET) < 0) {
            fprintf(stderr, "Could not authenticate\n");
            return;
        } else {
            printf("Authentication succeeded\n");
        }

        // ...then trigger enumerate
        ipcon_enumerate(ipcon);
    }

    // Print incoming enumeration information
    void cb_enumerate(const char *uid, const char *connected_uid,
                      char position, uint8_t hardware_version[3],
                      uint8_t firmware_version[3], uint16_t device_identifier,
                      uint8_t enumeration_type, void *user_data) {
        // avoid unused parameter warnings
        (void)user_data; (void)connected_uid; (void)position;
        (void)hardware_version; (void)firmware_version; (void)device_identifier;

        printf("UID: %s, Enumeration Type: %d\n", uid, enumeration_type);
    }

    int main() {
        // Create IP Connection
        IPConnection ipcon;
        ipcon_create(&ipcon);

        // Register connected callback to "cb_connected"
        ipcon_register_callback(&ipcon,
                                IPCON_CALLBACK_CONNECTED,
                                (void *)cb_connected,
                                &ipcon);

        // Register enumeration callback to "cb_enumerate"
        ipcon_register_callback(&ipcon,
                                IPCON_CALLBACK_ENUMERATE,
                                (void *)cb_enumerate,
                                NULL);

        // Connect to brickd
        if(ipcon_connect(&ipcon, HOST, PORT) < 0) {
            fprintf(stderr, "Could not connect to brickd\n");
            exit(1);
        }

        printf("Press key to exit\n");
        getchar();
        ipcon_destroy(&ipcon); // Calls ipcon_disconnect internally
    }

## API

Every function of the C/C++ bindings returns an integer which describes an error code.

Possible error codes are:

- E_OK = 0
- E_TIMEOUT = -1
- E_NO_STREAM_SOCKET = -2
- E_HOSTNAME_INVALID = -3
- E_NO_CONNECT = -4
- E_NO_THREAD = -5
- E_NOT_ADDED = -6 (unused since bindings version 2.0.0)
- E_ALREADY_CONNECTED = -7
- E_NOT_CONNECTED = -8
- E_INVALID_PARAMETER = -9
- E_NOT_SUPPORTED = -10
- E_UNKNOWN_ERROR_CODE = -11

as defined in `ip_connection.h`.

### Basic Functions

void `ipcon_create`(IPConnection *ipcon)

  Creates an IP Connection object that can be used to enumerate the available devices. It is also required for the constructor of Bricks and Bricklets.

void `ipcon_destroy`(IPConnection *ipcon)

  Destroys the IP Connection object. Calls `ipcon_disconnect()` internally. The connection to the Brick Daemon gets closed and the threads of the IP Connection are terminated.

int `ipcon_connect`(IPConnection *ipcon, const char *host, uint16_t port)

  Creates a TCP/IP connection to the given `host` and `port`. The host and port can refer to a Brick Daemon or to a WIFI/Ethernet Extension.

  Devices can only be controlled when the connection was established successfully.

  Blocks until the connection is established and returns an error code if there is no Brick Daemon or WIFI/Ethernet Extension listening at the given host and port.

int `ipcon_disconnect`(IPConnection *ipcon)

  Disconnects the TCP/IP connection from the Brick Daemon or the WIFI/Ethernet Extension.

int `ipcon_authenticate`(IPConnection *ipcon, const char *secret)

  Performs an authentication handshake with the connected Brick Daemon or WIFI/Ethernet Extension. If the handshake succeeds the connection switches from non-authenticated to authenticated state and communication can continue as normal. If the handshake fails then the connection gets closed. Authentication can fail if the wrong secret was used or if authentication is not enabled at all on the Brick Daemon or the WIFI/Ethernet Extension.

  See the authentication tutorial for more information.

  New in version 2.1.0.

int `ipcon_get_connection_state`(IPConnection *ipcon)

  Can return the following states:

  - IPCON_CONNECTION_STATE_DISCONNECTED (0): No connection is established.
  - IPCON_CONNECTION_STATE_CONNECTED (1): A connection to the Brick Daemon or the WIFI/Ethernet Extension is established.
  - IPCON_CONNECTION_STATE_PENDING (2): IP Connection is currently trying to connect.

void `ipcon_set_auto_reconnect`(IPConnection *ipcon, bool auto_reconnect)

  Enables or disables auto-reconnect. If auto-reconnect is enabled, the IP Connection will try to reconnect to the previously given host and port, if the connection is lost.

  Default value is true.

bool `ipcon_get_auto_reconnect`(IPConnection *ipcon)

  Returns true if auto-reconnect is enabled, false otherwise.

void `ipcon_set_timeout`(IPConnection *ipcon, uint32_t timeout)

  Sets the timeout in milliseconds for getters and for setters for which the response expected flag is activated.

  Default timeout is 2500.

uint32_t `ipcon_get_timeout`(IPConnection *ipcon)

  Returns the timeout as set by `ipcon_set_timeout()`.

int `ipcon_enumerate`(IPConnection *ipcon)

  Broadcasts an enumerate request. All devices will respond with an enumerate callback.

void `ipcon_wait`(IPConnection *ipcon)

  Stops the current thread until `ipcon_unwait()` is called.

  This is useful if you rely solely on callbacks for events, if you want to wait for a specific callback or if the IP Connection was created in a thread.

  `wait` and `unwait` act in the same way as `acquire` and `release` of a semaphore.

void `ipcon_unwait`(IPConnection *ipcon)

  Unwaits the thread previously stopped by `ipcon_wait()`

  `wait` and `unwait` act in the same way as `acquire` and `release` of a semaphore.

### Callback Configuration Functions

void `ipcon_register_callback`(IPConnection *ipcon, uint8_t id, void *callback, void *user_data)

  Registers a callback with ID `id` to the function `callback`.

  The available IDs with corresponding callback function signatures are described below.

### Callbacks

Callbacks can be registered to be notified about events. The registration is done with the `ipcon_register_callback()` function. The parameters consist of the IP Connection object, the callback ID, the callback function and optional user data:

    void my_callback(int p, void *user_data) {
        printf("parameter: %d\n", p);
    }

    ipcon_register_callback(&ipcon, IPCON_CALLBACK_EXAMPLE, (void*)my_callback, NULL);

The available constants with corresponding callback function signatures are described below.

`IPCON_CALLBACK_ENUMERATE`

      void callback(const char *uid, const char *connected_uid, char position, uint8_t hardware_version[3], uint8_t firmware_version[3], uint16_t device_identifier, uint8_t enumeration_type, void *user_data)

  The callback has seven parameters:

  - `uid`: The UID of the device.
  - `connected_uid`: UID where the device is connected to. For a Bricklet this will be a UID of the Brick where it is connected to. For a Brick it will be the UID of the bottom Master Brick in the stack. For the bottom Master Brick in a stack this will be "0". With this information it is possible to reconstruct the complete network topology.
  - `position`: For Bricks: '0' - '8' (position in stack). For Bricklets: 'a' - 'd' (position on Brick).
  - `hardware_version`: Major, minor and release number for hardware version.
  - `firmware_version`: Major, minor and release number for firmware version.
  - `device_identifier`: A number that represents the device.
  - `enumeration_type`: Type of enumeration.

  Possible enumeration types are:

  - IPCON_ENUMERATION_TYPE_AVAILABLE (0): Device is available (enumeration triggered by user).
  - IPCON_ENUMERATION_TYPE_CONNECTED (1): Device is newly connected (automatically send by Brick after establishing a communication connection). This indicates that the device has potentially lost its previous configuration and needs to be reconfigured.
  - IPCON_ENUMERATION_TYPE_DISCONNECTED (2): Device is disconnected (only possible for USB connection). In this case only `uid` and `enumeration_type` are valid.

  It should be possible to implement plug-and-play functionality with this (as is done in Brick Viewer).

  The device identifier numbers can be found here. There are also constants for these numbers named following this pattern:

      <device-type>_DEVICE_IDENTIFIER

  For example: `MASTER_DEVICE_IDENTIFIER` or `AMBIENT_LIGHT_DEVICE_IDENTIFIER`.

`IPCON_CALLBACK_CONNECTED`

      void callback(uint8_t connect_reason, void *user_data)

  This callback is called whenever the IP Connection got connected to a Brick Daemon or to a WIFI/Ethernet Extension, possible reasons are:

  - IPCON_CONNECT_REASON_REQUEST (0): Connection established after request from user.
  - IPCON_CONNECT_REASON_AUTO_RECONNECT (1): Connection after auto-reconnect.

`IPCON_CALLBACK_DISCONNECTED`

      void callback(uint8_t disconnect_reason, void *user_data)

  This callback is called whenever the IP Connection got disconnected from a Brick Daemon or from a WIFI/Ethernet Extension, possible reasons are:

  - IPCON_DISCONNECT_REASON_REQUEST (0): Disconnect was requested by user.
  - IPCON_DISCONNECT_REASON_ERROR (1): Disconnect because of an unresolvable error.
  - IPCON_DISCONNECT_REASON_SHUTDOWN (2): Disconnect initiated by Brick Daemon or WIFI/Ethernet Extension.

The content of this page is licensed under Creative Commons Attribution 3.0 Unported License.