Perl - 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++
    - C/C++ (iOS)
    - C#
    - C# (Windows Phone)
    - Delphi/Lazarus
    - Java
    - Java (Android)
    - JavaScript
    - LabVIEW
    - Mathematica
    - MATLAB/Octave
    - Perl
      - Requirements
      - Installation
      - Testing an Example
      - Known Problems
      - API Reference and Examples
        - IP Connection
          - Examples
            - Enumerate
            - Authenticate
          - API
            - Basic Functions
            - Callback Configuration Functions
            - Callbacks
        - Bricks
        - Bricklets
    - 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

# Perl - IP Connection

This is the description of the Perl 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 Perl API bindings is part of their general description.

## Examples

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

### Enumerate

Download (example_enumerate.pl)

     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

    #!/usr/bin/perl

    use Tinkerforge::IPConnection;

    use constant HOST => 'localhost';
    use constant PORT => 4223;

    # Create connection and connect to brickd
    my $ipcon = Tinkerforge::IPConnection->new();

    # Print incoming enumeration
    sub cb_enumerate
    {
        my ($uid, $connected_uid, $position, $hardware_version,
            $firmware_version, $device_identifier, $enumeration_type) = @_;

        print "UID:               $uid\n";
        print "Enumeration Type:  $enumeration_type\n";

        if ($enumeration_type == Tinkerforge::IPConnection->ENUMERATION_TYPE_DISCONNECTED)
        {
            print "\n";
            return;
        }

        print "Connected UID:     $connected_uid\n";
        print "Position:          $position\n";
        print "Hardware Version:  ".join('.', @$hardware_version)."\n";
        print "Firmware Version:  ".join('.', @$firmware_version)."\n";
        print "Device Identifier: $device_identifier\n";
        print "\n";
    }

    $ipcon->connect(&HOST, &PORT);

    # Register Enumerate Callback
    $ipcon->register_callback($ipcon->CALLBACK_ENUMERATE, 'cb_enumerate');

    # Trigger Enumerate
    $ipcon->enumerate();

    print "Press any key to exit...\n";
    <STDIN>;
    $ipcon->disconnect();

### Authenticate

Download (example_authenticate.pl)

     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

    #!/usr/bin/perl

    use Tinkerforge::IPConnection;

    use constant HOST => 'localhost';
    use constant PORT => 4223;
    use constant SECRET => 'My Authentication Secret!';

    # Create IPConnection
    our $ipcon = Tinkerforge::IPConnection->new();

    # Authenticate each time the connection got (re-)established
    sub cb_connected
    {
        my ($connect_reason) = @_;

        if ($connect_reason == $ipcon->CONNECT_REASON_REQUEST)
        {
            print "Connected by request\n";
        }
        elsif ($connect_reason == $ipcon->CONNECT_REASON_AUTO_RECONNECT)
        {
            print "Auto-Reconnect\n";
        }

        # Authenticate first...
        eval
        {
            $ipcon->authenticate(&SECRET);
            print "Authentication succeeded\n";
        };
        if ($!)
        {
            print "Could not authenticate: $!\n";
            return;
        }

        # ...then trigger Enumerate
        $ipcon->enumerate();
    }

    # Print incoming enumeration
    sub cb_enumerate
    {
        my ($uid, $connected_uid, $position, $hardware_version,
            $firmware_version, $device_identifier, $enumeration_type) = @_;

        print "UID: $uid, Enumeration Type: $enumeration_type\n";
    }

    # Register Connected Callback
    $ipcon->register_callback($ipcon->CALLBACK_CONNECTED, 'cb_connected');

    # Register Enumerate Callback
    $ipcon->register_callback($ipcon->CALLBACK_ENUMERATE, 'cb_enumerate');

    # Connect to brickd
    $ipcon->connect(&HOST, &PORT);

    print "Press any key to exit...\n";
    <STDIN>;
    $ipcon->disconnect();

## API

Generally, every subroutine of the Perl bindings can report an error as `Tinkerforge::Error` object via `croak()`. The object has a `get_code()` and a `get_message()` subroutine. There are different error code:

- Error->ALREADY_CONNECTED = 11
- Error->NOT_CONNECTED = 12
- Error->CONNECT_FAILED = 13
- Error->INVALID_FUNCTION_ID = 21
- Error->TIMEOUT = 31
- Error->INVALID_PARAMETER = 41
- Error->FUNCTION_NOT_SUPPORTED = 42
- Error->UNKNOWN_ERROR = 43

All methods listed below are thread-safe.

### Basic Functions

`IPConnection``->``new`()

  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.

`IPConnection``->``connect`($host, $port)

  Parameters:

  - $host -- string
  - $port -- int

  Return type: | undef

  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 throws an exception if there is no Brick Daemon or WIFI/Ethernet Extension listening at the given host and port.

`IPConnection``->``disconnect`()

  Return type: | undef

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

`IPConnection``->``authenticate`($secret)

  Parameters: | $host -- string
  Return type: | undef

  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.

`IPConnection``->``get_connection_state`()

  Return type: | int

  Can return the following states:

  - IPConnection->CONNECTION_STATE_DISCONNECTED (0): No connection is established.
  - IPConnection->CONNECTION_STATE_CONNECTED (1): A connection to the Brick Daemon or the WIFI/Ethernet Extension is established.
  - IPConnection->CONNECTION_STATE_PENDING (2): IP Connection is currently trying to connect.

`IPConnection``->``set_auto_reconnect`($auto_reconnect)

  Parameters: | $auto_reconnect -- bool
  Return type: | undef

  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 1.

`IPConnection``->``get_auto_reconnect`()

  Return type: | bool

  Returns 1 if auto-reconnect is enabled, 0 otherwise.

`IPConnection``->``set_timeout`($timeout)

  Parameters: | $timeout -- float
  Return type: | undef

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

  Default timeout is 2.5.

`IPConnection``->``get_timeout`()

  Return type: | float

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

`IPConnection``->``enumerate`()

  Return type: | undef

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

### Callback Configuration Functions

`IPConnection``->``register_callback`($id, $callback)

  Parameters:

  - $id -- int
  - $callback -- string

  Return type: | undef

  Registers a callback with ID `$id` to the function named `$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 `register_callback()` function. The first parameter is the callback ID and the second parameter the callback function:

    sub my_callback
    {
        print "@_[0]";
    }

    $ipcon->register_callback(IPConnection->CALLBACK_EXAMPLE, 'my_callback')

The callback function will be called from an internal thread of the IP Connection. In contrast to many other programming languages, variables are not automatically shared between threads in Perl. If you want to share a global variable between a callback function and the rest for your program it has to be marked as `:shared`. See the documentation of the threads::shared Perl module for more details.

The available constants with inherent number and type of parameters are described below.

`IPConnection``->``CALLBACK_ENUMERATE`

  Parameters:

  - $uid -- string
  - $connected_uid -- string
  - $position -- char
  - @hardware_version -- [int, int, int]
  - @firmware_version -- [int, int, int]
  - $device_identifier -- int
  - $enumeration_type -- int

  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:

  - IPConnection->ENUMERATION_TYPE_AVAILABLE (0): Device is available (enumeration triggered by user).
  - IPConnection->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.
  - IPConnection->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-class>->DEVICE_IDENTIFIER

  For example: `BrickMaster->DEVICE_IDENTIFIER` or `BrickletAmbientLight->DEVICE_IDENTIFIER`.

`IPConnection``->``CALLBACK_CONNECTED`

  Parameters: | $connect_reason -- int

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

  - IPConnection->CONNECT_REASON_REQUEST (0): Connection established after request from user.
  - IPConnection->CONNECT_REASON_AUTO_RECONNECT (1): Connection after auto-reconnect.

`IPConnection``->``CALLBACK_DISCONNECTED`

  Parameters: | $disconnect_reason -- int

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

  - IPConnection->DISCONNECT_REASON_REQUEST (0): Disconnect was requested by user.
  - IPConnection->DISCONNECT_REASON_ERROR (1): Disconnect because of an unresolvable error.
  - IPConnection->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.