pip install edbot
Python is an interpreted, cross-platform, object-oriented programming language created by Guido van Rossum in 1991. It supports modules and packages, which encourages program modularity and code reuse and its simple, easy to learn syntax emphasises readability.
The Edbot Dream Python API implemented as a Python 3 package. It allows a Python program to control your Edbot Dream robots. This guide assumes you are familiar with writing Python code.
Visit the Python downloads page to download and install Python 3.x for your platform. For Windows, make sure you select the option to add Python to the path.
Next you'll need the edbot Python package published through PyPI. You can install it with easy_install or pip. Using pip on the command line:
pip install edbot
Check the installed and latest version with:
pip index versions edbot
If you've already installed it, run the following command to make sure you have the latest version:
pip install --upgrade edbot
Alternatively you can install an integrated development environment (IDE) with a bundled Python interpreter, such as the popular Thonny.
Make sure you are running the latest version of the Edbot Software available from the download page. For the purposes of this guide we'll assume you've set up your Edbot server and you're running it locally. If the Edbot Software is running remotely, you'll need to change the localhost references to the name of the remote server.
The Python examples folder is part of the Edbot Software installation. In Windows the folder is located in your 'Documents' folder:
Documents\Edbot\python
Similarly for macOS and Linux:
Documents/Edbot/python
The folder should contain sample Python programs for some of the robots, including:
dream_airplane.py
dream_crocodile.py
dream_elephant.py
dream_motorcycle.py
dream_scorpion.py
We're using classic Python 3.11.1 on Windows for this guide. Start a command prompt and run Python in interactive mode. If you're using Thonny, start it up and type the commands in the shell window.
> python
Python 3.11.1 (tags/v3.11.1:a7a450f, Dec 6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "licence" for more information.
>>>
The Edbot Dream Python API enables your Python program to connect to the Edbot Software which acts as the server. First things first. Import the edbot package.
>>> import edbot
Now create an instance of the EdbotClient class. Specify the Edbot server running locally on the default port of 8080. You can use the API to connect to a remote Edbot server too, but we'll stick to a server running locally for this guide. The client parameter can be any string to identify your program to the server. It defaults to "Python".
>>> ec = edbot.EdbotClient("localhost", 8080)
Your program should only create one instance of the EdbotClient class. |
Next connect to the Edbot server both to send commands and receive data updates.
>>> ec.connect()
You can now query the robot names available. Let's assume we have configured an Edbot Dream called "Anna":
>>> ec.get_robot_names()
['Anna']
You can specify an optional model to only return robots of that type:
>>> ec.get_robot_names("dream")
['Anna']
After connecting to the Edbot server, your program will need to wait for control of the Edbot Dream.
>>> ec.wait_until_active("Anna")
Grant control using the active user menu in the Edbot Software. See below.
If you're developing solo, the Edbot Software provides a convenient per-robot option "Open access" in the Server → Setup → Configure window. This will allow any connection to control the robot. Check this option while developing so that you don't need to give control each time you test your program. To stop other network users inadvertently accessing the robot, uncheck the "Available on network" option. |
You can now send commands to your Edbot Dream. For example to play buzzer melody 0, use:
>>> ec.set_buzzer("Anna", "0/255")
To turn on a motor plugged into port 1 at full speed, use:
>>> ec.set_servo_speed("Anna", "1/100")
and to turn it off:
>>> ec.set_servo_speed("Anna", "1/0")
You can control motors, servos, the built-in buzzer, an optional LED module, access built-in sensors and external sensors and even get your Edbot Dream to speak using the API functions detailed in the Reference section.
After connecting, the Edbot Software sends real time data to your client program. Use the following function to get the data as a Python dictionary.
>>> ec.get_data()
The dictionary gives access to lots of useful information you can use in your code. Here's what the values mean:
{
"server": { # server information
"version": "7.0.0.1691",
"platform": "Windows 10, 10.0.17134.523, amd64"
},
"auth": "9TBvXvf9", # private session token
"initComplete": True, # true after connect() returns
"robots": {
"Anna": { # name of the robot
"enabled": True, # enabled?
"connected": True, # Bluetooth connected?
"reporters": { (1)
...
},
"activeUser": "Python...", # currently active user
"model": { # the robot model
"name": "Edbot Dream",
"type": "ERD150",
"key": "dream"
}
}
},
"user": "Python <Clive@[192.168.1.24]:51144>",
"users": [
"Python <Clive@[192.168.1.24]:51144>",
"Scratch 2.0 <Clive@[192.168.1.24]:0>",
]
}
1 | The reporters dictionary or None if not connected. |
The reporters dictionary provides real time data from the robot microcontroller.
The Edbot Dream has 4 built-in sensors (3 IR sensors and a clap counter), an internal buzzer, 2 motor only ports and 2 ports to connect other external devices such as servos or sensors. You can obtain the raw values of the built-in sensors and external device ports from the following reporter keys:
"reporters": {
"leftIR": 223,
"centreIR": 14,
"rightIR": 322,
"clapCountLast": 0,
"clapCountLive": 0,
"port3": 580,
"port4": 22,
...
}
The built-in microphone detects the number of claps (loud noises) that have occurred in the last few seconds. This is called the live count (clapCountLive). When silence is detected, the live count is transferred to the last count (clapCountLast) and the live count is set back to 0.
There are 3 internal IR sensors: left, right and centre. To convert a raw sensor value to centimetres use the raw_to_CM150_dist function.
The internal IR sensors are not the same as external IRSS-10 sensor described below, so be sure to use the correct conversion function. |
Edbot Dream is supplied with a servo (SM-10), the remaining sensors are optionally available. Contact us if you need to purchase them. Use the appropriate function in the table below to convert the raw value of the external ports (port 3 / port 4), depending on what is attached.
Servo position (SM-10) |
raw_to_SM10_angle |
|
IR sensor (IRSS-10) |
raw_to_IRSS10_dist |
|
DMS sensor (DMS-80) |
raw_to_DMS80_dist |
|
Temperature sensor (TPS-10) |
raw_to_TPS10_temp |
|
Touch sensor (TS-10) |
raw_to_TS10_touch |
|
Magnetic sensor (MGSS-10) |
raw_to_MGSS10_mag |
The speechCurrentWord reporter gives the current word as it is being spoken. The reporter is set to None when not speaking. It can be used to add visual emphasis during speech.
"reporters": {
"speechCurrentWord": "Hello",
...
}
The current word reporter is only available on Windows and Mac platforms. |
Read through the following examples to gain an understanding of how to use the API. The Reference section details the API functions with their parameters and return values.
We'll begin by stepping through the Crocodile example.
import sys
import time
import edbot (1)
#
# Connect to the Edbot server. The Edbot Software needs to be running.
#
ec = edbot.EdbotClient("localhost", 8080) (2)
ec.connect() (3)
#
# Set the name.
#
name = "Anna"
if not ec.set_edbot_name(name) == True: (4)
print(name + " is not configured")
ec.disconnect()
sys.exit()
#
# Wait for control of the Dream.
#
print("Type Ctrl-C to exit")
print("Waiting to control " + name + "... ", end="", flush=True)
ec.wait_until_active() (5)
print("Got control!")
#
# Variable used globally.
#
opened = 0
#
# Define the functions.
#
def open(): (6)
global opened
if opened == 0:
ec.set_servo_speed("2/50")
time.sleep(0.5)
ec.set_servo_speed("2/0")
opened = 1
def shut():
global opened
if opened == 1:
ec.set_servo_speed("2/-70")
time.sleep(0.2)
ec.set_servo_speed("2/0")
opened = 0
time.sleep(0.5)
ec.say("Clap three times to open")
def move():
ec.set_servo_speed("1/30")
time.sleep(1)
ec.set_servo_speed("1/-30")
time.sleep(1)
ec.set_servo_speed("1/0")
#
# Start with an open mouth :-O
#
open() (7)
ec.say("Put your finger in the bottom of my mouth")
while True:
try:
#
# Reporter data is only returned when the Dream is connected.
#
reporters = msg["edbots"][name]["reporters"]
if "centreIR" in reporters:
#
# Convert to centimetres.
#
distance_raw = reporters["centreIR"]
distance_cms = edbot.raw_to_CM150_dist(distance_raw)
if distance_cms < 5: (8)
shut()
if "clapCountLive" in reporters:
live_count = reporters["clapCountLive"]
if live_count == 3: (9)
open()
move()
except KeyboardInterrupt:
ec.disconnect()
sys.exit()
except:
continue
1 | Import the "edbot" package. |
2 | Create a new EdbotClient instance. |
3 | Connect to the Edbot server. |
4 | Set the Edbot Dream name. |
5 | Wait for control of the Edbot Dream. |
6 | Define the functions. |
7 | Start with an open mouth. |
8 | Finger detected in mouth! |
9 | Three claps to open. |
Next the Scorpion example.
import sys
import time
import edbot (1)
#
# Connect to the Edbot server. The Edbot Software needs to be running.
#
ec = edbot.EdbotClient("localhost", 8080) (2)
ec.connect() (3)
#
# Set the name.
#
name = "Anna"
if not ec.set_edbot_name(name) == True: (4)
print(name + " is not configured")
ec.disconnect()
sys.exit()
#
# Wait for control of the Dream.
#
print("Type Ctrl-C to exit")
print("Waiting to control " + name + "... ", end="", flush=True)
ec.wait_until_active() (5)
print("Got control!")
#
# Define the stinger function.
#
def sting(): (6)
ec.set_servo_speed("2/-100")
time.sleep(1)
ec.set_servo_speed("2/100")
time.sleep(1)
ec.set_servo_speed("2/0")
while True:
try:
#
# Reporter data is only returned when the Dream is connected.
#
data = ec.get_data()
reporters = data["edbots"][name]["reporters"]
if "centreIR" in reporters:
#
# Convert to centimetres.
#
distance_raw = reporters["centreIR"]
distance_cms = edbot.raw_to_CM150_dist(distance_raw)
if distance_cms < 10: (7)
#
# Within 10cm. Start the sequence...
#
ec.say("Python is going to sting you!")
ec.set_servo_speed("1/-70")
time.sleep(2)
ec.set_servo_speed("1/0")
sting()
ec.set_servo_speed("1/100")
time.sleep(1)
ec.set_servo_speed("1/0")
#
# Wait a second before checking the sensor.
#
time.sleep(1)
except KeyboardInterrupt:
ec.disconnect()
sys.exit()
except:
continue
1 | Import the "edbot" package. |
2 | Create a new EdbotClient instance. |
3 | Connect to the Edbot server. |
4 | Set the Edbot Dream name. |
5 | Wait for control of the Edbot Dream. |
6 | Define the functions. |
7 | Start the sting seqence. |
The Python API enables you to supply a boolean wait parameter in calls to say. The default value of True causes the function to wait until the speech has completed before returning. This is convenient for command line programs but not so useful if you're writing a GUI program which will need to perform other tasks before the speech has completed.
To address this issue you can set the wait parameter to False and pass a unique sequence number in your call to say. A reporter will be set to this sequence number when the speech has completed. The following example illustrates the reporter data format. Here <auth> is the session token and <seq> is the sequence number passed in to the call.
"reporters": {
"speechComplete": <auth>_self_s_<seq>,
...
}
The example code below demonstrates how to use this technique to detect when the speech has completed.
import time
import threading
import edbot
seq = 1
name = "Anna"
event = threading.Event()
ec = edbot.EdbotClient("localhost", 8080)
#
# This function will get called when the server sends a notification.
#
def my_callback(msg):
try:
data = ec.get_data()
complete = data["robots"][name]["reporters"]["speechComplete"]
if complete.endswith(str(seq)):
# We've received our sequence number. We've finished speaking!
event.set()
except:
pass
#
# Pass the callback in the call to connect().
#
ec.connect(my_callback)
#
# Wait for control.
#
print("Type Ctrl-C to exit")
print("Waiting to control " + name + "... ", end="", flush=True)
ec.wait_until_active(name)
print("Got control!")
#
# Say "Hello", wait until finished, then repeat.
#
while True:
#
# Reset the internal flag so that calls to event.is_set() will block until
# event.set() is called in the callback.
#
event.clear()
#
# Now say "Hello", passing in the sequence number and return immediately.
#
print("Saying Hello!")
ec.say(name, "Hello", wait=False, speech_seq=seq)
# Don't use event.wait() - it isn't interruptible!
while not event.is_set():
time.sleep(0.1)
# Increment the sequence number.
seq += 1
The EdbotClient class in the edbot package encapsulates the Edbot Dream Python API.
Create a new instance by calling the constructor and assigning it to a variable.
edbot.EdbotClient(server, port, client=Python)
Parameters:
server |
string |
The ip address or hostname of the Edbot server. |
port |
integer |
The port number on which the server is running. |
client |
string |
Client description. |
Returns:
A new EdbotClient instance. |
Open a connection to the Edbot server.
connect(callback=None)
Parameters:
callback |
function |
Optional callback function, see below. |
If you supply a callback function it will be called when the server sends a change notification. Your function should be of the following form, where msg is of type dict.
my_callback(msg)
Check if this client instance is connected to the Edbot server.
get_connected()
Returns:
True if connected, otherwise False. |
Close the connection to the Edbot server. This functon will initiate an orderly disconnection.
disconnect()
Get an unsorted array containing the names of the robots configured on this server.
get_robot_names(model=None)
Parameters:
model |
string |
Optionally pass in the model key to filter a specific type of robot. Currently defined keys are "edbot", "dream" and "play". |
Returns:
The robot names as an array of strings. |
Return the named robot as a dictionary.
get_robot(name)
Parameters:
name |
string |
The name of the robot. |
Returns:
A dictionary with the following keys:
model |
dict |
A dictionary containing the robot model name, type and key. |
enabled |
boolean |
True if the robot is enabled. |
connected |
boolean |
True if the robot is connected via Bluetooth. |
activeUser |
string |
The currently active user. None means open access. |
reporters |
dict |
A dictionary containing the reporters or None if not connected via Bluetooth. |
Get a dictionary containing the Edbot server data.
get_data()
Returns:
A dictionary with the following keys:
robots |
dict |
The robots configured on the server. Each robot is keyed on name and its value is a robot dictionary. |
initComplete |
boolean |
If True the connection has finished initialising. |
server |
dict |
A dictionary containing the server version and platform. |
auth |
string |
A unique token allocated by the server used to identify this session. |
user |
string |
The current user connection. |
users |
array |
An Array of users connected to the server. |
Does this connection have control of the robot? See wait_for_control.
is_active(name)
Parameters:
name |
string |
The name of the robot. |
Returns:
True if the current user is active, otherwise False. |
You can retrieve the name of the currently active user using:
|
Wait for control of the Edbot Dream. See wait_for_control.
wait_until_active(name)
Parameters:
name |
string |
The name of the robot. |
Switch servos on or off. Setting the torque on will automatically set joint mode.
set_servo_torque(name, path)
Parameters:
name |
string |
The name of the robot. |
path |
string |
A string formed by the port number followed by "/" followed by 0 or 1 to turn the servo off or on respectively. Specify multiple servos by repeating the sequence, for example "3/1/4/1". |
Returns:
A dictionary with the following keys.
success |
boolean |
True on success, otherwise False. |
message |
string |
The Edbot server response message. |
Set the servo speed. In wheel mode this will immediately set the motor to the speed you specify. If the servo is in joint mode it will set the speed for subsequent calls to set_servo_position.
set_servo_speed(name, path)
Parameters:
name |
string |
The name of the robot. |
path |
string |
A string formed by the port number followed by "/" followed by the speed as a percentage. For motors and servos in wheel mode, specify a negative percentage to rotate clockwise and a positive percentage to rotate anti-clockwise. Specify multiple servos by repeating the sequence, for example "1/50/2/50". To stop a motor just set its speed to zero. Servos in joint mode expect a positive percentage. If you enter a negative number the minus sign will be ignored. |
Returns:
A dictionary with the following keys.
success |
boolean |
True on success, otherwise False. |
message |
string |
The Edbot server response message. |
Set the servo position. You must set joint mode with a call to set_servo_mode or this function will have no effect.
set_servo_position(name, path)
Parameters:
name |
string |
The name of the robot. |
path |
string |
A string formed by the port number followed by "/" followed by the position which is an angle from 0 to 300 degrees.
Specify multiple servos by repeating the sequence, for example "3/250/4/50". |
Returns:
A dictionary with the following keys.
success |
boolean |
True on success, otherwise False. |
message |
string |
The Edbot server response message. |
Your Edbot Dream is supplied with two motors (GM-10) and a servo (SM-10). Connect motors to port 1 / port 2 of the microcontroller using a 2-wire cable. You can control the motor speed and direction.
The servo connects to port 3 / port 4 using a 5-wire cable. By default the servo operates in wheel mode when it acts just like a motor. It can also operate in joint mode when you can set it to a specific position. If the servo is moving when you call this function, it will stop.
set_servo_mode(name, path)
Parameters:
name |
string |
The name of the robot. |
path |
string |
A string formed by the port number followed by "/" followed by 0 or 1 to set wheel mode or joint mode respectively. Specify multiple servos by repeating the sequence, for example "3/1/4/1". |
Returns:
A dictionary with the following keys.
success |
boolean |
True on success, otherwise False. |
message |
string |
The Edbot server response message. |
Play a note or built-in melody on the internal buzzer.
set_buzzer(name, path)
Parameters:
name |
string |
The name of the robot. |
path |
string |
To play a note, path should be a string formed by the pitch followed by "/" followed by the duration. The pitch is a number from 0 to 48 and the duration is from 3 to 50 in units of 0.1 seconds. To play a built-in melody, specify path as a melody index followed by "/" followed by 255. Melody indices range from 0 to 24. We use the term melody loosely here! |
Returns:
A dictionary with the following keys.
success |
boolean |
True on success, otherwise False. |
message |
string |
The Edbot server response message. |
This advanced function allows you to set a value in the microcontroller's control table.
set_custom(name, path)
A description of the control table can be found at the following link:
As an example you can use this function to reset the clap counter using a path of "86/1/0". |
Parameters:
name |
string |
The name of the robot. |
path |
string |
A string formed by the control table address (0 - 65535) followed by a "/" followed by the size in bytes (1 or 2) followed by "/" followed by the option value to write (0 - 255 if 1 byte : 0 - 65535 if 2 bytes). |
Returns:
A dictionary with the following keys.
success |
boolean |
True on success, otherwise False. |
message |
string |
The Edbot server response message. |
Set global options. These options are set to defaults when the robot is reset either by an explicit call to reset, or when the active user is changed on the Edbot server. Edbot Dream currently does not support any options.
set_options(name, path)
Parameters:
name |
string |
The name of the robot. |
path |
string |
A string formed by the option name followed by "/" followed by the option value. Specify multiple options by repeating the sequence. |
Returns:
A dictionary with the following keys.
success |
boolean |
True on success, otherwise False. |
message |
string |
The Edbot server response message. |
Specify text for the robot to speak. This function assumes the robot has been configured with speech on the Edbot server.
Unicode escapes are fully supported.
say(name, text, wait=True, speech_seq=None)
Parameters:
name |
string |
The name of the robot. |
text |
string |
The text to speak. |
wait |
boolean |
Wait for the speech to complete before returning. |
speech_seq |
integer |
Supply a unique number for this speech request. See Asynchronous coding. |
Returns:
A dictionary with the following keys.
success |
boolean |
True on success, otherwise False. |
message |
string |
The Edbot server response message. |
Reset the Edbot Dream. This will stop any connected motors or servos, turn off the LED module if plugged into port 3 / port 4, set the last clap count back to 0 and halt any speech on a word boundary and empty the request queue.
reset(name)
Parameters:
name |
string |
The name of the robot. |
Returns:
A dictionary with the following keys.
success |
boolean |
True on success, otherwise False. |
message |
string |
The Edbot server response message. |
Convert the raw value from one of the three internal IR sensors to centimetres. The measuring range is 3cm to 20cm.
edbot.raw_to_CM150_dist(raw)
Parameters:
raw |
integer |
The raw sensor reading in the range 0 - 1023. |
Returns:
Distance in centimetres rounded to 1 decimal place. |
The function returns 100.0 if the raw value is 0 (out of range).
The sensor was calibrated using the distance between the front edge of the feet and a vertical white A4 card. The card was held a known distance from the sensor and the raw sensor value was noted. This was repeated for different distances. A non-linear power curve was then used to fit the data points. Note the sensor readings will differ for different coloured objects placed the same distance away.
Convert the raw value from the SM-10 servo to an angle from 0 to 300 degrees, see set_servo_position.
edbot.raw_to_SM10_angle(raw)
Parameters:
raw |
integer |
The raw sensor reading in the range 64 - 959. |
Returns:
Return the angle from 0 to 300 degrees rounded to 1 decimal place. |
Convert the raw value from the IRSS-10 IR sensor to centimetres. The measuring range is 3cm to 30cm.
edbot.raw_to_IRSS10_dist(raw)
Parameters:
raw |
integer |
The raw sensor reading in the range 0 - 1023. |
Returns:
Distance in centimetres rounded to 1 decimal place. |
The function returns 100.0 if the raw value is 0 (out of range).
The sensor was calibrated using the distance between the front edge of the feet and a vertical white A4 card. The card was held a known distance from the sensor and the raw sensor value was noted. This was repeated for different distances. A non-linear power curve was then used to fit the data points. Note the sensor readings will differ for different coloured objects placed the same distance away.
Convert the raw value from the DMS-80 IR sensor to centimetres. The measuring range is 8cm to 80cm.
edbot.raw_to_DMS80_dist(raw)
Parameters:
raw |
integer |
The raw sensor reading in the range 0 - 1023. |
Returns:
Distance in centimetres rounded to 1 decimal place. |
The function returns 100.0 if the raw value is 0 (out of range).
The sensor was calibrated using the distance between the front edge of the feet and a vertical white A4 card. The card was held a known distance from the sensor and the raw sensor value was noted. This was repeated for different distances. A non-linear power curve was then used to fit the data points.
Convert the raw value from the TPS-10 temperature sensor to degrees Celsius.
edbot.raw_to_TPS10_temp(raw)
Parameters:
raw |
integer |
The raw sensor reading in the range 0 - 1023. |
Returns:
Temperature in degrees Celsius. |
Convert the raw value from the TS-10 micro-switch to 0 or 1.
edbot.raw_to_TS10_touch(raw)
Parameters:
raw |
integer |
The raw sensor reading in the range 0 - 1023. |
Returns:
Return 1 if the switch is depressed, otherwise 0. |
Convert the raw value from the MGSS-10 reed switch to 0 or 1.
edbot.raw_to_MGSS10_mag(raw)
Parameters:
raw |
integer |
The raw sensor reading in the range 0 - 1023. |
Returns:
Return 1 if a magnet is present, otherwise 0. |