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() { |
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() { |
cleanUp() |
N/A | If defined, this function is called once just before the program stops. | function cleanUp() { |
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.
|
function mouseEvent(pressed, x, y, firstPress) { |
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() { |
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 |
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() { 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); |
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() |
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"); |
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 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"); |
onReceive |
N/A | Sets the callback for when data is received. |
udp.onReceive = function(ip, port, data) { }; |
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() { |
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:
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({ IoEClient.setup({ |
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. 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. 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(); |
setParentGraphic(path) | |||
setParentGraphic(path) | |||
setParentGraphicFromComponent(componentName, index) | |||
setLogicalParentGraphicFromComponent(componentName, index) | |||
setPhysicalParentGraphicFromComponent(componentName, index) | |||
getAttributeOfDeviceAtSlot(attribute, slot) | |||
getAttributeOfDevice(attribute) | |||
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 (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. | http.post(url, {"num":1, "str":"hello"}); |
put(url, data) | N/A | Puts data to an URL. | http.put(url, {"num":1, "str":"hello"}); |
deleteResource(url) | N/A | Sends a delete to an URL. | http.deleteResource(url); |
onDone |
N/A | Sets the callback for when the request is done. |
http.onDone = function(status, data) { }; |
|
|
|
|
Short-hands without creating a RealHTTPClient | |||
RealHTTPClient.get(url, callback) | N/A | Gets an URL. | RealHTTPClient.get("http://www.cisco.com", function(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 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) { }; |
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); |