diff --git a/libs/broadcast/broadcast.ts b/libs/broadcast/broadcast.ts new file mode 100644 index 00000000..bbf0b0f5 --- /dev/null +++ b/libs/broadcast/broadcast.ts @@ -0,0 +1,66 @@ +/** + * Message broadcasting + */ +//% weight=70 +//% color="#58AB41" +namespace broadcast { + const broadcastEventId = control.allocateNotifyEvent(); + const broadcastDoneEventId = control.allocateNotifyEvent(); + + function normalizeId(id: number) { + // upper ids are reserved for answer + return ((id + 1) | 0) & 0xffff; + } + + /** + * An enum shim + */ + //% shim=ENUM_GET + //% blockId=msg_enum_shim + //% block="$arg" + //% enumName="Messages" + //% enumMemberName="message" + //% enumPromptHint="e.g. Move, Turn, ..." + //% enumInitialMembers="message1" + //% blockHidden=1 + //% enumIsHash=1 + export function __messageShim(arg: number) { + // This function should do nothing, but must take in a single + // argument of type number and return a number value. + return arg; + } + + /** + * Register code to run when a message is received + */ + //% block="on %id=msg_enum_shim|received" + //% blockId=broadcastonreceived draggableParameters + export function onMessageReceived(message: number, body: () => void) { + const messageid = normalizeId(message); + control.onEvent(broadcastEventId, messageid, function () { + body(); + control.raiseEvent(broadcastDoneEventId, messageid); + }) + } + + /** + * Sends a message to activate code + */ + //% block="send %id=msg_enum_shim" + //% blockId=broadcastsend draggableParameters + export function sendMessage(message: number) { + const messageid = normalizeId(message); + control.raiseEvent(broadcastEventId, messageid); + } + + /** + * Sends a message and pauses until the handler to finishes. + */ + //% block="send %id=msg_enum_shim| and pause" + //% blockId=broadcastsendpause + export function sendMessageAndPause(message: number) { + const messageid = normalizeId(message); + control.raiseEvent(broadcastEventId, messageid); + control.waitForEvent(broadcastDoneEventId, messageid); + } +} \ No newline at end of file diff --git a/libs/broadcast/pxt.json b/libs/broadcast/pxt.json new file mode 100644 index 00000000..ea10e5b3 --- /dev/null +++ b/libs/broadcast/pxt.json @@ -0,0 +1,11 @@ +{ + "name": "broadcast", + "description": "Broadcasting messages - beta", + "files": [ + "broadcast.ts" + ], + "public": true, + "dependencies": { + "core": "file:../core" + } +} \ No newline at end of file diff --git a/pxtarget.json b/pxtarget.json index 6dcce922..3b1bacd7 100644 --- a/pxtarget.json +++ b/pxtarget.json @@ -17,7 +17,8 @@ "libs/gyro-sensor", "libs/screen", "libs/ev3", - "libs/storage" + "libs/storage", + "libs/broadcast" ], "simulator": { "autoRun": true,