Edbot

Support Template

Introduction

JavaScript is a cross-platform scripting language created by Brendan Eich in 1995. It is an interpreted programming language with object-oriented capabilities. Alongside HTML and CSS, JavaScript is one of the three core technologies of Web content. The code is usually embedded in a Web page to add interactivity and highly responsive interfaces.

It is important to note that JavaScript is distinct from Java. The two languages are completely different although some aspects look similar.

This guide assumes you are familiar with writing HTML Web pages containing JavaScript code. The API uses jQuery to simplify coding and you should have some familiarity with it: jQuery is a fast and concise JavaScript library created by John Resig in 2006 with the motto, "write less, do more".

Getting started

IDE setup

Download and install the JavaScript IDE (Integrated Development Environment) of your choice. For Windows choose from a fully integrated package such as Visual Studio or use an advanced text editor like Komodo or Notepad++. Linux (including Raspbian) also has a variety of IDEs available such as Bluefish and Geany.

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 JavaScript examples folder is part of the Edbot Software installation. In Windows the folder is located in your 'Documents' folder:

Documents\Edbot\javascript

Similarly for macOS and Linux:

Documents/Edbot/javascript

On Android look in the Edbot folder in your external storage:

/storage/emulated/0/Edbot/javascript

The folder should initially contain the following files and folders:

edbot
  edbot-client.js
  jquery.js
  util.js
base.css
monitor.html

The edbot folder contains the EdbotClient class which implements the API. An example using the API is included:

  • monitor.html displays the Edbot server status in real time.

You can save your own code in this folder to make it easy to develop and test.

The API makes use of AJAX to send requests to the Edbot server. As a result you must load the HTML sample page using http. The local file protocol (file:///) will not work due to basic browser security.

For this purpose the Edbot Software runs a Web server locally. You can view the sample folder using the following link:

If you've changed the server port in the Edbot server setup, substitute your port in the link above.

Time to code

Connecting

The EdbotClient class implements the Edbot API in JavaScript. Make the class available using a <script> tag in the <head> section of your Web page. You'll need to reference jQuery first:

<script src="edbot/jquery.js"></script>
<script src="edbot/edbot-client.js"></script>
<script src="edbot/util.js"></script>

Still in the <head> section, add your code in a <script> tag:

<script>
... your code ...
</script>

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 user parameter can be any string to identify your program to the server. It defaults to "User".

var ec = new EdbotClient("localhost", 8080, { user: "MyJavaScriptApp" });

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. The data updates can occur at any time after connecting - they are asynchronous. However, JavaScript code runs in a single execution thread, unlike other languages such as Java or Python. This problem is solved with the use of event callbacks: in essence you register a function to be called when a specific event occurs at which point program execution jumps to the function you registered. Execution then returns to the code running before the event occurred. The Edbot JavaScript API uses this technique to handle data updates from the Edbot server.

Register your callbacks as part of the connect function. For more details consult the Reference section.

ec.connect(
  {
    onopen: function(event) {
      // Not a great deal of use.
    },
    oninit: function(event) {
      // Called once when data for each configured robot has been received.
    },
    onmessage: function(event) {
      // Called every time a message is received.
    },
    onclose: function(event) {
      // The connection has been closed.
    }
  }
);

After connecting to the Edbot server, your program will need control of the robot. Grant control using the active user menu in the Edbot Software. See below.

edbotsw javascript

If you're developing solo, 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

When you have successfully connected to the Edbot server you can send commands to your robot. For example to play buzzer melody 0, use:

ec.setBuzzer("Anna", "0/255")

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

ec.setServoSpeed("Anna", "1/100")

and to turn it off:

ec.setServoSpeed("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 Play&Code to speak using the API methods detailed in the Reference section.

Queries

A call to getData()will return real time data as a JSON object. The JSON object gives access to lots of useful information you can use in your code. You can run the Monitor example below to examine the current values. 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": "MyJavaScript...", # currently active user
      "model": {                       # the robot model
          "name": "Edbot Play&Code",
          "type": "ERP50",
          "key": "play"
      }
    }
  },
  "user": "MyJavaScriptApp <Clive@[192.168.1.24]:51144>",
  "users": [
    "MyJavaScriptApp <Clive@[192.168.1.24]:51144>",
    "Scratch 2.0 <Clive@[192.168.1.24]:0>",
  ]
}
1 The reporter object or null if not connected.

Reporters

The reporter properties provide real time data from the robot microcontroller.

The Edbot Play&Code has 4 built-in sensors (3 IR sensors and a clap counter), an internal buzzer and 2 motors. You can obtain the raw values of the built-in sensors from the following reporter properties:

"reporters": {
  "leftIR": 223,
  "centreIR": 14,
  "rightIR": 322,
  "clapCountLast": 0,
  "clapCountLive": 0,
  ...
}
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 rawToCM50Dist function.

Current word

The speechCurrentWord 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": {
  "speechCurrentWord": "Hello",
  ...
}

The current word reporter is only available on Windows and Mac platforms.

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.

Monitor

Take some time to step through the monitor example.

<html lang="en">
<head>
<meta charset="utf-8">
<title>Edbot Server Monitor</title>
<link rel="stylesheet" href="base.css">
<script src="edbot/jquery.js"></script> (1)
<script src="edbot/edbot-client.js"></script> (2)
<script src="edbot/util.js"></script>
<script>
var ec = null;
$(document).ready(
  function() {
    // Make sure we are loading the page with http.
    if(!location.protocol.startsWith("http")) {
      $(".nohttp").show();
      return;
    } else {
      $(".container").show();
    }

    // Examine the page URL for host and port parameters.
    var url = new URL(window.location.href);
    var host, port;
    try {
      host = url.searchParams.get("host");
      if(host != null) {
        host = host.trim();
      }
      if(host == null || host.length < 1) {
        host = "localhost";
      }
      port = parseInt(url.searchParams.get("port"));
      if(isNaN(port) || port < 1023 || port > 65535) {
        port = 8080;
      }
    } catch(err) {}
    $("#header").append(" " + host + ":" + port);
    $("title").append(" " + host + ":" + port);

    // Create a new EdbotClient instance and connect.
    ec = new EdbotClient(host, port, { user: "Monitor" }); (3)
    connect();
  }
);
function connect() {
  ec.connect( (4)
    {
      onmessage: function(event) { (5)
        var data = ec.getData();
        var robots = data.robots;
        for(var name in robots) {
          // Sort reporters by key.
          if(robots[name].reporters) {
            var reporters = {};
            Object.keys(robots[name].reporters).sort().forEach(
              function(key) {
                reporters[key] = robots[name].reporters[key];
              }
            );
            robots[name].reporters = reporters;
          }
        }

        // Update the textarea.
        $("#reporter").val(JSON.stringify(data, null, 4));
      },
      onclose: function(event) { (6)
        // Server connection has gone away - clean up.
        $("#reporter").val("");
        connect();    // attempt to reconnect
      }
    }
  );
}
</script>
</head>

<body>
<div class="nohttp">
  <p>You must load this Web page using HTTP.
  Run the Edbot Software and use the following link:
  <p><a href="http://localhost:8080/coding/javascript/monitor.html">http://localhost:8080/coding/javascript/monitor.html</a>
  <p>If you\'ve changed the server port in the server setup, substitute your port in the link above.
</div>
<div class="container">
  <p id="header">Monitoring Edbot server on </p>
  <textarea id="reporter" readonly="true"></textarea>
</div>
</body>
</html>
1 The Edbot JavaScript API uses jQuery. This should be included first.
2 Include the Edbot JavaScript API.
3 Create a new EdbotClient instance.
4 Call the EdbotClient connect method to connect to the Edbot server.
5 Handle received messsages.
6 Register an onclose callback to handle a closed connection.

You can try this example by clicking on the link below:

If you've changed the server port in the Edbot server setup, substitute your port in the link above.

Reference

EdbotClient

The EdbotClient class encapsulates the Edbot JavaScript API.

Constructor

Create a new instance by calling the constructor and assigning it to a variable.

new edbot.EdbotClient(server, port[, options])

Parameters:

server

string

The ip address or hostname of the Edbot server.

port

integer

The port number on which the server is running.

options

object

Optional properties:

user

string

User name, default: "User".

client

string

Client description, default: "JavaScript".

Return:

A new EdbotClient instance.


connect

Open a connection to the Edbot server.

connect([options])

Parameters:

options

object

Optional properties:

onopen(event)

function

Callback fired after opening a connection to the Edbot server. Event is of type Event.

oninit(event)

function

Callback fired once when data for each configured robot has been received. Event is of type MessageEvent.

onmessage(event)

function

Callback fired when a message is received from the Edbot server. Event is of type MessageEvent. The message data is available in the event's data property.

onclose(event)

function

Callback fired when the connection is closed. Event is of type CloseEvent.

onerror(event)

function

Callback fired when an error occurs. Event is of type Event.

Return:

None.


getConnected

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

getConnected()

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.


getRobotNames

Get an unsorted array containing the names of the robots on this server.

getRobotNames([model])

Parameters:

model

string

Optionally pass in the model key to filter a specific type of robot. Currently defined keys are are "edbot", "dream" and "play".

Return:

The robot names as an array of strings.


getRobot

Return the named robot as an object.

getRobot(name)

Parameters:

name

string

The name of the robot.

Return:

An object with the following properties:

model

object

An object 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. null means the active user is bypassed.

reporters

object

An object containing the Reporters such as sensor values.


getData

Get an object containing the Edbot server data.

getData()

Parameters:

None.

Return:

An object with the following properties:

robots

dict

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

initComplete

boolean

Call to connect() has initialised.

server

object

An object 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.


isActive

Does this connection have control of the robot?

isActive(name)

Parameters:

name

string

The name of the robot.

Return:

Returns true if the current user is active, otherwise false.

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

getRobot(name).activeUser

getRemoteServers

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

getRemoteServers([, cb][, cbd])

Parameters:

cb

function

Callback fired when the response is returned. The callback should be of the form:

cb = function(res, cbd) {}

The res object contains the following properties:

status

object

Object with boolean property success and string property message.

data

object

The returned data on success, else null. The returned data is an array of Edbot servers. Each array element is an object with properties host and port.

cbd

object

User data passed to the response callback above.

Return:

None.


setServoSpeed

Set the servo speed.

setServoSpeed(name, path[, cb][, cbd])

Parameters

name

string

The name of the robot.

path

string

A string formed by the servo number followed by "/" followed by the speed expressed as a percentage greater than zero. Specify multiple servos by repeating the sequence, for example "1/50/2/50/3/50/4/50". Servo number 0 means all servos, so "0/12.5" will set all servos to one eighth speed.

cb

function

Callback fired when the response is returned. The callback should be of the form:

cb = function(res, cbd) {}

The res object contains the following properties:

status

object

Object with boolean property success and string property message.

cbd

object

User data passed to the response callback above.

Return:

None.


setBuzzer

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

setBuzzer(name, path[, cb][, cbd])

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!

cb

function

Callback fired when the response is returned. The callback should be of the form:

cb = function(res, cbd) {}

The res object contains the following properties:

status

object

Object with boolean property success and string property message.

cbd

object

User data passed to the response callback above.

Return:

None.


setCustom

This advanced function allows you to set a value in the microcontroller's control table.

setCustom(name, path[, cb][, cbd])

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

cb

function

Callback fired when the response is returned. The callback should be of the form:

cb = function(res, cbd) {}

The res object contains the following properties:

status

object

Object with boolean property success and string property message.

cbd

object

User data passed to the response callback above.

Return:

None.


setOptions

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 Play&Code currently does not support any options.

setOptions(name, path[, cb][, cbd])

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.

cb

function

Callback fired when the response is returned. The callback should be of the form:

cb = function(res, cbd) {}

The res object contains the following properties:

status

object

Object with boolean property success and string property message.

cbd

object

User data passed to the response callback above.

Return:

None.


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[, cb][, cbd])

Parameters

name

string

The name of the robot.

text

string

The text to speak.

cb

function

Callback fired when the response is returned. The callback should be of the form:

cb = function(res, cbd) {}

The res object contains the following properties:

status

object

Object with boolean property success and string property message.

cbd

object

User data passed to the response callback above.

Return:

The speech sequence string.


reset

Reset the Edbot Play&Code. This will stop the motors, set the last clap count back to 0 and halt any speech on a word boundary and empty the request queue.

reset(name[, cb][, cbd])

Parameters

name

string

The name of the robot.

cb

function

Callback fired when the response is returned. The callback should be of the form:

cb = function(res, cbd) {}

The res object contains the following properties:

status

object

Object with boolean property success and string property message.

cbd

object

User data passed to the response callback above.

Return:

None.


rawToCM50Dist

Convert the raw value from one of the three internal IR sensors to centimetres. The measuring range is 3cm to 20cm.

edbot.rawToCM50Dist(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.