Delphi/Lazarus - IP Connection

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

Examples

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

Enumerate

Download (ExampleEnumerate.pas)

 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
program ExampleEnumerate;

{$ifdef MSWINDOWS}{$apptype CONSOLE}{$endif}
{$ifdef FPC}{$mode OBJFPC}{$H+}{$endif}

uses
  SysUtils, IPConnection, Device;

type
  TExample = class
  private
    ipcon: TIPConnection;
  public
    procedure EnumerateCB(sender: TIPConnection;
                          const uid: string; const connectedUid: string; const position: char;
                          const hardwareVersion: TVersionNumber; const firmwareVersion: TVersionNumber;
                          const deviceIdentifier: word; const enumerationType: byte);
    procedure Execute;
  end;

const
  HOST = 'localhost';
  PORT = 4223;

var
  e: TExample;

{ Print incoming enumeration }
procedure TExample.EnumerateCB(sender: TIPConnection;
                               const uid: string; const connectedUid: string; const position: char;
                               const hardwareVersion: TVersionNumber; const firmwareVersion: TVersionNumber;
                               const deviceIdentifier: word; const enumerationType: byte);
begin
  WriteLn('UID:               ' + uid);
  WriteLn('Enumerate Type:    ' + IntToStr(enumerationType));

  if (enumerationType <> IPCON_ENUMERATION_TYPE_DISCONNECTED) then begin
    WriteLn('Connected UID:     ' + connectedUid);
    WriteLn('Position:          ' + position);
    WriteLn('Hardware Version:  ' + IntToStr(hardwareVersion[0]) + '.' +
                                    IntToStr(hardwareVersion[1]) + '.' +
                                    IntToStr(hardwareVersion[2]));
    WriteLn('Firmware Version:  ' + IntToStr(firmwareVersion[0]) + '.' +
                                    IntToStr(firmwareVersion[1]) + '.' +
                                    IntToStr(firmwareVersion[2]));
    WriteLn('Device Identifier: ' + IntToStr(deviceIdentifier));
  end;

  WriteLn('');
end;

procedure TExample.Execute;
begin
  { Create connection and connect to brickd }
  ipcon := TIPConnection.Create;
  ipcon.Connect(HOST, PORT);

  { Register enumerate callback to "EnumerateCB" }
  ipcon.OnEnumerate := {$ifdef FPC}@{$endif}EnumerateCB;

  { Trigger enumerate }
  ipcon.Enumerate;

  WriteLn('Press key to exit');
  ReadLn;
  ipcon.Destroy; { Calls ipcon.Disconnect internally }
end;

begin
  e := TExample.Create;
  e.Execute;
  e.Destroy;
end.

Authenticate

Download (ExampleAuthenticate.pas)

 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
87
88
89
90
91
92
93
94
95
program ExampleAuthenticate;

{$ifdef MSWINDOWS}{$apptype CONSOLE}{$endif}
{$ifdef FPC}{$mode OBJFPC}{$H+}{$endif}

uses
  SysUtils, IPConnection, Device;

type
  TExample = class
  private
    ipcon: TIPConnection;
  public
    procedure ConnectedCB(sender: TIPConnection; const connectReason: byte);
    procedure EnumerateCB(sender: TIPConnection;
                          const uid: string; const connectedUid: string; const position: char;
                          const hardwareVersion: TVersionNumber; const firmwareVersion: TVersionNumber;
                          const deviceIdentifier: word; const enumerationType: byte);
    procedure Execute;
  end;

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

var
  e: TExample;

{ Authenticate each time the connection got (re-)established }
procedure TExample.ConnectedCB(sender: TIPConnection; const connectReason: byte);
begin
  case connectReason of
    IPCON_CONNECT_REASON_REQUEST:
    begin
      WriteLn('Connected by request');
    end;
    IPCON_CONNECT_REASON_AUTO_RECONNECT:
    begin
      WriteLn('Auto-Reconnect');
    end;
  end;
  { Authenticate first... }
  try
    sender.Authenticate(SECRET);
    WriteLn('Authentication succeeded');
  except
    WriteLn('Could not authenticate');
    exit;
  end;

  { ...reenable auto reconnect mechanism, as described below... }
  sender.SetAutoReconnect(true);

  { ...then trigger enumerate }
  sender.Enumerate;
end;

{ Print incoming enumeration }
procedure TExample.EnumerateCB(sender: TIPConnection;
                               const uid: string; const connectedUid: string; const position: char;
                               const hardwareVersion: TVersionNumber; const firmwareVersion: TVersionNumber;
                               const deviceIdentifier: word; const enumerationType: byte);
begin
  WriteLn('UID: ' + uid + ', Enumerate Type: ' + IntToStr(enumerationType));
end;

procedure TExample.Execute;
begin
  { Create IP Connection }
  ipcon := TIPConnection.Create;

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

  { Register connected callback to "ConnectedCB" }
  ipcon.OnConnected := {$ifdef FPC}@{$endif}ConnectedCB;

  { Register enumerate callback to "EnumerateCB" }
  ipcon.OnEnumerate := {$ifdef FPC}@{$endif}EnumerateCB;

  { Connect to brickd }
  ipcon.Connect(HOST, PORT);

  WriteLn('Press key to exit');
  ReadLn;
  ipcon.Destroy; { Calls ipcon.Disconnect internally }
end;

begin
  e := TExample.Create;
  e.Execute;
  e.Destroy;
end.

API

Basic Functions

constructor TIPConnection.Create

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.

destructor TIPConnection.Destroy

Destroys the IP Connection object. Calls Disconnect internally. The connection to the Brick Daemon gets closed and the threads of the IP Connection are terminated.

procedure TIPConnection.Connect(const host: string; const port: word)

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.

procedure TIPConnection.Disconnect

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

procedure TIPConnection.Authenticate(const 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.

function TIPConnection.GetConnectionState: byte

Can return the following states:

  • IPCON_CONNECTION_STATE_DISCONNECTED = 0: No connection is established.
  • IPCON_CONNECTION_STATE_CONNECTED = 1: A connection to the Brick Daemon or the WIFI/Ethernet Extension is established.
  • IPCON_CONNECTION_STATE_PENDING = 2: IP Connection is currently trying to connect.
procedure TIPConnection.SetAutoReconnect(const autoReconnect: 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.

function TIPConnection.GetAutoReconnect: boolean

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

procedure TIPConnection.SetTimeout(const timeout: longword)

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

Default timeout is 2500.

function TIPConnection.GetTimeout: longword

Returns the timeout as set by SetTimeout.

procedure TIPConnection.Enumerate

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

procedure IPConnection.Wait

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.

procedure TIPConnection.Unwait

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 assigning a procedure to an callback property of the TIPConnection object:

procedure TExample.MyCallback(sender: TIPConnection; const param: word);
begin
  WriteLn(param);
end;

ipcon.OnExample := {$ifdef FPC}@{$endif}example.MyCallback;

The available callback property and their type of parameters are described below.

property TIPConnection.OnEnumerate
procedure(sender: TIPConnection; const uid: string; const connectedUid: string; const position: char; const hardwareVersion: TVersionNumber; const firmwareVersion: TVersionNumber; const deviceIdentifier: word; const enumerationType: byte) of object;

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.
  • enumerationType: Type of enumeration.

Possible enumeration types are:

  • IPCON_ENUMERATION_TYPE_AVAILABLE = 0: Device is available (enumeration triggered by user: Disconnect). This enumeration type can occur multiple times for the same device.
  • IPCON_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.
  • IPCON_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-type>_DEVICE_IDENTIFIER

For example: BRICK_MASTER_DEVICE_IDENTIFIER or BRICKLET_AMBIENT_LIGHT_DEVICE_IDENTIFIER.

property TIPConnection.OnConnected
procedure(sender: TIPConnection; const connectReason: byte) of object;

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

  • IPCON_CONNECT_REASON_REQUEST = 0: Connection established after request from user.
  • IPCON_CONNECT_REASON_AUTO_RECONNECT = 1: Connection after auto-reconnect.
property TIPConnection.OnDisconnected
procedure(sender: TIPConnection; const disconnectReason: byte) of object;

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

  • IPCON_DISCONNECT_REASON_REQUEST = 0: Disconnect was requested by user.
  • IPCON_DISCONNECT_REASON_ERROR = 1: Disconnect because of an unresolvable error.
  • IPCON_DISCONNECT_REASON_SHUTDOWN = 2: Disconnect initiated by Brick Daemon or WIFI/Ethernet Extension.