Adding promises to return on BLE write. Some refactoring.

This commit is contained in:
Evelyn Eastmond 2018-06-21 14:36:10 -04:00 committed by Ray Schamp
parent 701f430e56
commit 73cc149783
3 changed files with 22 additions and 19 deletions

View file

@ -111,20 +111,22 @@ class MicroBit {
/** /**
* @param {string} text - the text to display. * @param {string} text - the text to display.
* @return {Promise} - a Promise that resolves when writing to device.
*/ */
displayText (text) { displayText (text) {
const output = new Uint8Array(text.length); const output = new Uint8Array(text.length);
for (let i = 0; i < text.length; i++) { for (let i = 0; i < text.length; i++) {
output[i] = text.charCodeAt(i); output[i] = text.charCodeAt(i);
} }
this._writeSessionData(BLECommand.CMD_DISPLAY_TEXT, output); return this._writeSessionData(BLECommand.CMD_DISPLAY_TEXT, output);
} }
/** /**
* @param {Uint8Array} matrix - the matrix to display. * @param {Uint8Array} matrix - the matrix to display.
* @return {Promise} - a Promise that resolves when writing to device.
*/ */
displayMatrix (matrix) { displayMatrix (matrix) {
this._writeSessionData(BLECommand.CMD_DISPLAY_LED, matrix); return this._writeSessionData(BLECommand.CMD_DISPLAY_LED, matrix);
} }
/** /**
@ -212,6 +214,7 @@ class MicroBit {
* Write a message to the device BLE session. * Write a message to the device BLE session.
* @param {number} command - the BLE command hex. * @param {number} command - the BLE command hex.
* @param {Uint8Array} message - the message to write. * @param {Uint8Array} message - the message to write.
* @return {Promise} - a Promise that resolves when writing to device.
* @private * @private
*/ */
_writeSessionData (command, message) { _writeSessionData (command, message) {
@ -220,8 +223,8 @@ class MicroBit {
for (let i = 0; i < message.length; i++) { for (let i = 0; i < message.length; i++) {
output[i + 1] = message[i]; output[i + 1] = message[i];
} }
const b64enc = Base64Util.uint8ArrayToBase64(output); const data = Base64Util.uint8ArrayToBase64(output);
this._ble.write(BLEUUID.service, BLEUUID.txChar, b64enc, 'base64'); return this._ble.write(BLEUUID.service, BLEUUID.txChar, data, 'base64');
} }
} }
@ -494,17 +497,18 @@ class Scratch3MicroBitBlocks {
/** /**
* Display text on the 5x5 LED matrix. * Display text on the 5x5 LED matrix.
* @param {object} args - the block's arguments. * @param {object} args - the block's arguments.
* @return {Promise} - a Promise that resolves when writing to device.
* Note the limit is 19 characters * Note the limit is 19 characters
*/ */
displayText (args) { displayText (args) {
const text = String(args.TEXT).substring(0, 19); const text = String(args.TEXT).substring(0, 19);
this._device.displayText(text); return this._device.displayText(text);
return;
} }
/** /**
* Display a predefined symbol on the 5x5 LED matrix. * Display a predefined symbol on the 5x5 LED matrix.
* @param {object} args - the block's arguments. * @param {object} args - the block's arguments.
* @return {Promise} - a Promise that resolves when writing to device.
*/ */
displaySymbol (args) { displaySymbol (args) {
const hex = symbols2hex[args.SYMBOL]; const hex = symbols2hex[args.SYMBOL];
@ -514,8 +518,7 @@ class Scratch3MicroBitBlocks {
this._device.ledMatrixState[2] = (hex >> 10) & 0x1F; this._device.ledMatrixState[2] = (hex >> 10) & 0x1F;
this._device.ledMatrixState[3] = (hex >> 5) & 0x1F; this._device.ledMatrixState[3] = (hex >> 5) & 0x1F;
this._device.ledMatrixState[4] = hex & 0x1F; this._device.ledMatrixState[4] = hex & 0x1F;
this._device.displayMatrix(this._device.ledMatrixState); return this._device.displayMatrix(this._device.ledMatrixState);
return;
} }
/** /**

View file

@ -18,6 +18,7 @@ class BLESession extends JSONRPCWebSocket {
this._socketPromise = new Promise((resolve, reject) => { this._socketPromise = new Promise((resolve, reject) => {
this._ws.onopen = resolve; this._ws.onopen = resolve;
this._ws.onerror = this._sendError(); // TODO: socket error? this._ws.onerror = this._sendError(); // TODO: socket error?
// TODO: generally handle socket disconnects as errors
}); });
this._availablePeripherals = {}; this._availablePeripherals = {};
@ -37,18 +38,14 @@ class BLESession extends JSONRPCWebSocket {
requestDevice () { requestDevice () {
// TODO: add timeout for 'no devices yet found' ? // TODO: add timeout for 'no devices yet found' ?
if (this._ws.readyState === 1) { if (this._ws.readyState === 1) {
// TODO: what if discover doesn't initiate?
this.sendRemoteRequest('discover', this._deviceOptions) this.sendRemoteRequest('discover', this._deviceOptions)
.catch(e => { .catch(e => this._sendError(e));
// TODO: what if discover doesn't initiate?
this._sendError(e);
});
} else { } else {
// Try again to connect to the websocket // Try again to connect to the websocket
// TODO: what if discover doesn't initiate?
this._socketPromise(this.sendRemoteRequest('discover', this._deviceOptions)) this._socketPromise(this.sendRemoteRequest('discover', this._deviceOptions))
.catch(e => { .catch(e => this._sendError(e));
// TODO: what if discover doesn't initiate?
this._sendError(e);
});
} }
} }
@ -64,7 +61,7 @@ class BLESession extends JSONRPCWebSocket {
this._connectCallback(); this._connectCallback();
}) })
.catch(e => { .catch(e => {
// TODO: what if the peripheral loses power? // TODO: what if the peripheral loses power? (web socket closes?)
// TODO: what if tries to connect to an unknown peripheral id? // TODO: what if tries to connect to an unknown peripheral id?
this._sendError(e); this._sendError(e);
}); });
@ -77,8 +74,7 @@ class BLESession extends JSONRPCWebSocket {
* @return {object} - optional return value. * @return {object} - optional return value.
*/ */
didReceiveCall (method, params) { didReceiveCall (method, params) {
// TODO: does didReceiveCall receive any errors? // TODO: Add peripheral 'undiscover' handling with timeout?
// TODO: Add peripheral 'undiscover' handling
switch (method) { switch (method) {
case 'didDiscoverPeripheral': case 'didDiscoverPeripheral':
this._availablePeripherals[params.peripheralId] = params; this._availablePeripherals[params.peripheralId] = params;

View file

@ -27,6 +27,10 @@ class JSONRPCWebSocket extends JSONRPC {
_onSocketMessage (e) { _onSocketMessage (e) {
const json = JSON.parse(e.data); const json = JSON.parse(e.data);
if (json.method !== 'characteristicDidChange') {
console.log('received message: ');
console.log(json);
}
this._handleMessage(json); this._handleMessage(json);
} }