JavaScript - Tilt Bricklet

This is the description of the JavaScript API bindings for the Tilt Bricklet. General information and technical specifications for the Tilt Bricklet are summarized in its hardware description.

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

Simple (Node.js)

Download (ExampleSimple.js)

 1var Tinkerforge = require('tinkerforge');
 2
 3var HOST = 'localhost';
 4var PORT = 4223;
 5var UID = 'XYZ'; // Change XYZ to the UID of your Tilt Bricklet
 6
 7var ipcon = new Tinkerforge.IPConnection(); // Create IP connection
 8var t = new Tinkerforge.BrickletTilt(UID, ipcon); // Create device object
 9
10ipcon.connect(HOST, PORT,
11    function (error) {
12        console.log('Error: ' + error);
13    }
14); // Connect to brickd
15// Don't use device before ipcon is connected
16
17ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
18    function (connectReason) {
19        // Get current tilt state
20        t.getTiltState(
21            function (state) {
22                if(state === Tinkerforge.BrickletTilt.TILT_STATE_CLOSED) {
23                    console.log('Tilt State: Closed');
24                }
25                else if(state === Tinkerforge.BrickletTilt.TILT_STATE_OPEN) {
26                    console.log('Tilt State: Open');
27                }
28                else if(state === Tinkerforge.BrickletTilt.TILT_STATE_CLOSED_VIBRATING) {
29                    console.log('Tilt State: Closed Vibrating');
30                }
31            },
32            function (error) {
33                console.log('Error: ' + error);
34            }
35        );
36    }
37);
38
39console.log('Press key to exit');
40process.stdin.on('data',
41    function (data) {
42        ipcon.disconnect();
43        process.exit(0);
44    }
45);

Callback (Node.js)

Download (ExampleCallback.js)

 1var Tinkerforge = require('tinkerforge');
 2
 3var HOST = 'localhost';
 4var PORT = 4223;
 5var UID = 'XYZ'; // Change XYZ to the UID of your Tilt Bricklet
 6
 7var ipcon = new Tinkerforge.IPConnection(); // Create IP connection
 8var t = new Tinkerforge.BrickletTilt(UID, ipcon); // Create device object
 9
10ipcon.connect(HOST, PORT,
11    function (error) {
12        console.log('Error: ' + error);
13    }
14); // Connect to brickd
15// Don't use device before ipcon is connected
16
17ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
18    function (connectReason) {
19        // Enable tilt state callback
20        t.enableTiltStateCallback();
21    }
22);
23
24// Register tilt state callback
25t.on(Tinkerforge.BrickletTilt.CALLBACK_TILT_STATE,
26    // Callback function for tilt state callback
27    function (state) {
28        if(state === Tinkerforge.BrickletTilt.TILT_STATE_CLOSED) {
29            console.log('Tilt State: Closed');
30        }
31        else if(state === Tinkerforge.BrickletTilt.TILT_STATE_OPEN) {
32            console.log('Tilt State: Open');
33        }
34        else if(state === Tinkerforge.BrickletTilt.TILT_STATE_CLOSED_VIBRATING) {
35            console.log('Tilt State: Closed Vibrating');
36        }
37    }
38);
39
40console.log('Press key to exit');
41process.stdin.on('data',
42    function (data) {
43        ipcon.disconnect();
44        process.exit(0);
45    }
46);

Simple (HTML)

Download (ExampleSimple.html), Test (ExampleSimple.html)

 1<!DOCTYPE html>
 2<html>
 3    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 4    <head>
 5        <title>Tinkerforge | JavaScript Example</title>
 6    </head>
 7    <body>
 8        <div style="text-align:center;">
 9            <h1>Tilt Bricklet Simple Example</h1>
10            <p>
11                <input value="localhost" id="host" type="text" size="20">:
12                <input value="4280" id="port" type="text" size="5">,
13                <input value="uid" id="uid" type="text" size="5">
14                <input value="Start Example" id="start" type="button" onclick="startExample();">
15            </p>
16            <p>
17                <textarea readonly id="text" cols="80" rows="24" style="resize:none;"
18                          >Press "Start Example" to begin ...</textarea>
19            </p>
20        </div>
21        <script src="./Tinkerforge.js" type='text/javascript'></script>
22        <script type='text/javascript'>
23            var ipcon;
24            var textArea = document.getElementById("text");
25            function startExample() {
26                textArea.value = "";
27                var HOST = document.getElementById("host").value;
28                var PORT = parseInt(document.getElementById("port").value);
29                var UID = document.getElementById("uid").value;
30                if(ipcon !== undefined) {
31                    ipcon.disconnect();
32                }
33                ipcon = new Tinkerforge.IPConnection(); // Create IP connection
34                var t = new Tinkerforge.BrickletTilt(UID, ipcon); // Create device object
35                ipcon.connect(HOST, PORT,
36                    function(error) {
37                        textArea.value += 'Error: ' + error + '\n';
38                    }
39                ); // Connect to brickd
40                // Don't use device before ipcon is connected
41
42                ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
43                    function (connectReason) {
44                        // Get current tilt state
45                        t.getTiltState(
46                            function (state) {
47                                if(state === Tinkerforge.BrickletTilt.TILT_STATE_CLOSED) {
48                                    textArea.value += 'Tilt State: Closed\n';
49                                }
50                                else if(state === Tinkerforge.BrickletTilt.TILT_STATE_OPEN) {
51                                    textArea.value += 'Tilt State: Open\n';
52                                }
53                                else if(state === Tinkerforge.BrickletTilt.TILT_STATE_CLOSED_VIBRATING) {
54                                    textArea.value += 'Tilt State: Closed Vibrating\n';
55                                }
56                            },
57                            function (error) {
58                                textArea.value += 'Error: ' + error + '\n';
59                            }
60                        );
61                    }
62                );
63            }
64        </script>
65    </body>
66</html>

Callback (HTML)

Download (ExampleCallback.html), Test (ExampleCallback.html)

 1<!DOCTYPE html>
 2<html>
 3    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 4    <head>
 5        <title>Tinkerforge | JavaScript Example</title>
 6    </head>
 7    <body>
 8        <div style="text-align:center;">
 9            <h1>Tilt Bricklet Callback Example</h1>
10            <p>
11                <input value="localhost" id="host" type="text" size="20">:
12                <input value="4280" id="port" type="text" size="5">,
13                <input value="uid" id="uid" type="text" size="5">
14                <input value="Start Example" id="start" type="button" onclick="startExample();">
15            </p>
16            <p>
17                <textarea readonly id="text" cols="80" rows="24" style="resize:none;"
18                          >Press "Start Example" to begin ...</textarea>
19            </p>
20        </div>
21        <script src="./Tinkerforge.js" type='text/javascript'></script>
22        <script type='text/javascript'>
23            var ipcon;
24            var textArea = document.getElementById("text");
25            function startExample() {
26                textArea.value = "";
27                var HOST = document.getElementById("host").value;
28                var PORT = parseInt(document.getElementById("port").value);
29                var UID = document.getElementById("uid").value;
30                if(ipcon !== undefined) {
31                    ipcon.disconnect();
32                }
33                ipcon = new Tinkerforge.IPConnection(); // Create IP connection
34                var t = new Tinkerforge.BrickletTilt(UID, ipcon); // Create device object
35                ipcon.connect(HOST, PORT,
36                    function(error) {
37                        textArea.value += 'Error: ' + error + '\n';
38                    }
39                ); // Connect to brickd
40                // Don't use device before ipcon is connected
41
42                ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
43                    function (connectReason) {
44                        // Enable tilt state callback
45                        t.enableTiltStateCallback();
46                    }
47                );
48
49                // Register tilt state callback
50                t.on(Tinkerforge.BrickletTilt.CALLBACK_TILT_STATE,
51                    // Callback function for tilt state callback
52                    function (state) {
53                        if(state === Tinkerforge.BrickletTilt.TILT_STATE_CLOSED) {
54                            textArea.value += 'Tilt State: Closed\n';
55                        }
56                        else if(state === Tinkerforge.BrickletTilt.TILT_STATE_OPEN) {
57                            textArea.value += 'Tilt State: Open\n';
58                        }
59                        else if(state === Tinkerforge.BrickletTilt.TILT_STATE_CLOSED_VIBRATING) {
60                            textArea.value += 'Tilt State: Closed Vibrating\n';
61                        }
62                        textArea.scrollTop = textArea.scrollHeight;
63                    }
64                );
65            }
66        </script>
67    </body>
68</html>

API

Generally, every function of the JavaScript bindings can take two optional parameters, returnCallback and errorCallback. These are two user defined callback functions. The returnCallback function is called with the results as arguments, if the function returns its results asynchronously. 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

  • IPConnection.ERROR_STREAM_OUT_OF_SYNC = 51

  • IPConnection.ERROR_NON_ASCII_CHAR_IN_SECRET = 71

  • IPConnection.ERROR_WRONG_DEVICE_TYPE = 81

  • IPConnection.ERROR_DEVICE_REPLACED = 82

  • IPConnection.ERROR_WRONG_RESPONSE_LENGTH = 83

  • IPConnection.ERROR_INT64_NOT_SUPPORTED = 91

The namespace for the JavaScript bindings is Tinkerforge.*.

Basic Functions

new BrickletTilt(uid, ipcon)
Parameters:
  • uid – Type: string
  • ipcon – Type: IPConnection
Returns:
  • tilt – Type: BrickletTilt

Creates an object with the unique device ID uid:

var tilt = new BrickletTilt("YOUR_DEVICE_UID", ipcon);

This object can then be used after the IP Connection is connected.

BrickletTilt.getTiltState([returnCallback][, errorCallback])
Callback Parameters:
  • state – Type: int, Range: See constants
Returns:
  • undefined

Returns the current tilt state. The state can either be

  • 0 = Closed: The ball in the tilt switch closes the circuit.

  • 1 = Open: The ball in the tilt switch does not close the circuit.

  • 2 = Closed Vibrating: The tilt switch is in motion (rapid change between open and close).

Tilt states

The following constants are available for this function:

For state:

  • BrickletTilt.TILT_STATE_CLOSED = 0

  • BrickletTilt.TILT_STATE_OPEN = 1

  • BrickletTilt.TILT_STATE_CLOSED_VIBRATING = 2

Advanced Functions

BrickletTilt.getIdentity([returnCallback][, errorCallback])
Callback Parameters:
  • uid – Type: string, Length: up to 8
  • connectedUid – Type: string, Length: up to 8
  • position – Type: char, Range: ['a' to 'h', 'z']
  • hardwareVersion – Type: [int, ...], Length: 3
    • 0: major – Type: int, Range: [0 to 255]
    • 1: minor – Type: int, Range: [0 to 255]
    • 2: revision – Type: int, Range: [0 to 255]
  • firmwareVersion – Type: [int, ...], Length: 3
    • 0: major – Type: int, Range: [0 to 255]
    • 1: minor – Type: int, Range: [0 to 255]
    • 2: revision – Type: int, Range: [0 to 255]
  • deviceIdentifier – Type: int, Range: [0 to 216 - 1]
Returns:
  • undefined

Returns the UID, the UID where the Bricklet is connected to, the position, the hardware and firmware version as well as the device identifier.

The position can be 'a', 'b', 'c', 'd', 'e', 'f', 'g' or 'h' (Bricklet Port). A Bricklet connected to an Isolator Bricklet is always at position 'z'.

The device identifier numbers can be found here. There is also a constant for the device identifier of this Bricklet.

Callback Configuration Functions

BrickletTilt.on(callback_id, function[, errorCallback])
Parameters:
  • callback_id – Type: int
  • function – Type: function
Returns:
  • undefined

Registers the given function with the given callback_id.

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

BrickletTilt.enableTiltStateCallback([returnCallback][, errorCallback])
Callback Parameters:
  • undefined
Returns:
  • undefined

Enables the CALLBACK_TILT_STATE callback.

BrickletTilt.disableTiltStateCallback([returnCallback][, errorCallback])
Callback Parameters:
  • undefined
Returns:
  • undefined

Disables the CALLBACK_TILT_STATE callback.

BrickletTilt.isTiltStateCallbackEnabled([returnCallback][, errorCallback])
Callback Parameters:
  • enabled – Type: boolean, Default: false
Returns:
  • undefined

Returns true if the CALLBACK_TILT_STATE callback is enabled.

Callbacks

Callbacks can be registered to receive time critical or recurring data from the device. The registration is done with the on() function of the device object. The first parameter is the callback ID and the second parameter the callback function:

tilt.on(BrickletTilt.CALLBACK_EXAMPLE,
    function (param) {
        console.log(param);
    }
);

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

Note

Using callbacks for recurring events is always preferred compared to using getters. It will use less USB bandwidth and the latency will be a lot better, since there is no round trip time.

BrickletTilt.CALLBACK_TILT_STATE
Callback Parameters:
  • state – Type: int, Range: See constants

This callback provides the current tilt state. It is called every time the state changes.

See getTiltState() for a description of the states.

The following constants are available for this function:

For state:

  • BrickletTilt.TILT_STATE_CLOSED = 0

  • BrickletTilt.TILT_STATE_OPEN = 1

  • BrickletTilt.TILT_STATE_CLOSED_VIBRATING = 2

Virtual Functions

Virtual functions don't communicate with the device itself, but operate only on the API bindings device object. They can be called without the corresponding IP Connection object being connected.

BrickletTilt.getAPIVersion()
Returns:
  • apiVersion – Type: [int, ...], Length: 3
    • 0: major – Type: int, Range: [0 to 255]
    • 1: minor – Type: int, Range: [0 to 255]
    • 2: revision – Type: int, Range: [0 to 255]

Returns the version of the API definition implemented by this API bindings. This is neither the release version of this API bindings nor does it tell you anything about the represented Brick or Bricklet.

BrickletTilt.getResponseExpected(functionId[, errorCallback])
Parameters:
  • functionId – Type: int, Range: See constants
Returns:
  • responseExpected – Type: boolean

Returns the response expected flag for the function specified by the function ID parameter. It is true if the function is expected to send a response, false otherwise.

For getter functions this is enabled by default and cannot be disabled, because those functions will always send a response. For callback configuration functions it is enabled by default too, but can be disabled by setResponseExpected(). For setter functions it is disabled by default and can be enabled.

Enabling the response expected flag for a setter function allows to detect timeouts and other error conditions calls of this setter as well. The device will then send a response for this purpose. If this flag is disabled for a setter function then no response is sent and errors are silently ignored, because they cannot be detected.

The following constants are available for this function:

For function_id:

  • BrickletTilt.FUNCTION_ENABLE_TILT_STATE_CALLBACK = 2

  • BrickletTilt.FUNCTION_DISABLE_TILT_STATE_CALLBACK = 3

BrickletTilt.setResponseExpected(functionId, responseExpected[, errorCallback])
Parameters:
  • functionId – Type: int, Range: See constants
  • responseExpected – Type: boolean
Returns:
  • undefined

Changes the response expected flag of the function specified by the function ID parameter. This flag can only be changed for setter (default value: false) and callback configuration functions (default value: true). For getter functions it is always enabled.

Enabling the response expected flag for a setter function allows to detect timeouts and other error conditions calls of this setter as well. The device will then send a response for this purpose. If this flag is disabled for a setter function then no response is sent and errors are silently ignored, because they cannot be detected.

The following constants are available for this function:

For function_id:

  • BrickletTilt.FUNCTION_ENABLE_TILT_STATE_CALLBACK = 2

  • BrickletTilt.FUNCTION_DISABLE_TILT_STATE_CALLBACK = 3

BrickletTilt.setResponseExpectedAll(responseExpected)
Parameters:
  • responseExpected – Type: boolean
Returns:
  • undefined

Changes the response expected flag for all setter and callback configuration functions of this device at once.

Constants

BrickletTilt.DEVICE_IDENTIFIER

This constant is used to identify a Tilt Bricklet.

The getIdentity() function and the IPConnection.CALLBACK_ENUMERATE callback of the IP Connection have a device_identifier parameter to specify the Brick's or Bricklet's type.

BrickletTilt.DEVICE_DISPLAY_NAME

This constant represents the human readable name of a Tilt Bricklet.