Ruby - IP Connection

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

Examples

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

Enumerate

Download (example_enumerate.rb)

 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
#!/usr/bin/env ruby
# -*- ruby encoding: utf-8 -*-

require 'tinkerforge/ip_connection'

include Tinkerforge

HOST = 'localhost'
PORT = 4223

# Create IP connection to brickd
ipcon = IPConnection.new
ipcon.connect HOST, PORT

# Enumerate Bricks and Bricklets
ipcon.register_callback(IPConnection::CALLBACK_ENUMERATE) do |uid, connected_uid, position,
                                                              hardware_version, firmware_version,
                                                              device_identifier, enumeration_type|
  puts "UID:               #{uid}"
  puts "Enumeration Type:  #{enumeration_type}"

  if enumeration_type != IPConnection::ENUMERATION_TYPE_DISCONNECTED
    puts "Connected UID:     #{connected_uid}"
    puts "Position:          #{position}"
    puts "Hardware Version:  #{hardware_version}"
    puts "Firmware Version:  #{firmware_version}"
    puts "Device Identifier: #{device_identifier}"
  end

  puts ''
end

ipcon.enumerate

puts 'Press key to exit'
$stdin.gets
ipcon.disconnect

Authenticate

Download (example_authenticate.rb)

 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
#!/usr/bin/env ruby
# -*- ruby encoding: utf-8 -*-

require 'tinkerforge/ip_connection'

include Tinkerforge

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

# Create IP connection
ipcon = IPConnection.new

# Disable auto reconnect mechanism, in case we have the wrong secret.
# If the authentication is successful, reenable it.
ipcon.set_auto_reconnect false

# Authenticate each time the connection got (re-)established
ipcon.register_callback(IPConnection::CALLBACK_CONNECTED) do |connect_reason|
  case connect_reason
    when IPConnection::CONNECT_REASON_REQUEST
      puts 'Connected by request'
    when IPConnection::CONNECT_REASON_AUTO_RECONNECT
      puts 'Auto-Reconnect'
  end

  # Authenticate first...
  begin
    ipcon.authenticate SECRET
    puts 'Authentication succeeded'

    # ...reenable auto reconnect mechanism, as described above...
    ipcon.set_auto_reconnect true

    # ...then trigger enumerate
    ipcon.enumerate
  rescue
    puts 'Could not authenticate'
  end
end

# Print incoming enumeration
ipcon.register_callback(IPConnection::CALLBACK_ENUMERATE) do |uid, connected_uid, position,
                                                              hardware_version, firmware_version,
                                                              device_identifier, enumeration_type|
  puts "UID: #{uid}, Enumeration Type: #{enumeration_type}"
end

# Connecte to brickd
ipcon.connect HOST, PORT

puts 'Press key to exit'
$stdin.gets
ipcon.disconnect

API

Basic Functions

IPConnection::new → ipcon

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) → nil
Parameters:
  • host -- str
  • 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.

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 → nil

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

IPConnection#authenticate(secret) → nil
Parameters:secret -- str

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#get_connection_state → 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#set_auto_reconnect(auto_reconnect) → nil
Parameters:auto_reconnect -- bool

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#get_auto_reconnect → bool

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

IPConnection#set_timeout(timeout) → nil
Parameters:timeout -- float

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

Default timeout is 2.5.

IPConnection#get_timeout → float

Returns the timeout as set by #set_timeout.

IPConnection#enumerate → nil

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

IPConnection#wait → nil

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 → nil

Unwaits the thread previously stopped by #wait

wait and unwait act in the same way as acquire and release of a semaphore.

Callback Configuration Functions

IPConnection#register_callback(callback_id) { |param [, ...]| block } → nil
Parameters:callback_id -- int

Registers the given block with the given callback_id.

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

Callbacks

Callbacks can be registered to be notified about events. The registration is done with the #register_callback function. The first parameter is the callback ID and the second parameter is a block:

ipcon.register_callback IPConnection::CALLBACK_EXAMPLE, do |param|
  puts "#{param}"
end

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

IPConnection::CALLBACK_ENUMERATE
Parameters:
  • uid -- str
  • connected_uid -- str
  • position -- chr
  • hardware_version -- [int, int, int]
  • firmware_version -- [int, int, int]
  • device_identifier -- int
  • enumeration_type -- int

The callback has seven parameters:

  • uid: The UID of the device.
  • connected_uid: 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).
  • hardware_version: Major, minor and release number for hardware version.
  • firmware_version: Major, minor and release number for firmware version.
  • device_identifier: 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.

IPConnection::CALLBACK_CONNECTED
Parameters:connect_reason -- 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:disconnect_reason -- 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.