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.
The example code below is Public Domain (CC0 1.0).
Download (ExampleEnumerate.js)
1var Tinkerforge = require('tinkerforge');
2
3var HOST = 'localhost';
4var PORT = 4223;
5
6ipcon = new Tinkerforge.IPConnection(); // Create IP connection
7ipcon.connect(HOST, PORT,
8 function(error) {
9 console.log('Error: '+error);
10 }
11); // Connect to brickd
12
13// Register Connected Callback
14ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
15 function(connectReason) {
16 // Trigger Enumerate
17 ipcon.enumerate();
18 }
19);
20
21// Register Enumerate Callback
22ipcon.on(Tinkerforge.IPConnection.CALLBACK_ENUMERATE,
23 // Print incoming enumeration
24 function(uid, connectedUid, position, hardwareVersion, firmwareVersion,
25 deviceIdentifier, enumerationType) {
26 console.log('UID: '+uid);
27 console.log('Enumeration Type: '+enumerationType);
28
29 if(enumerationType === Tinkerforge.IPConnection.ENUMERATION_TYPE_DISCONNECTED) {
30 console.log('');
31 return;
32 }
33
34 console.log('Connected UID: '+connectedUid);
35 console.log('Position: '+position);
36 console.log('Hardware Version: '+hardwareVersion);
37 console.log('Firmware Version: '+firmwareVersion);
38 console.log('Device Identifier: '+deviceIdentifier);
39 console.log('');
40 }
41);
42
43console.log("Press any key to exit ...");
44process.stdin.on('data',
45 function(data) {
46 ipcon.disconnect();
47 process.exit(0);
48 }
49);
Download (ExampleAuthenticate.js)
1var Tinkerforge = require('tinkerforge');
2
3var HOST = 'localhost';
4var PORT = 4223;
5var SECRET = 'My Authentication Secret!';
6
7ipcon = new Tinkerforge.IPConnection(); // Create IP connection
8ipcon.connect(HOST, PORT,
9 function(error) {
10 console.log('Error: '+error);
11 }
12); // Connect to brickd
13
14// Disable auto reconnect mechanism, in case we have the wrong secret.
15// If the authentication is successful, reenable it.
16ipcon.setAutoReconnect(false);
17
18// Register Connected Callback
19ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
20 // Authenticate each time the connection got (re-)established
21 function(connectReason) {
22 switch(connectReason) {
23 case Tinkerforge.IPConnection.CONNECT_REASON_REQUEST:
24 console.log('Connected by request');
25 break;
26 case Tinkerforge.IPConnection.CONNECT_REASON_AUTO_RECONNECT:
27 console.log('Auto-Reconnected');
28 break;
29 }
30 ipcon.authenticate(SECRET,
31 function() {
32 console.log('Authentication succeeded');
33
34 // ...reenable auto reconnect mechanism, as described above...
35 ipcon.setAutoReconnect(true);
36
37 // ...then trigger Enumerate
38 ipcon.enumerate();
39 },
40 function(error) {
41 console.log('Could not authenticate: '+error);
42 }
43 );
44 }
45);
46
47// Register Enumerate Callback
48ipcon.on(Tinkerforge.IPConnection.CALLBACK_ENUMERATE,
49 // Print incoming enumeration
50 function(uid, connectedUid, position, hardwareVersion, firmwareVersion,
51 deviceIdentifier, enumerationType) {
52 console.log('UID: '+uid+', Enumeration Type: '+enumerationType);
53 }
54);
55
56console.log("Press any key to exit ...");
57process.stdin.on('data',
58 function(data) {
59 ipcon.disconnect();
60 process.exit(0);
61 }
62);
Download (ExampleEnumerate.html), Test (ExampleEnumerate.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>Enumerate 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="Start Example" id="start" type="button" onclick="startExample();">
14 </p>
15 <p>
16 <textarea id="text" cols="80" rows="24" style="resize:none;"
17 >Press "Start Example" to begin ...</textarea>
18 </p>
19 </div>
20 <script src="./Tinkerforge.js" type='text/javascript'></script>
21 <script type='text/javascript'>
22 var ipcon;
23 var textArea = document.getElementById("text");
24 function startExample() {
25 textArea.value = "";
26 var HOST = document.getElementById("host").value;
27 var PORT = parseInt(document.getElementById("port").value);
28 if(ipcon !== undefined) {
29 ipcon.disconnect();
30 }
31 ipcon = new Tinkerforge.IPConnection(); // Create IP connection
32 ipcon.connect(HOST, PORT,
33 function(error) {
34 textArea.value += 'Error: '+error+ '\n';
35 }
36 ); // Connect to brickd
37 // Don't use device before ipcon is connected
38
39 // Register Connected Callback
40 ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
41 function(connectReason) {
42 // Trigger Enumerate
43 ipcon.enumerate();
44 }
45 );
46 // Register Enumerate Callback
47 ipcon.on(Tinkerforge.IPConnection.CALLBACK_ENUMERATE,
48 // Print incoming enumeration
49 function(uid, connectedUid, position, hardwareVersion,
50 firmwareVersion, deviceIdentifier, enumerationType) {
51 textArea.value += 'UID: '+uid+'\n';
52 textArea.value += 'Enumeration Type: '+enumerationType+'\n';
53 if(enumerationType === Tinkerforge.IPConnection.ENUMERATION_TYPE_DISCONNECTED) {
54 textArea.value += '\n';
55 textArea.scrollTop = textArea.scrollHeight;
56 return;
57 }
58 textArea.value += 'Connected UID: '+connectedUid+'\n';
59 textArea.value += 'Position: '+position+'\n';
60 textArea.value += 'Hardware Version: '+hardwareVersion+'\n';
61 textArea.value += 'Firmware Version: '+firmwareVersion+'\n';
62 textArea.value += 'Device Identifier: '+deviceIdentifier+'\n';
63 textArea.value += '\n';
64 textArea.scrollTop = textArea.scrollHeight;
65 }
66 );
67 }
68 </script>
69 </body>
70</html>
Download (ExampleAuthenticate.html), Test (ExampleAuthenticate.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>Authenticate 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="My Authentication Secret!" id="secret" type="text" size="30">:
14 <input value="Start Example" id="start" type="button" onclick="startExample();">
15 </p>
16 <p>
17 <textarea 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 SECRET = document.getElementById("secret").value;
30 if(ipcon !== undefined) {
31 ipcon.disconnect();
32 }
33 ipcon = new Tinkerforge.IPConnection(); // Create IP connection
34
35 // Disable auto reconnect mechanism, in case we have the wrong secret.
36 // If the authentication is successful, reenable it.
37 ipcon.setAutoReconnect(false);
38
39 ipcon.connect(HOST, PORT,
40 function(error) {
41 textArea.value += 'Error: '+error+ '\n';
42 }
43 ); // Connect to brickd
44 // Don't use device before ipcon is connected
45
46 // Register Connected Callback
47 ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
48 // Authenticate each time the connection got (re-)established
49 function(connectReason) {
50 switch(connectReason) {
51 case Tinkerforge.IPConnection.CONNECT_REASON_REQUEST:
52 textArea.value += 'Connected by request\n';
53 break;
54 case Tinkerforge.IPConnection.CONNECT_REASON_AUTO_RECONNECT:
55 textArea.value += 'Auto-Reconnected\n';
56 break;
57 }
58 ipcon.authenticate(SECRET,
59 function() {
60 textArea.value += 'Authentication succeeded\n';
61
62 // ...reenable auto reconnect mechanism, as described above...
63 ipcon.setAutoReconnect(true);
64
65 // ...then trigger Enumerate
66 ipcon.enumerate();
67 },
68 function(error) {
69 textArea.value += 'Could not authenticate: '+error+'\n';
70 }
71 );
72 }
73 );
74 // Register Enumerate Callback
75 ipcon.on(Tinkerforge.IPConnection.CALLBACK_ENUMERATE,
76 // Print incoming enumeration
77 function(uid, connectedUid, position, hardwareVersion, firmwareVersion,
78 deviceIdentifier, enumerationType) {
79 textArea.value += 'UID: '+uid+', Enumeration Type: '+enumerationType+'\n';
80 textArea.scrollTop = textArea.scrollHeight;
81 }
82 );
83 }
84 </script>
85 </body>
86</html>
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
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.*.
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.
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.
Disconnects the TCP/IP connection from the Brick Daemon or the WIFI/Ethernet Extension.
secret -- string
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.
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.
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 currently existing connection is lost.
Therefore, auto-reconnect only does something after a successful
connect() call.
Default value is true.
boolean
Returns true if auto-reconnect is enabled, false otherwise.
timeout -- int
Sets the timeout in milliseconds for getters and for setters for which the response expected flag is activated.
Default timeout is 2500.
int
Returns the timeout as set by setTimeout().
Broadcasts an enumerate request. All devices will respond with an enumerate callback.
callback_id -- int
function -- function
Registers the given function with the given callback_id.
The available callback IDs with corresponding function signatures are described below.
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.
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
is the UID of the Brick or Bricklet it is connected to. For a Brick it is
the UID of the bottommost Brick in the stack. For the bottommost Brick
in a stack it is "0". With this information it is possible to
reconstruct the complete network topology.
position: For Bricks: '0' - '8' (position in stack). For Bricklets:
'a' - 'h' (position on Brick) or 'i' (position of the Raspberry Pi (Zero) HAT)
or 'z' (Bricklet on Isolator Bricklet).
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: enumerate()). This enumeration type can occur multiple times
for the same device.
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.
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.
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.