JavaScript API


 

Program Structure and Events

Function 

Return Type

Description 

Example 

setup()

N/A

If defined, this function is called once when the program starts.

function setup() {
 pinMode(0, INPUT);
}

loop()

N/A

If defined, this function is called continuously when the program is running. The frequency of the calls depends on the complexity of this function, the number of other devices running programs and their complexity, and the machine's processing power.

function loop() {
 Serial.println(digitalRead(0));
}

cleanUp()

N/A

If defined, this function is called once just before the program stops.

function cleanUp() {
 Serial.println("program is stopping.");
}

mouseEvent(pressed, x, y)

N/A

If defined, this function is called when the user clicks and/or moves the mouse on the workspace icon of this device.

  • pressed - a boolean indicating whether the left mouse button is pressed down

  • x - the x coordinate (in pixels) of the mouse relative to the workspace icon's top left corner

  • y - the y coordinate (in pixels) of the mouse relative to the workspace icon's top left corner

  • firstPress - a boolean indicating whether the left mouse button is the first time being pressed down after the last call to this function; pressed is true when the mouse button is pressed and moved, but firstPress is true only when the mouse button is first pressed but not when moved.

 

function mouseEvent(pressed, x, y, firstPress) {
 if (firstPress)
  doSomething();
}

measurementSystemChangeEvent()

N/A

If defined, this function is called when the user changes the measurement system between Metric and Imperial in Preferences. Use isUsingMetric() to get the current setting.

function measurementSystemChangeEvent() {
 METRIC = isUsingMetric();
 unit = METRIC ? "C" : "F";
 refresh();
}

 

 

Digital I/O 

Function

Return Type

Description 

Example 

pinMode(slot, mode) 

N/A

Set a digital slot to INPUT or OUTPUT. 

pinMode(1, OUTPUT); 

pinMode(2, INPUT); 

digitalRead(slot) 

int

Reads from a digital slot, returns HIGH or LOW. 

var val = digitalRead(1); 

digitalWrite(slot, value) 

N/A

Writes to a digital slot with HIGH or LOW. 

digitalWrite(1, HIGH); 

 

 

Analog I/O 

Function

Return Type

Description 

Example 

pinMode(slot, mode) 

N/A

Set a digital slot to INPUT or OUTPUT. 

pinMode(1, OUTPUT); 

pinMode(2, INPUT); 

analogRead(slot) 

int

Reads from an analog slot, returns 0 to 1023. 

var val = analogRead(A1); 

analogWrite(slot, value) 

N/A

Writes a PWM wave to a digital slot, from 0 to 255. 

analogWrite(A1, 128); 

 

 

Custom I/O 

Function

Return Type

Description 

Example 

customRead(slot) 

string

Reads from an custom slot, returns a string

var val = customRead(1); 

customWrite(slot, value) 

N/A

Writes a string to a digital slot. You can use customRead directly from the other side

customWrite(1, "hello"); 

  

 

Input Interrupts

Function

Return Type

Description 

Example 

attachInterrupt(slot, callback)

N/A

Registers a function to be called when the input of a slot changes.

This works for analog, digital and custom inputs. Whenever the input changes, the callback is called.

Only one function is registered per slot. Calling this a second time for the same slot will remove the first callback.

function isr() {
  input = analogRead(0);
}
attachInterrupt(0, isr);

detachInterrupt(slot) 

N/A

Unregisters the slot for input changes.

detachInterrupt(0);




 

Time

Function

Return Type

Description 

Example 

delay(ms) 

N/A

Pauses the program for ms. 

delay(1000); 

uptime()

Number

Returns the time since the device was started in seconds.

Serial.println(uptime());

 

 

Debug Outputs 

Function

Return Type

Description 

Example 

Serial.print(msg) 

N/A

Prints message to debug outputs.

Serial.print("hello");


Serial.println(msg) 

N/A

Prints message with a \n at the end to debug outputs.

Serial.println("hello");

 

 

 

Basic Networking 

Function

Return Type

Description 

Example 

Network.localIP() 

string

Returns the local IP. 

var ip = Network.localIP(); 

Network.subnetMask() 

string

Returns the subnet mask. 

var mask = Network.subnetMask(); 

Network.gatewayIP() 

string

Returns the gateway IP. 

var gateway = Network.gatewayIP(); 

 

 

HTTP Client

Function

Return Type

Description 

Example 

new HTTPClient() 

HTTPClient

Creates a HTTP Client. 

var http = new HTTPClient();

  

open(url) 

N/A

Gets an URL. 

http.open(“http://www.cisco.com”); 

stop() 

N/A

Stops the request. 

http.stop(); 

onDone 

N/A

Sets the callback for when the request is done. 

http.onDone = function(status, data) { 

}; 

 

 

HTTP Server (SBC only)

Function

Return Type

Description 

Example 

HTTPServer.route(path, method, callback); 

N/A

Sets up a route for path and calls callback when it is requested. Routes also support wildcards using *.

HTTPServer.route("/hello", function(url, response) { 

  response.send("world"); 

});



HTTPServer.route("/*", function(url, response) { 

  response.send("hi"); 

});

HTTPServer.start(port) 

boolean

Starts listening on port. 

HTTPServer.start(80); 

HTTPServer.stop() 

N/A

Stops listening.

HTTPServer.stop(); 


 

 

 

 

Response class

 

Passed into the HTTPServer route handler.

 

send(content)

N/A

Sends content back as response.

response.send("hello");

setContentType(type)

N/A

Sets the content type in the response.

response.setContentType("text/plain");

sendFile(filePath)

N/A

Sends a file back as response. The file path is in the device's file manager, not relative to the source code of the current project/script.

response.sendFile("/test.txt")

sendNotFound()

N/A

Sends a file not found as response.

response.sendNotFound()

 

  

 

Email

Function

Return Type

Description 

Example 

EmailClient.setup(email, server, username, password) 

N/A

Sets up the email client to be used. 

EmailClient.setup(“user@cisco.com”, "cisco.com", "username", "password"); 

EmailClient.send(address, subject, body) 

N/A

Sends an email. 

EmailClient.send("pt@cisco.com", "subject", "body); 

EmailClient.receive() 

N/A

Receives emails. 

EmailClient.receive(); 

EmailClient.onSend 

N/A

Sets the callback for when sending an email is done. 

EmailClient.onSend = function(success) { 

}; 

EmailClient.onReceive 

N/A

Sets the callback for when emails are received. 

EmailClient.onReceive = function(sender, subject, body) { 

}; 

 

 

TCP

Function

Return Type

Description 

Example 

new TCPClient() 

TCPClient

Creates a TCP Client. 

var client = new TCPClient(); 

connect(ip, port) 

boolean

Connects to ip and port. 

client.connect(IPAddress("1.1.1.1"), 2000); 

close() 

N/A

Disconnects. 

client.close(); 

state() 

int

Returns the state of the connection. 

client.state(); 

remoteIP() 

string

Returns the remote IP. 

client.remoteIP(); 

remotePort() 

int

Returns the remote port. 

client.remotePort(); 

send(data) 

N/A

Sends data to remote. 

client.send("hello"); 

sendWithPDUInfo(data, pduInfo)

bool

Sends data to remote connection with PDU info.

var data = "hello";var pduInfo = new PDUInfo(0xffff00); pduInfo.setOutFormat("MyProtocol", "MyPDU", {"type": "REPLY", "data": data});pduInfo.addOutMessage("I am sending some data."); client.sendWithPDUInfo(data, pduInfo);

onReceive 

N/A

Sets the callback for when data is received. 

client.onReceive = function(data) { 

}; 

onReceiveWithPDUInfo

N/A

Sets the callback for when data is received and includes the PDU info.

client.onReceiveWithPDUInfo = function(data, pduInfo) {

pduInfo.addInMessage("I got some data."); pduInfo.setAccepted();};

onConnectionChange 

N/A

Sets the callback for when the connection changes. 

client.onConnectionChange = function(type) { 

}; 

  

 

  

  

new TCPServer() 

TCPServer

Creates a TCP Server. 

var server = TCPServer(); 

listen(port) 

N/A

Starts listening on port. 

server.listen(2000); 

stop() 

N/A

Stops listening. 

server.stop(); 

onNewClient 

N/A

Sets the callback for when a new client comes in. 

server.onNewClient = function(client) { 

}; 

 

 

UDP

Function

Return Type

Description 

Example 

new UDPSocket() 

UDPSocket

Creates an UDP Socket. 

var udp = new UDPSocket(); 

begin(port) 

boolean

Starts listening on port. 

udp.begin(2000); 

stop() 

N/A

Stops listening. 

udp.stop(); 

send(ip, port, data) 

boolean

Sends data. 

udp.send(IPAddress("1.1.1.1"), 2000, "hello"); 

sendWithPDUInfo(ip, port, data, pduInfo)

bool

Sends data with PDU info.

var data = "hello";var pduInfo = new PDUInfo(0xffff00); pduInfo.setOutFormat("MyProtocol", "MyPDU", {"type": "REPLY", "data": data});pduInfo.addOutMessage("I am sending some data."); udp.sendWithPDUInfo("1.1.1.1", 2000, data, pduInfo);

onReceive 

N/A

Sets the callback for when data is received. 

udp.onReceive = function(ip, port, data) { 

}; 

onReceiveWithPDUInfo

N/A

Sets the callback for when data is received and includes PDU info.

udp.onReceiveWithPDUInfo = function(ip, port, data) {

pduInfo.addInMessage("I got some data."); pduInfo.setAccepted(); };

 

 

File (SBC only)

Function

Return Type

Description 

Example 

FileSystem.exists(path) 

boolean

Returns whether a file exists in the file system. 

FileSystem.exists("/file.txt") 

FileSystem.open(path,  mode) 

File

Opens a file for reading or writing. 

var file = FileSystem.open("/file.txt", File.READ);  Modes = File.READ | File.WRITE | File.APPEND

FileSystem.remove(path) 

boolean

Removes a file. 

FileSystem.remove("/file.txt"); 

FileSystem.mkdir(path) 

boolean

Creates a directory including all intermediate directories. 

FileSystem.mkdir("/dir1/dir2"); 

FileSystem.rmdir(path) 

boolean

Removes a directory. 

FileSystem.rmdir("/dir1/dir2"); 

FileSystem.dir(path) 

Array of File

Lists all files in a directory. 

var files = FileSystem.dir("/dir1"); 

  

 

  

  

name() 

string

Returns name of file. 

file.name(); 

dir() 

string

Returns directory path. 

file.dir(); 

available() 

int

# of bytes available for reading in file. 

var bytes = file.available(); 

close() 

N/A

Closes the file. 

file.close(); 

position() 

int

Returns the current reading position of the file. 

var position = file.position(); 

seek(position) 

boolean

Seeks to position in file. 

file.seek(0); 

print(val) 

int

Prints to file, returns the number of bytes written. 

file.print("Hello"); 

println(val) 

int

Prints to file with a \n at the end, returns the number of bytes written. 

file.println("Hello"); 

readln() 

string

Reads a line of string or to the end of file. 

var val = file.readln(); 

readch() 

string

Reads one character and removes it from buffer. 

var val = file.readch(); 

peekch() 

string

Reads one character without removing from buffer. 

var val = file.peekch(); 

read() 

int

Reads the first byte and removes from buffer, or -1 if none. 

var val = file.read(); 

peek() 

int

Returns the next byte without removing it from buffer, or -1 if none. 

var val = file.peek(); 

write(val) 

int

Writes as binary. 

file.write(val); 

 

 

 

USB

Function

Return Type

Description 

Example 

USB0

USB

The variable for USB0 port.

USB0.begin(9600);

USB1 (SBC only)

USB

The variable for USB1 port.

USB1.begin(9600);

begin(speed) 

N/A

Begin communication. 

USB0.begin(9600); 

end() 

N/A

Ends communication. 

USB0.end(); 

print(val) 

int

Prints to USB, returns the number of bytes written. 

USB0.print("Hello"); 

println(val) 

int

Prints to USB with a \n at the end, returns the number of bytes written. 

USB0.println("Hello"); 

available() 

int 

# of bytes available for reading in buffer. 

var bytes = USB0.available();

readln() 

string

Reads a line of string or to the end of stream. 

var val = USB0.readln(); 

readch() 

string

Reads one character and removes it from buffer. 

var val = USB0.readch(); 

peekch() 

string

Reads one character without removing from buffer. 

var val = USB0.peekch(); 

read() 

int

Reads the first byte and removes from buffer, or -1 if none. 

var val = USB0.read(); 

peek() 

int

Returns the next byte without removing it from buffer, or -1 if none. 

var val = USB0.peek(); 

write(val) 

int

Writes as binary. 

USB0.write(val); 


 

 

 

 

PTmata0

PTmata

The variable for PTmata communication over USB0 port.

PTmata0.begin(9600);

PTmata1 (SBC only)

PTmata

The variable for PTmata communication over USB1 port.

PTmata1.begin(9600);

begin(speed) 

N/A

Begin communication. 

PTmata0.begin(9600); 

end() 

N/A

Ends communication. 

PTmata0.end(); 

pinMode(slot, mode) 

N/A

Set a digital slot on other side to INPUT or OUTPUT. 

PTmata0.pinMode(1, OUTPUT); 

PTmata0.pinMode(2, INPUT); 

digitalRead(slot) 

int

Reads from a digital slot on other side, returns HIGH or LOW. 

var val = PTmata0.digitalRead(1); 

digitalWrite(slot, value) 

N/A

Writes to a digital slot on other side with HIGH or LOW. 

PTmata0.digitalWrite(1, HIGH); 

analogRead(slot) 

int

Reads from an analog slot on other side, returns 0 to 1023. 

var val = PTmata0.analogRead(A1); 

analogWrite(slot, value) 

N/A

Writes a PWM wave to a digital slot on other side, from 0 to 255. 

PTmata0.analogWrite(A1, 128); 

customRead(slot) 

string

Reads from an custom slot on other side, returns a string

var val = PTmata0.customRead(1); 

customWrite(slot, value) 

N/A

Writes a string to a digital slot on other side. You can use customRead directly from the other side

PTmata0.customWrite(1, "hello"); 

available() 

int 

# of bytes available for reading in buffer. 

var bytes = PTmata0.available();

processInput()

N/A

Reads from buffer and processes inputs for commands and reports of states.

function loop() {
  while (PTmata0.available())
    PTmata0.processInput();
  PTmata0.readAndReportData();
}

readAndReportData()

N/A

Reads this side's slot values and report to other side if they are changed.

PTmata0.readAndReportData();



 

IoE Client (SBC only)

Function

Return Type

Description 

Example 

IoEClient.setup(api)

N/A

Sets up the API for remote monitor and control from IoE server.

The api is an object with the following properties describing the device:

  • type - a string for the type of this device

  • states - an Array of objects with the following properties describing the state:

    • name - a string for this state

    • type - a string for the type of this state; can be "bool", "number", "options", "string"

    • options (required if type is "options") - an object that maps values to names

    • unit (optional if type is "number") - the default or Metric unit label; the value of a number state sent to the IoE Server should be in this unit

    • imperialUnit (optional if type is "number") - the Imperial System unit label

    • toImperialConversion (optional if type is "number") - a string to be evaluated to convert the default value to Imperial unit where x is the default value

    • toMetricConversion (optional if type is "number") - a string to be evaluated to convert the value in Imperial unit to the default or Metric unit, where x is the Imperial value

    • decimalDigits (optional if type is "number") - the number of decimal digits to round to on IoE Server pages; default is to not round

    • controllable - a boolean indicating whether it is remotely controllable

    • minValue (required if type is "number" and controllable is true) - the minimum value to allow the IoE Server to set in default or Metric unit

    • maxValue (required if type is "number" and controllable is true) - the maximum value to allow the IoE Server to set in default or Metric unit

For measurement systems other than Metric and Imperial, use only the "unit" property. That means if you want a device to show more than Metric and Imperial, you need to create another device for other measurement systems.

IoEClient.setup({
  type: "Door",
  states: [{
    name: "Open",
    type: "bool"
  }, {
    name: "Lock",
    type: "options",
    options: {
      "0": "Unlock",
      "1": "Lock"
    },
    controllable: true
  }]
});
IoEClient.setup({
 type: "Thermostat",
 states: [{
  name: "Status",
  type: "options",
  options: {
   "0": "Off",
   "1": "Cooling",
   "2": "Heating",
   "3": "Auto"
  },
  controllable: true
 }, {
  name: "Temperature",
  type: "number",
  unit: "°C",
  imperialUnit: "°F",
  toImperialConversion: "x*1.8+32",
  toMetricConversion: "(x-32)/1.8",
  decimalDigits: 1
 }, {
  name: "Auto Cool Temperature",
  type: "number",
  unit: "°C",
  imperialUnit: "°F",
  toImperialConversion: "x*1.8+32",
  toMetricConversion: "(x-32)/1.8",
  decimalDigits: 1,
  controllable: true,
  minValue: 10,
  maxValue: 100
 }, {
  name: "Auto Heat Temperature",
  type: "number",
  unit: "°C",
  imperialUnit: "°F",
  toImperialConversion: "x*1.8+32",
  toMetricConversion: "(x-32)/1.8",
  decimalDigits: 1,
  controllable: true,
  minValue: -100,
  maxValue: 20
 }]
});

IoEClient.reportStates(states)

N/A

Reports the states of this device to the IoE server.
The argument is a string representing all states of this device. Each state is separated by a comma.
The argument can also be an array representing all states.
The number of states must match the length of the states property in setup().

IoEClient.reportStates("0,1");

IoEClient.reportStates([0, 1, "str"]);

IoEClient.onInputReceive

N/A

Sets the callback for processing inputs received from IoE server.
The argument to the callback is a string containing all states of this device.

This is called with all states info. onStateSet is called with only the state that was changed.

IoEClient.onInputReceive = function(input) {
};

IoEClient.onStateSet

N/A

Sets the callback for processing inputs received from IoE server.
The arguments to the callback are state name and state value.

This is called with only the state that was changed. onInputReceive is called with all states info.

IoEClient.onStateSet = function(stateName, value) {
}; 

 

 

Physical

Function

Return Type

Description 

Example 

move(x,y) 

N/A

Move thing to position x and y in screen coordinates.

move(200,200);  

moveBy(x,y)

N/A

Increment position of thing by x and y in screen coordinates.

moveBy(1,0);

moveItemInWorkspace(name, x, y);

bool

Moves the item defined by name to x and y in screen coordinates in the active workspace. The parameters expect x and y to be ints. Casting may be required.

moveItemInWorkspace("building", 300,300);

getX()

float

Gets the x position of thing in screen coordinates.

var x = getX();

getY()

float

Gets the y position of thing in screen coordinates.

var y = getY();

getCenterX()

float

Gets the x position of the center of the thing in screen coordinates

var x = getCenterX();

getCenterY()

float

Gets the y position of the center of the thing in screen coordinates

var y = getCenterY();

devicesAt(x, y, width, height)

Array of string

Gets a list of devices at position x and y with a boundary of width and height. The parameters expect x and y to be ints. Casting may be required.

 

devicesAt(10,10,100,100);


devicesIncludingClustersAt(x, y, width, height)

Array of string

Gets a list of devices at position x and y with a boundary of width and height including clusters. The parameters expect x and y to be ints. Casting may be required.

devicesIncludingClustersAt(10, 10, 100, 100);

getName()

string

Gets the name of the thing

var devName = getName()

getDeviceProperty(deviceName, property)

string

Gets the property of a device with the specified property

getDeviceProperty("Car", "material")

setDeviceProperty(deviceName, property, value)

N/A

Set property for device

setDeviceProperty("Car", "material", "metal")

setComponentOpacity(componentName, value)

N/A

Set the opacity of a component in the thing. The value is from 0 to 1, where 1 is opaque.

setComponentOpacity("light", 0.5)

setComponentRotation(componentName, value)

N/A

Sets the component rotation in degrees

setComponentRotation("hourHand", 90)

setRotation(value)

N/A

Sets the entire thing rotation in degrees

setRotation(180)

getSerialNumber()

string

Gets the serial number of the thing

var serialNo = getSerialNumber()

setCustomText(x,y,width,height,text)

N/A

Write some text on the Thing viewable on the workspace.

setCustomText(0,0,100,100,"Device is On");

setLogicalBackgroundPath(text)

N/A

 

 

fillColor(componentName, red, green, blue)

N/A

Fill the component with the specified RGB values. The component original image will have to be transparent for the color to show up.

fillColor("led", 0,0,255)

addSound(soundID, soundPath)

N/A

Adds a sound to the device so it can be used.  Sound is referenced by the ID for later use.  PT sound folder is:

"/../Sounds/"

addSound('sound1', '/../Sounds/buzzLow.wav');

playSound(soundID, playLength)

N/A

Plays a sound that has been added to the device.  soundID references the ID the sound was added with, playLength is how many times the sound should run.  -1 will make the sound loop forever.

playSound('sound1', 2);

stopSound(soundID)

N/A

Stops a sound.  soundID references the ID the sound played.

stopSound('sound1');

destroySounds()

N/A

Stops any sounds playing in the devices and removes them.  They can't be played again unless re-added.

destroySounds();

setParentGraphicFromComponent(componentName, index)

N/A

Sets the parent container of both physical and logical view to a graphic from component.

setParentGraphicFromComponent("name", 0);

setLogicalParentGraphicFromComponent(componentName, index)

N/A

Sets the parent container of logical view to a graphic from component.

setLogicalParentGraphicFromComponent("name", 0);

setPhysicalParentGraphicFromComponent(componentName, index)

N/A

Sets the parent container of physical view to a graphic from component.

setPhysicalParentGraphicFromComponent("name", 0);

setLogicalBackgroundPath(path)

N/A

Sets the logical view background to an image at path.

setLogicalBackgroundPath("path");

getAttributeOfDeviceAtSlot(attribute, slot)

Number

Returns the attribute value of the device connected at the specified slot.

var value = getAttributeOfDeviceAtSlot("name", 0);

getAttributeOfDevice(attribute)

Number

Returns the attribute value of this device.

var value = getAttributeOfDevice("name");

getSlotsCount()

int

Returns the number of slots this device has.

var slots = getSlotsCount();

 

 

Environment

Function

Return Type

Description

Example

get(environmentID)

float

Gets the value of the environment by its ID. You can get the ID by placing your mouse over the environment name in the Environment GUI.

If the environment does not exist, it will return -1.

Environment.get("Ambient Temperature")

setGlobalProperty(propertyName, value) 

N/A

Sets a global property with a value. Both are strings.

Environment.setGlobalProperty("CLOCK", "12:00:00 pm")

getGlobalProperty(propertyName)

string

Returns the global property value.

Environment.getGlobalProperty("CLOCK")

hasGlobalProperty(propertyName)

boolean

Returns true if the property name exists, otherwise false.

Environment.hasGlobalProperty("CLOCK")

setContribution(environmentID, rate, limit, bCumulative)

 

Set the things contribution to an environment based on it's environment ID. You do not need to worry about how much time has passed and you only need to call this function when you need different parameters.

rate: the rate to add or subtract from the total environment value in value/second. Value should be in metric.

limit: the maximum or minimum this thing is allowed to contribute. The limit should be in metric.

bCumulative: add up contributed values over time. For environments like light sources that disappear when off, bCumulative should be set to false.

// increase the Ambient Temperature at 0.05C/second until 100C.

Environment.setContribution("Ambient Temperature", 0.05, 100, true)

removeCumulativeContribution(environmentID)

 

Remove the overall cumulative contribution from the Thing. In most cases, you do not need to do this. Rather, you should set up the container to use transference or other things to remove accumulated contributions.

Environment.removeCumulativeContribution("Ambient Temperature")

setTransferenceMultiplier(environmentID, multiplier)

 

Increase or decrease the current transference value by multiplier.

For example, if you open the door to the house, you may want to speed up the Ambient Temperature convergence with the outside by increasing the container's transference by the multiplier.

Environment.setTransferenceMultiplier("Ambient Temperature", 2)

getTotalContributions(environmentID)

float

Returns the total value of contributions by all things

Environment.getTotalContributions("Wind Speed")

getCumulativeContribution(environmentID)

 

Returns the cumulativeContribution for just the thing that is calling the function

Environment.getCumulativeContribution("Wind Speed")

getMetricValue(environmentID)

float

Returns the metric value of the environmentID regardless of user preference

Environment.getMetricValue("Ambient Temperature")

getValueWithUnit(environmentID)

string

Returns the value in metric or imperial based on the user preference and also append the unit

Environment.getValueWithUnit("Ambient Temperature")

getUnit(environmentID)

string

Returns the unit for the environmentID. The unit can be metric or imperial based on the user preferences

Environment.getUnit("Ambient Temperature")

getVolume()

float

Returns the volume size of the container in meters^3 that caller of the function is in

Environment.getVolume()

getTimeInSeconds()

int

Returns the current time

Environment.getTimeInSeconds();

getElapsedTime(lastTime)

int

Returns the time passed since the lastTime value

var time = Environment.getTimeInSeconds();

delay(1000);

Environment.getElapsedTime(time);

 

 

Real HTTP Server (External Network Access)

Function

Return Type

Description 

Example 

new RealHTTPServer() 

RealHTTPServer

Creates a Real HTTP Server. 

var http = new RealHTTPServer();

  

start( port )

N/A

Start server listening on port.

http.start( 8765 );

stop( )

N/A

Stop server listening.

http.stop();

isListening( )

boolean

Returns the listening status of the server.

http.isListening( );

route( url-pattern, request-types, callback)

N/A

Adds callback to be run for all request-types matching url-pattern.

callback: function (request, reply)
requst: RealHttpServerRequest
response: RealHttpServerResponse

url-pattern: string
request-types: array of strings (“GET”, “POST”, “PUT”, “UPDATE”, “DELETE”)

function on_get_files( request, reply ){...}
function on_posts( request, reply ){...}
function on_everything( request, reply ){...}
http.route( “/files/*”, [“GET”], on_get_files);
http.route( “*”, [“POST”], on_posts);
http.route( “*”, [], on_everything);

websocket( url-pattern, callback)

N/A

Adds callback be run for incoming websocket connections matching url-pattern.

callback: function (client)
client: RealWSClient

url-pattern: string

function callback( client ) {...}
http.websocket( "/ws", callback);





RealHTTPServerRequest


Request object passed to routing callbacks.


headers( )

object

Returns object containing request headers.

var headers = request.headers( );
... headers[“Content-Type”] ...

method( )

string

Returns request's method (“GET”, etc.)

if( request.method() == “POST” ) {
...
}

body( )

string

Returns the body of the request.

request.body();

url( )

string

Returns requested URL.

request.url();

ip( )

string

Returns IP address of the request origin.

if( request.ip() == “1.1.1.1” ) ...





RealHTTPServerResponse


Response object passed to routing callbacks.


setStatus( code )

N/A

Sets response status to code.

code: number

response.setCode( 200 ); // for OK response

setHeaders( headers )

N/A

Sets response headers in bulk. Object properties define header names and values.

headers: object

response.setHeaders({
“Authorization”: “basic”,
“Cookie”: “Id=1234; Group=users”
});

addHeader( name, value )

N/A

Sets header name to value.

name: string
value: string

response.addHeader( “Cookie”, “Group=inner” );

appendContent( content )

N/A

Appends content to response body.

content: string

response.appendContent( “more stuff“ );

resetContent( )

N/A

Resets the body of the response to empty.

response.resetContent();

end( )

N/A

Initiates network transfer for the response.

response.setContent( “Hello, world!” );
response.end();

response.setToPath( “my-file.txt” );
response.end();

setContent( content )

N/A

Sets the body of the response to content.

content: string

response.setContent( “Hello, world!” );

setToFile( path )

N/A

Sets content of the response to the contents of the file at path. The path must be local to the device running the server.

path: string

response.setToFile( “intro.html” );

setToNotFound( )

N/A

Canned response for when a requested resource can not be located.

response.setToNoFound();

send( content )

N/A

Sends content as plain text.

content: string

response.send( “Hello, world!” );

setContentType( type )

N/A

Sets Content-Type header to type.

type: string

response.setContentType( “text/html” );

sendFile( path )

N/A

Sends the contents of the file at path.

path: file path local to the device running the server.

response.send( “my-file.txt” );

sendNotFound( )

N/A

Sends canned response for when a requested resource can not be located.

response.sendNotFound();

 

 

 

Real HTTP Client (External Network Access)

Function

Return Type

Description 

Example 

new RealHTTPClient() 

RealHTTPClient

Creates a Real HTTP Client. 

var http = new RealHTTPClient();

  

get(url) 

N/A

Gets an URL. 

http.get(“http://www.cisco.com”); 

post(url, data)

N/A

Posts data to an URL.

data can be a string or a dictionary; if dictionary, it will be URL-encoded into the body.

http.post(url, {"num":1, "str":"hello"});

put(url, data)

N/A

Puts data to an URL.

data can be a string or a dictionary; if dictionary, it will be URL-encoded into the body.

http.put(url, {"num":1, "str":"hello"});

deleteResource(url)

N/A

Sends a delete to an URL.

http.deleteResource(url);

getWithHeader(url, header)

N/A

Gets an URL with custom header fields as a dictionary.

http.getWithHeader("https://api.ciscospark.com/v1/people/me",{"Authorization": "Bearer xxyyzz"});

postWithHeader(url, data, header)

N/A

Posts data to an URL with custom header fields as a dictionary.

data can be a string or a dictionary; if dictionary and custom header field has "application/json" as the "content-type", it will be json-encoded, otherwise it will be URL-encoded into the body.

http.postWithHeader("https://api.ciscospark.com/v1/messages",{"toPersonId": "722bb271-d7ca-4bce-a9e3-471e4412fa77", "text": "Hi Sparky"},{"Authorization": "Bearer xxyyzz", "Content-Type": "application/json"});

putWithHeader(url, data, header)

N/A

Puts data to an URL with custom header fields as a dictionary.

data can be a string or a dictionary; if dictionary and custom header field has "application/json" as the "content-type", it will be json-encoded, otherwise it will be URL-encoded into the body.

http.putWithHeader("https://api.ciscospark.com/v1/rooms/xxyyzz",{"title": "New room name"},{"Authorization": "Bearer xxyyzz"});

deleteResourceWithHeader(url, header)

N/A

Sends a delete to an URL with custom header fields as a dictionary.

http.deleteResourceWithHeader("https://api.ciscospark.com/v1/messages/xxyyzz",{"Authorization": "Bearer xxyyzz"});

onDone

N/A

Sets the callback for when the request is done.

replyHeader is a dictionary of header fields in the reply. It is added to 7.1 and is optional.

http.onDone = function(status, data, replyHeader) {

};

 

 

  

  

Short-hands without creating a RealHTTPClient

 

 

 

RealHTTPClient.get(url, callback)

N/A

Gets an URL.

RealHTTPClient.get("http://www.cisco.com", function(status, data) {
Serial.println(status + ", " + data);
}); 

RealHTTPClient.post(url, data, callback)

N/A

Posts data to an URL.

RealHTTPClient.post(url, {"num":1, "str":"hello"}, function(status, data) {
});

RealHTTPClient.put(url, data, callback)

N/A

Puts data to an URL.

RealHTTPClient.put(url, {"num":1, "str":"hello"}, function(status, data) {
});

RealHTTPClient.deleteResource(url, callback)

N/A

Sends a delete to an URL.

RealHTTPClient.deleteResource(url, function(status, data) {
});

 

 

 

Real WebSocket Client (External Network Access)

Function

Return Type

Description 

Example 

new RealWSClient() 

RealWSClient

Creates a Real WebSocket Client. 

var client = new RealWSClient(); 

connect(url) 

boolean

Connects to server URL. 

client.connect("ws://1.1.1.1:2000"); 

close() 

N/A

Disconnects. 

client.close(); 

connected()

boolean

Returns whether it is in connected state.

client.connected();

state() 

int

Returns the state of the connection. 

client.state(); 

remoteIP() 

string

Returns the remote IP. 

client.remoteIP(); 

remoteHost()

string

Returns the name of the server.

client.remoteHost();

remotePort() 

int

Returns the remote port. 

client.remotePort(); 

localIP()

string

Returns the local IP.

client.localIP();

localPort()

int

Returns the local port.

client.localPort();

send(data) 

N/A

Sends data to remote. 

client.send("hello"); 

error()

int

Returns the last error code.

client.error();

errorString()

string

Returns the last error in string.

client.errorString();

onReceive 

N/A

Sets the callback for when data is received. 

client.onReceive = function(data) { 

}; 

onConnectionChange 

N/A

Sets the callback for when the connection changes. 

client.onConnectionChange = function(type) { 

}; 

 

 

 

Real TCP (External Network Access)

Function

Return Type

Description 

Example 

new RealTCPClient() 

RealTCPClient

Creates a Real TCP Client. 

var client = new RealTCPClient(); 

connect(ip, port) 

boolean

Connects to ip and port. 

client.connect(IPAddress("1.1.1.1"), 2000); 

close() 

N/A

Disconnects. 

client.close(); 

connected()

boolean

Returns whether it is in connected state.

client.connected();

state() 

int

Returns the state of the connection. 

client.state(); 

remoteIP() 

string

Returns the remote IP. 

client.remoteIP(); 

remoteHost()

string

Returns the name of the server.

client.remoteHost();

remotePort() 

int

Returns the remote port. 

client.remotePort(); 

localIP()

string

Returns the local IP.

client.localIP();

localPort()

int

Returns the local port.

client.localPort();

send(data) 

N/A

Sends data to remote. 

client.send("hello"); 

error()

int

Returns the last error code.

client.error();

errorString()

string

Returns the last error in string.

client.errorString();

onReceive 

N/A

Sets the callback for when data is received. 

client.onReceive = function(data) { 

}; 

onConnectionChange 

N/A

Sets the callback for when the connection changes. 

client.onConnectionChange = function(type) { 

}; 

 

new RealTCPServer()

RealTCPServer

Creates a Real TCP Server.

var server = new RealTCPServer();

listen(port)

boolean

Listens on port on host device and returns whether it was successful.

server.listen(1234);

isListening()

boolean

Returns true if listening.

server.isListening();

stop()

N/A

Stops listening. All connections remain open.

server.stop();

listeningIP()

string

Returns the listening IP.

server.listeningIP();

listeningPort()

int

Returns the listening port.

server.listeningPort();

error()

int

Returns the last error code.

server.error();

errorString()

string

Returns the last error in string.

server.errorString();

onNewClient 

N/A

Sets the callback for when a new client is connected.

server.onNewClient(function(client) { 

}); 

 

 

Real UDP (External Network Access)

Function

Return Type

Description 

Example 

new RealUDPSocket() 

RealUDPSocket

Creates an Real UDP Socket. 

var udp = new RealUDPSocket(); 

begin(port) 

boolean

Starts listening on port. 

udp.begin(2000); 

stop() 

N/A

Stops listening. 

udp.stop(); 

joinMulticastGroup(ip)

boolean

Joins a multicast group. Must call begin() first.

udp.joinMulticastGroup("224.0.0.1");

leaveMulticastGroup(ip)

boolean

Leaves a multicast group.

udp.leaveMulticastGroup("224.0.0.1");

localIP()

string

Returns the local IP.

udp.localIP();

localPort()

int

Returns the local port.

udp.localPort();

send(ip, port, data) 

N/A

Sends data. 

udp.send(IPAddress("1.1.1.1"), 2000, "hello"); 

error()

int

Returns the last error code.

udp.error();

errorString()

string

Returns the last error in string.

udp.errorString();

onReceive 

N/A

Sets the callback for when data is received. 

udp.onReceive = function(ip, port, data) { 

}; 


 

  

JSON

Function

Return Type

Description 

Example 

JSON.stringify(obj) 

string

Serialize an object into JSON string.

var str = JSON.stringify({"num":1, "s":"str"});

JSON.parse(str)

object

Converts a JSON string to an object.

var obj = JSON.parse(str);

 

GUI (SBC, Thing, some End Devices)

Function 

Return Type

Description 

Example 

GUI.setup()

N/A

Initializes the GUI and tells the GUI to display the html file configured in the manifest file. If the app is not installed, it throws an error.

function setup() { GUI.setup();}

GUI.update(type, args)

N/A

Asynchronously calls the html file's update() function passing in type and args. Type is a string and args can be any JSON valid object.

GUI.update("status", "playing");

guiEvent(type, args)

N/A

If defined, this function is called asynchronously when the html file calls guiEvent(type, args). Type is a string and args can be any JSON valid object.

function guiEvent(type, args) {  Serial.println('guiEvent: ' + type + ',' + JSON.stringify(args));} 

 

 

CLI (SBC, Thing, some End Devices)

Function 

Return Type

Description 

Example 

CLI.setup()

N/A

Initializes the CLI and will call the cliEvent() function if the app was started from a command in the Command Prompt.

function setup() { CLI.setup();}

CLI.exit()

N/A

Exits the CLI mode and returns back to the Command Prompt.

CLI.exit();

cliEvent(type, args)

N/A

If defined, this function is called synchronously when different CLI events happen. Type is a string and args can be any JSON valid object.

Type can be:

  • "invoked" - this is called when the command is invoked from the Command Prompt; args is a list of command arguments where the first element is the command name.

  • "interrupted" - this is called when the user uses break shortcut (Ctrl+C) while this app is running in CLI mode.

function cliEvent(type, args) {  Serial.println('cliEvent: ' + type + ',' + JSON.stringify(args));} 

 

 

Simulation

Function 

Return Type

Description 

Example 

Simulation.isInSimulationMode()

bool

Returns whether PT is currently in Simulation Mode.

if (Simulation.isInSimulationMode()) Serial.println("In sim mode");

Simulation.addCustomProtocolType(protocol)

bool

Adds a new protocol type to the current file/network. The protocol will show up in the Event List Filters. Returns true if successful, false otherwise.

Simulation.addCustomProtocolType("MyProtocol");

Simulation.hasCustomProtocolType(protocol)

bool

Returns whether the protocol type is already added to the current file/network.

if (!Simulation.hasCustomProtocolType("MyProtocol")) Simulation.addCustomProtocolType("MyProtocol");

Simulation.addCustomPDU(protocol, pduType, definition)

bool

Adds a new protocol type and PDU type to the current file/network. The protocol will show up in the Event List Filters, and the PDU with its definition will show up in PDU details. Returns true if successful, false if the definition is invalid. It will replace existing definitions if using the same protocol and PDU type names.

The definition argument is an object with the following properties describing the layout and fields of the PDU:

  • title - a string that shows up as the title in PDU Details

  • units - a string

  • unit_marks - an array of numbers indicating where the marks are to show up

  • width - an integer indicating the width of PDU

  • fields - an array of objects representing each field in the PDU; each object must contain the following properties:

    • value - a label that can contain a variable inside curly braces; the variable will be replaced with a value in the PDUInfo fields object

    • size - an integer indicating the size of the field

Simulation.addCustomPDU("MyProtocol", "MyPDU", {  "title": "My PDU",  "units": "Bits",  "unit_marks": [16],  "width": 32,  "fields": [    {      "value": "TYPE: {type}",      "size": 32    },    {      "value": "DATA: {data}",      "size": 32    }  ]});

Simulation.hasCustomPDU(protocol, pduType)

bool

Returns whether the protocol and PDU type is already added to the current file/network.

if (!Simulation.hasCustomPDU("MyProtocol", "MyPDU")) // add it

PDUInfo(color)

PDUInfo

Creates a PDU Info object with the pdu color. A PDUInfo is required to show PDU with more details in Simulation Mode.

var pduInfo = new PDUInfo(0xffff00);

setOutFormat(protocol, pduType, fields)

N/A

Sets the outgoing PDU to be displayed in a custom PDU definition. The fields argument is an object with the variables defined in the PDU definition fields property.

pduInfo.setOutFormat("MyProtocol", "MyPDU", {"type": "REPLY", "data": data})

addOutMessage(message)

N/A

Adds a message to the outgoing OSI layer 7.

pduInfo.addOutMessage("I am sending some data.")

addInMessage(message)

N/A

Adds a message to the incoming OSI layer 7.

pduInfo.addInMessage("I received some data.")

setAccepted()

N/A

Sets the PDU as accepted.

pduInfo.setAccepted()

setDropped()

N/A

Sets the PDU as dropped.

pduInfo.setDropped()

 

 

Workspace

Function 

Return Type

Description 

Example 

getPhysicalObject()

PhysicalObject

Returns the current device's physical object.

po = getPhysicalObject();

getName()

str

Returns the name of this physical object.

Serial.println(po.getName());

getType()

int

Returns the type of this physical object. Valid values are:

INTER_CITY = 0CITY = 1BUILDING = 2WIRING_CLOSET = 3RACK = 4TABLE = 5DEVICE = 6MULTIUSER = 7GENERIC_CONTAINER = 8

Serial.println(po.getType());

getX()

float

Returns the x coordinate relative to its parent in meters.

Serial.println(po.getX());

getY()

float

Returns the y coordinate relative to its parent in meters.

Serial.println(po.getY());

getCenterX()

float

Returns the center x coordinate relative to its parent in meters.

Serial.println(po.getCenterX());

getCenterY()

float

Returns the center y coordinate relative to its parent in meters.

Serial.println(po.getCenterY());

getGlobalX()

float

Returns the global x coordinate of this physical object in meters.

Serial.println(po.getGlobalX());

getGlobalY()

float

Returns the global y coordinate of this physical object in meters.

Serial.println(po.getGlobalX());

getWidth()

float

Returns the width of this physical object in meters.

Serial.println(po.getWidth());

getHeight()

float

Returns the height of this physical object in meters.

Serial.println(po.getHeight());

moveTo(x, y)

N/A

Moves this physical object's top left corner to the specified coordinates in meters relative to its parent.

po.moveTo(10, 20);

moveCenterTo(x, y)

N/A

Moves this physical object's center to the specified coordinates in meters relative to its parent.

po.moveCenterTo(10, 20);

moveBy(x, y)

N/A

Moves this physical object by the specified coordinates in meters.

po.moveBy(10, 20);

setVelocity(x, y)

N/A

Sets this physical object's velocity in meters. This physical object then moves automatically.

po.setVelocity(1, 2);

getXVelocity()

float

Returns the x velocity of this physical object in meters.

Serial.println(po.getXVelocity());

getYVelocity()

float

Returns the y velocity of this physical object in meters.

Serial.println(po.getYVelocity());

getParent()

PhysicalObject

Returns this physical object's parent.

parentPO = po.getParent();

moveOutOfParent()

bool

Moves this physical object out of its parent to the same level as the parent, and returns whether it was successful.

po.moveOutOfParent();

moveInto(name)

bool

Moves this physical object into a container with the specified name that is in the same level as this physical object, and returns whether it was successful.

po.moveInto("Corporate Office");

getChildCount()

int

Returns the number of children this physical object has.

Serial.println(po.getChildCount());

getChildAt(index)

PhysicalObject

Returns the child physical object at the specified index.

childPO = po.getChildAt(0);

getChild(name)

PhysicalObject

Returns the child physical object with the specified name.

childPO = po.getChild("Wiring Closet");

getLogicalObject()

LogicalObject

Returns the current device's logical object.

lo = getLogicalObject();

getName()

str

Returns the name of this logical object.

Serial.println(lo.getName());

getType()

int

Returns the type of this logical object. Valid values are:

ROOT = 1099DEVICE = 1100CLUSTER = 1104MULTIUSERITEM = 1108

Serial.println(lo.getType());

getX()

int

Returns the x coordinate relative to its parent in pixels.

Serial.println(lo.getX());

getY()

int

Returns the y coordinate relative to its parent in pixels.

Serial.println(lo.getY());

getCenterX()

int

Returns the center x coordinate relative to its parent in pixels.

Serial.println(lo.getCenterX());

getCenterY()

int

Returns the center y coordinate relative to its parent in pixels.

Serial.println(lo.getCenterY());

getWidth()

int

Returns the width of this logical object in pixels.

Serial.println(lo.getWidth());

getHeight()

int

Returns the height of this logical object in pixels.

Serial.println(lo.getHeight());

moveTo(x, y)

N/A

Moves this logical object's top left corner to the specified coordinates in pixels relative to its parent.

lo.moveTo(10, 20);

moveCenterTo(x, y)

N/A

Moves this logical object's center to the specified coordinates in pixels relative to its parent.

lo.moveCenterTo(10, 20);

moveBy(x, y)

N/A

Moves this logical object by the specified coordinates in pixels.

lo.moveBy(10, 20);

setVelocity(x, y)

N/A

Sets this logical object's velocity in pixels. This logical object then moves automatically.

lo.setVelocity(1, 2);

getXVelocity()

float

Returns the x velocity of this logical object in pixels.

Serial.println(lo.getXVelocity());

getYVelocity()

float

Returns the y velocity of this logical object in pixels.

Serial.println(lo.getYVelocity());

getParent()

LogicalObject

Returns this logical object's parent.

parentLO = lo.getParent();

moveOutOfParent()

bool

Moves this logical object out of its parent to the same level as the parent, and returns whether it was successful.

lo.moveOutOfParent();

moveInto(name)

bool

Moves this logical object into a container with the specified name that is in the same level as this logical object, and returns whether it was successful.

lo.moveInto("Cluster0");

getChildCount()

int

Returns the number of children this logical object has.

Serial.println(lo.getChildCount());

getChildAt(index)

LogicalObject

Returns the child logical object at the specified index.

childlo = lo.getChildAt(0);

getChild(name)

LogicalObject

Returns the child logical object with the specified name.

childlo = lo.getChild("Cluster0");

 

Bluetooth Manager

Function

Return Type

Description 

Example 

init() N/A Initialize Bluetooth functionality for the device.
function setup(){
Bluetooth.init();
}

onDeviceDiscovered(macAddress, deviceName)

N/A

This event handler is called when a device is discovered.

Bluetooth.onDeviceDiscovered = function()(macAddress, deviceName) {
...
}

Bluetooth.discover()

 

onDevicePaired(macAddress) N/A This event handler is called when a device is paired. Bluetooth.onDevicePaired = function(macAddress){...}
onDeviceUnPaired(macAddress) N/A This event handler is called when a device is unpaired. Bluetooth.onDeviceUnpaired = function(macAddress){...}
onDeviceConnected(macAddress) N/A This event handler is called when a device is connected. Bluetooth.onDeviceConnected = function(macAddress){...}
onDeviceDisconnected(macAddress) N/A This event handler is called when a device is disconnected. Bluetooth.onDeviceDisconnected = function(macAddress){...}
setDiscoverable(discoverable) N/A Sets the bluetooth device to discoverable or not. Bluetooth.setDiscoverable(true)
isDiscoverable() bool Returns true if discoverable otherwise false. Bluetooth.isDiscoverable()
discover() N/A Starts the discovering process. If devices are discovered, the onDeviceDiscovered() event will trigger. Bluetooth.discover()
pair(mac) N/A Starts pairing with mac address. Bluetooth.pair(macAddress)
unpair(mac) N/A Starts unpairing with mac address. Bluetooth.unpair(macAddress)
onPairRequest(macAddress, deviceName) N/A This event handler is called if there's a pair request and the bluetooth manager is set to accept pair requests.

Bluetooth.setAcceptingPairRequest(true)


Bluetooth.onPairRequest = function(macAddress, deviceName){...}
setAcceptingPairRequest(accepting) N/A Sets the bluetooth manager to accept pair requests Bluetooth.setAcceptingPairRequest(true)
acceptPairRequest(macAddress, deviceName) N/A Accepts the pair request with macAddress and deviceName Bluetooth.acceptPairRequest(macAddress, deviceName)
getPairedDevices() Array Returns an array of paired bluetooth devices. var devices = Bluetooth.getPairedDevices()
getConnectedDevices() Array Returns an array of connected devices. var devices = Bluetooth.getConnectedDevices()
enableBroadcast() N/A Enables bluetooth broadcast. Bluetooth.enableBroadcast()
isBroadcastEnabled() bool Returns true if broadcast is enabled. Bluetooth.isBroadcastEnabled()
broadcastBeacon(beaconUuid, data) bool Broadcast beacon with beaconUuid and data. Bluetooth.broadcastBeacon(uuid, data)

 

Bluetooth Service

Function

Return Type

Description 

Example 

start(uuid)

N/A

Starts the bluetooth service.

var bts = new BluetoothService();

var dstService = "{00000000-0000-0000-0000-000000000001}"

bts.start(dstService)

 

connect(dstMac, dstServiceUuid) bool Returns true if connected to dstMac and dstServiceUuid; false otherwise. bts.connect(dstMac, dstServiceUuid)
stop() N/A Stops the bluetooth service. bts.stop()
send(dstMac, dstServiceUuid, data) N/A Sends data to dstMac and dstServiceUuid with data. bts.send(dstMac, dstServiceUuid, "hello")
sendToConnected(data) N/A Sends data to connected device. bts.sendToConnected("hello")
onReceive(srcMac, srcService, dstMac, dstService, data) N/A This event handler receives data from srcMac, srcService, dstMac and dstService with data. bts.onReceive = function(srcmac, srcData, dstMac, dstService, data){...}