MATLAB/Octave - 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
      - Requirements
      - Installation
      - Testing an Example
      - Known Problems
      - API Reference and Examples
        - IP Connection
          - Examples
            - Enumerate (MATLAB)
            - Authenticate (MATLAB)
            - Enumerate (Octave)
            - Authenticate (Octave)
          - API
            - Basic Functions
            - Callbacks
        - Bricks
        - Bricklets
    - 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

# MATLAB/Octave - IP Connection

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

## Examples

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

### Enumerate (MATLAB)

Download (matlab_example_enumerate.m)

     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

    function matlab_example_enumerate()
        import com.tinkerforge.IPConnection;

        HOST = 'localhost';
        PORT = 4223;

        ipcon = IPConnection(); % Create IP connection

        ipcon.connect(HOST, PORT); % Connect to brickd

        % Register Enumerate Callback
        set(ipcon, 'EnumerateCallback', @(h, e) cb_enumerate(e));

        % Trigger Enumerate
        ipcon.enumerate();

        input('Press any key to exit...\n', 's');
        ipcon.disconnect();
    end

    % Print incoming enumeration
    function cb_enumerate(e)
        ipcon = e.getSource();

        fprintf('UID: %s\n', char(e.uid));
        fprintf('Enumeration Type: %g\n', e.enumerationType);

        if e.enumerationType == ipcon.ENUMERATION_TYPE_DISCONNECTED
            fprintf('\n');
            return;
        end

        fprintf('Connected UID: %s\n', char(e.connectedUid));
        fprintf('Position: %s\n', e.position);
        fprintf('Hardware Version: ');
        fprintf('%d', rot90(e.hardwareVersion));
        fprintf('\n');
        fprintf('Firmware Version: ');
        fprintf('%d', rot90(e.firmwareVersion));
        fprintf('\n');
        fprintf('Device Identifier: %g\n', e.deviceIdentifier);
        fprintf('\n');
    end

### Authenticate (MATLAB)

Download (matlab_example_authenticate.m)

     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

    function matlab_example_authenticate()
        import com.tinkerforge.IPConnection;

        global SECRET;

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

        ipcon = IPConnection(); % Create IP connection

        % Register Connected Callback
        set(ipcon, 'ConnectedCallback', @(h, e) cb_connected(e));

        % Register Enumerate Callback
        set(ipcon, 'EnumerateCallback', @(h, e) cb_enumerate(e));

        ipcon.connect(HOST, PORT); % Connect to brickd

        input('Press any key to exit...\n', 's');
        ipcon.disconnect();
    end

    % Authenticate each time the connection got (re-)established
    function cb_connected(e)
        ipcon = e.getSource();

        global SECRET;

        if e.connectReason == ipcon.CONNECT_REASON_REQUEST
            fprintf('Connected by request\n');
        elseif e.connectReason == ipcon.CONNECT_REASON_AUTO_RECONNECT
            fprintf('Auto-Reconnect\n');
        end

        % Authenticate first...
        try
            ipcon.authenticate(SECRET);
            fprintf('Authentication succeeded\n');
        catch ex
            fprintf('Could not authenticate\n');
            return
        end

        % ...then trigger enumerate
        ipcon.enumerate();
    end

    % Print incoming enumeration
    function cb_enumerate(e)
        fprintf('UID: %s, Enumeration Type: %g\n', char(e.uid), e.enumerationType);
    end

### Enumerate (Octave)

Download (octave_example_enumerate.m)

     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

    function octave_example_enumerate()
        more off;

        HOST = "localhost";
        PORT = 4223;

        ipcon = java_new("com.tinkerforge.IPConnection"); % Create IP connection

        ipcon.connect(HOST, PORT); % Connect to brickd

        % Register Enumerate Callback
        ipcon.addEnumerateCallback(@cb_enumerate);

        % Trigger Enumerate
        ipcon.enumerate();

        input("Press any key to exit...\n", "s");
        ipcon.disconnect();
    end

    % Print incoming enumeration
    function cb_enumerate(e)
        ipcon = e.getSource();

        fprintf("UID: %s\n", e.uid);
        fprintf("Enumeration Type: %s\n", e.enumerationType.toString());

        if strcmp(e.enumerationType.toString(), ipcon.ENUMERATION_TYPE_DISCONNECTED.toString())
            fprintf("\n");
            return;
        end

        hardwareVersion = e.hardwareVersion;
        firmwareVersion = e.firmwareVersion;

        fprintf("Connected UID: %s\n", e.connectedUid);
        fprintf("Position: %s\n", e.position.toString());
        fprintf("Hardware Version: %s.%s.%s\n", hardwareVersion(1).toString(), ...
                                                hardwareVersion(2).toString(), ...
                                                hardwareVersion(3).toString());
        fprintf("Firmware Version: %s.%s.%s\n", firmwareVersion(1).toString(), ...
                                                firmwareVersion(2).toString(), ...
                                                firmwareVersion(3).toString());
        fprintf("Device Identifier: %g\n", e.deviceIdentifier);
        fprintf("\n");
    end

### Authenticate (Octave)

Download (octave_example_authenticate.m)

     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

    function octave_example_authenticate()
        more off;

        global SECRET;

        HOST = "localhost";
        PORT = 4223;
        SECRET = "My Authentication Secret!";

        ipcon = java_new("com.tinkerforge.IPConnection"); % Create IP connection

        % Register Connected Callback
        ipcon.addConnectedCallback(@cb_connected);

        % Register Enumerate Callback
        ipcon.addEnumerateCallback(@cb_enumerate);

        ipcon.connect(HOST, PORT); % Connect to brickd

        input("Press any key to exit...\n", "s");
        ipcon.disconnect();
    end

    % Authenticate each time the connection got (re-)established
    function cb_connected(e)
        ipcon = e.getSource();

        global SECRET;

        if strcmp(e.connectReason.toString(), ipcon.CONNECT_REASON_REQUEST.toString())
            fprintf("Connected by request\n");
        elseif strcmp(e.connectReason.toString(), ipcon.CONNECT_REASON_AUTO_RECONNECT.toString())
            fprintf("Auto-Reconnect\n");
        end

        % Authenticate first...
        try
            ipcon.authenticate(SECRET);
            fprintf("Authentication succeeded\n");
        catch ex
            fprintf("Could not authenticate\n");
            return
        end

        % ...then trigger enumerate
        ipcon.enumerate();
    end

    % Print incoming enumeration
    function cb_enumerate(e)
        fprintf("UID: %s, Enumeration Type: %s\n", e.uid, e.enumerationType.toString());
    end

## API

### Basic Functions

public class `IPConnection`()

  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.

  In MATLAB:

      import com.tinkerforge.IPConnection;

      ipcon = IPConnection();

  In Octave:

      ipcon = java_new("com.tinkerforge.IPConnection");

public void `connect`(String host, int 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 throws an exception if there is no Brick Daemon or WIFI/Ethernet Extension listening at the given host and port.

public void `disconnect`()

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

public void `authenticate`(String 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.

public byte `getConnectionState`()

  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.

public void `setAutoReconnect`(boolean autoReconnect)

  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.

public boolean `getAutoReconnect`()

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

public void `setTimeout`(int timeout)

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

  Default timeout is 2500.

public int `getTimeout`()

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

public void `enumerate`()

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

### Callbacks

Callbacks can be registered to be notified about events. The registration is done with "set" function of MATLAB. The parameters consist of the IP Connection object, the callback name and the callback function. For example, it looks like this in MATLAB:

    function cb_example(e)
        fprintf('Parameter: %s\n', e.param);
    end

    set(ipcon, 'ExampleCallback', @(h, e) cb_example(e));

Due to a difference in the Octave Java support the "set" function cannot be used in Octave. The registration is done with "add*Callback" functions of the IP Connection object. It looks like this in Octave:

    function cb_example(e)
        fprintf("Parameter: %s\n", e.param);
    end

    ipcon.addExampleCallback(@cb_example);

It is possible to add several callback functions and to remove them with the corresponding "remove*Callback" function.

The parameters of the callback are passed to the callback function as fields of the structure `e`, which is derived from the `java.util.EventObject` class. The available callback names with corresponding structure fields are described below.

public callback `IPConnection.EnumerateCallback`

  Parameters:

  - uid -- String
  - connectedUid -- String
  - position -- char
  - hardwareVersion -- short[]
  - firmwareVersion -- short[]
  - deviceIdentifier -- int
  - enumerationType -- short

  The callback function receives seven parameters as fields of the structure `e`:

  - `uid`: The UID of the device.
  - `connectedUID`: 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).
  - `hardwareVersion`: Major, minor and release number for hardware version.
  - `firmwareVersion`: Major, minor and release number for firmware version.
  - `deviceIdentifier`: A number that represents the device.
  - `enumerationType`: 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 `enumerationType` 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`.

  In MATLAB the `set()` function can be used to register a callback function to this callback.

  In Octave a callback function can be added to this callback using the `addEnumerateCallback()` function. An added callback function can be removed with the `removeEnumerateCallback()` function.

public callback `IPConnection.ConnectedCallback`

  Parameters: | connectReason -- short

  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.

  In MATLAB the `set()` function can be used to register a callback function to this callback.

  In Octave a callback function can be added to this callback using the `addConnectedCallback()` function. An added callback function can be removed with the `removeConnectedCallback()` function.

public callback `IPConnection.DisconnectedCallback`

  Parameters: | disconnectReason -- short

  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.

  In MATLAB the `set()` function can be used to register a callback function to this callback.

  In Octave a callback function can be added to this callback using the `addDisconnectedCallback()` function. An added callback function can be removed with the `removeDisconnectedCallback()` function.

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