Python API


Program Structure and Events

Package = N/A

Function 

Return Type

Description 

Example 

cleanUp()

N/A If defined, this function is called once just before the program stops.
def cleanUp():
print("program is stopping.")

mouseEvent(pressed, x, y, firstPress)

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.

 

def 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 Options.isUsingMetric() in the options package to get the current setting.
from options import *

def measurementSystemChangeEvent():
METRIC = Options.isUsingMetric()
unit = "C" if METRIC else "F"
refresh()

 

 

Digital I/O 

Package = gpio

Function 

Return Type

Description 

Example 

pinMode(slot, mode) 

N/A

Set a digital slot to INPUT or OUTPUT. 

pinMode(1, OUT)

pinMode(2, IN)

digitalRead(slot) 

int

Reads from a digital slot, returns HIGH or LOW. 

val = digitalRead(1) 

digitalWrite(slot, value) 

N/A

Writes to a digital slot with HIGH or LOW. 

digitalWrite(1, HIGH) 

 

 

Analog I/O 

Package = gpio

Function 
Return Type

Description 

Example 

analogRead(slot) 

int

Reads from an analog slot, returns 0 to 1023. 

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 

Package = gpio

Function  Return Type Description  Example 
customRead(slot)  str Reads from an custom slot, returns a String 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/Events 

Package = gpio

Function  Return Type Description  Example 
add_event_detect(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.

def detect():
input = analogRead(0)
# do something

add_event_detect(0, detect)
remove_event_detect(slot) N/A Unregisters the slot for input changes. remove_event_detect(0)

Time

Package = time

Function 

Return Type

Description 

Example 

delay(ms) 

N/A

Pauses the program for ms. 

delay(1000) 

 

 

Basic Networking 

Package = networking

Function 

Return Type

Description 

Example 

localIP() 

str

Returns the local IP. 

ip = localIP()

subnetMask() 

str

Returns the subnet mask. 

mask = subnetMask()

gatewayIP() 

str

Returns the gateway IP. 

gateway = gatewayIP()  

 

 

HTTP Client

Package = http

Function 

Return Type

Description 

Example 

HTTPClient() 

HTTPClient

Creates a HTTP Client. 

http = HTTPClient()

open(url) 

N/A

Gets an URL. 

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

stop() 

N/A

Stops the request. 

http.stop()

onDone(callback) 

N/A

Sets the callback for when the request is done. 

def onHTTPDone(status, data): 
print(data)

...

http.onDone(onHTTPDone)

 

HTTP Server (SBC only)

   Package = http
Function Return Type Description Example

route(path, callback);

N/A

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

def onRouteHello(url, response):
response.send("hello")
HTTPServer.route("/hello", onRouteHello)


def onRouteAll(url, response):
response.send("world")
HTTPServer.route("/*", onRouteAll)

 

start(port) 

bool

Starts listening on port. 

HTTPServer.start(80)

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

Package = email

Function 

Return Type

Description 

Example 

setup(email, server, username, password) 

N/A

Sets up the email client to be used. 

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

send(address, subject, body) 

N/A

Sends an email. 

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

receive() 

N/A

Receives emails. 

EmailClient.receive()

onSend(callback)

N/A

Sets the callback for when sending an email is done. 

def onEmailSend(success): 
print(success)

...

EmailClient.onSend(onEmailSend) 

onReceive(callback) 

N/A

Sets the callback for when emails are received. 

def onEmailReceive(sender, subject, body): 
print(body)
...
EmailClient.onReceive(onEmailReceive)

 

 

TCP

Package = tcp

Function 

Return Type

Description 

Example 

TCPClient() 

TCPClient

Creates a TCP Client. 

client = TCPClient()

connect(ip, port) 

bool

Connects to ip and port. 

client.connect("1.1.1.1", 2000)

connected() bool Returns true if connected client.connected()

close() 

N/A

Disconnects. 

client.close()

state() 

int

Returns the state of the connection. 

client.state()

remoteIP() 

str

Returns the remote IP. 

client.remoteIP()

remotePort() 

int

Returns the remote port. 

client.remotePort()

localIP() str Returns the local IP client.localIP()
localPort() int Returns the local port client.localPort()

send(data) 

N/A

Sends data to remote connection

client.send("hello")

onReceive(callback)

N/A

Sets the callback for when data is received. 

def onTCPReceive(data): 
print(data)
...
client.onReceive(onTCPReceive)

onConnectionChange(callback) 

N/A

Sets the callback for when the connection changes. 

def onTCPConnectionChange(type): 
print(type)
...
client.onConnectionChange(onTCPConnectionChange)

 

 

  

  

TCPServer() 

TCPServer

Creates a TCP Server. 

server = TCPServer() 

listen(port) 

N/A

Starts listening on port. 

server.listen(2000)

stop() 

N/A

Stops listening. 

server.stop()

onNewClient(callback)

N/A

Sets the callback for when a new client comes in. 

def onTCPNewClient(client): 
print(client)
...
server.onNewClient(onTCPNewClient)

 

 

UDP

Package = udp

Function 

Return Type

Description 

Example 

UDPSocket() 

UDPSocket

Creates an UDP Socket. 

udp = UDPSocket() 

begin(port) 

bool

Starts listening on port. 

udp.begin(2000)

stop() 

N/A

Stops listening. 

udp.stop()

send(ip, port, data) 

bool

Sends data. 

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

onReceive(callback)

N/A

Sets the callback for when data is received. 

def onUDPReceive(ip, port, data):
print(data)
...

udp.onReceive(onUDPReceive)

 

 

File (SBC only)

Package = file, os, os.path

Function 

Return Type

Description 

Example 

bool exists(path) 

bool

Returns whether a file exists in the file system. 

exists("/file.txt") 

File open(path,  mode) 

File

Opens a file for reading or writing. 

file = open("/file.txt", "r") 

bool remove(path) 

bool

Removes a file. 

remove("/file.txt")

bool mkdir(path) 

bool

Creates a directory including all intermediate directories. 

mkdir("/dir1/dir2")

bool rmdir(path) 

bool

Removes a directory. 

rmdir("/dir1/dir2")

listdir(path) 

list

Lists all files in a directory. 

files = listdir("/dir1")

exists(path)  

bool

Test if path exists  

val = exists("/file")  

isfile(path) bool Test if path is a file val = exists("/file")
isdir(path) bool Test if path is a directory val = exists("/file")
       

tell()

int

Return read/write pointer of the file

file.tell()

close() 

N/A

Closes the file. 

file.close()

seek(position) 

bool

Seeks to position in file. 

file.seek(0)

readline() 

str

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

val = file.readline()

read(length) 

str

Reads the length of byte into string

val = file.read()

write(val) 

N/A

Writes as binary. 

file.write(val)

 

 

USB

Package = usb

Function 

Return Type

Description 

Example 

USB( usbNum, speed) USB The variable for USB port. usb = USB(0, 9600);

close() 

N/A

Ends communication. 

usb.close(); 

inWaiting() 

int 

# of bytes available for reading in buffer. 

bytes = usb.inWaiting();

readLine() 

string

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

val = usb.readLine(); 

read() 

string

Reads the first character and removes from buffer. 

val = usb.read(); 

peek() string Reads one character without removing from buffer. val = usb.peek();

write(val) 

int

Prints to USB, returns the number of bytes written. 

val = usb.write(val); 


       
PTmata(usbNum, speed) PTmata The variable for PTmata communication over USB port. ptmata = PTmata(0, 9600)

close() 

N/A

Ends communication. 

ptmata.close() 

pinMode(slot, mode) 

N/A

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

ptmata.pinMode(1, OUT)

ptmata.pinMode(2, IN)

digitalRead(slot) 

int

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

val = ptmata.digitalRead(1)

digitalWrite(slot, value) 

N/A

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

ptmata.digitalWrite(1, HIGH)

analogRead(slot) 

int

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

val = ptmata.analogRead(A1); 

analogWrite(slot, value) 

N/A

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

ptmata.analogWrite(A1, 128); 

customRead(slot) 

string

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

val = ptmata.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

ptmata.customWrite(1, "hello"); 

inWaiting() 

int 

# of bytes available for reading in buffer. 

bytes = ptmata.inWaiting();

processInput()

N/A Reads from buffer and processes inputs for commands and reports of states.
def loop() :
while ptmata.inWaiting():
ptmata.processInput()
ptmata.readAndReportData()

readAndReportData()

N/A Reads this side's slot values and report to other side if they are changed. ptmata.readAndReportData();

 

 

IoE Client (SBC only)


Package = ioeclient

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 can be 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(callback) 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.

def onInputReceiveDone(input): 
print(input)

...
IoEClient.onInputReceive(onInputReceiveDone)

IoEClient.onStateSet(callback) 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.

def onStateSet(stateName, value):
print(stateName + ": " + value)
...
IoEClient.onStateSet(onStateSet) 

 

 

Physical

Package = physical

Function 

Return Type

Description 

Example 

move(x,y) 

N/A

Move thing to position x and y in screen coordinates. The parameters expect x and y are ints. Casting may be required.

move(200,200)

moveBy(x,y)

N/A

Increment position of thing by x and y in screen coordinates. The parameters expect x and y are ints. Casting may be required.

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 moveItemInWorkspace("building", 300,300)

getX()

float

Gets the x position of thing in screen coordinates.

x = getX()

getY()

float

Gets the y position of thing in screen coordinates.

y = getY()

devicesAt(x, y, width, height)

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

devices = devicesAt(10,10,100,100)

getName() str Gets the name of the thing devName = getName()
getDeviceProperty(deviceName, property) str Gets the property of a device with the specified property prop = getDeviceProperty("Car", "material")
setDeviceProperty(deviceName, property, value) N/A Set property for device prop= 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)
setThingRotation(value) N/A Sets the entire thing rotation in degrees setThingRotation(180)
getSerialNumber() str Gets the serial number of the thing 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")
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();

 

 

Environment

Package = environment (from environment import *) or (from environment import Environment)

Function 

Return Type

Description 

Example 

change(environmentName, number)

N/A

Changes the environment value by number. This function effectively adds number to the current environment value.

Environment.change("TEMPERATURE", 1.0)

set(environmentName, number)

N/A

Sets the environment to number. 

Environment.set("TEMPERATURE", 32)

get(environmentName)

float

Gets the value of the environment.

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

Environment.get("TEMPERATURE")

has(environmentName)

bool

Checks if the environment exist. Return true if it does otherwise false.

Environment.has("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) str Returns the global property value. Environment.getGlobalProperty("CLOCK")
hasGlobalProperty(propertyName) bool Returns true if the property name exists, otherwise false. Environment.hasGlobalProperty("CLOCK")
setEnvironmentPropagation(environmentName, number) N/A Sets the environmental propagation number. When an environment is set or changed in a container, it's children container will receive a multiple of the "number" as the environment value. By default, the propagation value is 1. Environment.setEnvironmentPropagation("TEMPERATURE", 0.8)
getEnvironmentPropagation(environmentName) float Return the environment propagation value. Environment.getEnvironmentPropagation("TEMPERATURE")
hasEnvironmentPropagation(environmentName) bool Returns true if the environment propagation value exists otherwise false. Environment.hasEnvironmentPropagation("TEMPERATURE")

 

 

Real HTTP
(External Network Access)

Package = realhttp

Function 

Return Type

Description 

Example 

RealHTTPClient() 

RealHTTPClient

Creates a Real HTTP Client. 

http = 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(callback) 

N/A

Sets the callback for when the request is done. 

def onHTTPDone(status, data): 
print(data)

...

http.onDone(onHTTPDone)

 

 

Real TCP
(External Network Access) 

Package = realtcp

Function 

Return Type

Description 

Example 

RealTCPClient() 

RealTCPClient

Creates a Real TCP Client. 

client = RealTCPClient()

connect(ip, port) 

N/A

Connects to ip and port. 

client.connect("1.1.1.1", 2000)

connected() bool Returns true if connected. client.connected()

close() 

N/A

Disconnects. 

client.close()

state() 

int

Returns the state of the connection. 

client.state()

remoteIP() 

str

Returns the remote IP. 

client.remoteIP()

remoteHost() str Returns the remote server host name. client.remoteHost()

remotePort() 

int

Returns the remote port. 

client.remotePort()

localIP() str Returns the local IP. client.localIP()
localPort() int Returns the local port. client.localPort()

send(data) 

N/A

Sends data to remote connection.

client.send("hello")

error() int Returns the last error code. client.error()
errorString() str Returns the last error in string. client.errorString()

onReceive(callback)

N/A

Sets the callback for when data is received. 

def onTCPReceive(data): 
print(data)
...
client.onReceive(onTCPReceive)

onConnectionChange(callback) 

N/A

Sets the callback for when the connection changes. 

def onTCPConnectionChange(type): 
print(type)
...
client.onConnectionChange(onTCPConnectionChange)

 

 

Real UDP
(External Network Access) 

Package = realudp

Function 

Return Type

Description 

Example 

RealUDPSocket() 

RealUDPSocket

Creates an Real UDP Socket. 

udp = RealUDPSocket() 

begin(port) 

bool

Starts listening on port. 

udp.begin(2000)

stop() 

N/A

Stops listening. 

udp.stop()

joinMulticastGroup(ip) bool Joins a multicast group. Must call begin() first. udp.joinMulticastGroup("224.0.0.1")
leaveMulticastGroup(ip) bool Leaves a multicast group. udp.leaveMulticastGroup("224.0.0.1")
localIP() str Returns the local IP. udp.localIP()
localPort() int Returns the local port. udp.localPort()

send(ip, port, data) 

bool

Sends data. 

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

onReceive(callback)

N/A

Sets the callback for when data is received. 

def onUDPReceive(ip, port, data):
print(data)
...

udp.onReceive(onUDPReceive)

error() int Returns the last error code. udp.error()
errorString() str Returns the last error in string. udp.errorString()

 

JSON

Package = json

Function 

Return Type

Description 

Example 

dumps(obj) 

str

Serializes a Python object into JSON string. 

jsonStr = json.dumps({"num":1, "s":"str"})

loads(jsonStr) 

python object

Converts a JSON string into a Python object.

obj = json.loads(s)