Mathematica - IP Connection

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

Examples

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

Enumerate

Download (ExampleEnumerate.nb)

 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
Needs["NETLink`"]
LoadNETAssembly["Tinkerforge",NotebookDirectory[]<>".."]

host="localhost"
port=4223

(* Create IPConnection *)
ipcon=NETNew["Tinkerforge.IPConnection"]
ipcon@Connect[host,port]

(* Print incoming enumeration information *)
EnumerateCB[sender_,uid_,connectedUid_,position_,hardwareVersion_,firmwareVersion_,
            deviceIdentifier_,enumerationType_]:=
 Module[{},
  Print["UID:               "<>uid];
  Print["Enumeration Type:  "<>ToString[enumerationType]];
  If[enumerationType!=Tinkerforge`IPConnection`ENUMERATIONUTYPEUDISCONNECTED,
   Print["Connected UID:     "<>connectedUid];
   Print["Position:          "<>FromCharacterCode[position]];
   Print["Hardware Version:  "<>StringJoin[Riffle[Map[ToString,hardwareVersion],{".","."}]]];
   Print["Firmware Version:  "<>StringJoin[Riffle[Map[ToString,firmwareVersion],{".","."}]]];
   Print["Device Identifier: "<>ToString[deviceIdentifier]]
  ];
  Print[""]
 ]

AddEventHandler[ipcon@EnumerateCallback,EnumerateCB]

(* Trigger enumerate *)
ipcon@Enumerate[]

Input["Click OK to exit"]

(* Clean up *)
ipcon@Disconnect[]
ReleaseNETObject[ipcon]

Authenticate

Download (ExampleAuthenticate.nb)

 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
Needs["NETLink`"]
LoadNETAssembly["Tinkerforge",NotebookDirectory[]<>".."]

host="localhost"
port=4223
secret="My Authentication Secret!"

(* Create IPConnection *)
ipcon=NETNew["Tinkerforge.IPConnection"]

(* Authenticate each time the connection got (re-)established *)
ConnectedCB[sender_,connectReason_]:=
 Module[{},
  If[connectReason==Tinkerforge`IPConnection`CONNECTUREASONUREQUEST,Print["Connected by request"]];
  If[connectReason==Tinkerforge`IPConnection`CONNECTUREASONUAUTOURECONNECT,Print["Auto-Reconnect"]];
  (* Authenticate first... *)
  sender@Authenticate[secret];
  (* ...then trigger enumerate *)
  sender@Enumerate[]
 ]

AddEventHandler[ipcon@Connected,ConnectedCB]

(* Print incoming enumeration information *)
EnumerateCB[sender_,uid_,connectedUid_,position_,hardwareVersion_,firmwareVersion_,
            deviceIdentifier_,enumerationType_]:=
 Print["UID: "<>uid<>", Enumeration Type: "<>ToString[enumerationType]]

AddEventHandler[ipcon@EnumerateCallback,EnumerateCB]

(* Connect to brickd *)
ipcon@Connect[host,port]

Input["Click OK to exit"]

(* Clean up *)
ipcon@Disconnect[]
ReleaseNETObject[ipcon]

API

The namespace for the IPConnection is Tinkerforge.*.

Basic Functions

IPConnection[] → ipcon
Returns:
  • ipcon -- NETObject[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.

ipcon=NETNew["Tinkerforge.IPConnection"]

The .NET runtime has built-in garbage collection that frees objects that are no longer in use by a program. But because Mathematica can not automatically tell when a Mathematica "program" doesn't use a .NET object anymore, this has to be done by the program. For this the ReleaseNETObject[] function is used in the examples.

For further information about object management in .NET/Link see the corresponding Mathematica .NET/Link documentation.

IPConnection@Connect[host, port] → Null
Parameters:
  • host -- String
  • port -- Integer

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[] → Null

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

IPConnection@Authenticate[secret] → Null
Parameters:
  • secret -- String

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@GetConnectionState[] → connectionState
Returns:
  • connectionState -- Integer

Can return the following states:

  • IPConnection`CONNECTIONUSTATEUDISCONNECTED (0): No connection is established.
  • IPConnection`CONNECTIONUSTATEUCONNECTED (1): A connection to the Brick Daemon or the WIFI/Ethernet Extension is established.
  • IPConnection`CONNECTIONUSTATEUPENDING (2): IP Connection is currently trying to connect.
IPConnection@SetAutoReconnect[autoReconnect] → Null
Parameters:
  • autoReconnect -- True/False

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.

IPConnection@GetAutoReconnect[] → autoReconnect
Returns:
  • autoReconnect -- True/False

Returns True if auto-reconnect is enabled, False otherwise.

IPConnection@SetTimeout[timeout] → Null
Parameters:
  • timeout -- Integer

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

Default timeout is 2500.

IPConnection@GetTimeout[] → timeout
Parameters:
  • timeout -- Integer

Returns the timeout as set by SetTimeout[].

IPConnection@Enumerate[] → Null

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

IPConnection@Wait[] → Null

Stops the current thread until Unwait[] is called.

This is useful if you rely solely on callbacks for events, if you want to wait for a specific callback or if the IP Connection was created in a thread.

Wait and Unwait act in the same way as Acquire and Release of a semaphore.

IPConnection@Unwait[] → Null

Unwaits the thread previously stopped by Wait[]

Wait and Unwait act in the same way as Acquire and Release of a semaphore.

Callbacks

Callbacks can be registered to be notified about events. The registration is done by appending your callback handler to the corresponding event:

MyCallback[sender_,value_]:=Print["Value: "<>ToString[value]]

AddEventHandler[ipcon@ExampleCallback,MyCallback]

For further information about event handling using .NET/Link see the corresponding Mathematica .NET/Link documentation.

The available events are described below.

event IPConnection@EnumerateCallback[sender, uid, connectedUid, position, {hardwareVersion1, hardwareVersion2, hardwareVersion3}, {firmwareVersion1, firmwareVersion2, firmwareVersion3}, deviceIdentifier, enumerationType]
Parameters:
  • sender -- NETObject[IPConnection]
  • uid -- String
  • connectedUid -- String
  • position -- Integer
  • hardwareVersioni -- Integer
  • firmwareVersioni -- Integer
  • deviceIdentifier -- Integer
  • enumerationType -- Integer

The event receives 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).
  • hardwareVersioni: Major, minor and release number for hardware version.
  • firmwareVersioni: Major, minor and release number for firmware version.
  • deviceIdentifier: A number that represents the device.
  • enumerationType: Type of enumeration.

Possible enumeration types are:

  • IPConnection`ENUMERATIONUTYPEUAVAILABLE (0): Device is available (enumeration triggered by user: Enumerate[]). This enumeration type can occur multiple times for the same device.
  • IPConnection`ENUMERATIONUTYPEUCONNECTED (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`ENUMERATIONUTYPEUDISCONNECTED (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>`DEVICEUIDENTIFIER

For example: BrickMaster`DEVICEUIDENTIFIER or BrickletAmbientLight`DEVICEUIDENTIFIER.

event IPConnection@ConnectedCallback[sender, connectReason]
Parameters:
  • sender -- NETObject[IPConnection]
  • connectReason -- Integer

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

  • IPConnection`CONNECTUREASONUREQUEST (0): Connection established after request from user.
  • IPConnection`CONNECTUREASONUAUTOURECONNECT (1): Connection after auto-reconnect.
event IPConnection@DisconnectedCallback[sender, disconnectReason]
Parameters:
  • sender -- NETObject[IPConnection]
  • disconnectReason -- Integer

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

  • IPConnection`DISCONNECTUREASONUREQUEST (0): Disconnect was requested by user.
  • IPConnection`DISCONNECTUREASONUERROR (1): Disconnect because of an unresolvable error.
  • IPConnection`DISCONNECTUREASONUSHUTDOWN (2): Disconnect initiated by Brick Daemon or WIFI/Ethernet Extension.