Scripting

One of the biggest strengths in Total Control is the scripting capability. Total Control offers rich set of API to control one or multiple Android devices. It offers 2 sets of APIs: JavaScript and REST API. JavaScript will run the script locally, REST API offers flexibility in language and hosts. You can also use REST API to control multiple PCs running "Total Control" application.

JavaScript API

Language

Total Control provide the following framework for JavaScript (ECMAScript 5 with selected ES6 features)

The bonus with Rhino is the ability to call Java API (Total Control 8 is using OpenJDK 15) directly if Rhino + RingoJS do not provide sufficient functionality.

Total Control offers many classes, several examples:

  • Device
  • DeviceArray
  • UiElement (Total Control 8)
  • UiElementArray (Total Control 8)
  • Notification
  • Keyboard
  • Excel

Device and DeviceArray Classes

When a device is connected (auto connect or "Connect" button is pressed), a device object from "Device" class is created, use static method "searchObject" to locate the device objects. For multiple device objects, it offers "DeviceArray" class (subclass from Array). Devices in DeviceArray objects will be perform the same task at the same time.

Device class offers close to 100 methods and properties to manipulate a device. DeviceArray class offers about 20+ commonly used methods. Please refer to {{JavaScript API documentation}} for all methods. You can extend Device and DeviceArray with ease, (See Extending Device and DeviceArray).

Use "Device.searchObject()" to locate created device objects, the device object format is "device@<10 digits>".

// Return one device object
var mySamsung = Device.searchObject('Samsung-S9');
// Return all device objects, DeviceArray
var allDevices = Device.searchObject(tcConst.DevAll);
// Return device objects belong to same group, DeviceArray
var allGroupX = Device.searchObject(tcConst.DevGroup, 'first row');
var allGroupY = Device.searchObject(tcConst.DevGroup, 'second row');
// Combine 2 groups to form a larger group, DeviceArray
var groupXY = allGroupX.concat(allGroupY);

Since DeviceArray() is a subclass of Array(), it inherits most of the methods from Array class, since all the TC specific methods are tied to DeviceArray, if you have an array, use "var ary = new DeviceArray().concat(ary)" to convert to DeviceArray.

// This will fail since there is no "click" method in Array
var device = Device.getMain();
var ary = [device];
ary.click(100,100);

// This will work
var device = Device.getMain();
var ary = new DeviceArray(device);
ary.click(100, 100);    // or ary.clickSync("OK");

Couple of examples:

// click location 100,200 on device name "Samsung-S10".
var device = Device.searchObject('Samsung-S10');
if (device) {
    device.click(100,200); 	// or device.clickSync("Start");
}
// click in the middle of the screen on all connected devices.
var devices = Device.searchObject(tcConst.DevAll);
if (devices) {
    devices.click(0.5, 0.5); 	// or device.clickSync("John");
}

Directory and Userlib.js

By default, the scripting directory is located at \Users\<user name>\Documents\Scripts directory, you can change it by clicking "Script", in "Script List" top line to change the directory.

Within it, you can create a file called "Userlib.js", this file will always be loaded before script execution, you can include commonly used functions, add prototypes to existing classes or bring in 3rd party software.

To debug "Userlib.js", use "Terminal", to reload "Userlib.js", click reload icon on the bottom right Terminal window.

Absolute vs Relative Coordinates

For x, y coordinates, TC offers "absolute" and "relative" coordinates (the system settings show coordinates will show both coordinates), absolute coordinates from (0, 0) to (width – 1, height – 1), relative coordinates are usually 4 decimal points from (0, 0) to (0.9999, 0.9999). The relative coordinates multiply by device width and height will get the absolute coordinates. Coordinates are not ideal, Professional supports AAI that use text in the UI elements to retrieve the coordinates in the runtime.

Extending Device and DeviceArray

The added bonus of JavaScript is the extensibility, you can extend the methods by adding prototype to the classes. Assuming you want to create a method "longPress" for both single and multiple devices, one way to write it is:

Device.prototype.longPress = function(x, y) {
    var retval = this.click(x, y, tcConst.STATE_DOWN);
    if (retval != 0) {
        return retval;
    }
    delay(500);
    return this.click(x, y, tcConst.STATE_UP);
}

DeviceArray.prototype.longPress = function(x, y) {
    for (let i = 0; i < this.length; ++i) {
        retval = this[i].longPress(x,y);
        if (retval != 0) {
            return retval;
        }
}
return 0;
}

This implementation not efficient for large number of devices in DeviceArray, the method can take up to 50 seconds if there are 100 devices in the array.

The best way is to send STATE_DOWN to all devices first, then wait till the remaining of 500 ms runs out. Fortunately, Device and DeviceArray (multiple devices) introduced "sendAll", it will execute the method specified and wait until time specified is expired. This way, the execution time is almost 500 ms. Since "sendAll" is available in Device and DeviceArray, the code to implement Device and DeviceArray is exactly the same.

Device.prototype.longPress = function(x, y) {
var retval = this.sendAll(Device.prototype.click, 
     [x, y, tcConst.STATE_DOWN], 500);
    if (retval != 0) {
        return retval;
    }
    return this.sendAll(Device.prototype.click, [x, y, tcConst.STATE_UP]);
}

DeviceArray.prototype.longPress = Device.prototype.longPress; 
 

sendAll only applies to methods that returns 0 on success.

Scripting Tools

There are many tools available in Total Control, click "Script" will open a new window:

Terminal: Open Rhino + RingoJS command prompt, you can use it for testing or development purpose. Click button on the bottom right to reload the interpreter and Userlib.js. Can use load("filename.js") to run a script.

Script List ⇒ Path: Script default path, click icon to change the path to other directory.

Script List ⇒ JS source files: Use to quickly execute a JavaScript file, it provide a simple editor for quick change or click arrow key to execute the script.

Script List ⇒ Record Script: Record the actions on the devices into an Excel file, Excel file can also be used to generate JS script or JSON file (maybe useful for REST API). Users with no experience in JavaScript can use this tool to generate simple script.

Script List ⇒ Image Helper. Generate BMP file from main device screen content, the image is needed for seekImage(), it extends BMP file to provide additional information such as app name, activity, width and height information. seekImage() will utilize these information without providing lots of parameters.

Script List ⇒ Color Helper. Load the screen content from the main device (like image helper), a magnified color chooser to pick RGB values of the colors and generate seekColor() with complex parameters. Can support single and multiple colors.

Execute (will be renamed to Task). Create a task to run a script on various number of conditions such as date & time, number of iterations, regular intervals or the devices. The output and the results of the task execution will be saved for review. Task can be also be created or changed via JS API.

Inspect: Inspect the various internal variables related to scripts and engines.

Automation and Accessibility Integration (AAI) (Total Control 8+)

Accessibility is a feature in Android that map on-screen UI elements to underlying nodes, the node can represent an UI element (e.g. button) or a group of UI elements or layout of certain elements. A node (element, group or layout) can be identified by a node ID (represent in string of hex). We integrate Accessibility, TC scripting framework and UI Automator library to achieve the following goals:

  • Coordinate independent makes the script more portable with different resolutions and multiple brands.
  • Synchronous API will wait until the screen is repaint, make the script simpler, do not need to guess the time to sleep. Synchronous API will not slow down the multi-device execution.
  • Can retrieve the string from the app with ease, instead of using error-prone OCR.

The simplest case of AAI:

  • Click "OK" on the screen if found, far better than click(100, 100) for specific resolution: devices.clickSync("OK")
  • Enter text into text entry, position is specified, enter into nth position on multiple text entry lines.
    devices.inputTextSync([position], "text")    // Enter text, the position is used for multiple inputs
  • Run or restart application, without query, it will return on screen refresh; with query, it will match the query after screen is refreshed.
    devices.runAppSync(<package name>, [query]) 
    devices.restartAppSync(<package name>, [query])

For more complex scripting, you need to locate node ID or list of node ID by query the accessibility nodes. UI Automator in Java provides "UiSelector" and "BySelector" in UiDevice.findObject() or findObjects() to locate nodes, it can be complex for multiple conditions:

new UiSelector().className("android.widget.TextView").text("OK")

We created a simple query language, that is shorter and portable since need to send this to lots of devices, the above query can be rewritten in:

"C: android.widget.TextView||T:OK"

The query syntax can contain "!" for not, ">", "<" for greater than or less than, "*" for wild card match and "/<regexp>/" for regular expression. It can match package name, class name, resource ID, text, description, child count and input type.

Use UiElement.findObject() to return an object of a node if found, since the object has the device object stored, to execute you do not need to specify device like other action/movement commands.

var obj = UiElement.findObject(device, "T:OK");
if (obj) {
   obj.clickSync();
}

If you have multiple devices, it will return array of objects in class UiElementArray, an action will cause all devices to react, the code below will click all devices with text of "OK":

var objs =  UiElement.findObject(devices, "T:OK");
if (objs) {
   objs.clickSync();
}

You can also retrieve the information from the app, e.g. clock with hour, minute and second:

var hour = UiElement.findObject(devices, "R:" + app + ":id/timeHour").getText();
var min = UiElement.findObject(devices, "R:" + app + ":id/timeMinute").getText();
var sec = UiElement.findObject(devices, "R:" + app + ":id/timeSecond").getText();
print("The current time is " + hour + ":" + min + ":" + sec);

Alternatively, you can retrieve the information from "UI Explorer" to find the query syntax of a node (not the most optimize query). e.g.


To offload the complexity of JavaScript and CPU utilization of Total Control, all the search is conducted in the devices.

The program on the device to parse query, locate nodes and actions to the nodes is called "FindNode". device.sendAAi() and devices.sendAai() are way to communicate with FindNode with one or list of devices. The JS object will be translated to JSON before sending to device, it will return the output. If error is encountered, the return is null, the lastError() contains error message. UiElement is developed based on sendAai().

The command is separated to "preAction" and "postAction" and "postActions", "preAction" is before the search/count is conducted, "postAction" and "postActions" are the action toward the output of the search.

"query" contains the query syntax for the search.

There are 14 different keys to compose a query, they are:

  • C: Class name (S)
  • R: Resource ID (S)
  • D: Description (S)
  • T: Text (S)
  • IT: Input type (I/S)
  • CC: Child count (I/S)
  • ID: Node ID returned by other queries (S)
  • BI: Bound in: [x, y] or [left, top, right, bottom], if x or y is -1, it will be ignored
  • IX: Index (I)
  • OX: Offset on x (I)
  • OY: Offset on y (I)
  • TP: Template (S)
  • ON: One node selection (S)
  • LT: Line number (I)
  • LB: Line number (I)

A simple query example, to obtain the text of Model name, use X offset of 1:

>> device.sendAai({query:"T:Model name||OX:1", postAction:"getText"})
{retval: 'Galaxy S10+'}

FindNode can even detects the fixed icons on the top/bottom of the screen:

>> device.sendAai({query:"LB:-1", postAction:"getText"})
{retval: ['Chats','Calls','Contacts','Notifications']}

The following 3 commands, doing the same thing, click on the "Calls" text:

>> device.sendAai({query:"LB:-1||T:Calls", postAction:"click"})
{retval: true}
>> device.sendAai({query:"LB:-1||IX:1", postAction:"click"})
{retval: true}
>> device.sendAai({query:"LB:-1||T:Chats||OX:1", postAction:"click"})
{retval: true}

Click "Contacts" icon:

>> device.sendAai({query:"LB:-1||T:Contacts||OY:-1", postAction:"click"})
{retval: true}
>> device.sendAai({query:"LB:1||IX:2", postAction:"click"})
{retval: true}
>> device.sendAai({query:"T:Contacts||IX:-1||OY:-1", postAction:"click"})
{retval: true}

Please read FindNode User Guide for more information.

Background Query (offer in 8.0 update 20)

Background query allows user to map query in a device to a JavaScript callback function, when the query condition is met, it will trigger a callback function with a node ID.

For instance, if you want to close a calculator application when the calculator shows 999.

function closeMe(name, device, packageName, nodeId) {
	device.closeApp(packageName);
	return true;
}

addQueryListener("closeCalculator", device, "T:/^999$/", closeMe);

If the device is not running the calculator application, need to include calculator packageName: E.g. "P:com.sigma_rt.calc||T:/^999$/".

"return true" allows the Total Control to reactivate the background query, without "return true", the callback only run once.

Enter "999" in the calculator application to terminate the calculator.

Synchronous API

Before version 8, all action or movement commands are asynchronous, when a command (e.g. device.click()) return, it means the command has been passed down to our mobile agent for execution, when the command returns, it is likely the command is not executed, so a sleep is required to give time for the action to be done and screen is refreshed:

	device.click(100, 100);
	sleep(300);

This can happen to all action and movement commands which make the coding cumbersome. UI Automator includes synchronous command and wait for window to update, when a click is pressed, a window has been updated, most likely the command is completed. All synchronous commands are suffixed by "Sync". All "Sync" commands are using AAI label instead of coordinate:

runAppSync()

restartAppSync()

clickSync()

inputTextSync()/p>

UiElement and UiElementArray object methods

One drawback of the synchronous feature is the time it takes for the commands to complete is much longer than asynchronous commands, this can slow down the script executions for large number of devices, we have addressed this issue.

The subsequent versions will provide synchronous feature to all action and movement functions.