Rust - IP Connection

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

Examples

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

Enumerate

Download (example_enumerate.rs)

 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
use std::{error::Error, io, thread};
use tinkerforge::ip_connection::{EnumerateResponse, EnumerationType, IpConnection};

const HOST: &str = "localhost";
const PORT: u16 = 4223;

fn print_enumerate_response(response: &EnumerateResponse) {
    println!("UID:               {}", response.uid);
    println!("Enumeration Type:  {:?}", response.enumeration_type);

    if response.enumeration_type == EnumerationType::Disconnected {
        println!("");
        return;
    }

    println!("Connected UID:     {}", response.connected_uid);
    println!("Position:          {}", response.position);
    println!("Hardware Version:  {}.{}.{}", response.hardware_version[0], response.hardware_version[1], response.hardware_version[2]);
    println!("Firmware Version:  {}.{}.{}", response.firmware_version[0], response.firmware_version[1], response.firmware_version[2]);
    println!("Device Identifier: {}", response.device_identifier);
    println!("");
}

fn main() -> Result<(), Box<dyn Error>> {
    let ipcon = IpConnection::new(); // Create IP connection

    ipcon.connect((HOST, PORT)).recv()??; // Connect to brickd

    let receiver = ipcon.get_enumerate_callback_receiver();

    // Spawn thread to react to enumerate callback messages.
    // This thread must not be terminated or joined,
    // as it will end when the IP connection (and the receiver's sender) is dropped.
    thread::spawn(move || {
        for response in receiver {
            print_enumerate_response(&response);
        }
    });

    // Trigger Enumerate
    ipcon.enumerate();

    println!("Press enter to exit.");
    let mut _input = String::new();
    io::stdin().read_line(&mut _input)?;
    ipcon.disconnect();
    Ok(())
}

Authenticate

Download (example_authenticate.rs)

 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
79
80
81
82
83
84
85
86
use std::{error::Error, io, thread};
use tinkerforge::ip_connection::{ConnectReason, EnumerateResponse, EnumerationType, IpConnection, IpConnectionRequestSender};

const HOST: &str = "localhost";
const PORT: u16 = 4223;
const SECRET: &str = "My Authentication Secret!";

fn authenticate(reason: ConnectReason, request_sender: &mut IpConnectionRequestSender) {
    match reason {
        ConnectReason::Request => println!("Connected by request"),
        ConnectReason::AutoReconnect => println!("Auto-Reconnected"),
    }

    // Authenticate first...
    match request_sender.authenticate(SECRET) {
        Ok(rx) => {
            if let Ok(_) = rx.recv() {
                println!("Authentication succeded");

                // ...reenable auto reconnect mechanism, as described below...
                request_sender.set_auto_reconnect(true);

                // ...then trigger enumerate
                request_sender.enumerate();
            } else {
                println!("Authentication request sent, but got no response. Maybe your secret is wrong?")
            }
        }
        Err(e) => println!("Could not authenticate: {}", e),
    }
}

fn print_enumerate_response(response: &EnumerateResponse) {
    println!("UID:               {}", response.uid);
    println!("Enumeration Type:  {:?}", response.enumeration_type);

    if response.enumeration_type == EnumerationType::Disconnected {
        println!("");
        return;
    }

    println!("Connected UID:     {}", response.connected_uid);
    println!("Position:          {}", response.position);
    println!("Hardware Version:  {}.{}.{}", response.hardware_version[0], response.hardware_version[1], response.hardware_version[2]);
    println!("Firmware Version:  {}.{}.{}", response.firmware_version[0], response.firmware_version[1], response.firmware_version[2]);
    println!("Device Identifier: {}", response.device_identifier);
    println!("");
}

fn main() -> Result<(), Box<dyn Error>> {
    let mut ipcon = IpConnection::new(); // Create IP connection

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

    let connect_receiver = ipcon.get_connect_callback_receiver();

    // Spawn thread to react to connect callback messages.
    // This thread must not be terminated or joined,
    // as it will end when the IP connection (and the receiver's sender) is dropped.
    let mut request_sender = ipcon.get_request_sender();
    thread::spawn(move || {
        for reason in connect_receiver {
            authenticate(reason, &mut request_sender)
        }
    });

    // Get Enumerate Receiver
    let enumerate_receiver = ipcon.get_enumerate_callback_receiver();

    // Spawn thread to react to enumerate events. This thread must not be terminated or joined,
    // as it will end when the IP connection (and the receiver's sender) is dropped.
    thread::spawn(move || {
        for response in enumerate_receiver {
            print_enumerate_response(&response);
        }
    });

    ipcon.connect((HOST, PORT)).recv()??; // Connect to brickd

    println!("Press enter to exit.");
    let mut _input = String::new();
    io::stdin().read_line(&mut _input)?;
    ipcon.disconnect();
    Ok(())
}

API

The IpConnection is defined in the module tinkerforge::ip_connection.

Basic Functions

pub fn IpConnection::new() → IpConnection

Creates an IP Connection instance that can be used to enumerate the available devices. It is also required for the constructor of Bricks and Bricklets.

pub fn IpConnection::get_request_sender(&self) → IpConnectionRequestSender

The IP connection can not be shared with other threads. To still be able to use its functionality in other threads, this method can create IP connection request senders. These offer the same functionality, but can be created, cloned, moved into other threads and destroyed at will, as the IP connection instance itself owns the connection.

pub fn IpConnection::connect<T: ToSocketAddrs>(&self, addr: T) → Receiver<Result<(), ConnectError>>

Creates a TCP/IP connection to the given addr. addr has to implement ToSocketAddrs. For example you can use a tuple (host, port) where host is a string (either an ip address or a host name) and port is a u16. The address can refer to a Brick Daemon or to a WIFI/Ethernet Extension.

Devices can only be controlled when the connection was established successfully.

Returns a receiver, which will receive either () or an ConnectError if there is no Brick Daemon or WIFI/Ethernet Extension listening at the given host and port.

pub fn IpConnection::disconnect(&self) → Receiver<Result<(), DisconnectErrorNotConnected>>

Disconnects the TCP/IP connection from the Brick Daemon or the WIFI/Ethernet Extension. Returns a receiver, which will receive either () or an error if there is no connection to disconnect.

pub fn IpConnection::authenticate(&self, secret: &str) → Result<ConvertingReceiver<()>, AuthenticateError>

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.

pub fn IpConnection::get_connection_state(&self) → ConnectionState

Can return the following states:

  • ConnectionState::Disconnected = 0: No connection is established.
  • ConnectionState::Connected = 1: A connection to the Brick Daemon or the WIFI/Ethernet Extension is established.
  • ConnectionState::Pending = 2: IP Connection is currently trying to connect.
pub fn IpConnection::set_auto_reconnect(&mut self, auto_reconnect_enabled: bool)

Enables or disables auto-reconnect. If auto-reconnect is enabled, the IP Connection will try to reconnect to the previously given address, if the currently existing connection is lost. Therefore, auto-reconnect only does something after a successful connect() call.

Default value is true.

pub fn IpConnection::get_auto_reconnect(&self) → bool

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

pub fn IpConnection::set_timeout(&mut self, timeout: std::time::Duration)

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

Default timeout is 2500 ms.

pub fn IpConnection::get_timeout(&self) → std::time::Duration

Returns the timeout as set by set_timeout().

pub fn IpConnection::enumerate(&self)

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

Callbacks

Callbacks can be registered to be notified about events. The registration is done by creating a message receiver. Received messages can be handled asynchronously by spawning a new thread:

let receiver = ipcon.get_example_callback_receiver();
// No join is needed here, as the iteration over the receiver ends when the ipcon is dropped.
thread::spawn(move || {
    for value in receiver {
        println!("Value: {:?}", value);
    }
};

The available events are described below.

pub fn IpConnection::get_enumerate_callback_receiver(&self) → ConvertingCallbackReceiver<EnumerateResponse>

The event receives a struct with seven members:

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

  • EnumerationType::Available = 0: Device is available (enumeration triggered by user: enumerate()). This enumeration type can occur multiple times for the same device.
  • EnumerationType::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.
  • EnumerationType::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: MasterBrick::DEVICE_IDENTIFIER or AmbientLightBricklet::DEVICE_IDENTIFIER.

pub fn IpConnection::get_connect_callback_receiver(&self) → Receiver<ConnectReason>

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

  • ConnectReason::Request = 0: Connection established after request from user.
  • ConnectReason::AutoReconnect = 1: Connection after auto-reconnect.
pub fn IpConnection::get_disconnect_callback_receiver(&self) → Receiver<DisconnectReason>

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

  • DisconnectReason::Request = 0: Disconnect was requested by user.
  • DisconnectReason::Error = 1: Disconnect because of an unresolvable error.
  • DisconnectReason::Shutdown = 2: Disconnect initiated by Brick Daemon or WIFI/Ethernet Extension.