JavaScript - 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
      - Requirements
      - Installation
      - Testing an Example
      - API Reference and Examples
        - IP Connection
          - Examples
            - Enumerate (Node.js)
            - Authenticate (Node.js)
            - Enumerate (HTML)
            - Authenticate (HTML)
          - API
            - Basic Functions
            - Callback Configuration Functions
            - Callbacks
        - Bricks
        - Bricklets
    - 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

# JavaScript - IP Connection

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

## Examples

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

### Enumerate (Node.js)

Download (ExampleEnumerate.js)

     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

    var Tinkerforge = require('tinkerforge');

    var HOST = 'localhost';
    var PORT = 4223;

    ipcon = new Tinkerforge.IPConnection(); // Create IP connection
    ipcon.connect(HOST, PORT,
        function(error) {
            console.log('Error: '+error);
        }
    ); // Connect to brickd

    // Register Connected Callback
    ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
        function(connectReason) {
            // Trigger Enumerate
            ipcon.enumerate();
        }
    );

    // Register Enumerate Callback
    ipcon.on(Tinkerforge.IPConnection.CALLBACK_ENUMERATE,
        // Print incoming enumeration
        function(uid, connectedUid, position, hardwareVersion, firmwareVersion,
                 deviceIdentifier, enumerationType) {
            console.log('UID:               '+uid);
            console.log('Enumeration Type:  '+enumerationType);
            if(enumerationType === Tinkerforge.IPConnection.ENUMERATION_TYPE_DISCONNECTED) {
                console.log('');
                return;
            }
            console.log('Connected UID:     '+connectedUid);
            console.log('Position:          '+position);
            console.log('Hardware Version:  '+hardwareVersion);
            console.log('Firmware Version:  '+firmwareVersion);
            console.log('Device Identifier: '+deviceIdentifier);
            console.log('');
        }
    );

    console.log("Press any key to exit ...");
    process.stdin.on('data',
        function(data) {
            ipcon.disconnect();
            process.exit(0);
        }
    );

### Authenticate (Node.js)

Download (ExampleAuthenticate.js)

     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

    var Tinkerforge = require('tinkerforge');

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

    ipcon = new Tinkerforge.IPConnection(); // Create IP connection
    ipcon.connect(HOST, PORT,
        function(error) {
            console.log('Error: '+error);
        }
    ); // Connect to brickd

    // Register Connected Callback
    ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
        // Authenticate each time the connection got (re-)established
        function(connectReason) {
            switch(connectReason) {
            case Tinkerforge.IPConnection.CONNECT_REASON_REQUEST:
                console.log('Connected by request');
                break;
            case Tinkerforge.IPConnection.CONNECT_REASON_AUTO_RECONNECT:
                console.log('Auto-Reconnected');
                break;
            }
            ipcon.authenticate(SECRET,
                function() {
                    console.log('Authentication succeeded');

                    // ...then trigger Enumerate
                    ipcon.enumerate();
                },
                function(error) {
                    console.log('Could not authenticate: '+error);
                }
            );
        }
    );

    // Register Enumerate Callback
    ipcon.on(Tinkerforge.IPConnection.CALLBACK_ENUMERATE,
        // Print incoming enumeration
        function(uid, connectedUid, position, hardwareVersion, firmwareVersion,
                 deviceIdentifier, enumerationType) {
            console.log('UID: '+uid+', Enumeration Type: '+enumerationType);
        }
    );

    console.log("Press any key to exit ...");
    process.stdin.on('data',
        function(data) {
            ipcon.disconnect();
            process.exit(0);
        }
    );

### Enumerate (HTML)

Download (ExampleEnumerate.html), Test (ExampleEnumerate.html)

     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
    69
    70

    <!DOCTYPE html>
    <html>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <head>
            <title>Tinkerforge | JavaScript Example</title>
        </head>
        <body>
            <div style="text-align:center;">
                <h1>Enumerate Example</h1>
                <p>
                    <input value="localhost" id="host" type="text" size="20">:
                    <input value="4280" id="port" type="text" size="5">
                    <input value="Start Example" id="start" type="button" onclick="startExample();">
                </p>
                <p>
                    <textarea id="text" cols="80" rows="24" style="resize:none;"
                              >Press "Start Example" to begin ...</textarea>
                </p>
            <div>
            <script src="./Tinkerforge.js" type='text/javascript'></script>
            <script type='text/javascript'>
                var ipcon;
                var textArea = document.getElementById("text");
                function startExample() {
                    textArea.value = "";
                    var HOST = document.getElementById("host").value;
                    var PORT = parseInt(document.getElementById("port").value);
                    if(ipcon !== undefined) {
                        ipcon.disconnect();
                    }
                    ipcon = new Tinkerforge.IPConnection(); // Create IP connection
                    ipcon.connect(HOST, PORT,
                        function(error) {
                            textArea.value += 'Error: '+error+ '\n';
                        }
                    ); // Connect to brickd
                    // Don't use device before ipcon is connected

                    // Register Connected Callback
                    ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
                        function(connectReason) {
                            // Trigger Enumerate
                            ipcon.enumerate();
                        }
                    );
                    // Register Enumerate Callback
                    ipcon.on(Tinkerforge.IPConnection.CALLBACK_ENUMERATE,
                        // Print incoming enumeration
                        function(uid, connectedUid, position, hardwareVersion,
                                 firmwareVersion, deviceIdentifier, enumerationType) {
                            textArea.value += 'UID:               '+uid+'\n';
                            textArea.value += 'Enumeration Type:  '+enumerationType+'\n';
                            if(enumerationType === Tinkerforge.IPConnection.ENUMERATION_TYPE_DISCONNECTED) {
                                textArea.value += '\n';
                                textArea.scrollTop = textArea.scrollHeight;
                                return;
                            }
                            textArea.value += 'Connected UID:     '+connectedUid+'\n';
                            textArea.value += 'Position:          '+position+'\n';
                            textArea.value += 'Hardware Version:  '+hardwareVersion+'\n';
                            textArea.value += 'Firmware Version:  '+firmwareVersion+'\n';
                            textArea.value += 'Device Identifier: '+deviceIdentifier+'\n';
                            textArea.value += '\n';
                            textArea.scrollTop = textArea.scrollHeight;
                        }
                    );
                }
            </script>
        </body>
    </html>

### Authenticate (HTML)

Download (ExampleAuthenticate.html), Test (ExampleAuthenticate.html)

     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
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78

    <!DOCTYPE html>
    <html>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <head>
            <title>Tinkerforge | JavaScript Example</title>
        </head>
        <body>
            <div style="text-align:center;">
                <h1>Authenticate Example</h1>
                <p>
                    <input value="localhost" id="host" type="text" size="20">:
                    <input value="4280" id="port" type="text" size="5">,
                    <input value="My Authentication Secret!" id="secret" type="text" size="30">:
                    <input value="Start Example" id="start" type="button" onclick="startExample();">
                </p>
                <p>
                    <textarea id="text" cols="80" rows="24" style="resize:none;"
                              >Press "Start Example" to begin ...</textarea>
                </p>
            <div>
            <script src="./Tinkerforge.js" type='text/javascript'></script>
            <script type='text/javascript'>
                var ipcon;
                var textArea = document.getElementById("text");
                function startExample() {
                    textArea.value = "";
                    var HOST = document.getElementById("host").value;
                    var PORT = parseInt(document.getElementById("port").value);
                    var SECRET = document.getElementById("secret").value;
                    if(ipcon !== undefined) {
                        ipcon.disconnect();
                    }
                    ipcon = new Tinkerforge.IPConnection(); // Create IP connection
                    ipcon.connect(HOST, PORT,
                        function(error) {
                            textArea.value += 'Error: '+error+ '\n';
                        }
                    ); // Connect to brickd
                    // Don't use device before ipcon is connected

                    // Register Connected Callback
                    ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
                        // Authenticate each time the connection got (re-)established
                        function(connectReason) {
                            switch(connectReason) {
                            case Tinkerforge.IPConnection.CONNECT_REASON_REQUEST:
                                textArea.value += 'Connected by request\n';
                                break;
                            case Tinkerforge.IPConnection.CONNECT_REASON_AUTO_RECONNECT:
                                textArea.value += 'Auto-Reconnected\n';
                                break;
                            }
                            ipcon.authenticate(SECRET,
                                function() {
                                    textArea.value += 'Authentication succeeded\n';

                                    // ...then trigger Enumerate
                                    ipcon.enumerate();
                                },
                                function(error) {
                                    textArea.value += 'Could not authenticate: '+error+'\n';
                                }
                            );
                        }
                    );
                    // Register Enumerate Callback
                    ipcon.on(Tinkerforge.IPConnection.CALLBACK_ENUMERATE,
                        // Print incoming enumeration
                        function(uid, connectedUid, position, hardwareVersion, firmwareVersion,
                                 deviceIdentifier, enumerationType) {
                            textArea.value += 'UID: '+uid+', Enumeration Type: '+enumerationType+'\n';
                            textArea.scrollTop = textArea.scrollHeight;
                        }
                    );
                }
            </script>
        </body>
    </html>

## API

Generally, every method of the JavaScript bindings can take two optional parameters, `returnCallback` and `errorCallback`. These are two user defined callback functions. The `returnCallback` is called with the return values as parameters, if the method returns something. The `errorCallback` is called with an error code in case of an error. The error code can be one of the following values:

- IPConnection.ERROR_ALREADY_CONNECTED = 11
- IPConnection.ERROR_NOT_CONNECTED = 12
- IPConnection.ERROR_CONNECT_FAILED = 13
- IPConnection.ERROR_INVALID_FUNCTION_ID = 21
- IPConnection.ERROR_TIMEOUT = 31
- IPConnection.ERROR_INVALID_PARAMETER = 41
- IPConnection.ERROR_FUNCTION_NOT_SUPPORTED = 42
- IPConnection.ERROR_UNKNOWN_ERROR = 43

The namespace for the JavaScript bindings is `Tinkerforge.*`.

### Basic Functions

new `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.

`IPConnection.``connect`(host, port[, errorCallback])

  Parameters:

  - host -- string
  - port -- int

  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.

`IPConnection.``disconnect`([errorCallback])

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

`IPConnection.``authenticate`(secret[, returnCallback][, errorCallback])

  Parameters:

  - secret -- string

  Callback: | undefined

  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.

`IPConnection.``getConnectionState`()

  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.``setAutoReconnect`(autoReconnect)

  Parameters:

  - auto_reconnect -- boolean

  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.

`IPConnection.``getAutoReconnect`()

  Return type: | boolean

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

`IPConnection.``setTimeout`(timeout)

  Parameters:

  - timeout -- int

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

  Default timeout is 2500.

`IPConnection.``getTimeout`()

  Return type: | int

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

`IPConnection.``enumerate`([errorCallback])

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

### Callback Configuration Functions

`IPConnection.``on`(id, callback)

  Parameters:

  - id -- int
  - callback -- function

  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 `on()` function. The first parameter is the callback ID and the second parameter the callback function:

    ipcon.on(IPConnection.CALLBACK_EXAMPLE,
        function (param) {
            console.log(param);
        }
    );

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

`IPConnection.``CALLBACK_ENUMERATE`

  Parameters:

  - uid -- string
  - connectedUid -- string
  - position -- char
  - hardwareVersion -- [int, int, int]
  - firmwareVersion -- [int, int, int]
  - deviceIdentifier -- int
  - enumerationType -- int

  The callback has seven parameters:

  - `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.
  - `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:

  - connectReason -- 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:

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