How Can We Help?

API Lists

app.getVersion

Function: Obtains the version of the current API

Available versions: V1.0.0 or later

Parameter: None

Return: string

Note: This is an asynchronous function that requires the await keyword when being called.

Example:

1    // (onRun)
2    async (args, app, device, block) => {
3    return await app.getVersion();
4    }

app.log

Function: Prints Information to the Web debug window, same function as console. Log

Available versions: V1.0.0 or later

Parameter:

…msgs[], multiple output strings

Return: None

Example:

1    app.log(“blah-blah”,”no one”, “nothing”, 1, true);

app.warn

Function: Prints warning information to the Web debug window, same function as console. warn

Available versions: V1.0.0 or later

Parameter:

…msgs[], multiple output strings

Return: None

Example:

1    app.warn(“something dangerous”);

app.error

Function: Prints error information to the Web debug window, same function as with console. error

Available versions: V1.0.0 or later

Parameter:

…msgs[], multiple output strings

Return: None

Example:

1    app.error(“fatal!”);

app.workspace.broadcast

Function: Initiates an mBlock broadcast

Available versions: V1.0.0 or later

Parameter: message:string, message name

Return: None

Example:

1    // The following simulates the block: broadcast (message)
2    (args, app, device, block) => {
3           app.workspace.broadcast(args.MSG);
4    }

app .workspace .onBroadcast

Function: Executes the subsequent statements when receiving the broadcast of mBlock

Available versions: V1.0.0 or later

Parameter: message:string, message name

Return: None

Example:

1    const _cancel = app.workspace.onBroadcast(msg => {
2            app.log(‘got a message from mblock:’, msg);
3    });
4    // …
5    // to cancel this event handler
6    // _cancel()
7    // The following simulates the block: when I receive (message)
8    // onRun
9    (args, app, device, block) => {
10         if (self._ON_BROADCAST_MSG == args.MSG) {
11             self._ON_BROADCAST_MSG = null;
12             return true; // true indicates that the hat block is triggered
13         } else {
14              return false; // false indicates that the hat block is not triggered
15         }
16    }
17    // onAdd
18    (app, device, block) => {
19           // Registration message event, the global variable self.__ON_BROADCAST_CANCELLER stores “deregistration”
20           self.__ON_BROADCAST_CANCELLER = app.workspace.onBroadcast(msg => {
21                 self._ON_BROADCAST_MSG = msg; // Global variable self.__ON_BROADCAST_MSG stores the received broadcast variable
22                 app.workspace.runBlocks(block.opcode);
23           });
24   }
25   // onRemove
26   (app, device, block) => {
27          if (self.__ON_BROCAST_CANCELLER) self.__ON_BROCAST_CANCELLER();
28    }

app.workspace.getVariable

Function: Obtains a variable of mBlock. Note that this API is available only for global variable names.

Available versions: V1.0.0 or later

Parameter: varName:string, variable name

Return: value: string | number, variable value

Note: This is an asynchronous function that requires the await keyword when being called.

Example:

1    // The following simulates the block: variable
2    async (args, app, device, block) => {
3            return await app.workspace.getVariable(args.VAR);
4    }

app.workspace.setVariable

Function: Sets a variable name and value of mBlock. Note that this API is available only for global variable names.

Available versions: V1.0.0 or later

Parameter:

varName:string, variable name

value: string | number, variable value

Return: void

Example:

1    // The following simulates the block: set <variable> to <numeric value>
2    // onRun
3    async (args, app, device, block) => {
4            await app.workspace.setVariable(args.VAR, args.VAL);
5     }

app.workspace.runBlocks

Function: Executes a hat block. Note that it does not necessarily trigger the hat block. After .onRun is executed, whether the hat block is triggered depends on the result returned.

Available versions: V1.0.0 or later

Parameter:

opcode: string, block opcode

coldDown?: number, colddonw time (ms) (optional, applied to throttle in scenarios where triggering is frequently performed. The default value is 50 ms.

Return: void

Note: This is an asynchronous function that requires the await keyword when being called.

Example:

1    await app.workspace.runBlocks(‘your_extension_id.block_id’);

app.workspace.disableBlocks

Function: Disables a block.

Available versions: V1.0.0 or later

Parameter:

…opcodes: string[], block ID

Return: None

Example:

1    app.workspace.disableBlocks(‘your_extension_id.block_1’, ‘your_extension_id.block_2’, ‘your_extension_id.block_3’)
2    // you cannot use these blocks from now
3    // The following block function disables the block itself.
4    (args, app, device, block) => {
5           app.workspace.disableBlocks(block.opcode);
6    }

app.workspace.enableBlocks

Function: Enables a block.

Available versions: V1.0.0 or later

Parameter:

…opcodes: string[], block ID

Return: None

Example:

1    app.workspace.enableBlocks(‘your_extension_id.block_1’, ‘your_extension_id.block_2’, ‘your_extension_id.block_3’)
2    // you can use these blocks again

app.workspace.resetEvents

Function: Resets block events, usually used when a device is programmed in the live mode

Available versions: V1.0.0 or later

Parameter: None

Return: None

Example:

1    function onConnect(app, device) {
2        // sometimes device may disconnect by accident, then the state of mblock communicate to device is messed up, you need to reset it.
3    app.workspace.resetEvents();
4    }

app.sendMessage

Function: Transmits events across different extensions. Different from app.workspace.broadcast, this API does not interact with mBlock.

Available versions: V1.0.0 or later

Parameter:

msgName: string, message name

…datas: any[], message data

Return: None

Example:

1    // in one extension/file ……
2    app.sendMessage(“echo”, 1234);
3    // in other extension/file ……
4    app.subscribeMessage (“echo”, datas=>{
5           app.sendMessage(“echo back”, datas);
6    } )

app.subscribeMessage

Function: Receives events across different extensions. The events are not accumulated. The current registration cancels the last registration.

Available versions: V1.0.0 or later

Parameter:

msgName: string, message name

handle: function, event response function

Return: None

Example:

1    // in one file ……
2    app.sendMessage(“echo”, 1234);
3    // in other files ……
4    app.subscribeMessage (“echo”, (datas)=>{
5           app.sendMessage(“echo back”, datas);
6    } )

app.receiveMessage

Function: Receives events across different extensions, waiting return asynchronously (async/await)

Available versions: V1.0.0 or later

Parameter:

msgName: string, message name

Return: Data returned asynchronously by promise

Example:

1    // in one file ……
2    app.sendMessage(“echo”, [“balabala”, 1234]);
3    // in other files ……
4    let datas = await app.receiveMessage(“echo”);
5    app.log(‘received datas of ${datas}’);

target.id / device.id

Function: Obtains a device ID.

Available versions: V1.0.0 or later

Parameter: None

Return: string, name

Example:

1    // The following block function returns the ID of the current device:
2    (args, app, device, block) => {
3           return device.id;
4    }

device.isSelected

Function: Determines whether a device is currently selected/edited

Available versions: V1.0.0 or later

Parameter: None

Return: string, name

Note: This is an asynchronous function that requires the await keyword when being called.

Example:

The following block function returns whether the current block is selected.

1    async (args, app, device, block) => {
2    return await device.isSelected();
3    }

device.getCode

Function: Obtains the converted code (if code conversion is allowed)

Available versions: V1.0.0 or later

Parameter: None

Return: ICode, containing the type and text fields, as shown in example

Note: This is an asynchronous function that requires the await keyword when being called.

Example:

1    async (args, app, device, block) => {
2             let {type, text} = await device.getCode();
3             console.log(`code of ${type}: ${text}`);
4             return text;
5    }

device.writeRaw

Function: Writes data in bytes to a device through a serial port or Bluetooth

Available versions: V1.0.0 or later

Parameter:

data: number[]

channel?: string, channel name, optional. The default value is “”.

Return: None

Example:

1    device.writeRaw([0xff, 0xff]);

device.setTextDecder

Function: Sets the text decoding type

Available versions: V1.0.0 or later

Parameter: decoderType : ‘utf8’ | ‘ascii’, decoding type

Return: None

Example:

1    device.setTextDecoder(‘utf8’);

device.writeText

Function: Writes data in texts to a device

Available versions: V1.0.0 or later

Parameter:

text: string, text

channel?: string, channel name, optional. The default value is “”.

Return: Uint8Array

Example:

1    device.setTextDecoder(‘utf8’);
2    device.writeText(‘text’);

device.readText

Function: Reads data in texts from the buffer. Note that the data is directly returned from the buffer.

Available versions: V1.0.0 or later

Parameter: consume?: bool, whether to delete data from the buffer after reading it. The default value is true.

Return: string

Note: This is an asynchronous function that requires the await keyword when being called.

Example:

1    device.setTextDecoder(‘utf8’);
2    let text = await device.readText();
3    app.log(‘text received from device’, text);

device.writeHex

Function: Writes data in bytes to a serial port, represented in a hexadecimal string

Available versions: V1.0.0 or later

Parameter:

text: string, hexadecimal string

channel?: string, channel name, optional. The default value is “”.

Return: None

Example:

1    device.writeHex(‘eeff00’);

device.readHex

Function: Reads data in bytes from the buffer, represented in a hexadecimal string

Available versions: V1.0.0 or later

Parameter:

consume?: bool, whether to delete data from the buffer after reading it, optional. The default value is true.

Return: string

Note: This is an asynchronous function that requires the await keyword when being called.

Example:

1    ‘let hexStr = device.readHex();
2    app.log(‘hex received from device’, hexStr);

device.asyncReadProtocol

Function: Reads protocol data asynchronously. The protocol data is returned when it meets the protocol format. (For details, see the protocol communication description document.)

Available versions: V1.0.0 or later

Parameter:

protocolName: string, protocol name

pattern: any[], format

timeout? : number, timeout time in ms, optional. The default value is 3,000 ms.

Return: Promise

Note: This is an asynchronous function that requires the await keyword when being called.

Example:

1    let datas = await device.asyncReadProtocol(‘your_protocol’, [“ff55”, ‘string’, ‘float’]);
2    if(datas == null) {
3         app.log(‘receive nothing or not a valid protocol’);
4    } else {
5         app.log(‘receive datas, string of ${datas[0]}, float of ${datas[1]}’);
6    }

device.asyncWriteProtocol

Function: Writes data and encapsulates it into a protocol. Note that this is an asynchronous function that requires the await keyword. (For details, see the the protocol communication description document.)

Available versions: V1.0.0 or later

Parameter:

protocolStr: string, protocol name

pattern: any[], format

channel?: string, channel, see device.writeRaw

Return: number[], protocol data

Note: This is an asynchronous function that requires the await keyword when being called.

Example:

1    await device.asyncWriteProtocol(‘your_protocol’, [“ff55”, [‘string’, ‘some text’], [‘float’, 1.1]]);

device.subscribeReadProtocol

Function: Reads protocol data asynchronously. The protocol data triggers the handler when it meets the protocol format. (For details, see the protocol communication description document.)

Available versions: V1.0.0 or later

Parameter:

protocolName: string, protocol name

pattern: any[], format

handler: (datas: any[]) => void, triggering the handler when the protocol data meets the format Return: ()=>void, deregistration

Example:

1    device.subscribeReadProtocol(‘your_protocol’, [“ff55”, ‘string’, ‘float’], (datas)=>{
2           app.log(‘receive datas, string of ${datas[0]}, float of ${datas[1]}’);
3    });

device.isConnected

Function: Determines whether a device is connected

Available versions: V1.0.0 or later

Parameter: None

Return: bool

Note: This is an asynchronous function that requires the await keyword when being called.

Example:

1    onConnect(app, device) {
2         if(!(await device.isConnected())){
3           app.error(‘unreachable!’);
4         }
5    }

device.isUploadMode

Function: Whether it is in the upload mode or live mode

Available versions: V1.0.0 or later

Parameter: None

Return: bool

Note: This is an asynchronous function that requires the await keyword when being called.

Example:

1    afterChangeUploadMode (app, device) {
2       if(!(await device.isUploadMode())){
3         app.error(‘unreachable!’);
4        }
5    }

block.opcode

Function: Opcode type of a block

Available versions: V1.0.0 or later

Parameter: None

Return: string

Example:

1    onRun(args, app, device, block) {
2             app.log(‘start to run block type of ‘, block.opcode);
3             // ……
4    }

block.id

Function: ID of a block. Blocks of the same opcode types are defined with different IDs.

Available versions: V1.0.0 or later

Parameter: None

Return: string

Example:

1    onRun(args, app, device, block) {
2             app.log(‘start to run block id of ‘, block.id);
3             // ……
4    }

block.arguments

Function: Parameter of a block

Available versions: V1.0.0 or later

Parameter: None

Return: any

Example:

1    onRun(args, app, device, block) {
2             app.log(‘start to run block with arg1 of ‘, block.arguments.ARG1);
3             // ……
4    }