JS Main

View Umajin’s JavaScript documentation to start creating custom code for your app

Global

Members


ActionString

Enum for built in Action strings. This can be used with callAction.
Properties:
Name Type Description
SHOW_PAGE_BY_NAME

string

Show page by name (page)
SHOW_POPUP

string

Show popup (msg)
NAVIGATE_BACK

string

Navigate back
SHOW_WEBPAGE

string

Show Webpage in browser (url)
OPEN_MAP

string

Open map in browser (address)
DIAL_NUMBER

string

Dial number on device (number)
SMS_NUMBER

string

SMS number on a device (number)
SEND_EMAIL

string

Send email (To, CC, BCC, Subject, Body, Attachment, MIME type)
PLAY_ANIMATION

string

Play animation (animation component, animation name, loop)
STOP_ANIMATION

string

Stop animation (animation component)
PLAY_VIDEO

string

Play video (video component, video name)
STOP_VIDEO

string

Stop video (video component)
SET_TEXT

string

Set text (text component, text, expand)
SET_IMAGE_IN_ZOOMER

string

Set image in a zoomer (zoomer component, filename)
POSITION

string

Position component relative to another (destination component, x 0-100, y 0-100, ms)
ANIMATE

string

Animate component (animation component, animation [0 bounce : 1 zoom : 2 spin : 3 squash : 4 stretch : 5 rock : 6 flip : 7 fade in : 8 in left : 9 in right : 10 in top : 11 in bottom : 12 fade left : 13 fade right : 14 fade top : 15 fade bottom] delay ms)
ANIMATE_CONTROL

string

Animate a component with control (animation component, animation [0 bounce : 1 zoom : 2 spin : 3 squash : 4 stretch : 5 rock : 6 flip : 7 fade in : 8 in left : 9 in right : 10 in top : 11 in bottom : 12 fade left : 13 fade right : 14 fade top : 15 fade bottom], delay ms, length ms, scale 0-2)
SET_VISIBILITY

string

Set visibility of a component (bool visibility)
WAIT

string

Wait (ms)
SET_FEED_ITEM

string

Set feed item index (item view component, mode [“show_next”: “show_previous”: “loop”: “random”: “data_bound_index”: “custom_index”], custom index)
SET_FEED_URL

string

Set feed url (feed list component, url)
SET_FEED_ITEM_URL

string

Set feed item url (feed item component, url)
APPLY_FILTER

string

Set filter on a feed (feed list component, text entry component, default text, json columns to filter)
CLEAR_FILTER

string

Clear filter (feed list component, text entry component)
SET_GLOBAL_VAR

string

Set global var (name, value) this is equivalent to setGlobalVar and getGlobalVar
SET_FORM_DATA_VALUE

string

Set form field value (form component, field #, value)
NAVIGATE_GALLERY

string

Navigate gallery (galley component, bool animate)
SET_BUTTON_ENABLED

string

Set button enabled (button component, bool enabled)
SET_DISABLED_WHEN_EMPTY

string

Disable button component when empty
HIDE_IF_EMPTY

string

Hide if empty
HIDE_IF_NOT_EMPTY

string

Hide if not empty
SET_MENU_TEXT

string

Set menu text (menu component, title)
CLOSE_MENU

string

Close menu (menu component)
OPEN_MENU

string

Open menu (menu component)
TOGGLE_MENU

string

Toggle menu (menu component)
SET_TOOLBAR_INDEX

string

Set toolbar index (toolbar component, index)
ENABLE_BLUETOOTH

string

Enable bluetooth (bluetooth component)
CONNECT_TO_BLE_DEVICE

string

Connect to BLE device (device id)
SET_BLE_CHARCTERISTIC

string

Set BLE charcteristic (service id, characteristic id, value)
CLEAR_BLE_STATE

string

Clear BLE state (bluetooth component)
RESET_SCROLL_PANEL

string

Reset scroll panel (scroll panel component)
RESET_FEED_LIST

string

Reset feed list (feed list component)
RESET_PRODUCT_LIST

string

Reset product list (product list component)
NOTIFY_LATER

string

Notify later (title, body, id, delay ms)
NOTIFY_PAGE_CHANGE

string

Notify page change (title, body, delay ms, page, popup)
PLAY_SOUND

string

Play an MP3 (filename, bool looping, volume [0 min – 1 max])
STOP_SOUND

string

Stop an MP3 (filename)
STOP_ALL_SOUND

string

Stop all MP3 files

ComponentString

Enum for component type strings. This can be used with createComponent. It can also be used to built params strings (using concatenation) for registerAction, and component types for createComponent.
Properties:
Name Type Description
ACCORDION_MENU

string

“accordion_menu”
ANIMATED_FEED

string

“animated_feed”
ANIMATION

string

“animation”
APP_POPUP

string

“app_popup”
BLE

string

“ble”
BLE_ITEM

string

“ble_item”
BUTTON

string

“button”
CAMERA_VISUALIZE

string

“camera_visualize”
CAROUSEL

string

“carousel”
CAROUSEL_ITEM

string

“carousel_item”
CUBE

string

“cube”
DROPDOWN_MENU

string

“dropdown_menu”
DYNAMIC_ARTICLE

string

“dymanic_article”
DYNAMIC_FORM

string

“dynamic_form”
FEED_ITEM_VIEW

string

“feed_item_view”
FEED_LIST

string

“feed_list”
GALLERY

string

“gallery”
GAME_GEMS

string

“game_gems”
RENDERKIT

string

“renderkit”
GLASS_SHELF

string

“glass_shelf”
GROUP

string

“group”
HAMBURGER_MENU

string

“hamburger_menu”
HTML_ARTICLE

string

“html_article”
IMAGE

string

“image”
IMAGE_ZOOMER

string

“image_zoomer”
LINEAR_BOX

string

“linear_box”
LINEAR_BOX_ITEM

string

“linear_box_item”
LOYALTY_PROGRAM

string

“loyalty_program”
MAP_VIEW

string

“map_view”
MODEL_STATIC_3D

string

“model_static_3d”
NEAR_TOUCH

string

“near_touch”
NEAR_TOUCH_ITEM

string

“near_touch_item”
NEAR_TOUCH_SUB_ITEM

string

“near_touch_sub_item”
NFC

string

“nfc”
NFC_ITEM

string

“nfc_item”
NINE_SLICER

string

“nine_slicer”
PAGE

string

“page”
PARTICLE

string

“particle”
PHOTO_DECAL

string

“photo_decal”
PRODUCT_LIST

string

“product_list”
QUIZ

string

“quiz”
RECTANGLE

string

“rectangle”
REFLOW_GROUP

string

“reflow_group”
SCROLL_PANEL

string

“scroll_panel”
TEXT

string

“text”
TEXT_ENTRY

string

“text_entry”
TILER

string

“tiler”
TOGGLE_BUTTON

string

“toggle_button”
TOOL_BAR

string

“tool_bar”
TOOL_BAR_ITEM

string

“tool_bar_item”
TOUCH_CODE

string

“touch_code”
TOUCH_CODE_ITEM

string

“touch_code_item
VIDEO

string

“video”
VOICE_COMMAND

string

“voice_command”
VOICE_COMMAND_ITEM

string

“voice_command_item”

EventString

Enum for built in event strings. This can be used with bindEvent. This is specifically availiable for developers using registerComponent and createComponent so the interaction can be handled in your JS code.
Properties:
Name Type Description
on_press

string

“on_press any component, passes nothing (fired when an object has a down followed by an up event in the same location)”
on_up

string

“on_up any component, passes x, y and touch index”
on_down

string

“on_down any component, passes x, y and touch index”
on_move

string

“on_move any component, passes x, y and touch index”
on_tick

string

“on_tick for RenderKit only, passes nothing”
on_anim_complete

string

“on_anim_complete for RenderKit aimations only when play has completed, passes the modelid”
on_show

string

“Occurs when a custom component is made visible by explicit action – set visibility or animate. Does not occur when a page is shown.”

Methods


addGlassShelfItem(glass_shelf, filename)

addGlassShelfItem this will programatically add another image to a glass shelf
Parameters:
Name Type Description
glass_shelf

object

an instance of a glass shelf component
filename

string

an image in the local project image folder

addMapMarker(map_view, address, zoom_to_marker, show_info)

addMapMarker adds a marker at address in the map_view control, and optionally zooms to the marker.
Parameters:
Name Type Description
map_view

object

an instance of a map_view control
address

string

an address to geocode and add to the map
zoom_to_marker

bool

whether to zoom to the marker or not (true zooms to marker, false does not)
show_info

bool

whether to show the address information

addMapMarkerLatLong(map_view, lat,long, title, desc, img, zoom_to_marker, show_info)

addMapMarkerLatLong adds a Map Marker at a specific lat/long.
Parameters:
Name Type Description
map_view

object

an instance of a map_view control
lat,long

real

latitude and longitude for the marker
title

string

Title of the marker
desc

string

Text for the information
img

string

Custom image for the pin
zoom_to_marker

bool

whether to zoom to the marker or not (true zooms to marker, false does not)
show_info

bool

whether to show the extra information

addMapMarkerWithInfo(map_view, address, title, desc, img, zoom_to_marker, show_info)

addMapMarkerWithInfo adds a Map Marker with custom information on the marker.
Parameters:
Name Type Description
map_view

object

an instance of a map_view control
address

string

address for the marker
title

string

Title of the marker
desc

string

Text for the information
img

string

Custom image for the pin
zoom_to_marker

bool

whether to zoom to the marker or not (true zooms to marker, false does not)
show_info

bool

whether to show the extra information

addMapRoute(map_view, start_address, end_address, zoom_to_marker, route_type, show_info)

addMapRoute adds a route between two routes in blue, and optionally zooms to the route.
Parameters:
Name Type Description
map_view

object

an instance of a map_view control
start_address

string

address to start the route
end_address

string

address to end the route
zoom_to_marker

bool

whether to zoom to the marker or not (true zooms to marker, false does not)
route_type

int

0:car, 1:walk, 2:cycling, 3:transit
show_info

bool

whether to show the address information

addMapRouteLatLong(map_view, start_latitude, start_longitude, end_latitude, end_longitude, route_type, line_color, line_weight)

addMapRouteLatLong adds a route between two lat longs and specify line colour and weight.
Parameters:
Name Type Description
map_view

object

an instance of a map_view control
start_latitude

string

address to start the route
start_longitude

string

address to start the route
end_latitude

string

address to end the route
end_longitude

string

address to end the route
route_type

int

0:car, 1:walk, 2:cycling, 3:transit
line_color

color

e.g. 0x0000FFFF (blue)
line_weight

string

0:harline, 1:normal, 2:bold, 3:thick.. etc

apeConnect(channel, connect_function, data_function, error_function)

Opens up an AJAX Push Engine. This is a type of http based real time communication which uses the Umajin server as the central hub. Once a named channel is opened many applications can use this to send and receive broadcast messages.
Parameters:
Name Type Description
channel

string

a unique name for the communication channel
connect_function

string

the name of a Javascript function to use as a callback upon successful connection. It takes no paramters.
data_function

string

the name of a Javascript function to use as a callback when data is received through the channel. It takes two string parameters; the first parameter is the channel that data was received from and the second parameter is the data packet.
error_function

string

the name of a Javascript function to use as a callback if a channel cannot be established. It takes no parameters.
Example
apeConnect("mychannel","ape_on_connect","ape_on_data","")
function ape_on_connect(){
   apeSend("demo");
}
function ape_on_data(pubid,data_in){
   callAction("show_popup",data_in);
}

apeSend(data)

apeSend sends data through an AJAX Push Engine session that has been esablished by apeConnect. See apeConnect for an example of how to use the AJAX Push Engine.
You are sending data to the channel established in the apeConnect function – you cannot send to another channel without reconnecting.
Parameters:
Name Type Description
data

string

the data packet to send through the AJAX Push Engine channel.

base64Decode(s)

base64Decode will decode a base64 string back into a full unicode/ASCII string.
Parameters:
Name Type Description
s

string

the string to decode
Returns:
– the decoded string

base64Encode(s)

base64Encode is useful for when string data must be sent in emails, and for some protocols with 7 bit limitations. Pass a string to this function and it will encode it into base 64.
Parameters:
Name Type Description
s

string

the string to encode
Returns:
– the base64 encoded string

bindEvent(obj, event, callback)

bindEvent allows one of the supported events of the obj component to be handled by a custom event handler callback.
EventString has a list of the events you can bind to and the parameters passed.
Parameters:
Name Type Description
obj

object

a component object. May also be “self” to refer to the current instance of a custom object.
event

string

the string corresponding to one of the supported events. May be one of the properties of the EventString object.
callback

string

the name of a Javascript function that will be be called to handle future instances of event. THe parameters passed to callback may vary based on the event being handled.
Example
bindEvent(self,"on_move","slider_on_move")
bindEvent(self,"on_up","slider_on_up")
bindEvent(self,"on_down","slider_on_down")

browseImage(success_function)

browseImage This function browses the device for a user image and copies it into the cache folder.
Parameters:
Name Type Description
success_function

string

the name of a Javascript function which takes a filepath parameter.
Example
registerAction("browseImg","","browseImg","")
	function browseImg(){
		browseImage('browseImgCallback');
	}

	function browseImgCallback(filename){
			print("fn> " + filename);
			getImageSize(filename,'browseImgDisplay')
			thumbnailImage(filename,"demo.jpg",0.9,0.5,0.5,100,120);
	}

	function browseImgDisplay(x,y){
		print('Image has a width = ' + x + ' height = ' + y)
	}

cacheDbClose(filename)

cacheDbClose closes the SQLite database at filename that was previously opened with cacheDbOpen.
Parameters:
Name Type Description
filename

string

the same filename previously passed to cacheDbOpen
Returns:
success – true for success

cacheDbExec(filename, sql)

cacheDbExec executes a query on a SQLite DB that has already been opened with cacheDbOpen, which is not expected to return a result set. For SELECT queries, use cacheDbSelect.
Parameters:
Name Type Description
filename

string

the same filename that has previously been passed to cacheDbOpen and uniquely identifies the DB
sql

string

a SQLite compatible query that is not expected to return a result set
Returns:
success – true for success
Example
registerAction("dbDemo","","dbDemo","")
function dbDemo(){
	var success = cacheDbOpen("mydb.db");
	// drop and create table
	cacheDbExec("mydb.db","DROP TABLE IF EXISTS Company;");
	cacheDbExec("mydb.db","CREATE TABLE Company(ID INT PRIMARY KEY NOT NULL,NAME TEXT, AGE INT, ADDRESS CHAR(50), SALARY REAL);");
	// insert data
	cacheDbExec("mydb.db","INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Sally', 32, 'California', 200000.00 );");
	cacheDbExec("mydb.db","INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Stan', 20, 'Sweden', 120000.00 );");
}

cacheDbOpen(filename)

cacheDbOpen opens a SQLite DB on the devices local storage. If the DB does not exist it will be created.
After a DB is openened, it may be accessed with cacheDbSelect and cacheDbExec.
When done with a DB, it should be closed with cacheDbClose – however Umajin does it’s best to clean this up for you if you forget.
This system uses the excellent SQlite database, find out more here https://www.sqlite.org/lang.html
Parameters:
Name Type Description
filename

string

this is the name of the db it will be stored in the local project cache folder and subfolders cannot be used
Returns:
success – false if the database with that filename cannot be created and true for success
Example
var success = cacheDbOpen("mydb.db");

cacheDbSelect(filename, sql)

cacheDbSelect executes a SELECT query on a SQLite DB that has already been opened with cacheDbOpen. The results of the query are returned as JSON with an example below. For queries not expected to return a result set, use cacheDbExec.
Parameters:
Name Type Description
filename

string

the same filename that has previously been passed to cacheDbOpen and uniquely identifies the DB
sql

string

a SQLite compatible SELECT statement
Returns:
rawJSON – a stringified json result set is returned.
Example
registerAction("dbDemo","","dbDemo","")
function dbDemo(){
	var success = cacheDbOpen("mydb.db");
	// drop and create table
	cacheDbExec("mydb.db","DROP TABLE IF EXISTS Company;");
	cacheDbExec("mydb.db","CREATE TABLE Company(ID INT PRIMARY KEY NOT NULL,NAME TEXT, AGE INT, ADDRESS CHAR(50), SALARY REAL);");
	// insert data
	cacheDbExec("mydb.db","INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Sally', 32, 'California', 200000.00 );");
	cacheDbExec("mydb.db","INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Stan', 20, 'Sweden', 120000.00 );");
	cacheDbExec("mydb.db","INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'Jeff', 42, 'Texas', 82000.00 );");
	cacheDbExec("mydb.db","INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Fred', 45, 'Norway', 110000.00 );");
	cacheDbExec("mydb.db","INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (5, 'Mary', 39, 'Texas', 90000.00 );");
	cacheDbExec("mydb.db","INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (6, 'Ellen', 30, 'Texas', 98000.00 );");
	// perform query
	var rawJSON = cacheDbSelect("mydb.db","SELECT * FROM Company WHERE ADDRESS = 'Texas' ORDER by AGE")
	print(rawJSON);
}
// The resulting stringified JSON 
// [{"ADDRESS":"Texas", "AGE":"30", "ID":"6", "NAME":"Ellen", "SALARY":"98000"}, 
// {"ADDRESS":"Texas", "AGE":"39", "ID":"5", "NAME":"Mary", "SALARY":"90000"}, 
// {"ADDRESS":"Texas", "AGE":"42", "ID":"3", "NAME":"Jeff", "SALARY":"82000"}]
//
// pass this directly to a feed or parse and use it as below
// myJSON = JSON.parse(rawJSON);
// print(myJSON[0].ADDRESS);

callAction(name)

callAction calls a Umajin action and optionally passes parameters to that action. Where a component is a parameter use the get_component_uuid function to retrieve the correct reference.
Parameters:
Name Type Description
name

string

the name of the action to call. The ActionStrings enum can return the string for a given action.

parameters

Between 0 and 12 parameters to pass to the action, types depend on the action being called. See ActionString for more details.
Examples
//webpage
callAction("show_webpage","http://www.umajin.com");
//show page by name
callAction("show_page_by_name","my_page_name",3);
//show popup
callAction("show_popup","my_message");
//play a sound
callAction("stop_all_sound");
callAction("play_sound","demo.mp3",0,1);
//set a feed item view custom index
//this needs an component converted to an ID
var view_id = getProperty(view_component,'unique_id')
callAction("set_feed_item", view_id, "0", "custom_index", i)

cameraCapture(return_function)

Takes a photo, using the native device user interface for camera on Android and iOS.
On the desktop a similar user interface is simulated using webcams.
Note: the returned image file will be outside the normal project image path.
To display it in an Image component, use the prefix ‘file://’ in front of the file path.
Parameters:
Name Type Description
return_function

string

a callback function that gets called when the photo has been taken. The callback function is passed a filename of the image, or a blank string if the user cancelled.
Example
cameraCapture('captureResult');  
function captureResult(filePath) {
	if (filePath=='') {
		callAction('show_popup','Photo Cancelled!');
	} else {
		callAction('show_popup', 'Photo taken: ' +  filePath);
	}
}	

cameraCodeScan(return_function, message, format)

cameraCodeScan allows the user to scan various code formats, including QR and bar codes, with the device camera
(including webcams on the desktop). The code is returned to a callback as a string.
If the scan is cancelled the callback is notified with a blank string.

  • Formats accepted are: QR Code, Barcode, Data Matrix, Aztec, and PDF417.
  • Barcode sub formats accepted are: UPC A, UPC E, EAN 13, EAN 8, Codabar, Code 39, Code 93, Code 128, ITF.
Parameters:
Name Type Description
return_function

string

is a function with a single string paramter that represents the data encoded by the QR code or bar code.
message

string

the message displayed on the scanning window.
format

int

defines the code format that will be scanned for: 1 = QR Code, 2 = Any format
Example
cameraCodeScan("found_code", "Scan your QR code!", 1);
function found_code(code){
   print("Here is our QR code " + code)
}

cancelAllDelayedCalls()

cancelAllDelayedCalls cancels all waiting delayCall calls.

cancelAllNotifications()

Cancels all notifications previously scheduled with notifyLater or notifyAtDateTime

cancelDelayedCalls(delayed_function)

cancelDelayedCalls cancels all waiting delayCall calls that are supposed to call delayed_function.
Parameters:
Name Type Description
delayed_function

string

the name of a Javascript function (that has previously been passed to delayCall)

cancelScheduledNotification(id)

Cancels a notification previously scheduled with notifyLater or notifyAtDateTime
Parameters:
Name Type Description
id

string

The id that was used to set the notification.

cDecode(s)

cDecode This decodes a c langauge string back into Unicode.
Parameters:
Name Type Description
s

string

the c string to decode
Returns:
– the decoded Unicode string

cEncode(s)

cEncode This encodes a unicode string into a c langauge string. As an example a newline is encoded \n
Parameters:
Name Type Description
s

string

the Unicode string to encode
Returns:
– the c encoded string

checkFormValidation(form)

checkFormValidation This function checks all the “submit enabled” fields on a form and returns true if they are all valid.
Note that if validation fails, the form’s On Validation Failed event does not fire; you need to fire that manually using componentEvent()
Parameters:
Name Type Description
form

component

the Form component to validate fields on
Returns:
– true if all fields are valid.
Type

bool


createComponent(obj, className, x1, y1, x2, y2)

createComponent creates an instance of the className ComponentString inside your custom component, positioned at x1% from the left, x2% from the right,
y1% from the top and y2% from the bottom. The width and height of the component is automatically calculated based on the points provided.
Parameters:
Name Type Description
obj

object

the custom component or sub component you have created under which the component will be created.
className

string

the string name of the component class to create. Can use the ComponentString to find the names
x1

number

the percent width to offset from the left edge of the parent component
y1

number

the percent height to offset from the top edge of the parent component
x2

number

the percent width to offset from the right edge of the parent component
y2

number

the percent width to offset from the bottom edge of the parent component
Returns:
– a reference to the newly created component (or 0 if there is an error)
Type

object

Example
//create a new RenderKit component during initialisation of the custom component
function my_init(width, height){
	var rk = createComponent(self, "RenderKit", 0, 0, 100, 100)
}

createEditableAction(obj, eventID, action)

createEditableAction creates an action and assigns it to the event. This is designed to be used to create wizards which can help with repetitive tasks in the editor.
Parameters:
Name Type Description
obj

object

the custom component or sub component you have created under which the component will be created.
eventID

string

the string name of the event to bind with
action

string

the action with brackets and parameters. For custom actions add s_ before the action name. e.g. s_myCustomAction(“do_something”);
Example
createEditableAction(img,'on_press','show_popup("Hello World")');

createEditableComponent(obj, className, x1, y1, x2, y2)

createEditableComponent creates an instance of the className ComponentString inside your specified page or component which is editable. This is designed to be used to create wizards which can help with repetitive tasks in the editor.
This is positioned at x1% from the left, x2% from the right, y1% from the top and y2% from the bottom.
Parameters:
Name Type Description
obj

object

the custom component or sub component you have created under which the component will be created.
className

string

the string name of the component class to create. Can use the ComponentString to find the names
x1

number

the percent width to offset from the left edge of the parent component
y1

number

the percent height to offset from the top edge of the parent component
x2

number

the percent width to offset from the right edge of the parent component
y2

number

the percent width to offset from the bottom edge of the parent component
Returns:
– a reference to the newly created component (or 0 if there is an error)
Type

object

Example
var img = createEditableComponent(mypage,"image",0,0,100,100);
setProperty(img,"filename","sun.png");

createEditablePage()

createEditablePage creates a new page which is editable. This is designed to be used to create wizards which can help with repetitive tasks in the editor.
Returns:
– a reference to the newly created page (or 0 if there is an error)
Type

object

Example
var page = createEditablePage();
var img = createEditableComponent(page,"image",0,0,100,100);
setProperty(img,"filename","sun.png");
createEditableAction(img,'on_press','show_popup("hello world")');

cropImage(local_filepath_in, local_filepath_out, quality_ratio, src_x, src_y, src_width, src_height, des_width, des_height)

cropImage is a function to resize and crop an image
Parameters:
Name Type Description
local_filepath_in

string

the path to the local input file
local_filepath_out

string

the path to the local output file
quality_ratio

number

Quality of compression of the new thumbnail (0-1)
src_x

number

the left in pixels of the source crop
src_y

number

the top in pixels of the source crop
src_width

number

the width in pixels of the source crop
src_height

number

the height in pixels of the source crop
des_width

number

the final crop width in pixels
des_height

number

the final crop height in pixels

decode(string, mode)

decode deodes the input string from the format specified by mode. Mode can be “xml”, “url, or “c”, and defines the decoding scheme to use.
Parameters:
Name Type Description
string

string

input string
mode

string

the decoding method to use
Returns:
– the decoded string

delayCall(delayed_function, delay)

delayCall calls the function whose name is delayed_function after delay milliseconds.
delayCall calls can be canceled by cancelDelayedCalls or cancelAllDelayedCalls.
Parameters:
Name Type Description
delayed_function

string

the name of a Javascript function, optionally you can include stringified brackets and parameters
delay

int

the number of milliseconds to wait before calling delayed_function
Example
delayCall("function_to_call",100);
delayCall("function_to_call(parameter_to_pass)",100);

deleteComponent(base_custom_component, component)

deleteComponent deletes a component
Parameters:
Name Type Description
base_custom_component

object

the base / parent component to delete the component from
component

object

the component to delete
Example
registerComponent("dotIndicator", "", "dotIndicator", "dotIndicator", "", "", "dotIndicator_refresh", "imagepicker:doton_filename:dot_indicator_on.png,imagepicker:dotoff_filename:dot_indicator_off.png,number:dot_perc:3:1:10", "")

function dotIndicator_refresh(){
	//lets setup 6 initial dots to give us a visual
	dotIndicator_update(self,0,6)
}

registerAction("dotIndicator_update", "", "Set Dot Indicator", "component:indicator:custom,string:index,string:size")
function dotIndicator_update(comp, index, size){	
	//get dot names
	var dtOn = getData(comp,"doton_filename");
	var dtOff = getData(comp,"dotoff_filename");
	var width_dot = Number(getData(comp,"dot_perc"));
	
	//check we have the correct custom type
	if(getType(comp)=="custom_dotIndicator"){
		var cnt = getComponentChildCount(comp);
		//add extra components
		if (cnt < size){	
			for(i=cnt ; i < size ; i++){
				var dot = createComponent(comp, "image", 0, 5, 5, 95)
			}
		}
		//delete extra components
		if (size < cnt){
			for(i=size ; i < cnt ; i++){
				var dot = getComponentChild(comp,size);
				if (dot) deleteComponent(comp, dot);
			}
		}
			
		//now position everything
		var width = width_dot * size
		var start = 50 - (width / 2.0)
		for(i=0; i < size; i++){
			var dot = getComponentChild(comp,i);
			positionComponent(dot, start, 0, start + width_dot, 100);	
			start += width_dot;
			
			if (index==i){
				setProperty(dot,"filename",dtOn);
			}else{
				setProperty(dot,"filename",dtOff);	
			}
		}
	}	
}	

deleteCookie(key)

deleteCookie deletes the value stored at key. Future calls to hasCookie(key) will be false until setCookie(key) is called again.
Cookies can be set with setCookie, checked for existence with hasCookie, and retrieved with getCookie.
Parameters:
Name Type Description
key

string

is the key to check for existence

disperseFormData(form, data)

disperseFormData This function loads a JSON set of new field values to a form, where form field names match keys in the JSON.
Parameters:
Name Type Description
form

component

the Form component to load field data into
data

string

the new field values where the key is the form field name.

encode(string, mode)

encode encodes the input string in the format specified by mode. Mode can be "xml", "url, "c", or "md5", and defines the encoding scheme to use.
Parameters:
Name Type Description
string

string

input string
mode

string

the encoding method to use
Returns:
- the encoded string

findComponent(pagename, componenttype, componentname)

findComponent returns the first component object with the display name componentname that is of type componenttype that is on page pagename,
or '' or 0 if no such component is found.
Parameters:
Name Type Description
pagename

string

is the display name of a page in the app
componenttype

string

is the type of the component to return. Can be one of the elements of ComponentString.
componentname

string

is the name of the component to return
Returns:
- the matching component object or '' or 0 if no such component can be found
Type

object


findComponentInForeground(foreground_name, component_type, component_name)

findComponentInForeground This finds a component based on it's type and name on the specified foreground.
This is very useful for getting access to toolbars and menus that are on the foreground layer that you want to modify.
Parameters:
Name Type Description
foreground_name

string

the name of the foreground to search
component_type

string

the name of the type of component componentString
component_name

string

the name of the component
Returns:
object - either 0 or the specific component

findPage(pagename)

findPage returns the page object with the name pagename. If no such page exists, 0 or '' is returned.
Parameters:
Name Type Description
pagename

string

the display name of the page object to return
Returns:
- the specified page object or 0 or '' if no such page is found
Type

object


gatherFormData(form)

gatherFormData This function collects all the "submit enabled" fields from a form and returns them as a JSON string; keys are the Form Field Names.
Parameters:
Name Type Description
form

component

the Form component to collect data from
Returns:
- the JSON containing the Form Field names and values.
Type

string


getBluetoothCharacteristic(serviceId, characteristicId, callback)

getBluetoothCharacteristic This will retrieve a characteristic from a bluetooth device. This is the equivalent of setting a characteristic which can be done with callAction like so callAction('set_ble_charcteristic', SERVICES.nfc.uuid, SERVICES.nfc.chars.read, 'on');
Note : BLE devices have UUID's stored as hex values in this format uuid: '0DEF1000-6656-11E5-A4E0-23D9BD6569A7'
Parameters:
Name Type Description
serviceId

string

the uuid of the BLE parent service e.g. accelerometer.uuid: '0DEF5000-6656-11E5-A4E0-23D9BD6569A7'
characteristicId

string

The characteristic to query e.g. accelerometer.chars.acceleration: '0DEF5003-6656-11E5-A4E0-23D9BD6569A7'
callback

string

the function to call which takes a value string
Example
function init(){
	callAction('set_btle_frequency', 0);
	callAction('enable_bluetooth');
}

function getMovements(){
	getBluetoothCharacteristic(SERVICES.accelerometer.uuid, SERVICES.accelerometer.chars.acceleration, 'getMovementsCallback');
}

function getMovementsCallback(value) {
	if (!isCurrentPage(accelerometerPage)) return;	
	try {
		var jsonString = '[' + value.split('}{').join('},{') + ']';
		var values = JSON.parse(jsonString);
		
		if (values[0].hasOwnProperty('x') && values[0].hasOwnProperty('y') && values[0].hasOwnProperty('z')) {
			setProperty(accelerometerTextfields.x, 'text', parseFloat(values[0].x).toFixed(2));
			setProperty(accelerometerTextfields.y, 'text', parseFloat(values[0].y).toFixed(2));
			setProperty(accelerometerTextfields.z, 'text', parseFloat(values[0].z).toFixed(2));
		} else {
			print('getMovementsCallback: no x, y, z found on "values"');
		}
	} catch(err) {
		print('Error (getMovementsCallback): ' + err);
	}

	delayCall('getMovements', movementsInterval);
}

getComponentChild(obj, index)

getComponentChild returns the component that is the index-th child of the container obj, or 0 if obj is not a container or there is no child component at that index.
Parameters:
Name Type Description
obj

object

a container component
index

int

the index of the child object to return
Returns:
- the child component of container obj at the specified index, or 0 if obj is not a container or there is no component at that index
Type

object


getComponentChildCount(obj)

getComponentChildCount returns the number of child components that have been placed inside of the container obj.
If a non-container is passed, the result will be 0.
Parameters:
Name Type Description
obj

object

a component
Returns:
- the number of child components of the container component obj, or 0 if obj is not a container
Type

int


getComponentParent(obj)

getComponentParent returns the container object that is the parent of the component obj. This will not return a parent beyond the component you are inspecting.
Parameters:
Name Type Description
obj

object

a component object
Returns:
- the parent container component of obj
Type

object


getCookie(key)

getCookie returns the value of the persistent cookie that was stored at key.
Cookies can be set with setCookie, tested for existence with hasCookie, and deleted with deleteCookie.
Parameters:
Name Type Description
key

string

is the key whose value to return
Returns:
- the value stored at key
Type

string


getData(object, key)

getData returns the value that the data-bound component object has stored at key (using setData)
Parameters:
Name Type Description
object

object

a component object. "self" may be used to reference the current instance of a custom component.
key

string

the key to fetch data from.
Returns:
- the string value stored at key
Type

object


getFeed(id, ttl, success_function, error_function)

getFeed asynchronously returns the contents of the feed with given ID to success_function. Calls error_function if an error is encountered.
Parameters:
Name Type Description
id

string

the id of the feed to retrieve
ttl

int

the number of ms to wait before timing out
success_function

string

the name of a Javascript function to call after the feed contents is downloaded.
This passes the url requested and the filename of the downloaded feed file within the cache. Use getGlobal( 'cache_path' ) to find the cache path.
error_function

string

the name of a Javascript function to call if there is an error encountered during the download. This passes the url requested that was not able to be downloaded.

getFile(url, ttl, success_function, error_function)

getFile asynchronously returns the contents of the file at url to success_function. Calls error_function if an error is encountered.
Parameters:
Name Type Description
url

string

the URL of the file to retrieve
ttl

int

the number of ms to wait before timing out
success_function

string

the name of a Javascript function to call after the file is downloaded.
This passes the url requested and the filename of the downloaded file within the cache. Use getGlobal( 'cache_path' ) to find the cache path.
error_function

string

the name of a Javascript function to call if there is an error encountered during the download. This passes the url requested that was not able to be downloaded.

getFilesInFolder(path)

getFilesInFolder Returns a pipe delimited string of filenames that exist in a given folder.
Parameters:
Name Type Description
path

string

the path in the project folder to enumerate
Returns:
files - string containing the files with a pipe character between
Type

string

Example
var fileString = getFilesInFolder('images/');
var fileList = fileString.split("|");

getForeground(page_name)

getForeground This returns the current foreground associated with with the requested page.
Note : a page can only have one current foreground object (e.g. toolbar, menu etc).
Parameters:
Name Type Description
page_name

string

the name of the page to find the foreground
Returns:
foreground_name - The name of the foreground, will be '' if no foreground was applied to the requested page

getGlobal(property)

getGlobal returns the value of a global property with the given name (these are not the same as global variables)
Parameters:
Name Type Description
property

string

the name of the property to get.
Properties:
Name Type Description
uptime

string

time the app has been running in ms
tz_offset

string

time zone offset from utc in ms
utc

string

utc time in ms
os

string

string has the operating system name
compiled

string

clipboard

string

contents of clipboard
latitude

string

longitude

string

country_code

string

2 character iso country code eg US, NZ
country_name

string

country_latitude

string

country_longitude

string

country_location

string

language

string

deviceid

string

unique guid for that app on that particular device, changes if app is reinstalled
project_token

string

unique token for the app
project_id

string

unique id for the app (integer)
spinner_filename

string

image to show and spin
spinner_speed

string

tenths of a rotation per second, i.e. 5 = 180 deg/sec
width

string

page width pixels
height

string

page width pixels
http_spinner

string

Will the spinner show for JS http requests, true or false
http_blocker_alpha

string

(transparent 0-255 opaque)
current_page

string

current page name
apeid

string

your pubid on the ape channel
version

string

version of the editor / viewer
cache_path

string

fullpath to the cache folder
temp_path

string

fullpath to the temp folder
project_path

string

full path to the project folder
project_name

string

project_version

string

from the version.txt in the project folder eg 1.0.102
play_mode

string

a flag which is normall 1 but is 0 in edit mode
dpi

string

dots per inch of the devices screen
destination_page_name

string

set during a page transition
Returns:
- the value of the property.
Type

object


getGlobalVar(key)

getGlobalVar gets a key from the global data bound space.
Parameters:
Name Type Description
key

string

is the key to read from

getGps(update_function, error_function, accuracy_metres, interval_ms)

pollGps will request GPS locations to be sent back regularly
Note: currently only one callback can be used at once
Parameters:
Name Type Description
update_function

string

the function that is called with three parameters, latitude, longitude and accuracy
error_function

string

the function to receive an error message
accuracy_metres

real

the desired accuracy in metres, or -1 for any
interval_ms

int

the time between regular updates, or -1 if they should only be sent when the location changes

getGps(update_function, error_function, accuracy_metres, timeout_ms)

getGps will request a single GPS location to be returned
Note: currently only one callback can be used at once
Parameters:
Name Type Description
update_function

string

the function that is called with three parameters, latitude, longitude and accuracy
error_function

string

the function to receive an error message
accuracy_metres

real

the desired accuracy in metres, or -1 for any
timeout_ms

int

the maximum time in milliseconds to wait for the location with sufficient accuracy

getImageSize(local_filepath, success_function)

getImageSize This function calls back with the native width and height of an image.
Parameters:
Name Type Description
local_filepath

string

the path to the local file
success_function

string

the name of a Javascript function which takes a width and height parameter in pixels.

getName(component)

getName gets the display name of the specified component.
Parameters:
Name Type Description
component

object

The component you want to know the name of.
Returns:
- the name of the component.
Type

string


getPage(index)

getPage returns you the page by index number from the application.
Parameters:
Name Type Description
index

number

the page index number
Example
registerAction("printPageNames","","printPageNames","")
function printPageNames(){
	for(i=0;i " + getName(page)); 
	}
}

getPageCount()

getPageCount returns you the number of pages in the application.
Example
registerAction("printPageNames","","printPageNames","")
function printPageNames(){
	for(i=0;i " + getName(page)); 
	}
}

getProperty(object, property)

getProperty gets the value of a component's property.
To set the value of a property, use setProperty, setPropertyIn, or setPropertyInTween.
Parameters:
Name Type Description
object

object

the Component object whose property you want to get the current value of
property

string

the name of the property to get the current value of
Properties:
Name Type Description
width

string

any component
height

string

any component
native_width

string

text, html_article, image
native_height

string

text, html_article, image
x

string

any component
y

string

any component
visible

string

any component
lock_left

string

any component
lock_width

string

any component
lock_right

string

any component
lock_top

string

any component
lock_height

string

any component
lock_bottom

string

any component
instance_display_name

string

any component
unique_id

string

any component
text

string

text, text entry, html article
font_color

string

text, button
json

string

custom component
scroll_offset

string

any feed list or scroll panel
scroll_max

string

feed list
filename

string

image, video, animation
instance_display_name

string

any component
Returns:
- the value of the property.
Type

object


getTextStyleList()

getTextStyleList returns a pipe | delimited list of style names for the current project
Returns:
styleList - The styles
Type

string


getType(component)

getType gets the type of the specified component.
Parameters:
Name Type Description
component

object

The component you want to know the type of.
Returns:
- the type of the component.
Type

string


hasCookie(key)

hasCookie checks if a persistent cookie has been set for key.
Cookies can be set with setCookie, retrieved with getCookie, and deleted with deleteCookie.
Parameters:
Name Type Description
key

string

is the key to check for existence
Returns:
- true if a cookie has been set for key and false if it has not
Type

bool


hideSpinner()

Hides the standard project spinner

hmacSha1(key, secret)

hmacSha1 is a keyed-hash message authentication code (HMAC) this should be used instead of MD5 as it is much more secure.
This is a useful cryptographic function for implementing many secure token exchange protocols.
Parameters:
Name Type Description
key

string

any string
secret

string

any string
Returns:
- the HMAC string

httpDeleteHeaders(url, headers, success_function, error_function, cookieJar)

httpDeleteHeaders issues an asynchronous DELETE request to URL with the header data in headers. Upon success or failure, the appropriate callback is called.
Parameters:
Name Type Description
url

string

the full URL to DELETE
headers

string

the custom headers to include with the DELETE requests
success_function

string

the name of a Javascript function to call if the DELETE is successful
error_function

string

the name of a Javascript function to call if the DELETE is unsuccessful. The error message is passed.
cookieJar

string

Optional, String is in Netscape Cookie file format, same as that returned as success_function parameter

httpGet(url, success_function, errror_function)

Makes an asynchronous HTTP GET request to a specified URL. Upon success or failure, the appropriate is callback is called.
Parameters:
Name Type Description
url

string

the full URL to GET; may include a querystring
success_function

string

the name of a Javascript function that will be called upon a 200 response from the HTTP server. The function will be passed a single string parameter with the full text of the page retrieved.
errror_function

string

the name of a Javascript function that will be called if a 200 response is not received. The function will be passed the error message.
Example
httpGet("http://test.com", "cur_success", "cur_failure");
function cur_success(returnvalue, responseHeaders, cookieJar){
}
function cur_failure(errormessage, httpStatusCode, responseBody, responseHeaders, cookieJar) {
}

httpGetHeaders(url, headers, success_function, errror_function, cookieJar)

Make an asynchronous HTTP GET request to a specified URL, and pass a custom HTTP header. Upon success or failure, the appropriate is callback is called.
Note: to persist http cookies between requests you must store the cookieJar and pass it into the next request
Note: reponseHeaders are JSON formatted, if there were redirects in the request then multiple header groups will be present, "code" is used for response code eg [{"code": "HTTP/1.1 302", "content-length": "0", ... }]
Parameters:
Name Type Description
url

string

the full URL to GET; may include a querystring
headers

string

the string headers to pass with the HTTP GET request
success_function

string

the name of a Javascript function that will be called upon a 200 response from the HTTP server. The function will be passed a single string parameter with the full text of the page retrieved.
errror_function

string

the name of a Javascript function that will be called if a 200 response is not received. The function will be passed the error message.
cookieJar

string

Optional, String is in Netscape Cookie file format, same as that returned as success_function parameter
Examples
httpGetHeaders("http://test.com", "[possible header to pass]", "cur_success", "cur_failure", cookieJar);
function cur_success(returnvalue, responseHeaders, cookieJar){
}
function cur_failure(errormessage, httpStatusCode, responseBody, responseHeaders, cookieJar) {
}
registerAction("NewYorkWeather", "", "New York Weather", "component:output:text,component:wimage:image")
 
var g_output = 0; 
var g_wimage = 0;

function NewYorkWeather(output, wimage){
	g_output = output;
	g_wimage = wimage;
	
	//Weather data from Weather underground!!
	httpGet("http://api.umajin.com/1.2/get-weather.php?view=current&location=zmw:10001.5.99999", "cur_success", "cur_fail");
}
 
function cur_success(returnvalue, responseHeaders, cookieJar){
	//return data is a JSON string so read it in
	var result = JSON.parse(returnvalue);
	var headerObj = JSON.parse(responseHeaders);
	setProperty(g_output, "text", result[0].city + "\n" + result[0].temp_c + "degrees C \n" + result[0].conditions);
	setProperty(g_wimage, "filename", "weather/" + result[0].icon_name);
}
 
function cur_fail(message, httpStatusCode, responseBody, responseHeaders, cookieJar){
	setProperty(g_output, "text", "Error : " + message);
}

httpPost(url, data, success_function, errror_function)

Makes an asynchronous HTTP POST request to a specified URL and POSTs data with the request. Upon success or failure, the appropriate is callback is called.
Parameters:
Name Type Description
url

string

the full URL to GET
data

string

the data to post to the specified URL. For simple requests, this is the same as the GET querystring without the leading "?"
success_function

string

the name of a Javascript function that will be called upon a 200 response from the HTTP server. The function will be passed a single string parameter with the full text of the page retrieved.
errror_function

string

the name of a Javascript function that will be called if a 200 response is not received. The function will be passed the error message.
Example
httpPost("http://test.com/form.php", "username=name&password=pass", "cur_success", "cur_failure");
function cur_success(returnvalue, responseHeaders, cookieJar){
}
function cur_failure(errormessage, httpStatusCode, responseBody, responseHeaders, cookieJar) {
}

httpPostHeaders(url, data, headers, success_function, errror_function, cookieJar)

Makes an asynchronous HTTP POST request with a custom header to a specified URL, and POSTs data with the request. Upon success or failure, the appropriate is callback is called.
Parameters:
Name Type Description
url

string

the full URL to GET
data

string

the data to post to the specified URL. For simple requests, this is the same as the GET querystring without the leading "?"
headers

string

the string headers to pass with the HTTP POST request
success_function

string

the name of a Javascript function that will be called upon a 200 response from the HTTP server. The function will be passed a single string parameter with the full text of the page retrieved.
errror_function

string

the name of a Javascript function that will be called if a 200 response is not received. The function will be passed the error message.
cookieJar

string

Optional, String is in Netscape Cookie file format, same as that returned as success_function parameter
Example
httpPostHeaders("http://test.com/form.php", "username=name&password=pass", "server=3&size=2", "cur_success", "cur_failure", cookieJar);
function cur_success(returnvalue, responseHeaders, cookieJar){
}
function cur_failure(errormessage, httpStatusCode, responseBody, responseHeaders, cookieJar) {
}

httpPutHeaders(url, data, headers, success_function, error_function, cookieJar)

httpPutHeaders issues an asynchronous PUT request to URL with the header data in headers and the data to PUT in data. Upon success or failure, the appropriate callback is called.
Parameters:
Name Type Description
url

string

the full URL to PUT to
data

string

the data to PUT
headers

string

the custom headers to include with the PUT requests
success_function

string

the name of a Javascript function to call if the PUT is successful
error_function

string

the name of a Javascript function to call if the PUT is unsuccessful. The error message is passed.
cookieJar

string

Optional, String is in Netscape Cookie file format, same as that returned as success_function parameter

httpS3Upload(bucket, s3_file_path, local_filepath, s3_key, s3_secret, success_function, error_function)

httpS3upload asynchronously uploads the file at local_filepath to s3_file_path within the provided S3 bucket. If successful, calls success_function, otherwise, calls error_function.
Parameters:
Name Type Description
bucket

string

the S3 bucket to upload the file to
s3_file_path

string

the full path within the bucket to upload the file to (including the file name)
local_filepath

string

the path to the local file
s3_key

string

the Amazon S3 key for the account containing bucket
s3_secret

string

the Amazon S3 secret part associated wtih s3_key
success_function

string

the name of a Javascript function that will be called if the upload is successful.
error_function

string

the name of a Javascript function that will be called if the upload is unsuccessful. Error message will be passed.

md5(input)

md5 returns the md5 hash for a string.
Parameters:
Name Type Description
input

string

any string
Returns:
- the md5 hash of the input string

notifyAtDateTime(title, body, id, dateTime)

Sets a notification to occur at the specified date-time.
Parameters:
Name Type Description
title

string

The title of the notification to be shown to the user
body

string

The body text of the notification to be shown to the user
id

string

An identifier for the notification;
will be given to the app when the notification is acted on by the user, and can be used to cancel the notification
dateTime

int64

The date-time to fire the notification, as a UTC time_t (seconds since 1970)
This can be calculated with date.getTime() / 1000 + date.getTimezoneOffset() * 60

notifyLater(title, body, id, offsetSeconds)

Sets a notification to occur at the specified number of seconds in the future
Parameters:
Name Type Description
title

string

The title of the notification to be shown to the user
body

string

The body text of the notification to be shown to the user
id

string

An identifier for the notification;
will be given to the app when the notification is acted on by the user, and can be used to cancel the notification
offsetSeconds

string

How far into the future the notification should be

positionComponent(obj, x1, y1, x2, y2)

positionComponent respositions the component obj relative to its parent container. It will be positioned at x1,y1 top left and x2,y2 bottom right.
The width and height of the component is automatically calculated based on the points provided.
Parameters:
Name Type Description
obj

object

the component to reposition
x1

number

the percent from the left of the container to the left of the component
y1

number

the percent from the top of the container to the top of the component
x2

number

the percent from the left of the container to the right of the component
y2

number

the percent from the top of the container to the bottom of the component
Example
// fill the whole container
positionComponent(self,0,0,100,100);
// be 10% from the edges of the container
positionComponent(self,10,10,90,90);

positionComponentControl(obj, left, left_mm, top, top_mm, width, width_mm, height, height_mm, right, right_mm, bottom, bottom_mm)

positionComponentControl respositions the component obj relative to its parent container. It will be positioned using all of the detailed properties which can be set including locking optionally as a percentage or in mm.
It is possible to specify invalid amounts so the results will be normalised.
Parameters:
Name Type Description
obj

object

the component to reposition
left

number

left margin
left_mm

bool

percentage if false, mm if true
top

number

top margin
top_mm

bool

percentage if false, mm if true
width

number

width margin
width_mm

bool

percentage if false, mm if true
height

number

height margin
height_mm

bool

percentage if false, mm if true
right

number

right margin
right_mm

bool

percentage if false, mm if true
bottom

number

bottom margin
bottom_mm

bool

percentage if false, mm if true

positionHorizontal(left_lock, left_size, width_lock, width_size, right_lock, right_size)

positionHorizontal allows you to set any of the horizontal positioning properties on a component. The lock properties can be 0=% 1=mm. The size is the value as a % or mm as appropriate.
Parameters:
Name Type Description
left_lock

real

left_size

real

width_lock

real

width_size

real

right_lock

real

right_size

real


positionVertical(top_lock, top_size, height_lock, height_size, bottom_lock, bottom_size)

positionVertical allows you to set any of the vertical positioning properties on a component. The lock properties can be 0=% 1=mm. The size is the value as a % or mm as appropriate.
Parameters:
Name Type Description
top_lock

real

top_size

real

height_lock

real

height_size

real

bottom_lock

real

bottom_size

real


print(str)

print prints str to the output console. print is useful for debugging.
Parameters:
Name Type Description
str

string

the string to output to the console

raiseEvent(component, eventid, mydata)

raiseEvent fires the specified string eventid of the custom component, and passes mydata as parameters of the event handler.
Nothing will occur unless the eventid matches one of the registered events when the custom component was registered.
You can marshall any values to be exposed to the user of this action by adding them as named values in the stringified JSON packet in the style of {"value":3, "color":"red"}. These will be available to users as [value] and [color] in any actions they apply to this event.
Parameters:
Name Type Description
component

object

an instance of a component object. "self" refers to the current instance of a custom component from within that component's code.
eventid

string

the string that identifies the event. May use a property of EventString or a custom eventid.
mydata

string

a JSON formatted object, with properties that correspond to the parameters that the event handler for eventid are expected to receive
Example
// this passes the value varaible to the Action that handles the on_press event
raiseEvent(self, 'on_press','{"value":' + value + '}');

readTextfile(filename)

readTextfile reads in a text file. Specify the project subfolder and file you would like to read from, e.g. "images/myfile.json"
Parameters:
Name Type Description
filename

string

the combined path and name of the text filename to read - relative to the project folder (or a fully specified path to the temp or cache folders)
Returns:
string - The text in the file.
Examples
// load a string from the project files using a relative path 
	var local_text = readTextfile("images/demo.txt")
	print("local_text = " + local_text)
// load a string from cache using absolute path 
	var cache_text = readTextfile(getGlobal("cache_path") + "/244EDAE546E9A64427371792E3EA3100.json")
	print("cache_text = " + cache_text)

refreshFeed(title)

refreshFeed Tells the Umajin editor that the feed with the given title should be refreshed; typically because your code knows it has changed.
All the components that are referencing the feed will update their contents.
Parameters:
Name Type Description
title

string

the name of the feed used in registerFeed

registerAction(name, icon, title, params)

registerAction registers a new Action with Umajin. It is required that register or registerAction
be called to make a custom action accessible from within the Umajin editor.
Parameters:
Name Type Description
name

string

the Javascript function to call with the parameters defined by params. Must adhere to Javascript naming conventions.
icon

string

this will be the path to a custom icon in a future release
title

string

the friendly name of the Action within the editor. This is what gets presented to the user within the editor.
params

string

a string that defines the parameters that get passed to the name function. Currently five types of parameters are supported: bool (checkbox), string (textbox), int (range-bound integer slider), real (range-bound floating point slider), and component (can reference any component accessible within the Umajin editor). The parameters are built up as a comma separated string. Each of the types of parameters above need different information which are separated by colons. Parts in square brackets can be omitted.

  • bool:label[:default_value] – the label describes the parameter for the user. Examples: “bool:Expand” or “bool:With particles:yes”. default_value can be: true, false, on, off, yes, no
  • string:label[:default_value] – the label describes the parameter for the user
  • int:label[:default_value]:min:max – after the label, the default, min and max numeric values
  • real:label[:default_value]:min:max – after the label, the default, min and max real values
  • component:label:type – after the label the (optional) type of the component. All component types (including custom) are supported.
Example
registerAction('down', 'down', 'down', 'component:pic:image,component:result:text');

registerComponent(name, icon, title, description, callback_init, callback_resize, callback_refresh, property_list, event_list, help_url, x1, y1, x2, y2, callback_reset)

registerComponent registers a new developer-defined Component with Umajin. It is required that registerComponent
be called to make a custom component defined in a Javascript file accessible from within the Umajin editor.
Components can be added to projects using the visual editor, and expose properties that can be set without coding.
Components are required to handle init, resize, and refresh events, but may also fire custom events that can be attached
to actions within the editor.
Parameters:
Name Type Description
name

string

a unique name for the component which should not have spaces or special characters
icon

string

the relative path to the icon file from the root of the project folder. Forward slashes are used (even on windows systems).
title

string

this is the human readable version of the name
description

string

a text description of the component that gets displayed in the right panel of the umajin editor when the user highlights a component to add to the project.
callback_init

string

the name of a Javascript function that gets called when the component is first initialized. The function gets called with two parameters (width, height). Width is the width of the component in local coordinate space. Height is the height of the component in local coordinate space.
callback_resize

string

the name of a Javascript funciton that gets called when the component is resized by the user in the editor, or triggered at runtime. The function gets called with two parameters (width, height). Width is the width of the component in local coordinate space. Height is the height of the component in local coordinate space.
callback_refresh

string

the name of a Javascript function that gets called when the component is refreshed by changing a property in the property panel. The function gets called with two parameters (width, height). Width is the width of the component in local coordinate space. Height is the height of the component in local coordinate space.
property_list

string

this is a list of comma seperated properties. The types of properties are

  • bool:title[:default_value]
  • string:title[:default_value]
  • imagepicker:filename:default
  • animationpicker:filename:default
  • videopicker:filename:default
  • color:name:0x3345543
  • real:title[:default_value]:min_value:max_value
  • int:title[:default_value]:min_value:max_value
  • enum:title:default:v0|v1|v2|v3|v4
  • combo:title:default:v0|v1|v2|v3|v4
  • enum_callback:title:default:jsFunctionCallback
  • combo_callback:title:default:jsFunctionCallback
  • section:title - creates a section header within the properties. Following properties will go under this section.
  • beginstyle:title - creates a style section. After this, provide properties for the elements of the style as follows:
    • basestyle:property name:default e.g. default
    • alignment:property name:default 0=left, 1=center, 2=right, 3=full [Optional]
    • color:property name:default e.g. 0xFFFFFFFF
    • size:property name:default e.g. 12
    • font:property name:default e.g. vera.ttf
    • tracking:property name:default e.g. 1.0

    All properties must be provided, except alignment which is optional. The base style property must be provided, but your component code doesn't need to do anything with it.
    Unlike other properties, the property names are internal only; the titles displayed in the editor are fixed.
    The properties should be applied e.g. to a text component's font_size, font_color, font_filename, font_align and tracking properties.

  • Although defaults are optional, to make a useful intial style requires default values for all the properties.

  • endstyle:title - Marks the end of the style section.
event_list

string

a comma separated list of event names that get called when the matching raiseEvent is fired from within the component's code. The event_list names must match the names of the events that are fired. Umajin editor users can then attach Actions to these events from within the editor.
help_url

string

optional - A web URL pointing at a help page
x1

number

optional - the percent from the left of the container to the left of the component
y1

number

optional - the percent from the top of the container to the top of the component
x2

number

optional - the percent from the left of the container to the right of the component
y2

number

optional - the percent from the top of the container to the bottom of the component
callback_reset

string

the name of a Javascript function that gets called when the component is reset. This occurs after playing and stopping a project.
Examples
registerComponent("slider", "icons/cog2.png", "Slider", "Slider control", "slider_init", "", "slider_refresh", "imagepicker:filename,number:steps:0,number:min:0,number:max:100", "on_slide")
// register a component with a frequency slider which will contain a RenderKit
// on the RenderKit we will make an animating Sin curve
registerComponent("rk_shape", "", "rk_shape", "rk Shape", "rk_shape_init", "rk_shape_resize", "rk_shape_refresh", "real:frequency:1:1:5", "")

function rk_shape_init(width, height){
	// create a RenderKit
	var rk = createComponent(self, "RenderKit", 0, 0, 100, 100)
	// create a shape
	var id = RenderKitShapeCreate(rk, "");
	setData(rk,"shape_id",id);
	// register for the per frame tick event
	bindEvent(rk,"on_tick","rk_shape_on_tick");
}
var cnt = 0;
function rk_shape_on_tick(){
	rk_shape_draw(self);
	//increment the offset into the Sin curve
	cnt += 0.1;
}

function rk_shape_resize(width, height){
	// get the RenderKit from the parent and draw
	var rk = getComponentChild(self,0);
	rk_shape_draw(rk);
}

function rk_shape_refresh(width, height){
	//set the frequency value into the internal RenderKit and draw
	var frequency = getData(self, "frequency");
	var rk = getComponentChild(self,0);
	setData(rk, "frequency", frequency);
	rk_shape_draw(rk);
}

function rk_shape_draw(rk){
	// check size of RenderKit in local units
	var width = getProperty(rk, "width");
	var height2 = getProperty(rk, "height") / 2.0;
	var frequency = getData(rk, "frequency");
	var id = getData(rk,"shape_id");
	
	// clear the shape
	RenderKitShapeClear(rk,id);
	
	//setup the start of the curve
	var y = height2 + Math.sin(cnt + ((a * 0.0628) * frequency)) * height2;
	RenderKitShapeDoMove(rk,id,y,100);
	
	// draw the lines of a sin curve
	for (var a = 0; a < 101; a++){
		var y = height2 + Math.sin(cnt + ((a * 0.0628) * frequency)) * height2;
		RenderKitShapeDoLine(rk,id,a * width / 100.0, y);
	}
}

registerEventHandler(event, name)

registerEventHandler lets you lodge a javascript function against a number of global events including on_activate, on_deactivate, on_resume, on_suspend, on_resize and on_push_notification.
Events include devicemotion(x,y,z), on_resize(), on_deactivate(), on_activate(), on_suspend(), on_resume(), on_push_notification(message), on_edit_mode(), on_alarm(message, background)
Parameters:
Name Type Description
event

string

the name of one of the supported events that can be handled
name

string

the name of a Javascript function that will be called when the event is fired. Supported events may pass parameters to the handler function.
Examples
registerEventHandler('on_activate', 'onActivate');
function onActivate() {
print('onActivate');
}
registerEventHandler('on_deactivate', 'onDeactivate');
function onDeactivate() {
print('onDeactivate');
}
registerEventHandler('on_push_notification', 'onPushNotification');
function onPushNotification(message) {
print('onPushNotification: ' + message);
}

registerFeed(callback, title, params)

registerFeed registers a programatic data feed in the Umajin editor. This code can make any network or database calls and generate the json as you see fit.
Parameters:
Name Type Description
callback

string

a callback function that gets called when data is required. The callback function is passed a component object that represents the feed list to set. You use the setCustomFeed to apply your data.
title

string

the friendly name of the feed that gets displayed in the Umajin editor
params

string

just like parameters in the action these will be available to your feed code, for example a user may be required to enter a username or token for a web call.
Examples
// An example with no parameters
registerFeed('demoFeed', 'demoFeed', '');
function demoFeed(component) {
	  setCustomFeed(component, '[{"message":"Adam"},{"message":"Michael"},{"message":"Jenny"},{"message":"Ally"}]');
}
// An example which needs an address and optional order by key
// The parameters should be entered into the 'Custom Feed Parameters' property of your component
// and do not require speech marks or escape characters
// e.g. Texas,AGE 
// generates [{"ADDRESS":"Texas", "AGE":"30", "ID":"6", "NAME":"Ellen", "SALARY":"98000"}, {"ADDRESS":"Texas", "AGE":"39", "ID":"5", "NAME":"Mary", "SALARY":"90000"}, {"ADDRESS":"Texas", "AGE":"42", "ID":"3", "NAME":"Jeff", "SALARY":"82000"}]
registerFeed('demoFeed2', 'demoFeed2', 'string:address,string:sortkey');
function demoFeed2(component, address, sortkey) {
	cacheDbOpen("mydb.db");
	var mysql = "SELECT * FROM Company WHERE ADDRESS = '" + address + "'";
	if (sortkey.length){
		mysql += " ORDER by " + sortkey;
	}
	var rawJSON = cacheDbSelect("mydb.db",mysql)
	setCustomFeed(component, rawJSON);
	cacheDbClose("mydb.db");
}

removeGlassShelfItem(glass_shelf, index)

removeGlassShelfItem this will programatically remove and item from a glass shelf
Parameters:
Name Type Description
glass_shelf

object

an instance of a glass shelf component
index

int

an item to remove from the glass shelf

removeMapMarkerAddress(map_view, address, title)

removeMapMarkerAddress removes a Map Marker from a specific address.
Parameters:
Name Type Description
map_view

object

an instance of a map_view control
address

string

address for the marker
title

string

title of the marker

removeMapMarkerLatLong(map_view, lat,long, title)

removeMapMarkerLatLong removes a Map Marker from a specific lat/long.
Parameters:
Name Type Description
map_view

object

an instance of a map_view control
lat,long

real

latitude and longitude for the marker
title

string

title of the marker

removeMapRoute(map_view)

removeMapRoute removes the current route from the map.
Parameters:
Name Type Description
map_view

object

an instance of a map_view control

resetScrollPanel(scroll_panel)

resetScollPanel resets the position of the scroll_panel scroll panel component back to the top. If scroll_panel is not a scroll panel component, this function does nothing.
Parameters:
Name Type Description
scroll_panel

object

an instance of a scroll panel component

saveAsImage(component, width, filename, quality)

saveAsImage allows you to render a component into an image. This is useful for making snapshots of charts or perhaps users drawings.
Parameters:
Name Type Description
component

object

the component to save as an image
width

string

the width of the image in pixels (the height is calculated from the width)
filename

string

the name of the file including a .png, .jpg or .tga extension. The image is saved into the cache folder.
quality

string

This value is only used for jpg images to determine the compression. 0.8 to 0.9 are probably suitable compression values.
Example
register("saveComponentToImage","saveComponentToImage","component:component,string:width,string:filename,string:quality");
function saveComponentToImage(object, width, filename, quality){
	saveAsImage(object, width, filename, quality);	
}

serialClose()

serialClose This closes the currently open serial port.

serialEnumeratePorts()

serialEnumeratePorts This finds any serial ports and returns a JSON list.
Returns:
string - This returns a JSON string you can read to see the serial ports e.g. ["Com1","Com2"]
Example
var ports = JSON.parse(serialEnumeratePorts());
var first_port = ports[0];

serialOpen(port_name, baud_rate, flow_control, parity, stop_bits, buffer_ms, success_function, error_function, open_function, close_function)

serialOpen This opens a serial port with the specified parameters. Enumerate helps you find the ports serialEnumeratePorts
Parameters:
Name Type Description
port_name

string

the port name to open
baud_rate

int

the speed (e.g. 9600 bps)
flow_control

int

Flow control 0:none, 1:software, 2:hardware
parity

int

Parity 0:none, 1:odd, 2:even
stop_bits

int

Stop bits can be 0:One, 1:One and a half, 2:Two
buffer_ms

int

the number of miliseconds of no new data to consider the buffer completed. e.g. 1ms is a short buffer timeout, 100ms is a long buffer timeout.
success_function

string

success callback (takes a JavaScript buffer)
error_function

string

called when an error occurs (takes a numeric error type and a string message)
open_function

string

called when the serial port is opened
close_function

string

called when the serial port is closed
Example
serialOpen("Com1",9600,0,0,0,100,"serial_success","serial_error","serial_open","serial_close");

function serial_success(buffer){
	var s = "";
	for(var i=1;i20) s += String.fromCharCode(buffer[i]);
	}
	print("received " + s);
}

function serial_error(type, message){
	print("error " + message);
}

function serial_open(){
	print("open serial");
}

function serial_close(){
	print("close serial");
}

serialWrite(data)

serialWrite This writes to the current open serial port serialOpen
Parameters:
Name Type Description
data

buffer

this data is a JavaScript buffer.
Example
var serial_buffer_size_in_bytes = 20;
//declare buffer
var serial_buffer = new ArrayBuffer(serial_buffer_size_in_bytes);
//declare view into buffer
var serial_dataview = new DataView(serial_buffer);
//add data
serial_dataview.setUint8(cnt++,0xA0)
serial_dataview.setUint8(cnt++,0x04)
serial_dataview.setUint8(cnt++,0xB0)
//add crlf
serial_dataview.setUint8(cnt++,0x0D)
serial_dataview.setUint8(cnt++,0x0A)
//add null
serial_dataview.setUint8(cnt++,0x00)
//send
serialWrite(serial_buffer)

setCookie(key, value)

setCookie sets the string stored at key to value. A cookie is persistent across sessions and is only deleted upon a subsequent call to deleteCookie.
Cookies can be checked for existence with hasCookie, retrieved with getCookie, and deleted with deleteCookie.
Parameters:
Name Type Description
key

string

is the key to check for existence
value

string

the string value to store at key

setCustomFeed(object, JSON)

setCustomFeed takes a feed list, feed item or animated feed and applies your custom JSON data. This is often used to apply your data when your have registered your own programatic feed using registerFeed
Parameters:
Name Type Description
object

object

a feed list, feed item or animated feed
JSON

string

your stringified JSON data in the format returned by setCustomFeed
Example
registerFeed('demoFeed', 'demoFeed', '');
   function demoFeed(component) {
setCustomFeed(component, '[{"message":"Adam"},{"message":"Michael"},{"message":"Jenny"},{"message":"Ally"}]');
}

setData(object, key, value)

setData sets the value that the data-bound component object has stored at key. This data can be returned using getData.
Parameters:
Name Type Description
object

object

a component object. "self" may be used to reference the current instance of a custom component.
key

string

the key to store the value at. Subsequent calls to setData with the same key overwrite the data stored at that key.
value

object

the value to store at key which can be a base type (string, number etc)

setEditableProperty(object, property, value)

setEditableProperty sets a specified property of a component object to value - **note:** this sets the propery at the editor level and is specifically for use in Macros as this updates the underlying component.
Parameters:
Name Type Description
object

object

the component to update
property

string

a string property that is supported by this component
value

object

the new value to assign

setFocus(object)

setFocus sets the focus on a component.
Parameters:
Name Type Description
object

object

a component object. "self" may be used to reference the current instance of a custom component.

setForeground(page_name, foreground_name)

setForeground This sets the current foreground for the specified page name.
Note : a page can only have one current foreground object (e.g. toolbar, menu etc).
Parameters:
Name Type Description
page_name

string

the name of the page
foreground_name

string

the name of the foreground to apply to the page

setGlobal(property, value)

setGlobal sets the value of a global property
Parameters:
Name Type Description
property

string

the name of the property to set, currently 'clipboard' is supported as the majority of system globals are read only.
value

object

the value to set the property to.

setGlobalVar(key, value)

getGlobalVar gets a key from the global data bound space. This is accesible by users of the editor to use in their parameters simply by putting the key name in square brackets.
Parameters:
Name Type Description
key

string

is the key to write to
value

string

is the value to write

setProperty(object, property, value)

setProperty sets a specified property of a component object to value.
Some of these properties can be retrieved with getProperty.
Parameters:
Name Type Description
object

object

the component to update
property

string

a string property that is supported by this component
value

object

the new value to assign
Properties:
Name Type Description
hitmode

string

any component ("off", "on", "aabb", "bb")
x

string

any component
y

string

any component
width

string

any component
height

string

any component
angle

string

any component
scale

string

any component
scale_width

string

any component
scale_height

string

any component
origin_x

string

any component
origin_y

string

any component
visible

string

any component
alpha

string

any component
crop_mode

string

image (0=fill, 1=fit, 2=stretch)
font_size

string

text component
font_color

string

text component (0x0000FFFF) blue
font_filename

string

text component
font_align

string

text component (0=left, 1=center, 2=right, 3=full)
resize_type

string

text component (0=mm, 1=scale)
slice_left

string

nine slicer component
slice_top

string

nine slicer component
slice_bottom

string

nine slicer component
slice_right

string

nine slicer component
border_scale

string

nine slicer component
text

string

text, text_entry, button, html_article
fill_color

string

rectangle (0x0000FFFF) blue
scroll_offset

string

feed list
scroll_animate_y

string

feed list
enabled

string

button
spritesheet

string

RenderKit
clip

string

custom or group component
align_x

string

image
align_y

string

image
filename

string

image, video, nine_slicer, html article, gallery, 3d model
effect

string

3d model
feedid

string

any dynamic component
data_url

string

any dynamic component
json

string

any dynamic component
mapping

string

any dynamic component
template

string

any dynamic component
speed

string

carousel component

setPropertyIn(object, property, value, ms)

setPropertyIn sets a speicified property of a component object to value; it is similar to setProperty. For non-numeric properties, it waits ms milliseconds before making the change, while numeric properties are adjusted over ms milliseconds to produce an animation effect.
To get the value of a property, use getProperty.
Parameters:
Name Type Description
object

object

a Component object
property

string

a string property that is supported by object
value

object

the new value to set property to. Value must be of the type supported by property of object.
ms

int

an integer number of milliseconds (either a delay for non-numeric properties or the time period to animate the transition for numeric properties)
Properties:
Name Type Description
x

string

any component
y

string

any component
width

string

any component
height

string

any component
angle

string

any component
scale

string

any component
scale_width

string

any component
scale_height

string

any component
visible

string

any component
alpha

string

any component
align_x

string

image
align_y

string

image
filename

string

image, video, nine_slicer, html article, gallery, 3d model
scroll_offset

string

feed list

setPropertyInTween(object, property, value, ms, tween)

setPropertyInTween sets a speicified property of a component object to value; it is similar to setProperty. For non-numeric properties, it waits ms milliseconds before making the change, while numeric properties are adjusted over ms milliseconds to produce an animation effect. The tween variable defines how the animation should appear.
Parameters:
Name Type Description
object

object

a Component object
property

string

a string property that is supported by object (see list on setPropertyIn)
value

object

the new value to set property to. Value must be of the type supported by property of object.
ms

int

an integer number of milliseconds (either a delay for non-numeric properties or the time period to animate the transition for numeric properties)
tween

int

the transition type. The allowable values of tween are 0:none, 1:linear, 2:ease_in, 3:ease_out, 4:ease_both, 5:ease_rev, 6:cubic_in, 7:cubic_out, 8:cubic_in_out, 9:cubic_out_in, 10:ease_in_strong, 11:ease_out_strong, 12:ease_both_strong, 13:ease_both_strong_rev ,14:quint_in, 15:quint_out, 16:quint_in_out, 17:quint_out_in, 18:sine_in, 19:sine_out, 20:sine_in_out, 21:sine_out_in, 22:expo_in, 23:expo_out, 24:expo_in_out, 25:expo_out_in, 26:circ_in, 27:circ_out, 28:circ_in_out, 29:circ_out_in, 30:elastic_in, 31:elastic_out, 32:elastic_in_out, 33:elastic_out_in, 32:elastic_both, 34:back_in, 35:back_out, 36:back_in_out, 37:back_out_in, 36:back_both, 38:bounce_in, 39:bounce_out, 40:bounce_in_out, 41:bounce_out_in, 40:bounce_both, 42:simplex16, 43:curve_in, 44:curve_out, 45:curve_sine, 46:curve_cosine

setTextStyle(text, styleName)

setTextStyle Sets a style by name from the current style list on a text component
Parameters:
Name Type Description
text

object

the text component to apply the style to
styleName

string

the string name of the style to apply

shellExecute(A, List, start)

shellExecute allows you to launch a new process from the Umajin Viewer / Portal / Editor
Parameters:
Name Type Description
A

string

path to the file to run, this must be relative to the project folder for security purposes
List

string

of space seperated commands for the process
start

int

the process minimised 0 = false, 1 = true (note: only supported on Windows currently)
Example
//Launch an executable process
shellExecute("mybatchfile.bat", "23", 0);
//Launch via mime type 
shellExecute("http://www.stuff.co.nz", "", 0);

showCombo(callback, options)

showCombo displays a full screen combo box with the pipe delimited options provided.
Parameters:
Name Type Description
callback

string

the name of a Javascript function that will be called when the event is fired - this callback will have two parameters, the index and the value.
options

string

a string with a list of items seperated by vertical pipe characters
Example
showCombo("callback_function","red|blue|green");
function callback_function(index,value){
}

showMyLocation(map_view, zoom_level)

showMyLocation locates the map on your location.
Parameters:
Name Type Description
map_view

object

an instance of a map_view control
zoom_level

int

the zoom level to set

showSpinner()

Shows the standard project spinner to indicate the app is busy

stopGps()

stopGps will cancel a one-off or regular GPS callback setup by getGps or pollGps

subscribeForBluetoothCharacteristicChange(serviceId, characteristicId, callback, subscribes)

subscribeForBluetoothCharacteristicChange This will subscribe and report on a change in status of a BLE characteristic.
Parameters:
Name Type Description
serviceId

string

the uuid of the BLE parent service e.g. accelerometer.uuid: '0DEF5000-6656-11E5-A4E0-23D9BD6569A7'
characteristicId

string

The characteristic to query e.g. accelerometer.chars.acceleration: '0DEF5003-6656-11E5-A4E0-23D9BD6569A7'
callback

string

the function to call which takes a value string
subscribes

bool

the flag to enable or disable this subscription

subscribeForBluetoothDeviceConnected(callbackMethod, subscribes)

subscribeForBluetoothDeviceConnected This will fire a callback function when a device connects.
Parameters:
Name Type Description
callbackMethod

string

the function to call which takes the device ID as a string
subscribes

bool

the flag to enable or disable this subscription

subscribeForBluetoothDeviceDisconnected(callbackMethod, subscribes)

subscribeForBluetoothDeviceDisconnected This will fire a callback function when a device disconnects.
Parameters:
Name Type Description
callbackMethod

string

the function to call which takes the device ID as a string
subscribes

bool

the flag to enable or disable this subscription

thumbnailImage(local_filepath_in, local_filepath_out, quality_ratio, align_x, align_y, des_width, des_height)

thumbnailImage is a simple function to resize and crop an image with a minimum of parameters
Parameters:
Name Type Description
local_filepath_in

string

the path to the local input file
local_filepath_out

string

the path to the local output file
quality_ratio

number

Quality of compression of the new thumbnail (0-1)
align_x

number

alignment from left to right for cropping (0-1)
align_y

number

alignment from top to bottom for cropping (0-1)
des_width

number

the width in pixels of the thumbnail
des_height

number

the height in pixels of the thumbnail

uploadFile(local_filepath, dashboard_folder, success_function, error_function)

uploadFile asynchronously upload the file to the server. If successful, calls success_function, otherwise, calls error_function.
Parameters:
Name Type Description
local_filepath

string

the path to the local file
dashboard_folder

string

a local folder on the Umajin dashboard
success_function

string

the name of a Javascript function that will be called if the upload is successful.
error_function

string

the name of a Javascript function that will be called if the upload is unsuccessful. Error message will be passed.

urlDecode(s)

urlDecode takes a URL encoded string and returns the decoded version of the same content.
Parameters:
Name Type Description
s

string

the URL encoded string to decode
Returns:
- the unencoded represntation of the string
Example
var name = "John%20Smith";
var decodedname = urlDecode(name) // decodedname = "John Smith"

urlEncode(s)

urlEncode takes a string parameter that will be passed as part of a URL querystring and properly encodes it.
Parameters:
Name Type Description
s

string

an individual parameter to URL encode (and subsequently inlcude as part of a URL)
Returns:
- the url encoded representation of the string
Example
var name = "John Smith";
var url = "http://www.test.com/script.php?name=" + urlEncode(name) // url = "http://www.test.com/script.php?name=John%20Smith"

writeTextfile(data, filename)

writeTextfile saves a text file. Specify the string and the project subfolder and file you would like to write to, e.g. "testdata", "images/myfile.json"
Parameters:
Name Type Description
data

string

to write
filename

string

either a name of the text file to write to the temp folder or the combined path and name of the text filename. Note: only the temp and cache folders are available for writing text files.

wsDisconnect(ref)

wsDisconnect Disconnects the socket
Parameters:
Name Type Description
ref

int

the socket reference

wsNew()

wsNew returns a new web socket ref (reference).
Example
var ws = -1;
registerAction("wsEchoDemo","","wsEchoDemo","")

function wsEchoDemo(){
	ws = wsNew();
	wsOpen(ws, 'ws://echo.websocket.org', '');
	wsSetCallbacks(ws, 'wsOnError', 'wsOnConnected', '', '', '', '', 'wsTxtReceived', '');	
}

function wsOnError(error){
	print("> Error = " + error);
}

function wsOnConnected(){
	print("> Connected to Echo server");
	wsSendText(ws, 'I sent this text to the echo server');
}

function wsTxtReceived(message){
	print("> Echo message = " + message);
}

wsOpen(ref, url, protocol)

wsOpen opens a web socket client. This connection can send and receive text or binary data using the wsSendText and wsSendBinary methods along with receiving using the callbacks on_text_received and on_binary_received you can configure with wsSetCallbacks.
Note : with the OOP API we provide a fully browser compliant version of this API able to run libraries like the mosquitoJS MQTT implementation.
Parameters:
Name Type Description
ref

int

the socket reference
url

string

the url of the websocket
protocol

string

the protocol to use, not required

wsSendBinary(ref, message)

wsSendBinary sends binary data, this is an ArrayBuffer in javascript.
Parameters:
Name Type Description
ref

int

the socket reference
message

ArrayBuffer

the buffer to send
Example
var bytearray = new Uint8Array(100);
for (var i=0;i<100;i++) {
   bytearray[i] = i;
}
wsSendBinary(wsRef, bytearray.buffer);

wsSendText(ref, message)

wsSendText sends text
Parameters:
Name Type Description
ref

int

the socket reference
message

string

the text to send

wsSetCallbacks(ref, on_error, on_connected, on_connect_failed, on_disconnected, on_disconnect_failed, on_send_failed, on_text_received, on_binary_received)

wsSetCallbacks sets up the methods to raise when connections, errors, disconnections or data is received on a web socket. In this case of the on_disconnected event the list of codes can be found here https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
Parameters:
Name Type Description
ref

int

the socket reference
on_error

string

event which will pass an error string
on_connected

string

event when connecting no parameters
on_connect_failed

string

event which will pass an error string
on_disconnected

string

event which will pass an error code, error string and error reason string
on_disconnect_failed

string

event which will pass an error string
on_send_failed

string

event which will pass an error string
on_text_received

string

event which will pass a message string
on_binary_received

string

event which will pass a javascript ArrayBuffer

xmlDecode(s)

xmlDecode decodes a string from XML.
Parameters:
Name Type Description
s

string

an XML string
Returns:
- a decoded string

xmlEncode(s)

xmlEncode encodes a string suitably for including in an XML document. This will encode tab, newline and other characters outside the valid range XML accepts.
Parameters:
Name Type Description
s

string

incoming string
Returns:
- XML representation of s