Edbot

Support Template

Introduction

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 Dreams. This guide assumes you are familiar with writing Python code.

If you're moving from an earlier release to Edbot Software version 5.0 please read the Edbot Python API Migration Guide which summarises the API changes.

Setting up

Install Python

Classic

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

If you've already installed it, run the following command to make sure you have the latest version:

pip install --upgrade edbot

Bundled IDE

Alternatively you can install an integrated development environment (IDE) with a bundled Python interpreter, such as the popular Thonny. Follow the instructions in this article to add the edbot package to Thonny.

Edbot Software

Make sure you have installed the latest version of the Edbot Software 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.

Folder structure

The Python examples folder is part of the Edbot Software installation. In Windows the folder is located in the user's '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

Time to code

We're using classic Python 3.5.2 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.5.2 [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "licence" for more information.
>>>

Connecting

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

It's important to check the edbot package version corresponds to your version of the Edbot Software. The first 3 parts of the version string should match. Get the Edbot Software version from Help → About menu option. Get the package version with the following command:

>>> print(edbot.__version__)
5.1.0.1382

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, client="MyPythonApp")

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']

Waiting for control

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 Edbot Software. See below.

edbotsw

The Edbot Software provides a convenient per-robot option "Bypass active user" 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.

Commands

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 methods detailed in the Reference section.

Queries

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": "5.0.6.1247",
      "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": "MyPython...", # currently active user
      "model": {                   # the robot model
          "name": "Edbot Dream",
          "type": "ERD150",
          "key": "dream"
      }
    }
  },
  "user": "MyPythonApp <Clive@[192.168.1.24]:51144>",
  "users": [
    "MyPythonApp <Clive@[192.168.1.24]:51144>",
    "Scratch 2.0 <Clive@[192.168.1.24]:0>",
  ]
}
1 The reporters dictionary or None if not connected.

Reporters

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,
  ...
}
Internal Sensors

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.

External Devices

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.

sm 10

Servo position (SM-10)

raw_to_SM10_angle
Get the servo position in degrees. Valid range is 0 to 300 degrees rounded to 1 decimal place. See the servo diagram.

irss 10

IR sensor (IRSS-10)

raw_to_IRSS10_dist
The IR sensor uses infra-red to measure the distance to an object. It was calibrated using a vertical white A4 card. Note the sensor may give different measurements for different coloured objects placed the same distance away. The reading should be interpreted as an approximate distance in centimetres. The measuring range is 3cm to 30cm rounded to 1 decimal place.

dms 80

DMS sensor (DMS-80)

raw_to_DMS80_dist
The DMS sensor is an accurate distance sensor which uses triangulation and is not affected by object colour. It returns the distance in centimetres. The measuring range is 8cm to 80cm rounded to 1 decimal place.

tps 10

Temperature sensor (TPS-10)

raw_to_TPS10_temp
Returns the temperature in degrees Celsius.

ts 10

Touch sensor (TS-10)

raw_to_TS10_touch
The touch sensor is a micro-switch. It returns 1 if the switch is depressed, otherwise 0.

mgss 10

Magnetic sensor (MGSS-10)

raw_to_MGSS10_mag
The magnetic sensor is a reed switch which detects the presence of a magnet. It returns 1 when a magnet is present, otherwise 0.

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",
  ...
}

Examples

Read through the following examples to gain an understanding of how to use the API. The Reference section details the API methods with their parameters and return values.

Crocodile

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.
    #
    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 < 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 active 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.

Scorpion

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 active control of the Edbot Dream.
6 Define the functions.
7 Start the sting seqence.

Asynchronous coding

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

Reference

EdbotClient

The EdbotClient class in the edbot package encapsulates the Edbot Dream Python API.

Constructor

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.

Return:

A new EdbotClient instance.


connect

Open a connection to the Edbot server.

connect(callback=None)

Parameters:

callback

function

Optional callback function, see below.

Return:

None.

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)

get_connected

Check if this client instance is connected to the Edbot server.

get_connected()

Parameters:

None.

Return:

True if connected, otherwise False.


disconnect

Close the connection to the Edbot server. This functon will initiate an orderly disconnection.

disconnect()

Parameters:

None.

Return:

None.


get_robot_names

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" and "dream".

Return:

The robot names as an array of strings.


get_robot

Return the named robot as a dictionary.

get_robot(name)

Parameters:

name

string

The name of the robot.

Return:

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 the active user is bypassed.

reporters

dict

A dictionary containing the Reporters such as sensor values.


get_data

Get a dictionary containing the Edbot server data.

get_data()

Parameters:

None.

Return:

A dictionary with the following keys:

robots

dict

The robots configured on the server. See the [robot] parameters dictionary above.

initComplete

boolean

Call to connect() has initialised.

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

The users connected to the server.


is_active

Does this connection have control of the Edbot? See Waiting for control.

is_active(name)

Parameters:

name

string

The name of the robot.

Return:

True if the current user is active, otherwise False.

You can retrieve the name of the currently active user using:

get_robot(name)["activeUser"]

wait_until_active

Wait for control of the Edbot Dream. See Waiting for control.

wait_until_active(name)

Parameters:

name

string

The name of the robot.

Return:

None.


get_remote_servers

Return a list of the remote Edbot servers returned from the last network scan. Note this will not initiate a new network scan.

get_remote_servers()

Parameters:

None.

Return:

status

dict

A dictionary with boolean key success and string key message.

data

array

An array of Edbot servers. Each array element is a dictionary with keys host and port.


set_servo_torque

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

Return:

A dictionary with the following keys.

success

boolean

True on success, otherwise False.

message

string

The Edbot server response message.


set_servo_speed

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.

Return:

A dictionary with the following keys.

success

boolean

True on success, otherwise False.

message

string

The Edbot server response message.


set_servo_position

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". servo angle

Return:

A dictionary with the following keys.

success

boolean

True on success, otherwise False.

message

string

The Edbot server response message.


set_servo_mode

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

Return:

A dictionary with the following keys.

success

boolean

True on success, otherwise False.

message

string

The Edbot server response message.


set_buzzer

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!

Return:

A dictionary with the following keys.

success

boolean

True on success, otherwise False.

message

string

The Edbot server response message.


set_custom

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 - 1023) 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 - 1023 if 2 bytes).

Return:

A dictionary with the following keys.

success

boolean

True on success, otherwise False.

message

string

The Edbot server response message.


set_options

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.

Return:

A dictionary with the following keys.

success

boolean

True on success, otherwise False.

message

string

The Edbot server response message.


say

Specify text for the robot to speak. This method 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.

Return:

A dictionary with the following keys.

success

boolean

True on success, otherwise False.

message

string

The Edbot server response message.


reset

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.

Return:

A dictionary with the following keys.

success

boolean

True on success, otherwise False.

message

string

The Edbot server response message.


raw_to_CM150_dist

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.

Return:

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.


raw_to_SM10_angle

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.

Return:

Return the angle from 0 to 300 degrees rounded to 1 decimal place.


raw_to_IRSS10_dist

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.

Return:

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.


raw_to_DMS80_dist

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.

Return:

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.


raw_to_TPS10_temp

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.

Return:

Temperature in degrees Celsius.


raw_to_TS10_touch

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.

Return:

Return 1 if the switch is depressed, otherwise 0.


raw_to_MGSS10_mag

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.

Return:

Return 1 if a magnet is present, otherwise 0.