Event handler
Event handlers include two types, namely block event handler (live mode configuration) and extension event handler (common code configuration).
- block handler: block event handler, including block adding, removing, and executing, indicated by
block.*
. - extension handler: extension event handler, including extension loading, connecting, and state switching, indicated by
extension.*
.
API
All APIs of mBlock 5 Extension Builder are obtained from the app, device, and block objects. You can also use any web APIs except DOM. For details, see the related reference documents.
- app (application): obtains and operates the blocks and data of the mBlock 5 app.
- device: connects to the system of the current device, and reads and writes data.
- block: obtains the running information of blocks.
For more APIs, see API List.
Block event handler (live mode configuration)
block.onAdd
Function: Triggered when you add a hat block to the operation area
Note: This function is available in both the editing and playing states of a project. Usually, when a project is loaded, the virtual machine has already loaded the block, and so this function is triggered. In addition, when device.resetEvents is executed, this function is also triggered.
Example:
// (onAdd)
(app, device, block) => {
app.log("hat block of ${block.opcode} is add to workspace");
}
block.onRemove
Function: Triggered when you remove a hat block from the operation area
Note: This function is available in both the editing and playing states of a project. Usually, when a project is loaded, the virtual machine has already loaded the block, and so this function is triggered. In addition, when device.resetEvents is executed, this function is also triggered.
Example:
onRemove(app, device, block) {
app.log("hat block of ${block.opcode} is remove from workspace");
}
block.onRun
Function: Triggered when a hat block is executed
Note: The type of the returned value varies according to block type.
Examples:
// Hat block example
async onRun(args, app, device, block) { app.log("block of ${block.opcode} is checked to trigger"); if (args.ARGMENT1 > 100) { app.log("block of ${block.opcode} is condition satisfied, start this thread running"); return true; } else { app.log("block of ${block.opcode} is not condition satisfied, prohabit this thread from running"); return false; } }
//Command block example
async onRun(args, app, device, block) { app.log("block of ${block.opcode} is running"); // you can use promise to return laterly, or you can return immidiately return new Promise((resolve)=>{ resolve(); }); }
Value block example
async onRun(args, app, device, block) { app.log("block of ${block.opcode} is running"); // you can use promise to return laterly, or you can return immidiately return new Promise((resolve)=>{ window.settimeout(()=>app.log("block of ${block.opcode} is stoped then, return value of 100")); resolve(100); }); }
Extension event handler (common code configuration)
extension.onLoad
Function: Triggered when an extension is loaded
Note: This function can be triggered multiple times during the loading and unloading of an extension. When an extension is loaded only once, this function may also be triggered multiple times if the extension supports multiple sprites, triggered once for each sprite.
Example:
async onLoad(app, target)
{
// app.log prints information in the web ide debugging window, same function as console.log,
// target.id is the unique identifier of an extension
app.log('I am loaded, get ID of '+ target.id);
}
extension.onUnload
Function: Triggered when an extension is unloaded
Example:
onUnload(app, target)
{
app.log("I am unloading, bye, yours "+ target.id);
}
extension.onStopAll
Function: Triggered when you click the red button in mBlock or use the stop all block
Example:
onStopAll(app, device) {
app.log("stop running");
}
extension.onConnect
Function: Triggered when a device is connected
Note: The communication of a device must be performed after this function responds. You can determine whether a device is connected by using the device.isConnected function.
Example:
onConnect(app, device) {
app.log("${device.id} is connected, you can send data to ${device.id}");
device.writeText("a text message");
}
extension.onDisconnect
Function: Triggered when an extension is disconnected
Note: When this function is triggered, communication with the device fails. You can determine whether an extension is connected by using the device.isConnected function.
Example:
onDisconnect(app, device) {
app.log("${device.id} is not connected, you can not communicate to device any more");
}
extension.beforeChangeUploadMode
Function: Triggered when the upload mode is requested by sending data to a device to switch to the upload mode
Note: This function must be used in combination with afterChangeUploadMode. The afterChangeUploadMode function is triggered only when true is returned.
Example:
async beforeChangeUploadMode(app, device) {
// Asynchronous waiting, refer to the syntax of javascript es6
// Use a protocol of the F3 & F4 protocol group
await device.asyncWriteProtocol('f3f4', [0x0d, 0x00, 0x03]);
// Assume that the operation succeeds
return true;
}
extension.afterChangeUploadMode
Function: Triggered when the device enters the upload mode
Note: This function must be used in combination with beforeChangeUploadMode. It is triggered only when beforeChangeUploadMode returns true.
Example:
afterChangeUploadMode(app, device) {
app.log("${device.id} switch to upload mode successfully");
}
extension.beforeChangeDebugMode
Function: Triggered when the debugging (live) mode is requested by sending data to a device to switch to the debugging (live) mode
Note: This function must be used in combination with afterChangeDebugMode. The afterChangeDebugMode function is triggered only when true is returned.
Example:
async beforeChangeDebugMode(app, device) {
// Asynchronous waiting, refer to the syntax of javascript es6
// Use the mode switching protocol of the F3 & F4 protocol group
await device.asyncWriteProtocol('f3f4', [0x0d, 0x00, 0x00]);
// Assume that the operation succeeds
return true;
}
extension.afterChangeUploadMode
Function: Triggered when the device enters the debug (live) mode
Note: This function must be used in combination with beforeChangeDebugMode. The afterChangeDebugMode function is triggered only when beforeChangeDebugMode returns true.
Example:
afterChangeUploadMode(app, device) {
app.log("${device.id} switch to online mode successfully");
}
extension.onSelect
Function: Triggered when you click a sprite or device to switch to it in a project involving multiple devices
Note: This function is triggered again when the main extension of the device is loaded.
Example:
onSelect(app, device) {
app.log("switch to ${device.id}");
}
extension.onUnselect
Function: Triggered when you click a sprite or device to switch to it in a project involving multiple devices
Note: When you switch a sprite, the onUnselect function is triggered first, and then the onSelect function.
Example:
onUnselect(app, device) {
app.log("from ${device.id} switch to other target");
}
extension.onRead
Function: Triggered when device data is received
Note: This function is triggered only when data is obtained from a device.
Example:
onRead(app, device) {
let anyText = device.readText(false);
app.log("text receive from ${device.id}: ${anyText}");
}
extension.beforeCodeUpload
Function: Triggered in the upload mode when the code is ready to be uploaded to a device
Note: When this function is triggered, the code has not been uploaded to the device yet.
Example:
// The following obtains and modify the code before the code is uploaded to the device:
beforeCodeUpload(app, device) {
let {type, text} = device.getCode();
app.log("upload code of ${type}: ${text}");
return "# prepend before code\n" + text;
}
extension.afterCodeUpload
Function: Triggered in the upload mode when the uploading of the code is complete
Note: When this function is triggered, the code has been uploaded to the device.
Example:
onUnselect(app, device) { app.log("congratulations! you've uploaded code to ${device.id}"); }
API list
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:
// (onRun)
async (args, app, device, block) => {
return await app.getVersion();
}
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:
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:
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:
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:
// The following simulates the block: broadcast (message)
(args, app, device, block) => {
app.workspace.broadcast(args.MSG);
}
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:
const _cancel = app.workspace.onBroadcast(msg => {
app.log('got a message from mblock:', msg);
});
// ...
// to cancel this event handler
// _cancel()
// The following simulates the block: when I receive (message)
// onRun
(args, app, device, block) => {
if (self._ON_BROADCAST_MSG == args.MSG) {
self._ON_BROADCAST_MSG = null;
return true; // true indicates that the hat block is triggered
} else {
return false; // false indicates that the hat block is not triggered
}
}
// onAdd
(app, device, block) => {
// Registration message event, the global variable self.__ON_BROADCAST_CANCELLER stores "deregistration"
self.__ON_BROADCAST_CANCELLER = app.workspace.onBroadcast(msg => {
self._ON_BROADCAST_MSG = msg; // Global variable self.__ON_BROADCAST_MSG stores the received broadcast variable
app.workspace.runBlocks(block.opcode);
});
}
// onRemove
(app, device, block) => {
if (self.__ON_BROCAST_CANCELLER) self.__ON_BROCAST_CANCELLER();
}
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:
// The following simulates the block: variable
async (args, app, device, block) => {
return await app.workspace.getVariable(args.VAR);
}
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:
// The following simulates the block: set <variable> to <numeric value>
// onRun
async (args, app, device, block) => {
await app.workspace.setVariable(args.VAR, args.VAL);
}
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:
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:
app.workspace.disableBlocks('your_extension_id.block_1', 'your_extension_id.block_2', 'your_extension_id.block_3')
// you cannot use these blocks from now
// The following block function disables the block itself.
(args, app, device, block) => {
app.workspace.disableBlocks(block.opcode);
}
app.workspace.enableBlocks
Function: Enables a block.
Available versions: V1.0.0 or later
Parameter:
...opcodes: string[], block ID
Return: None
Example:
app.workspace.enableBlocks('your_extension_id.block_1', 'your_extension_id.block_2', 'your_extension_id.block_3')
// 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:
function onConnect(app, device) {
// sometimes device may disconnect by accident, then the state of mblock communicate to device is messed up, you need to reset it.
app.workspace.resetEvents();
}
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:
// in one extension/file ......
app.sendMessage("echo", 1234);
// in other extension/file ......
app.subscribeMessage ("echo", datas=>{
app.sendMessage("echo back", datas);
} )
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:
// in one file ......
app.sendMessage("echo", 1234);
// in other files ......
app.subscribeMessage ("echo", (datas)=>{
app.sendMessage("echo back", datas);
} )
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:
// in one file ......
app.sendMessage("echo", ["balabala", 1234]);
// in other files ......
let datas = await app.receiveMessage("echo");
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:
// The following block function returns the ID of the current device:
(args, app, device, block) => {
return device.id;
}
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.
async (args, app, device, block) => {
return await device.isSelected();
}
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:
async (args, app, device, block) => {
let {type, text} = await device.getCode();
console.log(`code of ${type}: ${text}`);
return text;
}
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:
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:
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:
device.setTextDecoder('utf8');
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:
device.setTextDecoder('utf8');
let text = await device.readText();
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:
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:
'let hexStr = device.readHex();
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:
let datas = await device.asyncReadProtocol('your_protocol', ["ff55", 'string', 'float']);
if(datas == null) {
app.log('receive nothing or not a valid protocol');
} else {
app.log('receive datas, string of ${datas[0]}, float of ${datas[1]}');
}
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:
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:
device.subscribeReadProtocol('your_protocol', ["ff55", 'string', 'float'], (datas)=>{
app.log('receive datas, string of ${datas[0]}, float of ${datas[1]}');
});
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:
onConnect(app, device) {
if(!(await device.isConnected())){
app.error('unreachable!');
}
}
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:
afterChangeUploadMode (app, device) {
if(!(await device.isUploadMode())){
app.error('unreachable!');
}
}
block.opcode
Function: Opcode type of a block
Available versions: V1.0.0 or later
Parameter: None
Return: string
Example:
onRun(args, app, device, block) {
app.log('start to run block type of ', block.opcode);
// ......
}
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:
onRun(args, app, device, block) {
app.log('start to run block id of ', block.id);
// ......
}
block.arguments
Function: Parameter of a block
Available versions: V1.0.0 or later
Parameter: None
Return: any[]
Example:
onRun(args, app, device, block) {
app.log('start to run block with arg1 of ', block.arguments.ARG1);
// ......
}
Comments
Please sign in to leave a comment.