This is the description of the Python 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 Python API bindings is part of their general description.
The example code below is Public Domain (CC0 1.0).
Download (example_enumerate.py)
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4HOST = "localhost"
5PORT = 4223
6
7from tinkerforge.ip_connection import IPConnection
8
9# Print incoming enumeration
10def cb_enumerate(uid, connected_uid, position, hardware_version, firmware_version,
11 device_identifier, enumeration_type):
12 print("UID: " + uid)
13 print("Enumeration Type: " + str(enumeration_type))
14
15 if enumeration_type == IPConnection.ENUMERATION_TYPE_DISCONNECTED:
16 print("")
17 return
18
19 print("Connected UID: " + connected_uid)
20 print("Position: " + position)
21 print("Hardware Version: " + str(hardware_version))
22 print("Firmware Version: " + str(firmware_version))
23 print("Device Identifier: " + str(device_identifier))
24 print("")
25
26if __name__ == "__main__":
27 # Create connection and connect to brickd
28 ipcon = IPConnection()
29 ipcon.connect(HOST, PORT)
30
31 # Register Enumerate Callback
32 ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, cb_enumerate)
33
34 # Trigger Enumerate
35 ipcon.enumerate()
36
37 input("Press key to exit\n") # Use raw_input() in Python 2
38 ipcon.disconnect()
Download (example_authenticate.py)
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4HOST = "localhost"
5PORT = 4223
6SECRET = "My Authentication Secret!"
7
8from tinkerforge.ip_connection import IPConnection
9
10# Authenticate each time the connection got (re-)established
11def cb_connected(connect_reason):
12 if connect_reason == IPConnection.CONNECT_REASON_REQUEST:
13 print("Connected by request")
14 elif connect_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT:
15 print("Auto-Reconnect")
16
17 # Authenticate first...
18 try:
19 ipcon.authenticate(SECRET)
20 print("Authentication succeeded")
21 except:
22 print("Could not authenticate")
23 return
24
25 # ...reenable auto reconnect mechanism, as described below...
26 ipcon.set_auto_reconnect(True)
27
28 # ...then trigger enumerate
29 ipcon.enumerate()
30
31# Print incoming enumeration
32def cb_enumerate(uid, connected_uid, position, hardware_version, firmware_version,
33 device_identifier, enumeration_type):
34 print("UID: " + uid + ", Enumeration Type: " + str(enumeration_type))
35
36if __name__ == "__main__":
37 # Create IPConnection
38 ipcon = IPConnection()
39
40 # Disable auto reconnect mechanism, in case we have the wrong secret.
41 # If the authentication is successful, reenable it.
42 ipcon.set_auto_reconnect(False)
43
44 # Register Connected Callback
45 ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, cb_connected)
46
47 # Register Enumerate Callback
48 ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, cb_enumerate)
49
50 # Connect to brickd
51 ipcon.connect(HOST, PORT)
52
53 input("Press key to exit\n") # Use raw_input() in Python 2
54 ipcon.disconnect()
Generally, every method of the Python bindings can throw an
tinkerforge.ip_connection.Error exception that has a value and a
description property. value can have different values:
Error.TIMEOUT = -1
Error.NOT_ADDED = -6 (unused since Python bindings version 2.0.0)
Error.ALREADY_CONNECTED = -7
Error.NOT_CONNECTED = -8
Error.INVALID_PARAMETER = -9
Error.NOT_SUPPORTED = -10
Error.UNKNOWN_ERROR_CODE = -11
Error.STREAM_OUT_OF_SYNC = -12
Error.INVALID_UID = -13
Error.NON_ASCII_CHAR_IN_SECRET = -14
Error.WRONG_DEVICE_TYPE = -15
Error.DEVICE_REPLACED = -16
Error.WRONG_RESPONSE_LENGTH = -17
All methods listed below are thread-safe.
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.
host -- str
port -- int
None
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.
None
Disconnects the TCP/IP connection from the Brick Daemon or the WIFI/Ethernet Extension.
secret -- str
None
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.
Added in version 2.1.0.
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.
auto_reconnect -- bool
None
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.
bool
Returns True if auto-reconnect is enabled, False otherwise.
timeout -- float
None
Sets the timeout in seconds for getters and for setters for which the response expected flag is activated.
Default timeout is 2.5.
float
Returns the timeout as set by set_timeout().
None
Broadcasts an enumerate request. All devices will respond with an enumerate callback.
None
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.
callback_id -- int
function -- callable
None
Registers the given function with the given callback_id.
The available callback IDs with corresponding function signatures are described below.
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 the callback function:
def my_callback(param):
print(param)
ipcon.register_callback(IPConnection.CALLBACK_EXAMPLE, my_callback)
The available constants with inherent number and type of parameters are described below.
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: Master.DEVICE_IDENTIFIER
or AmbientLight.DEVICE_IDENTIFIER.
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.
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.