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 package. It allows a Python program to control your Edbot Dreams. This guide assumes you are familiar with writing Python code.

The Edbot Dream Python API supports Python 3.

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.

The Edbot Software will only run in server mode if you’ve configured at least one Edbot Dream.

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 Mac OS X 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 a good idea to check the edbot package version corresponds with your version of the Edbot Software. Get the package version with the following command:

>>> print(edbot.__version__)
4.1.979

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 Edbot Dream names available. Let's assume we have configured an Edbot Dream called "Anna":

>>> ec.get_edbot_names()
['Anna']

You can set a default Edbot Dream name. This isn't necessary - you can pass the Edbot Dream name as an optional parameter to most API functions - but it's convenient.

>>> ec.set_edbot_name("Anna")
True

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()

Grant control using the Edbot Software. See below.

edbotsw

The Edbot Software provides a convenient option "Bypass Active User" in the Main → Server Setup → Settings tab. Set this option while developing so that you don’t need to give control each time you test your program.

Commands

You can now send commands to your Edbot Dream. For example to play buzzer melody 0, use:

ec.set_buzzer("0/255")

To turn on a motor plugged into port 1 at full speed, use:

ec.set_servo_speed("1/100")

and to turn it off:

ec.set_servo_speed("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:

{
  "edbots": {
    "Anna": {                    # name of the Edbot Dream
      "type": "ERD150",          # the Edbot Dream model
      "enabled": True,           # enabled?
      "connected": True,         # Bluetooth connected?
      "activeUser": "Python...", # currently active user
      "reporters": {             (1)
          ...
      }
    },
    ...
  },
  "auth": "...",                 # private session token
  "bypass": True,                # bypass active user?
  "user": "Python...",           # session user (me!)
  "users": [                     # array of connected users
    "Scratch...",
    "Python..."
  ]
}
1 The reporters dictionary or None if not connected.

Reporters

The reporters dictionary provides real time data from the Edbot Dream microcontroller which has 4 built-in sensors (3 IR sensors and a clap counter), an internal buzzer and 4 ports to connect external equipment. You can obtain the raw values of the built-in sensors and 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 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 optional. 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 speech-current-word reporter gives the current word as it is being spoken. The reporter is set to null when not speaking. It can be used to add visual emphasis during speech.

"reporters": {
  "speech-current-word": "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 EdboClient 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 < 5: (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 EdboClient 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 block 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.

"reporters": {
  "speech-complete": 201,
  ...
}

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 = "Bob"
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["edbots"][name]["reporters"]["speech-complete"]
    if complete == 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)

#
# Set the Edbot Dream name for convenience.
#
ec.set_edbot_name(name)

#
# Wait for control.
#
print("Type Ctrl-C to exit")
print("Waiting to control " + name + "... ", end="", flush=True)
ec.wait_until_active()
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("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 type on the Edbot server.

Return

A new EdbotClient instance.


get_server

Get the server name or ip address.

get_server()

Parameters

None.

Return

A string representing the server name or ip address.


get_port

Get the server port number.

get_port()

Parameters

None.

Return

The server port number.


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)

The Edbot Software will only run in server mode if you've set up at least one Edbot Dream.


disconnect

Close the connection to the Edbot server.

disconnect()

Parameters

None.

Return

None.


get_edbot_names

Get an unsorted array containing the names of the Edbot Dreams configured on this server.

get_edbot_names()

Parameters

None.

Return

The Edbot Dream names as an array of strings.


get_edbot

Return the named Edbot Dream as a dictionary.

get_edbot(name=None)

Parameters

name

string

The name of the Edbot Dream. Can be omitted if set with set_edbot_name.

Return

A dictionary with the following keys:

type

string

The Edbot Dream model type.

enabled

boolean

True if the Edbot Dream is enabled.

connected

boolean

True if the Edbot Dream is connected via Bluetooth.

activeUser

string

The currently active user.

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:

edbots

dict

The Edbot Dreams configured on the server. See the Edbot Dream dictionary above.

auth

string

A unique token allocated by the server used to identify this session.

bypass

boolean

Bypass the active user control?

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=None)

Parameters

name

string

The name of the Edbot Dream. Can be omitted if set with set_edbot_name.

Return

True if the current user is active, otherwise False.

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

get_edbot(name=None])["activeUser"]

wait_until_active

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

wait_until_active(name=None)

Parameters

name

string

The name of the Edbot Dream. Can be omitted if set with set_edbot_name.

Return

None.


set_edbot_name

Set the default Edbot Dream name.

set_edbot_name(name)

Parameters

name

string

The name of the Edbot Dream.

Return

True on success, otherwise False.


set_buzzer

Play a note or built-in melody on the internal buzzer.

set_buzzer(path, name=None)

Parameters

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!

name

string

The name of the Edbot Dream. Can be omitted if set with set_edbot_name.

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(path, name=None)

Parameters

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

name

string

The name of the Edbot Dream. Can be omitted if set with set_edbot_name.

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(path, name=None)

Parameters

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.

name

string

The name of the Edbot Dream. Can be omitted if set with set_edbot_name.

Return

A dictionary with the following keys.

success

boolean

True on success, otherwise False.

message

string

The Edbot server response message.


set_servo_torque

Switch servos on or off. Setting the torque on will automatically set joint mode.

set_servo_torque(path, name=None)

Parameters

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

name

string

The name of the Edbot Dream. Can be omitted if set with set_edbot_name.

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(path, name=None)

Parameters

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

name

string

The name of the Edbot Dream. Can be omitted if set with set_edbot_name.

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 Edbot Dream 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(path, name=None)

Parameters

path

string

A string formed by the option name followed by "/" followed by the option value. Specify multiple options by repeating the sequence.

name

string

The name of the Edbot Dream. Can be omitted if set with set_edbot_name.

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(path, name=None)

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

path

string

A string formed by the control table address (0 - 1023) followed by a "/" followed by the size in bytes (1 - 2) followed by "/" followed by the option value to write (0 - 255 if 1 byte : 0 - 1023 if 2 bytes).

name

string

The name of the Edbot Dream. Can be omitted if set with set_edbot_name.

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 Edbot Dream to speak. This method assumes the Edbot Dream has been configured with speech on the Edbot server. Unicode escapes are fully supported.

say(text, wait=True, speech_seq=None, name=None)

Parameters

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.

name

string

The name of the Edbot Dream. Can be omitted if set with set_edbot_name.

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=None)

Parameters

name

string

The name of the Edbot Dream. Can be omitted if set with set_edbot_name.

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.