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)

 1program ExampleEnumerate;
 2
 3{$ifdef MSWINDOWS}{$apptype CONSOLE}{$endif}
 4{$ifdef FPC}{$mode OBJFPC}{$H+}{$endif}
 5
 6uses
 7  SysUtils, IPConnection, Device;
 8
 9type
10  TExample = class
11  private
12    ipcon: TIPConnection;
13  public
14    procedure EnumerateCB(sender: TIPConnection;
15                          const uid: string; const connectedUid: string; const position: char;
16                          const hardwareVersion: TVersionNumber; const firmwareVersion: TVersionNumber;
17                          const deviceIdentifier: word; const enumerationType: byte);
18    procedure Execute;
19  end;
20
21const
22  HOST = 'localhost';
23  PORT = 4223;
24
25var
26  e: TExample;
27
28{ Print incoming enumeration }
29procedure TExample.EnumerateCB(sender: TIPConnection;
30                               const uid: string; const connectedUid: string; const position: char;
31                               const hardwareVersion: TVersionNumber; const firmwareVersion: TVersionNumber;
32                               const deviceIdentifier: word; const enumerationType: byte);
33begin
34  WriteLn('UID:               ' + uid);
35  WriteLn('Enumerate Type:    ' + IntToStr(enumerationType));
36
37  if (enumerationType <> IPCON_ENUMERATION_TYPE_DISCONNECTED) then begin
38    WriteLn('Connected UID:     ' + connectedUid);
39    WriteLn('Position:          ' + position);
40    WriteLn('Hardware Version:  ' + IntToStr(hardwareVersion[0]) + '.' +
41                                    IntToStr(hardwareVersion[1]) + '.' +
42                                    IntToStr(hardwareVersion[2]));
43    WriteLn('Firmware Version:  ' + IntToStr(firmwareVersion[0]) + '.' +
44                                    IntToStr(firmwareVersion[1]) + '.' +
45                                    IntToStr(firmwareVersion[2]));
46    WriteLn('Device Identifier: ' + IntToStr(deviceIdentifier));
47  end;
48
49  WriteLn('');
50end;
51
52procedure TExample.Execute;
53begin
54  { Create connection and connect to brickd }
55  ipcon := TIPConnection.Create;
56  ipcon.Connect(HOST, PORT);
57
58  { Register enumerate callback to "EnumerateCB" }
59  ipcon.OnEnumerate := {$ifdef FPC}@{$endif}EnumerateCB;
60
61  { Trigger enumerate }
62  ipcon.Enumerate;
63
64  WriteLn('Press key to exit');
65  ReadLn;
66  ipcon.Destroy; { Calls ipcon.Disconnect internally }
67end;
68
69begin
70  e := TExample.Create;
71  e.Execute;
72  e.Destroy;
73end.

Authenticate

Download (ExampleAuthenticate.pas)

 1program ExampleAuthenticate;
 2
 3{$ifdef MSWINDOWS}{$apptype CONSOLE}{$endif}
 4{$ifdef FPC}{$mode OBJFPC}{$H+}{$endif}
 5
 6uses
 7  SysUtils, IPConnection, Device;
 8
 9type
10  TExample = class
11  private
12    ipcon: TIPConnection;
13  public
14    procedure ConnectedCB(sender: TIPConnection; const connectReason: byte);
15    procedure EnumerateCB(sender: TIPConnection;
16                          const uid: string; const connectedUid: string; const position: char;
17                          const hardwareVersion: TVersionNumber; const firmwareVersion: TVersionNumber;
18                          const deviceIdentifier: word; const enumerationType: byte);
19    procedure Execute;
20  end;
21
22const
23  HOST = 'localhost';
24  PORT = 4223;
25  SECRET = 'My Authentication Secret!';
26
27var
28  e: TExample;
29
30{ Authenticate each time the connection got (re-)established }
31procedure TExample.ConnectedCB(sender: TIPConnection; const connectReason: byte);
32begin
33  case connectReason of
34    IPCON_CONNECT_REASON_REQUEST:
35    begin
36      WriteLn('Connected by request');
37    end;
38    IPCON_CONNECT_REASON_AUTO_RECONNECT:
39    begin
40      WriteLn('Auto-Reconnect');
41    end;
42  end;
43  { Authenticate first... }
44  try
45    sender.Authenticate(SECRET);
46    WriteLn('Authentication succeeded');
47  except
48    WriteLn('Could not authenticate');
49    exit;
50  end;
51
52  { ...reenable auto reconnect mechanism, as described below... }
53  sender.SetAutoReconnect(true);
54
55  { ...then trigger enumerate }
56  sender.Enumerate;
57end;
58
59{ Print incoming enumeration }
60procedure TExample.EnumerateCB(sender: TIPConnection;
61                               const uid: string; const connectedUid: string; const position: char;
62                               const hardwareVersion: TVersionNumber; const firmwareVersion: TVersionNumber;
63                               const deviceIdentifier: word; const enumerationType: byte);
64begin
65  WriteLn('UID: ' + uid + ', Enumerate Type: ' + IntToStr(enumerationType));
66end;
67
68procedure TExample.Execute;
69begin
70  { Create IP Connection }
71  ipcon := TIPConnection.Create;
72
73  { Disable auto reconnect mechanism, in case we have the wrong secret.
74    If the authentication is successful, reenable it. }
75  ipcon.SetAutoReconnect(false);
76
77  { Register connected callback to "ConnectedCB" }
78  ipcon.OnConnected := {$ifdef FPC}@{$endif}ConnectedCB;
79
80  { Register enumerate callback to "EnumerateCB" }
81  ipcon.OnEnumerate := {$ifdef FPC}@{$endif}EnumerateCB;
82
83  { Connect to brickd }
84  ipcon.Connect(HOST, PORT);
85
86  WriteLn('Press key to exit');
87  ReadLn;
88  ipcon.Destroy; { Calls ipcon.Disconnect internally }
89end;
90
91begin
92  e := TExample.Create;
93  e.Execute;
94  e.Destroy;
95end.

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.