PHP - IP Connection

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

Examples

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

Enumerate

Download (ExampleEnumerate.php)

 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
<?php

require_once('Tinkerforge/IPConnection.php');

use Tinkerforge\IPConnection;

const HOST = 'localhost';
const PORT = 4223;

// Print incoming enumeration
function cb_enumerate($uid, $connectedUid, $position,
                      $hardwareVersion, $firmwareVersion,
                      $deviceIdentifier, $enumerationType)
{
    echo "UID:               $uid\n";
    echo "Enumeration Type:  $enumerationType\n";

    if($enumerationType == IPConnection::ENUMERATION_TYPE_DISCONNECTED) {
        echo "\n";
        return;
    }

    echo "Connected UID:     $connectedUid\n";
    echo "Position:          $position\n";
    echo "Hardware Version:  $hardwareVersion[0].$hardwareVersion[1].$hardwareVersion[2]\n";
    echo "Firmware Version:  $firmwareVersion[0].$firmwareVersion[1].$firmwareVersion[2]\n";
    echo "Device Identifier: $deviceIdentifier\n";
    echo "\n";
}

// Create IP connection and connect to brickd
$ipcon = new IPConnection();
$ipcon->connect(HOST, PORT);

// Register enumerate callback to "cb_enumerate"
$ipcon->registerCallback(IPConnection::CALLBACK_ENUMERATE, 'cb_enumerate');

$ipcon->enumerate();

echo "Press ctrl+c to exit\n";
$ipcon->dispatchCallbacks(-1); // Dispatch callbacks forever

?>

Authenticate

Download (ExampleAuthenticate.php)

 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
<?php

require_once('Tinkerforge/IPConnection.php');

use Tinkerforge\IPConnection;
use Tinkerforge\TinkerforgeException;

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

// Authenticate each time the connection got (re-)established
function cb_connected($connectReason, $userData)
{
    $ipcon = $userData;

    switch ($connectReason) {
    case IPConnection::CONNECT_REASON_REQUEST:
        echo "Connected by request\n";
        break;
    }

    // Authenticate first...
    try {
        $ipcon->authenticate(SECRET);
        echo "Authentication succeeded\n";
    } catch (TinkerforgeException $e) {
        echo "Could not authenticate\n";
        return;
    }

    // ...then trigger enumerate
    $ipcon->enumerate();
}

// Print incoming enumeration
function cb_enumerate($uid, $connectedUid, $position,
                      $hardwareVersion, $firmwareVersion,
                      $deviceIdentifier, $enumerationType)
{
    echo "UID: $uid, Enumeration Type: $enumerationType\n";
}

// Create IP connection and connect to brickd
$ipcon = new IPConnection();

// Register connected callback to "cb_connected"
$ipcon->registerCallback(IPConnection::CALLBACK_CONNECTED, 'cb_connected', $ipcon);

// Register enumerate callback to "cb_enumerate"
$ipcon->registerCallback(IPConnection::CALLBACK_ENUMERATE, 'cb_enumerate');

$ipcon->connect(HOST, PORT);

echo "Press ctrl+c to exit\n";
$ipcon->dispatchCallbacks(-1); // Dispatch callbacks forever

?>

API

Basic Functions

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

void IPConnection::connect(string $host, int $port)

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.

void IPConnection::disconnect()

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

void IPConnection::authenticate(string $secret)

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.

int IPConnection::getConnectionState()

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.
void IPConnection::setTimeout(float $seconds)

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

Default timeout is 2.5.

int IPConnection::getTimeout()

Returns the timeout as set by setTimeout().

void IPConnection::enumerate()

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

void IPConnection::dispatchCallbacks(float $seconds)

Dispatches incoming callbacks for the given amount of time in seconds (negative value means infinity). Because PHP doesn't support threads you need to call this method periodically to ensure that incoming callbacks are handled. If you don't use callbacks you don't need to call this method.

The recommended dispatch time 0. This will just dispatch all pending callbacks without waiting for further callbacks.

Callback Configuration Functions

void IPConnection::registerCallback(int $callback_id, callable $function, mixed $user_data=NULL)

Registers the given $function with the given $callback_id. The optional $user_data will be passed as the last parameter to the $function.

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 registerCallback() function. The parameters consist of the callback ID, the callback function and optional user data:

<?php

function my_callback($param)
{
    echo $param . "\n";
}

$ipcon->registerCallback(IPConnection::CALLBACK_EXAMPLE, 'my_callback');

?>

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

int IPConnection::CALLBACK_ENUMERATE
<?php   void callback(string $uid, string $connectedUid, char $position, array $hardwareVersion, array $firmwareVersion, int $deviceIdentifier, int $enumerationType [, mixed $userData])   ?>

The callback receives 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.
  • $enumerationType: 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 $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>::DEVICE_IDENTIFIER

For example: BrickMaster::DEVICE_IDENTIFIER or BrickletAmbientLight::DEVICE_IDENTIFIER.

int IPConnection::CALLBACK_CONNECTED
<?php   void callback(int $connectReason [, mixed $userData])   ?>

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.
int IPConnection::CALLBACK_DISCONNECTED
<?php   void callback(int $connectReason [, mixed $userData])   ?>

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.