scratch-vm/src/extensions/scratch3_gdx_for/scratch-link-device-adapter.js

45 lines
1.2 KiB
JavaScript
Raw Normal View History

const Base64Util = require('../../util/base64-util');
/**
* Adapter class
*/
class ScratchLinkDeviceAdapter {
2019-01-10 10:21:32 -05:00
constructor (scratchLinkSocket, {service, commandChar, responseChar}) {
2019-01-07 18:20:45 -05:00
this.scratchLinkSocket = scratchLinkSocket;
2019-01-10 10:11:46 -05:00
this._service = service;
this._commandChar = commandChar;
this._responseChar = responseChar;
this._onResponse = this._onResponse.bind(this);
this._deviceOnResponse = null;
}
get godirectAdapter () {
return true;
}
writeCommand (commandBuffer) {
const data = Base64Util.uint8ArrayToBase64(commandBuffer);
2019-01-07 18:20:45 -05:00
return this.scratchLinkSocket
.write(this._service, this._commandChar, data, 'base64');
}
2019-01-07 18:09:23 -05:00
setup ({onResponse}) {
this._deviceOnResponse = onResponse;
2019-01-07 18:20:45 -05:00
return this.scratchLinkSocket
2019-01-10 10:11:46 -05:00
.startNotifications(this._service, this._responseChar, this._onResponse);
// TODO:
// How do we find out from scratch link if communication closes?
}
_onResponse (base64) {
const array = Base64Util.base64ToUint8Array(base64);
const response = new DataView(array.buffer);
return this._deviceOnResponse(response);
}
}
module.exports = ScratchLinkDeviceAdapter;