├── .github └── FUNDING.yml ├── LICENSE ├── _config.yml ├── dap.umd.js ├── dap.umd.js.map ├── docs ├── fonts │ ├── OpenSans-Bold-webfont.eot │ ├── OpenSans-Bold-webfont.svg │ ├── OpenSans-Bold-webfont.woff │ ├── OpenSans-BoldItalic-webfont.eot │ ├── OpenSans-BoldItalic-webfont.svg │ ├── OpenSans-BoldItalic-webfont.woff │ ├── OpenSans-Italic-webfont.eot │ ├── OpenSans-Italic-webfont.svg │ ├── OpenSans-Italic-webfont.woff │ ├── OpenSans-Light-webfont.eot │ ├── OpenSans-Light-webfont.svg │ ├── OpenSans-Light-webfont.woff │ ├── OpenSans-LightItalic-webfont.eot │ ├── OpenSans-LightItalic-webfont.svg │ ├── OpenSans-LightItalic-webfont.woff │ ├── OpenSans-Regular-webfont.eot │ ├── OpenSans-Regular-webfont.svg │ └── OpenSans-Regular-webfont.woff ├── global.html ├── index.html ├── scripts │ ├── linenumber.js │ └── prettify │ │ ├── Apache-License-2.0.txt │ │ ├── lang-css.js │ │ └── prettify.js ├── styles │ ├── jsdoc-default.css │ ├── prettify-jsdoc.css │ └── prettify-tomorrow.css └── ubitwebusb.js.html ├── index.html ├── jsdoc.md ├── readme.md ├── style.css └── ubitwebusb.js /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: bsiever 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Bill Siever 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-tactile -------------------------------------------------------------------------------- /dap.umd.js: -------------------------------------------------------------------------------- 1 | !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t=t||self).DAPjs={})}(this,(function(t){"use strict"; 2 | /*! ***************************************************************************** 3 | Copyright (c) Microsoft Corporation. All rights reserved. 4 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 5 | this file except in compliance with the License. You may obtain a copy of the 6 | License at http://www.apache.org/licenses/LICENSE-2.0 7 | 8 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 9 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 10 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 11 | MERCHANTABLITY OR NON-INFRINGEMENT. 12 | 13 | See the Apache Version 2.0 License for specific language governing permissions 14 | and limitations under the License. 15 | ***************************************************************************** */var e=function(t,r){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])})(t,r)};function r(t,r){function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}function n(t,e,r,n){return new(r||(r=Promise))((function(i,s){function o(t){try{c(n.next(t))}catch(t){s(t)}}function u(t){try{c(n.throw(t))}catch(t){s(t)}}function c(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(o,u)}c((n=n.apply(t,e||[])).next())}))}function i(t,e){var r,n,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function u(s){return function(u){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]0&&c.length>i){c.warned=!0;var h=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+e+" listeners added. Use emitter.setMaxListeners() to increase limit");h.name="MaxListenersExceededWarning",h.emitter=t,h.type=e,h.count=c.length,a=h,"function"==typeof console.warn?console.warn(a):console.log(a)}}else c=o[e]=r,++t._eventsCount;return t}function p(t,e,r){var n=!1;function i(){t.removeListener(e,i),n||(n=!0,r.apply(t,arguments))}return i.listener=r,i}function v(t){var e=this._events;if(e){var r=e[t];if("function"==typeof r)return 1;if(r)return r.length}return 0}function w(t,e){for(var r=new Array(e);e--;)r[e]=t[e];return r}s.prototype=Object.create(null),o.EventEmitter=o,o.usingDomains=!1,o.prototype.domain=void 0,o.prototype._events=void 0,o.prototype._maxListeners=void 0,o.defaultMaxListeners=10,o.init=function(){this.domain=null,o.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new s,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this},o.prototype.getMaxListeners=function(){return u(this)},o.prototype.emit=function(t){var e,r,n,i,s,o,u,d="error"===t;if(o=this._events)d=d&&null==o.error;else if(!d)return!1;if(u=this.domain,d){if(e=arguments[1],!u){if(e instanceof Error)throw e;var p=new Error('Uncaught, unspecified "error" event. ('+e+")");throw p.context=e,p}return e||(e=new Error('Uncaught, unspecified "error" event')),e.domainEmitter=this,e.domain=u,e.domainThrown=!1,u.emit("error",e),!1}if(!(r=o[t]))return!1;var v="function"==typeof r;switch(n=arguments.length){case 1:c(r,v,this);break;case 2:a(r,v,this,arguments[1]);break;case 3:h(r,v,this,arguments[1],arguments[2]);break;case 4:f(r,v,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),s=1;s0;)if(r[o]===e||r[o].listener&&r[o].listener===e){u=r[o].listener,i=o;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new s,this;delete n[t]}else!function(t,e){for(var r=e,n=r+1,i=t.length;n0?Reflect.ownKeys(this._events):[]};var y,m=1e7,b=function(){function t(){this.locked=!1}return t.prototype.lock=function(){return n(this,void 0,void 0,(function(){return i(this,(function(t){switch(t.label){case 0:return this.locked?[4,new Promise((function(t){return setTimeout(t,1)}))]:[3,2];case 1:return t.sent(),[3,0];case 2:return this.locked=!0,[2]}}))}))},t.prototype.unlock=function(){this.locked=!1},t}(),g=function(t){function e(e,r,n){void 0===r&&(r=0),void 0===n&&(n=m);var i=t.call(this)||this;i.transport=e,i.mode=r,i.clockFrequency=n,i.connected=!1,i.sendMutex=new b,i.blockSize=i.transport.packetSize-4-1;var s=i.transport.packetSize-2-1;return i.operationCount=Math.floor(s/5),i}return r(e,t),e.prototype.bufferSourceToUint8Array=function(t,e){if(!e)return new Uint8Array([t]);var r=void 0!==e.buffer?e.buffer:e,n=new Uint8Array(r.byteLength+1);return n.set([t]),n.set(new Uint8Array(r),1),n},e.prototype.selectProtocol=function(t){return n(this,void 0,void 0,(function(){var e;return i(this,(function(r){switch(r.label){case 0:return e=2===t?59196:59294,[4,this.swjSequence(new Uint8Array([255,255,255,255,255,255,255]))];case 1:return r.sent(),[4,this.swjSequence(new Uint16Array([e]))];case 2:return r.sent(),[4,this.swjSequence(new Uint8Array([255,255,255,255,255,255,255]))];case 3:return r.sent(),[4,this.swjSequence(new Uint8Array([0]))];case 4:return r.sent(),[2]}}))}))},e.prototype.send=function(t,e){return n(this,void 0,void 0,(function(){var r,n;return i(this,(function(i){switch(i.label){case 0:return r=this.bufferSourceToUint8Array(t,e),[4,this.sendMutex.lock()];case 1:i.sent(),i.label=2;case 2:return i.trys.push([2,,5,6]),[4,this.transport.write(r)];case 3:return i.sent(),[4,this.transport.read()];case 4:if((n=i.sent()).getUint8(0)!==t)throw new Error("Bad response for "+t+" -> "+n.getUint8(0));switch(t){case 3:case 8:case 9:case 10:case 17:case 18:case 19:case 29:case 23:case 24:case 26:case 21:case 22:case 4:if(0!==n.getUint8(1))throw new Error("Bad status for "+t+" -> "+n.getUint8(1))}return[2,n];case 5:return this.sendMutex.unlock(),[7];case 6:return[2]}}))}))},e.prototype.clearAbort=function(t){return void 0===t&&(t=30),n(this,void 0,void 0,(function(){return i(this,(function(e){switch(e.label){case 0:return[4,this.send(8,new Uint8Array([0,t]))];case 1:return e.sent(),[2]}}))}))},e.prototype.dapInfo=function(t){return n(this,void 0,void 0,(function(){var e,r,n,s;return i(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,4]),[4,this.send(0,new Uint8Array([t]))];case 1:if(e=i.sent(),0===(r=e.getUint8(1)))return[2,""];switch(t){case 240:case 254:case 255:case 253:if(1===r)return[2,e.getUint8(2)];if(2===r)return[2,e.getUint16(2)];if(4===r)return[2,e.getUint32(2)]}return n=Array.prototype.slice.call(new Uint8Array(e.buffer,2,r)),[2,String.fromCharCode.apply(null,n)];case 2:return s=i.sent(),[4,this.clearAbort()];case 3:throw i.sent(),s;case 4:return[2]}}))}))},e.prototype.swjSequence=function(t,e){return void 0===e&&(e=8*t.byteLength),n(this,void 0,void 0,(function(){var r,n;return i(this,(function(i){switch(i.label){case 0:r=this.bufferSourceToUint8Array(e,t),i.label=1;case 1:return i.trys.push([1,3,,5]),[4,this.send(18,r)];case 2:return i.sent(),[3,5];case 3:return n=i.sent(),[4,this.clearAbort()];case 4:throw i.sent(),n;case 5:return[2]}}))}))},e.prototype.swjClock=function(t){return n(this,void 0,void 0,(function(){var e;return i(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,4]),[4,this.send(17,new Uint8Array([255&t,(65280&t)>>8,(16711680&t)>>16,(4278190080&t)>>24]))];case 1:return r.sent(),[3,4];case 2:return e=r.sent(),[4,this.clearAbort()];case 3:throw r.sent(),e;case 4:return[2]}}))}))},e.prototype.swjPins=function(t,e,r){return n(this,void 0,void 0,(function(){var n;return i(this,(function(i){switch(i.label){case 0:return i.trys.push([0,2,,4]),[4,this.send(16,new Uint8Array([t,e,255&r,(65280&r)>>8,(16711680&r)>>16,(4278190080&r)>>24]))];case 1:return[2,i.sent().getUint8(1)];case 2:return n=i.sent(),[4,this.clearAbort()];case 3:throw i.sent(),n;case 4:return[2]}}))}))},e.prototype.dapDelay=function(t){return n(this,void 0,void 0,(function(){var e;return i(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,4]),[4,this.send(9,new Uint8Array([255&t,(65280&t)>>8]))];case 1:return r.sent(),[3,4];case 2:return e=r.sent(),[4,this.clearAbort()];case 3:throw r.sent(),e;case 4:return[2]}}))}))},e.prototype.configureTransfer=function(t,e,r){return n(this,void 0,void 0,(function(){var n,s,o;return i(this,(function(i){switch(i.label){case 0:n=new Uint8Array(5),(s=new DataView(n.buffer)).setUint8(0,t),s.setUint16(1,e,!0),s.setUint16(3,r,!0),i.label=1;case 1:return i.trys.push([1,3,,5]),[4,this.send(4,n)];case 2:return i.sent(),[3,5];case 3:return o=i.sent(),[4,this.clearAbort()];case 4:throw i.sent(),o;case 5:return[2]}}))}))},e.prototype.connect=function(){return n(this,void 0,void 0,(function(){var t,e,r;return i(this,(function(n){switch(n.label){case 0:return!0===this.connected?[2]:[4,this.transport.open()];case 1:n.sent(),n.label=2;case 2:return n.trys.push([2,5,,8]),[4,this.send(17,new Uint32Array([this.clockFrequency]))];case 3:return n.sent(),[4,this.send(2,new Uint8Array([this.mode]))];case 4:if(0===(t=n.sent()).getUint8(1)||0!==this.mode&&t.getUint8(1)!==this.mode)throw new Error("Mode not enabled.");return[3,8];case 5:return e=n.sent(),[4,this.clearAbort()];case 6:return n.sent(),[4,this.transport.close()];case 7:throw n.sent(),e;case 8:return n.trys.push([8,11,,13]),[4,this.configureTransfer(0,100,0)];case 9:return n.sent(),[4,this.selectProtocol(1)];case 10:return n.sent(),[3,13];case 11:return r=n.sent(),[4,this.transport.close()];case 12:throw n.sent(),r;case 13:return this.connected=!0,[2]}}))}))},e.prototype.disconnect=function(){return n(this,void 0,void 0,(function(){var t;return i(this,(function(e){switch(e.label){case 0:if(!1===this.connected)return[2];e.label=1;case 1:return e.trys.push([1,3,,5]),[4,this.send(3)];case 2:return e.sent(),[3,5];case 3:return t=e.sent(),[4,this.clearAbort()];case 4:throw e.sent(),t;case 5:return[4,this.transport.close()];case 6:return e.sent(),this.connected=!1,[2]}}))}))},e.prototype.reconnect=function(){return n(this,void 0,void 0,(function(){return i(this,(function(t){switch(t.label){case 0:return[4,this.disconnect()];case 1:return t.sent(),[4,new Promise((function(t){return setTimeout(t,100)}))];case 2:return t.sent(),[4,this.connect()];case 3:return t.sent(),[2]}}))}))},e.prototype.reset=function(){return n(this,void 0,void 0,(function(){var t;return i(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,4]),[4,this.send(10)];case 1:return[2,1===e.sent().getUint8(2)];case 2:return t=e.sent(),[4,this.clearAbort()];case 3:throw e.sent(),t;case 4:return[2]}}))}))},e.prototype.transfer=function(t,e,r,s){return void 0===e&&(e=2),void 0===r&&(r=0),void 0===s&&(s=0),n(this,void 0,void 0,(function(){var n,o,u,c,a,h,f;return i(this,(function(i){switch(i.label){case 0:n="number"==typeof t?[{port:t,mode:e,register:r,value:s}]:t,o=new Uint8Array(2+5*n.length),(u=new DataView(o.buffer)).setUint8(0,0),u.setUint8(1,n.length),n.forEach((function(t,e){var r=2+5*e;u.setUint8(r,t.port|t.mode|t.register),u.setUint32(r+1,t.value||0,!0)})),i.label=1;case 1:return i.trys.push([1,3,,5]),[4,this.send(5,o)];case 2:if((c=i.sent()).getUint8(1)!==n.length)throw new Error("Transfer count mismatch");if(2===(a=c.getUint8(2)))throw new Error("Transfer response WAIT");if(4===a)throw new Error("Transfer response FAULT");if(8===a)throw new Error("Transfer response PROTOCOL_ERROR");if(16===a)throw new Error("Transfer response VALUE_MISMATCH");if(7===a)throw new Error("Transfer response NO_ACK");return"number"==typeof t?[2,c.getUint32(3,!0)]:(h=4*n.length,[2,new Uint32Array(c.buffer.slice(3,3+h))]);case 3:return f=i.sent(),[4,this.clearAbort()];case 4:throw i.sent(),f;case 5:return[2]}}))}))},e.prototype.transferBlock=function(t,e,r){return n(this,void 0,void 0,(function(){var n,s,o,u,c,a,h,f;return i(this,(function(i){switch(i.label){case 0:o=4,"number"==typeof r?(n=r,s=2):(n=r.length,s=0,o+=r.byteLength),u=new Uint8Array(o),(c=new DataView(u.buffer)).setUint8(0,0),c.setUint16(1,n,!0),c.setUint8(3,t|s|e),"number"!=typeof r&&r.forEach((function(t,e){var r=4+4*e;c.setUint32(r,t,!0)})),i.label=1;case 1:return i.trys.push([1,3,,5]),[4,this.send(6,c)];case 2:if((a=i.sent()).getUint16(1,!0)!==n)throw new Error("Transfer count mismatch");if(2===(h=a.getUint8(3)))throw new Error("Transfer response WAIT");if(4===h)throw new Error("Transfer response FAULT");if(8===h)throw new Error("Transfer response PROTOCOL_ERROR");if(7===h)throw new Error("Transfer response NO_ACK");return"number"==typeof r?[2,new Uint32Array(a.buffer.slice(4,4+4*n))]:[3,5];case 3:return f=i.sent(),[4,this.clearAbort()];case 4:throw i.sent(),f;case 5:return[2,void 0]}}))}))},e}(o),A=/[\xc0-\xff][\x80-\xbf]*$/g,C=/[\xc0-\xff][\x80-\xbf]*/g,U=function(){function t(){}return t.prototype.decode=function(t){var e=Array.prototype.slice.call(new Uint8Array(t)),r=String.fromCodePoint.apply(void 0,e);this.partialChar&&(r=""+this.partialChar+r,this.partialChar=void 0);var n=r.match(A);if(n){var i=n[0].length;this.partialChar=r.slice(-i),r=r.slice(0,-i)}return r.replace(C,this.decoderReplacer)},t.prototype.decoderReplacer=function(t){var e=t.codePointAt(0)<<24,r=Math.clz32(~e),n=0,i=t.length,s="";if(r<5&&i>=r){for(e=e<>>24+r,n=1;n>10),56320+(1023&e))):n=0}for(;n0&&setTimeout((function(){if(n)throw n=!1,new Error("Wait timed out")}),e),i.label=1;case 1:return n?[4,t()]:[3,5];case 2:return!0===i.sent()?(n=!1,[2]):r>0?[4,new Promise((function(t){return setTimeout(t,e)}))]:[3,4];case 3:i.sent(),i.label=4;case 4:return[3,1];case 5:return[2]}}))}))},t.prototype.concatTypedArray=function(t){if(1===t.length)return t[0];for(var e=0,r=0,n=t;r0?(s=Math.min(n,Math.floor(this.proxy.blockSize/4)),[4,this.proxy.transferBlock(1,12,s)]):[3,4];case 3:return o=i.sent(),r.push(o),n-=s,[3,2];case 4:return[2,this.concatTypedArray(r)]}}))}))},t.prototype.writeBlock=function(t,e){return n(this,void 0,void 0,(function(){var r,n;return i(this,(function(i){switch(i.label){case 0:return[4,this.transferSequence([this.writeAPCommand(0,587202642),this.writeAPCommand(4,t)])];case 1:i.sent(),r=0,i.label=2;case 2:return r0})))||(e=t[0]),this.interfaceNumber=e.interfaceNumber,!this.alwaysControlTransfer){for(r=e.endpoints,this.endpointIn=void 0,this.endpointOut=void 0,n=0,s=r;n0})))||(e=t[0]),this.interfaceNumber=e.interfaceNumber,!this.alwaysControlTransfer)for(r=e.alternates[0].endpoints,this.endpointIn=void 0,this.endpointOut=void 0,n=0,s=r;n 2 | 3 | 4 | 5 | JSDoc: Global 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Global

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 |
30 | 31 |

32 | 33 | 34 |
35 | 36 |
37 |
38 | 39 | 40 | 41 | 42 | 43 | 44 |
45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 |
78 | 79 | 80 | 81 | 82 |
83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 |

Methods

100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 |

uBitConnectDevice(callback)

108 | 109 | 110 | 111 | 112 | 113 | 114 |
115 | Allow users to select a device to connect to. 116 |
117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 |
Parameters:
127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 |
NameTypeDescription
callback 155 | 156 | 157 | uBitEventCallback 158 | 159 | 160 | 161 | function for device events
173 | 174 | 175 | 176 | 177 | 178 | 179 |
180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 |
Source:
207 |
210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 |
218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 |

uBitDisconnect(device)

245 | 246 | 247 | 248 | 249 | 250 | 251 |
252 | Disconnect from a device 253 |
254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 |
Parameters:
264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 |
NameTypeDescription
device 292 | 293 | 294 | USBDevice 295 | 296 | 297 | 298 | to disconnect from
310 | 311 | 312 | 313 | 314 | 315 | 316 |
317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 |
Source:
344 |
347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 |
355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 |

uBitSend(device, data)

382 | 383 | 384 | 385 | 386 | 387 | 388 |
389 | Send a string to a specific device 390 |
391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 |
Parameters:
401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 |
NameTypeDescription
device 429 | 430 | 431 | USBDevice 432 | 433 | 434 | 435 |
data 452 | 453 | 454 | string 455 | 456 | 457 | 458 | to send (must not include newlines)
470 | 471 | 472 | 473 | 474 | 475 | 476 |
477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 |
Source:
504 |
507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 |
515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 |

Type Definitions

540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 |

uBitEventCallback(event, device, data)

548 | 549 | 550 | 551 | 552 | 553 | 554 |
555 | Callback for micro:bit events 556 | 557 | 558 | Event data varies based on the event string: 559 |
    560 |
  • "connection failure": null
  • 561 |
  • "connected": null
  • 562 |
  • "disconnected": null
  • 563 |
  • "error": error object
  • 564 |
  • "console": { "time":Date object "data":string}
  • 565 |
  • "graph-data": { "time":Date object "graph":string "series":string "data":number}
  • 566 |
  • "graph-event": { "time":Date object "graph":string "series":string "data":string}
  • 567 |
568 |
569 | 570 | 571 | 572 | 573 | 574 | 575 | 576 | 577 | 578 |
Parameters:
579 | 580 | 581 | 582 | 583 | 584 | 585 | 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | 599 | 600 | 601 | 602 | 603 | 604 | 605 | 606 | 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | 623 | 624 | 625 | 626 | 627 | 628 | 629 | 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 | 649 | 650 | 651 | 652 | 660 | 661 | 662 | 663 | 664 | 665 | 666 | 667 | 668 | 669 | 670 |
NameTypeDescription
event 607 | 608 | 609 | string 610 | 611 | 612 | 613 | ("connection failure", "connected", "disconnected", "error", "console", "graph-data", "graph-event" )
device 630 | 631 | 632 | USBDevice 633 | 634 | 635 | 636 | triggering the callback
data 653 | 654 | 655 | * 656 | 657 | 658 | 659 | (event-specific data object). See list above for variants
671 | 672 | 673 | 674 | 675 | 676 | 677 |
678 | 679 | 680 | 681 | 682 | 683 | 684 | 685 | 686 | 687 | 688 | 689 | 690 | 691 | 692 | 693 | 694 | 695 | 696 | 697 | 698 | 699 | 700 | 701 | 702 | 703 | 704 |
Source:
705 |
708 | 709 | 710 | 711 | 712 | 713 | 714 | 715 |
716 | 717 | 718 | 719 | 720 | 721 | 722 | 723 | 724 | 725 | 726 | 727 | 728 | 729 | 730 | 731 | 732 | 733 | 734 | 735 | 736 | 737 | 738 | 739 | 740 |
741 | 742 |
743 | 744 | 745 | 746 | 747 |
748 | 749 | 752 | 753 |
754 | 755 |
756 | Documentation generated by JSDoc 3.6.3 on Sun Oct 20 2019 21:05:08 GMT-0500 (Central Daylight Time) 757 |
758 | 759 | 760 | 761 | 762 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Home 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Home

21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |

30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 |
46 |

uBitWebUSB

47 |

JavaScript functions for interacting with micro:bit microcontrollers over WebUSB 48 | (Only works in Chrome browsers; Pages must be either HTTPS or local to have permission to access USB)

49 |

Main functions are:

50 |
    51 |
  1. uBitConnectDevice(callback): Prompt user to connect to device and provide callback function for device events 52 | 55 |
  2. 56 |
  3. uBitSend(device): Send data (a string) to a micro:bit
  4. 57 |
  5. uBitDisconnect(device): Disconnect from the designated micro:bit
  6. 58 |
59 |
60 | 61 | 62 | 63 | 64 | 65 | 66 |
67 | 68 | 71 | 72 |
73 | 74 |
75 | Documentation generated by JSDoc 3.6.3 on Sun Oct 20 2019 21:05:08 GMT-0500 (Central Daylight Time) 76 |
77 | 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /docs/scripts/linenumber.js: -------------------------------------------------------------------------------- 1 | /*global document */ 2 | (() => { 3 | const source = document.getElementsByClassName('prettyprint source linenums'); 4 | let i = 0; 5 | let lineNumber = 0; 6 | let lineId; 7 | let lines; 8 | let totalLines; 9 | let anchorHash; 10 | 11 | if (source && source[0]) { 12 | anchorHash = document.location.hash.substring(1); 13 | lines = source[0].getElementsByTagName('li'); 14 | totalLines = lines.length; 15 | 16 | for (; i < totalLines; i++) { 17 | lineNumber++; 18 | lineId = `line${lineNumber}`; 19 | lines[i].id = lineId; 20 | if (lineId === anchorHash) { 21 | lines[i].className += ' selected'; 22 | } 23 | } 24 | } 25 | })(); 26 | -------------------------------------------------------------------------------- /docs/scripts/prettify/Apache-License-2.0.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /docs/scripts/prettify/lang-css.js: -------------------------------------------------------------------------------- 1 | PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\f\r ]+/,null," \t\r\n "]],[["str",/^"(?:[^\n\f\r"\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*"/,null],["str",/^'(?:[^\n\f\r'\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*'/,null],["lang-css-str",/^url\(([^"')]*)\)/i],["kwd",/^(?:url|rgb|!important|@import|@page|@media|@charset|inherit)(?=[^\w-]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*)\s*:/i],["com",/^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//],["com", 2 | /^(?:<\!--|--\>)/],["lit",/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],["lit",/^#[\da-f]{3,6}/i],["pln",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i],["pun",/^[^\s\w"']+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[["kwd",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[["str",/^[^"')]+/]]),["css-str"]); 3 | -------------------------------------------------------------------------------- /docs/scripts/prettify/prettify.js: -------------------------------------------------------------------------------- 1 | var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; 2 | (function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= 3 | [],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), 9 | l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, 10 | q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, 11 | q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, 12 | "");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), 13 | a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} 14 | for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], 18 | "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], 19 | H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], 20 | J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ 21 | I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), 22 | ["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", 23 | /^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), 24 | ["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", 25 | hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= 26 | !k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p th:last-child { border-right: 1px solid #ddd; } 224 | 225 | .ancestors, .attribs { color: #999; } 226 | .ancestors a, .attribs a 227 | { 228 | color: #999 !important; 229 | text-decoration: none; 230 | } 231 | 232 | .clear 233 | { 234 | clear: both; 235 | } 236 | 237 | .important 238 | { 239 | font-weight: bold; 240 | color: #950B02; 241 | } 242 | 243 | .yes-def { 244 | text-indent: -1000px; 245 | } 246 | 247 | .type-signature { 248 | color: #aaa; 249 | } 250 | 251 | .name, .signature { 252 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 253 | } 254 | 255 | .details { margin-top: 14px; border-left: 2px solid #DDD; } 256 | .details dt { width: 120px; float: left; padding-left: 10px; padding-top: 6px; } 257 | .details dd { margin-left: 70px; } 258 | .details ul { margin: 0; } 259 | .details ul { list-style-type: none; } 260 | .details li { margin-left: 30px; padding-top: 6px; } 261 | .details pre.prettyprint { margin: 0 } 262 | .details .object-value { padding-top: 0; } 263 | 264 | .description { 265 | margin-bottom: 1em; 266 | margin-top: 1em; 267 | } 268 | 269 | .code-caption 270 | { 271 | font-style: italic; 272 | font-size: 107%; 273 | margin: 0; 274 | } 275 | 276 | .source 277 | { 278 | border: 1px solid #ddd; 279 | width: 80%; 280 | overflow: auto; 281 | } 282 | 283 | .prettyprint.source { 284 | width: inherit; 285 | } 286 | 287 | .source code 288 | { 289 | font-size: 100%; 290 | line-height: 18px; 291 | display: block; 292 | padding: 4px 12px; 293 | margin: 0; 294 | background-color: #fff; 295 | color: #4D4E53; 296 | } 297 | 298 | .prettyprint code span.line 299 | { 300 | display: inline-block; 301 | } 302 | 303 | .prettyprint.linenums 304 | { 305 | padding-left: 70px; 306 | -webkit-user-select: none; 307 | -moz-user-select: none; 308 | -ms-user-select: none; 309 | user-select: none; 310 | } 311 | 312 | .prettyprint.linenums ol 313 | { 314 | padding-left: 0; 315 | } 316 | 317 | .prettyprint.linenums li 318 | { 319 | border-left: 3px #ddd solid; 320 | } 321 | 322 | .prettyprint.linenums li.selected, 323 | .prettyprint.linenums li.selected * 324 | { 325 | background-color: lightyellow; 326 | } 327 | 328 | .prettyprint.linenums li * 329 | { 330 | -webkit-user-select: text; 331 | -moz-user-select: text; 332 | -ms-user-select: text; 333 | user-select: text; 334 | } 335 | 336 | .params .name, .props .name, .name code { 337 | color: #4D4E53; 338 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 339 | font-size: 100%; 340 | } 341 | 342 | .params td.description > p:first-child, 343 | .props td.description > p:first-child 344 | { 345 | margin-top: 0; 346 | padding-top: 0; 347 | } 348 | 349 | .params td.description > p:last-child, 350 | .props td.description > p:last-child 351 | { 352 | margin-bottom: 0; 353 | padding-bottom: 0; 354 | } 355 | 356 | .disabled { 357 | color: #454545; 358 | } 359 | -------------------------------------------------------------------------------- /docs/styles/prettify-jsdoc.css: -------------------------------------------------------------------------------- 1 | /* JSDoc prettify.js theme */ 2 | 3 | /* plain text */ 4 | .pln { 5 | color: #000000; 6 | font-weight: normal; 7 | font-style: normal; 8 | } 9 | 10 | /* string content */ 11 | .str { 12 | color: #006400; 13 | font-weight: normal; 14 | font-style: normal; 15 | } 16 | 17 | /* a keyword */ 18 | .kwd { 19 | color: #000000; 20 | font-weight: bold; 21 | font-style: normal; 22 | } 23 | 24 | /* a comment */ 25 | .com { 26 | font-weight: normal; 27 | font-style: italic; 28 | } 29 | 30 | /* a type name */ 31 | .typ { 32 | color: #000000; 33 | font-weight: normal; 34 | font-style: normal; 35 | } 36 | 37 | /* a literal value */ 38 | .lit { 39 | color: #006400; 40 | font-weight: normal; 41 | font-style: normal; 42 | } 43 | 44 | /* punctuation */ 45 | .pun { 46 | color: #000000; 47 | font-weight: bold; 48 | font-style: normal; 49 | } 50 | 51 | /* lisp open bracket */ 52 | .opn { 53 | color: #000000; 54 | font-weight: bold; 55 | font-style: normal; 56 | } 57 | 58 | /* lisp close bracket */ 59 | .clo { 60 | color: #000000; 61 | font-weight: bold; 62 | font-style: normal; 63 | } 64 | 65 | /* a markup tag name */ 66 | .tag { 67 | color: #006400; 68 | font-weight: normal; 69 | font-style: normal; 70 | } 71 | 72 | /* a markup attribute name */ 73 | .atn { 74 | color: #006400; 75 | font-weight: normal; 76 | font-style: normal; 77 | } 78 | 79 | /* a markup attribute value */ 80 | .atv { 81 | color: #006400; 82 | font-weight: normal; 83 | font-style: normal; 84 | } 85 | 86 | /* a declaration */ 87 | .dec { 88 | color: #000000; 89 | font-weight: bold; 90 | font-style: normal; 91 | } 92 | 93 | /* a variable name */ 94 | .var { 95 | color: #000000; 96 | font-weight: normal; 97 | font-style: normal; 98 | } 99 | 100 | /* a function name */ 101 | .fun { 102 | color: #000000; 103 | font-weight: bold; 104 | font-style: normal; 105 | } 106 | 107 | /* Specify class=linenums on a pre to get line numbering */ 108 | ol.linenums { 109 | margin-top: 0; 110 | margin-bottom: 0; 111 | } 112 | -------------------------------------------------------------------------------- /docs/styles/prettify-tomorrow.css: -------------------------------------------------------------------------------- 1 | /* Tomorrow Theme */ 2 | /* Original theme - https://github.com/chriskempson/tomorrow-theme */ 3 | /* Pretty printing styles. Used with prettify.js. */ 4 | /* SPAN elements with the classes below are added by prettyprint. */ 5 | /* plain text */ 6 | .pln { 7 | color: #4d4d4c; } 8 | 9 | @media screen { 10 | /* string content */ 11 | .str { 12 | color: #718c00; } 13 | 14 | /* a keyword */ 15 | .kwd { 16 | color: #8959a8; } 17 | 18 | /* a comment */ 19 | .com { 20 | color: #8e908c; } 21 | 22 | /* a type name */ 23 | .typ { 24 | color: #4271ae; } 25 | 26 | /* a literal value */ 27 | .lit { 28 | color: #f5871f; } 29 | 30 | /* punctuation */ 31 | .pun { 32 | color: #4d4d4c; } 33 | 34 | /* lisp open bracket */ 35 | .opn { 36 | color: #4d4d4c; } 37 | 38 | /* lisp close bracket */ 39 | .clo { 40 | color: #4d4d4c; } 41 | 42 | /* a markup tag name */ 43 | .tag { 44 | color: #c82829; } 45 | 46 | /* a markup attribute name */ 47 | .atn { 48 | color: #f5871f; } 49 | 50 | /* a markup attribute value */ 51 | .atv { 52 | color: #3e999f; } 53 | 54 | /* a declaration */ 55 | .dec { 56 | color: #f5871f; } 57 | 58 | /* a variable name */ 59 | .var { 60 | color: #c82829; } 61 | 62 | /* a function name */ 63 | .fun { 64 | color: #4271ae; } } 65 | /* Use higher contrast and text-weight for printable form. */ 66 | @media print, projection { 67 | .str { 68 | color: #060; } 69 | 70 | .kwd { 71 | color: #006; 72 | font-weight: bold; } 73 | 74 | .com { 75 | color: #600; 76 | font-style: italic; } 77 | 78 | .typ { 79 | color: #404; 80 | font-weight: bold; } 81 | 82 | .lit { 83 | color: #044; } 84 | 85 | .pun, .opn, .clo { 86 | color: #440; } 87 | 88 | .tag { 89 | color: #006; 90 | font-weight: bold; } 91 | 92 | .atn { 93 | color: #404; } 94 | 95 | .atv { 96 | color: #060; } } 97 | /* Style */ 98 | /* 99 | pre.prettyprint { 100 | background: white; 101 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 102 | font-size: 12px; 103 | line-height: 1.5; 104 | border: 1px solid #ccc; 105 | padding: 10px; } 106 | */ 107 | 108 | /* Specify class=linenums on a pre to get line numbering */ 109 | ol.linenums { 110 | margin-top: 0; 111 | margin-bottom: 0; } 112 | 113 | /* IE indents via margin-left */ 114 | li.L0, 115 | li.L1, 116 | li.L2, 117 | li.L3, 118 | li.L4, 119 | li.L5, 120 | li.L6, 121 | li.L7, 122 | li.L8, 123 | li.L9 { 124 | /* */ } 125 | 126 | /* Alternate shading for lines */ 127 | li.L1, 128 | li.L3, 129 | li.L5, 130 | li.L7, 131 | li.L9 { 132 | /* */ } 133 | -------------------------------------------------------------------------------- /docs/ubitwebusb.js.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Source: ubitwebusb.js 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Source: ubitwebusb.js

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 |
29 |

 30 | /*
 31 |  * JavaScript functions for interacting with micro:bit microcontrollers over WebUSB
 32 |  * (Only works in Chrome browsers;  Pages must be either HTTPS or local)
 33 |  */
 34 | 
 35 | // Add a delay() method to promises 
 36 | // NOTE: I found this on-line somewhere but didn't note the source and haven't been able to find it!
 37 | Promise.delay = function(duration){
 38 |     return new Promise(function(resolve, reject){
 39 |         setTimeout(function(){
 40 |             resolve();
 41 |         }, duration)
 42 |     });
 43 | }
 44 | 
 45 | const MICROBIT_VENDOR_ID = 0x0d28
 46 | const MICROBIT_PRODUCT_ID = 0x0204
 47 | const MICROBIT_DAP_INTERFACE = 4
 48 | 
 49 | const controlTransferGetReport = 0x01
 50 | const controlTransferSetReport = 0x09
 51 | const controlTransferOutReport = 0x200
 52 | const controlTransferInReport = 0x100
 53 | 
 54 | const uBitBadMessageDelay = 500         // Delay if message failed
 55 | const uBitIncompleteMessageDelay = 150  // Delay if no message ready now
 56 | const uBitGoodMessageDelay = 20         // Time to try again if message was good
 57 | 
 58 | 
 59 | const DAPOutReportRequest = {
 60 |     requestType: "class",
 61 |     recipient: "interface",
 62 |     request: controlTransferSetReport,
 63 |     value: controlTransferOutReport,
 64 |     index: MICROBIT_DAP_INTERFACE
 65 | }
 66 | 
 67 | const DAPInReportRequest =  {
 68 |     requestType: "class",
 69 |     recipient: "interface",
 70 |     request: controlTransferGetReport,
 71 |     value: controlTransferInReport,
 72 |     index: MICROBIT_DAP_INTERFACE
 73 | }
 74 | 
 75 | 
 76 | /*
 77 |    Open and configure a selected device and then start the read-loop
 78 |  */
 79 | function uBitOpenDevice(device, callback) {
 80 |     function controlTransferOutFN(data) {
 81 |         return () => { return device.controlTransferOut(DAPOutReportRequest, data) }
 82 |     }
 83 | 
 84 |     let buffer=""
 85 |     let decoder = new TextDecoder("utf-8")
 86 |     const parser = /([^.:]*)\.*([^:]+|):(.*)/
 87 | 
 88 |     let transferLoop = function () {
 89 |         device.controlTransferOut(DAPOutReportRequest, Uint8Array.from([0x83])) // DAP ID_DAP_Vendor3: https://github.com/ARMmbed/DAPLink/blob/0711f11391de54b13dc8a628c80617ca5d25f070/source/daplink/cmsis-dap/DAP_vendor.c
 90 |         .then(() => device.controlTransferIn(DAPInReportRequest, 64))
 91 |         .then((data) => { 
 92 |             if (data.status != "ok") {
 93 |                 return Promise.delay(uBitBadMessageDelay).then(transferLoop);
 94 |             }
 95 |             // First byte is echo of get UART command
 96 | 
 97 |             let arr = new Uint8Array(data.data.buffer)
 98 |             if(arr.length<2)  // Not a valid array: Delay
 99 |                 return Promise.delay(uBitIncompleteMessageDelay).then(transferLoop)
100 | 
101 |             // Data: Process and get more
102 |             let len = arr[1]  // Second byte is length of remaining message
103 |             if(len==0) // If no data: delay
104 |                 return Promise.delay(uBitIncompleteMessageDelay).then(transferLoop)
105 |             
106 |             let msg = arr.slice(2,2+len)
107 |             let string =  decoder.decode(msg);
108 |             buffer += string;
109 |             let firstNewline = buffer.indexOf("\n")
110 |             while(firstNewline>=0) {
111 |                 let messageToNewline = buffer.slice(0,firstNewline)
112 |                 let now = new Date() 
113 |                 // Deal with line
114 |                 // If it's a graph/series format, break it into parts
115 |                 let parseResult = parser.exec(messageToNewline)
116 |                 if(parseResult) {
117 |                     let graph = parseResult[1]
118 |                     let series = parseResult[2]
119 |                     let data = parseResult[3]
120 |                     let callbackType = "graph-event"
121 |                     // If data is numeric, it's a data message and should be sent as numbers
122 |                     if(!isNaN(data)) {
123 |                         callbackType = "graph-data"
124 |                         data = parseFloat(data)
125 |                     }
126 |                     // Build and send the bundle
127 |                     let dataBundle = {
128 |                         time: now,
129 |                         graph: graph, 
130 |                         series: series, 
131 |                         data: data
132 |                     }
133 |                     callback(callbackType, device, dataBundle)
134 |                 } else {
135 |                     // Not a graph format.  Send it as a console bundle
136 |                     let dataBundle = {time: now, data: messageToNewline}
137 |                     callback("console", device, dataBundle)
138 |                 }
139 | 
140 |                 buffer = buffer.slice(firstNewline+1)
141 |                 firstNewline = buffer.indexOf("\n")
142 |             }
143 |             // Delay long enough for complete message
144 |             return Promise.delay(uBitGoodMessageDelay).then(transferLoop);
145 |         })
146 |         // Error here probably means micro:bit disconnected
147 |         .catch(error => { if(device.opened) callback("error", device, error); device.close(); callback("disconnected", device, null);});
148 |     }
149 | 
150 |     device.open()
151 |         .then(() => device.selectConfiguration(1))
152 |         .then(() => device.claimInterface(4))
153 |         .then(controlTransferOutFN(Uint8Array.from([0x82, 0x00, 0xc2, 0x01, 0x00]))) // Vendor Specific command 2 (ID_DAP_Vendor2): https://github.com/ARMmbed/DAPLink/blob/0711f11391de54b13dc8a628c80617ca5d25f070/source/daplink/cmsis-dap/DAP_vendor.c ;  0x0001c200 = 115,200kBps
154 |         .then( () => { callback("connected", device, null); return Promise.resolve()}) 
155 |         .then(transferLoop)
156 |         .catch(error => callback("error", device, error))
157 | }
158 | 
159 | /**
160 |  * Disconnect from a device 
161 |  * @param {USBDevice} device to disconnect from 
162 |  */
163 | function uBitDisconnect(device) {
164 |     if(device && device.opened) {
165 |         device.close()
166 |     }
167 | }
168 | 
169 | /**
170 |  * Send a string to a specific device
171 |  * @param {USBDevice} device 
172 |  * @param {string} data to send (must not include newlines)
173 |  */
174 | function uBitSend(device, data) {
175 |     if(!device.opened)
176 |         return
177 |     // Need to send 0x84 (command), length (including newline), data's characters, newline
178 |     let fullLine = data+'\n'
179 |     let encoded = new TextEncoder("utf-8").encode(fullLine)
180 |     let message = new Uint8Array(1+1+fullLine.length)
181 |     message[0] = 0x84
182 |     message[1] = encoded.length
183 |     message.set(encoded, 2)
184 |     device.controlTransferOut(DAPOutReportRequest, message) // DAP ID_DAP_Vendor3: https://github.com/ARMmbed/DAPLink/blob/0711f11391de54b13dc8a628c80617ca5d25f070/source/daplink/cmsis-dap/DAP_vendor.c
185 | }
186 | 
187 | 
188 | /**
189 |  * Callback for micro:bit events
190 |  * 
191 |  
192 |    Event data varies based on the event string:
193 |   <ul>
194 |    <li>"connection failure": null</li>
195 |    <li>"connected": null</li>
196 |    <li>"disconnected": null</li>
197 |    <li>"error": error object</li>
198 |    <li>"console":  { "time":Date object "data":string}</li>
199 |    <li>"graph-data": { "time":Date object "graph":string "series":string "data":number}</li>
200 |    <li>"graph-event": { "time":Date object "graph":string "series":string "data":string}</li>
201 |   </ul>
202 | 
203 |  * @callback uBitEventCallback
204 |  * @param {string} event ("connection failure", "connected", "disconnected", "error", "console", "graph-data", "graph-event" )
205 |  * @param {USBDevice} device triggering the callback
206 |  * @param {*} data (event-specific data object). See list above for variants
207 |  * 
208 |  */
209 | 
210 | 
211 | /**
212 |  * Allow users to select a device to connect to.
213 |  * 
214 |  * @param {uBitEventCallback} callback function for device events
215 |  */
216 | function uBitConnectDevice(callback) { 
217 |     navigator.usb.requestDevice({filters: [{ vendorId: MICROBIT_VENDOR_ID, productId: 0x0204 }]})
218 |         .then(  d => { if(!d.opened) uBitOpenDevice(d, callback)} )
219 |         .catch( () => callback("connection failure", null, null))
220 | }
221 | 
222 |
223 |
224 | 225 | 226 | 227 | 228 |
229 | 230 | 233 | 234 |
235 | 236 |
237 | Documentation generated by JSDoc 3.6.3 on Sun Oct 20 2019 21:05:08 GMT-0500 (Central Daylight Time) 238 |
239 | 240 | 241 | 242 | 243 | 244 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Micro:bit WebUSB Console 7 | 8 | 9 | 10 |
11 |
12 | 13 |
14 |
15 | 16 |
17 |
18 | 19 |
20 |
21 | 22 |
23 | 24 |
25 | Waiting for connection. 26 |
27 |
28 | 29 | 30 | 31 | 32 | 33 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /jsdoc.md: -------------------------------------------------------------------------------- 1 | 2 | # uBitWebUSB 3 | 4 | JavaScript functions for interacting with micro:bit microcontrollers over WebUSB 5 | (Only works in Chrome browsers; Pages must be either HTTPS or local to have permission to access USB) 6 | 7 | Main functions are: 8 | 9 | 1. [`uBitConnectDevice(callback)`](./global.html#uBitConnectDevice): Prompt user to connect to device and provide callback function for device events 10 | * See [`uBitEventCallback`](./global.html#uBitEventCallback) for callback format and argument descriptions. 11 | 2. [`uBitSend(device)`](./global.html#uBitSend): Send data (a `string`) to a micro:bit 12 | 3. [`uBitDisconnect(device)`](./global.html#uBitDisconnect): Disconnect from the designated `micro:bit` 13 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | 2 | # Overview 3 | 4 | This provides an API for interacting with the micro:bit over USB. It also includes a demo application to show how it works. 5 | 6 | # Files / Manifest 7 | 8 | * `ubitwebusb.js`: The actual API (the only file needed for other applications) 9 | * Demo application (a web-based console that shows the different messages) 10 | * [`index.html`](https://github.com/bsiever/microbit-webusb/blob/master/index.html): HTML with in-line JavaScript for the application 11 | * [View Live Version](https://bsiever.github.io/microbit-webusb/) *Only works in Chrome* 12 | * `style.css` 13 | * Requires `ubitwebusb.js` 14 | * Documentation files 15 | * [`readme.md`](https://github.com/bsiever/microbit-webusb/blob/master/readme.md): Overview of project 16 | * [`docs`](https://bsiever.github.io/microbit-webusb/docs/): Directory including JSDoc documentation 17 | * `jsdoc.md`: Initial page / readme for JSDocs 18 | * `_config.yml`: GitHub pages config 19 | * `dap.umd.js`: [DAP.js](https://github.com/ARMmbed/dapjs) version 2.3 20 | * `dap.umd.js.map`: Source map for above. 21 | * [`LICENSE`](./LICENSE): MIT License 22 | 23 | # Overall Setup 24 | 25 | 1. Upgrade Micro:bit to latest firmware 26 | 2. Program the Micro:bit with one of the example programs that generates serial data 27 | 3. Setup a Web Server & Open the project's page to run the sample application ([`index.html`](./index.html)) ([Live Example of it](https://bsiever.github.io/microbit-webusb/)) (Can just open the `index.html` locally with current version) 28 | 29 | ## Upgrade Micro:bit to latest firmware 30 | 31 | This should only be needed one time for each micro:bit. 32 | 33 | Upgrade the micro:bit firmware as describe at: [Updating your micro:bit firmware 34 | ](https://microbit.org/guide/firmware/) 35 | 36 | ## Program the Micro:bit from Shared Project 37 | 38 | 1. Plug the Micro:bit into the computer 39 | 2. Open [https://makecode.microbit.org/_Pya288iq3eo2](https://makecode.microbit.org/_Pya288iq3eo2) 40 | 3. Select the Gear Menu in the upper right 41 | 4. Select the `Pair Device` option 42 | 5. Select `Pair Device` 43 | 6. Select the Micro:bit device 44 | 7. Download the code (Blue Download button at the bottom of the window) 45 | 8. See what data looks like with Makecode's existing graphs via the `Console Simulator` or `Console Device` buttons in the simulator. 46 | 9. Unplug/re-plug Micro:bit (to Un-Pair device) 47 | 48 | The micro:bit retains it's program until it is explicitly re-programmed or the firmware is upgraded. This programming process won't need to be repeated unless a different program is desired (which may be needed to demonstrate different the different ways to annotate graphs) 49 | 50 | ## Program the Micro:bit from JavaScript Source 51 | 52 | This is an alternative to the above. Either can be done, but there's no reason to do both. 53 | 54 | The program below will send serial data and can be used for initial testing/debugging. 55 | 56 | 1. Connect USB cable 57 | 2. Open the [MakeCode Editor](https://makecode.microbit.org/#editor) 58 | 3. Select JavaScript from the Blocks/JavaScript slider. 59 | 4. Paste in the code above 60 | ```javascript 61 | serial.onDataReceived(serial.delimiters(Delimiters.NewLine), function () { 62 | serial.writeLine("echo " + serial.readUntil(serial.delimiters(Delimiters.NewLine))) 63 | }) 64 | basic.forever(function () { 65 | serial.writeValue("x", Math.map(Math.randomRange(0, 100), 0, 100, -2.4, 18.2)) 66 | serial.writeValue("y data", Math.randomRange(0, 10)) 67 | serial.writeValue("graph2.a", Math.randomRange(-5, 10)) 68 | serial.writeValue("graph2.b data", Math.randomRange(-5, 10)) 69 | if (Math.randomRange(0, 10) == 5) { 70 | serial.writeLine("x:\"Hi\"") 71 | } 72 | if (Math.randomRange(0, 50) == 5) { 73 | serial.writeLine("console log") 74 | } 75 | basic.pause(500) 76 | }) 77 | ``` 78 | 5. Select the Gear Menu in the upper right 79 | 6. Select the `Pair Device` option 80 | 7. Select `Pair Device` 81 | 8. Select the Micro:bit device 82 | 9. Download the code (Blue Download button at the bottom of the window) 83 | 10. See what data looks like with Makecode's existing graphs via the `Console Simulator` or `Console Device` buttons in the simulator. 84 | 11. Unplug/re-plug Micro:bit (to Un-Pair device) 85 | 86 | 87 | # Open `index.html` locally 88 | 89 | 1. In browser go to file>open and browse to `index.html` or right-click on `index.html` and use file navigation to open in a browser. 90 | # Setup a Web Server 91 | 92 | 1. Install a local web server 93 | 1. Python 3 / Python: Use `pip` or `pip3` to install the `http` package. (ex: Open a terminal window / command prompt and run `pip install http`) 94 | 2. Run the `http.server` module in the directory containing the project: `python -m http.server` or `python3 -m http.server` as appropriate. 95 | 96 | ## Open the project's page 97 | 98 | 1. Open browser to [http://localhost:8000/](http://localhost:8000/) (Default page for Python Server) 99 | 2. Make sure the micro:bit is connected via the USB cable 100 | 3. Click on `Connect` 101 | 4. Select the micro:bit from the pop-up menu that appears 102 | 103 | # API 104 | 105 | ## Summary 106 | 107 | There are three main functions: 108 | 1. [`uBitConnectDevice(callback)`](https://bsiever.github.io/microbit-webusb/docs/global.html#uBitConnectDevice): Prompt user to connect to device and provide callback function for device events 109 | * See [`uBitEventCallback`](https://bsiever.github.io/microbit-webusb/docs/global.html#uBitEventCallback) for callback format and argument descriptions. 110 | 2. [`uBitSend(device)`](https://bsiever.github.io/microbit-webusb/docs/global.html#uBitSend): Send data (a `string`) to a micro:bit 111 | 3. [`uBitDisconnect(device)`](https://bsiever.github.io/microbit-webusb/docs/global.html#uBitDisconnect): Disconnect from the designated `micro:bit` 112 | 113 | ## JSDocs: Documentation on the functions 114 | 115 | [JSDocs Here](https://bsiever.github.io/microbit-webusb/docs/index.html) 116 | 117 | ## Example 118 | 119 | See [`index.html`](./index.html) for a complete example application. 120 | 121 | # Technical Details and Notes 122 | 123 | Now uses [DAP.js](https://github.com/ARMmbed/dapjs) for DAPLink (serial) interactions and events. 124 | 125 | ## Communication and App Message Formats 126 | 127 | ### Graph Message Types and Formats 128 | 129 | Data may be shown in a combination of zero or more graphs that show a single series and zero or more graphs that show multiple series. There may also be "events" (descriptive items with a string) 130 | 131 | The number of graphs and series will now be known in advance. It must be determined from the streaming data. 132 | 133 | ### Values for a graph with a single series 134 | 135 | Format: `NAME:NUMBER` 136 | * `NAME` is a string name of the graph (and the name of the series) 137 | * `NUMBER` is a numeric value to graph 138 | 139 | Format: `NAME:STRING` 140 | * `NAME` is a string name of the graph 141 | * `String` is a string for an event 142 | 143 | ### Values for a graph with multiple series 144 | 145 | Format: `NAME.SERIES:NUMBER` 146 | * `NAME` is a string name of the graph (and the name of the series) 147 | * `SERIES` is a string name of the series for the data 148 | * `NUMBER` is a numeric value to graph 149 | 150 | Format: `NAME.SERIES:STRING` 151 | * `NAME` is a string name of the graph 152 | * `SERIES` is a string name of the series for the data 153 | * `String` is a string for an event 154 | 155 | ### Console messages 156 | 157 | Any message that doesn't include a colon is a console message. Console messages should end with a newline (`\n`), which will be sent implicitly with `serial write line` (*not* `serial write`). Ex: `This is a message` sent via `serial write line`. 158 | 159 | ## Micro:bit USB & Console Data 160 | 161 | The micro:bit console messages (`serial write` blocks and `serial.*` TypeScript commands) are directed over the USB interface. They actually go through ARM's [CMSIS-DAP](https://arm-software.github.io/CMSIS_5/DAP/html/index.html). DAP is described as: 162 | > CMSIS-DAP is a specification and a implementation of a Firmware that supports access to the CoreSight Debug Access Port (DAP). 163 | 164 | DAP has several [well defined commands](https://arm-software.github.io/CMSIS_5/DAP/html/group__DAP__Commands__gr.html) as well as the ability to support custom vendor commands. Messages begin with a byte indicating the command type. The firmware in the micro:bit supports two custom messages that are used to configure the baud rate. 165 | 166 | 167 | ## DAPJS 168 | 169 | Current work uses [DAPJS](https://github.com/ARMmbed/dapjs). 170 | 171 | Get the DAPJS file: 172 | 173 | ``` 174 | mkdir temp 175 | cd temp 176 | npm install dapjs 177 | cp node_modules/dapjs/dist/dap.umd.js .. 178 | cp node_modules/dapjs/dist/dap.umd.js.map .. 179 | cd .. 180 | rm -Rf temp 181 | ``` 182 | 183 | # To Re-generate API Docs 184 | 185 | `jsdoc ubitwebusb.js -r jsdoc.md -d docs` 186 | 187 | 188 | 189 | --- 190 | # Below is old / historical data from prior versions 191 | --- 192 | # Below is old info from sniffing out USB UART 193 | 194 | ## Micro:bit USB Configuration Sequence 195 | 196 | Immediately after connection to micro:bit (this assumes the connected device is a micro:bit and all control transfers in/out go to endpoint 4, the CMSIS-DAP endpoint): 197 | 198 | 1. Select device configuration 1 199 | 2. Claim interface 4 (CMSIS-DAP) 200 | 3. Control Transfer Out [DAP Vendor Specific Command (`ID_DAP_Vendor2` or `0x82`)](https://github.com/ARMmbed/DAPLink/blob/0711f11391de54b13dc8a628c80617ca5d25f070/source/daplink/cmsis-dap/DAP_vendor.c) to set the UART baud to 115,200bps 201 | * Bytes: `[[0x82, 0x00, 0xc2, 0x01, 0x00]` 202 | 203 | ### Old version (not necessary) 204 | 205 | This approach was based on the sequence sent from Makecode, but it doesn't appear that the majority of it is necessary. 206 | 207 | 1. Select device configuration 1 208 | 2. Claim interface 4 (CMSIS-DAP) 209 | 3. Control Transfer Out [`DAP_Connect`](https://arm-software.github.io/CMSIS_5/DAP/html/group__DAP__Connect.html) to default (connect the default device) 210 | * Bytes: `[2, 0]` 211 | 4. Control Transfer Out [`DAP_SWJ_Clock`](https://arm-software.github.io/CMSIS_5/DAP/html/group__DAP__SWJ__Clock.html) to 10MHz 212 | * Bytes: `[0x11, 0x80, 0x96, 0x98, 0]` 213 | 5. Control Transfer Out [`DAP_SWD_Configure`](https://arm-software.github.io/CMSIS_5/DAP/html/group__DAP__SWD__Configure.html) to configure the software debug (1 clock turn around, no Wait/Fault phases) 214 | * Bytes: `[0x13, 0]]` 215 | 3. Control Transfer Out [DAP Vendor Specific Command (`ID_DAP_Vendor2` or `0x82`)](https://github.com/ARMmbed/DAPLink/blob/0711f11391de54b13dc8a628c80617ca5d25f070/source/daplink/cmsis-dap/DAP_vendor.c) to set the UART baud to 115,200bps 216 | * Bytes: `[[0x82, 0x00, 0xc2, 0x01, 0x00]` 217 | 218 | ## Micro:bit USB UART Data Read 219 | 220 | 1. Control Transfer Out [DAP Vendor Specific Command (`ID_DAP_VEndor3` or `0x83`)](https://github.com/ARMmbed/DAPLink/blob/0711f11391de54b13dc8a628c80617ca5d25f070/source/daplink/cmsis-dap/DAP_vendor.c) request UART data up to 64 bytes. 221 | 2. Control Transfer In of up to 64 bytes. 222 | * 1st byte is repeat of command (`0x83`) 223 | * 2nd byte is length of string 224 | * Remaining bytes (2..2+length) are utf-8 string 225 | 226 | ## Micro:bit USB UART Data Write 227 | 228 | 1. Control Transfer Out [DAP Vendor Specific Command (`ID_DAP_VEndor4` or `0x84`)](https://github.com/ARMmbed/DAPLink/blob/0711f11391de54b13dc8a628c80617ca5d25f070/source/daplink/cmsis-dap/DAP_vendor.c) request UART data up to 64 bytes. 229 | * Bytes: `[0x84, string length, string[0], string[1], ..., string[length-1]]` 230 | 231 | ## Capturing All USB functions in JavaScript 232 | 233 | This can be done to identify all the messages being sent to a USB device from a WebUSB page, like [MakeCode](http://makecode.microbit.org) 234 | 235 | 1. Open the page in question 236 | 2. Open the JavaScript console (Inspect the page via developer tools; Right-click on page and select Insepct) 237 | 3. Paste in the following code, which adds a debugging print message to all calls to most USB functions 238 | ```javascript 239 | var trackerLogOn = true; 240 | 241 | function addTracker(methodName, object) { 242 | var temp = object[methodName]; 243 | object[methodName] = function() { 244 | if(trackerLogOn) { 245 | console.log(methodName + ":"); 246 | console.dir(arguments); 247 | console.log("----------------") 248 | } 249 | // this is a USBDevice object 250 | return temp.apply(this, arguments) 251 | } 252 | } 253 | 254 | addTracker("claimInterface",USBDevice.prototype) 255 | addTracker("selectAlternateInterface", USBDevice.prototype) 256 | addTracker("controlTransferIn", USBDevice.prototype) 257 | addTracker("controlTransferOut", USBDevice.prototype) 258 | addTracker("transferIn", USBDevice.prototype) 259 | addTracker("transferOut", USBDevice.prototype) 260 | addTracker("selectConfiguration", USBDevice.prototype) 261 | addTracker("isochronousTransferIn", USBDevice.prototype) 262 | addTracker("isochronousTransferOut", USBDevice.prototype) 263 | ``` 264 | 4. Use the page to trigger USB operations 265 | 5. Enter `trackerLogOn = false` in the Console to stop collecting data, then scroll back and examine all messages/traffic. 266 | 267 | ## Capturing USB Packets on Mac 268 | 269 | Based on [https://www.umpah.net/how-to-sniff-usb-traffic-reverse-engineer-usb-device-interactions/](https://www.umpah.net/how-to-sniff-usb-traffic-reverse-engineer-usb-device-interactions/) 270 | 271 | 1. Enable virtual port for monitoring: `sudo ifconfig XHC20 up` 272 | 2. Open Wireshark for capture. 273 | 3. Select `XHC20` device for capture 274 | 4. Filter based on device's location ID (get it from Apple Menu, `About this Mac...`, `System Report`, `USB`, select the device and look at the Location ID): `usb.darwin.location_id == 0x14200000` 275 | 5. When done disable `XHC20`: `sudo ifconfig XHC20 down` 276 | 277 | ## Misc: App Notes / Docs on USB, WebUSB, etc. 278 | 279 | * [USB Made Simple](http://www.usbmadesimple.co.uk/): Sections on [Introduction](http://www.usbmadesimple.co.uk/ums_1.htm), [Data Flow](http://www.usbmadesimple.co.uk/ums_3.htm) and [Protocol](http://www.usbmadesimple.co.uk/ums_4.htm) are helpful. 280 | * [Makecode/pxt's webusb.ts source](https://github.com/microsoft/pxt/blob/83dcac3c75b8681cd2451919840a297d7e0b3c20/pxtlib/webusb.ts) 281 | 282 | 283 | ## Misc: USB Enumeration for Micro:Bit and communication details 284 | 285 | * 0: USBInterface ***USB Mass Storage*** 286 | * interfaceClass: 8 287 | * interfaceProtocol: 80 288 | * interfaceSubclass: 6 289 | * interfaceNumber: 0 290 | * 1: USBInterface ***CDC Control*** 291 | * interfaceClass: 2 292 | * interfaceProtocol: 1 293 | * interfaceSubclass: 2 294 | * interfaceNumber: 1 295 | * 2: USBInterface ***CDC - Data*** 296 | * interfaceClass: 10 297 | * interfaceProtocol: 0 298 | * interfaceSubclass: 0 299 | * interfaceNumber: 2 300 | * 3: USBInterface 301 | * interfaceNumber: 3 302 | * 4: USBInterface ***CMSIS-DAP*** 303 | * interfaceNumber: 4 304 | 305 | 306 | ## Captured / Decoded USB Sequence from Makecode 307 | 308 | 1. DAP_SWJ_CLOCK [17,128,150,152,0] 309 | 2. DAP_Connect [2,0] 310 | 3. DAP_TransferConfigure [4, 0, 80, 0, 0, 0] 311 | 4. SWD Configure [19, 0] 312 | 5. [18, 56, 255, 255, 255, 255, 255, 255, 255] // DAP_SWJ_Sequence 313 | 6. [18, 16, 158, 231] 314 | 7. [18, 8, 0] 315 | 8. DAP_Transfer [5, ...] 316 | 9. [130, 0, 194, 1, 0]// Set UART Config [https://github.com/ARMmbed/DAPLink/blob/0711f11391de54b13dc8a628c80617ca5d25f070/source/daplink/cmsis-dap/DAP_vendor.c](https://github.com/ARMmbed/DAPLink/blob/0711f11391de54b13dc8a628c80617ca5d25f070/source/daplink/cmsis-dap/DAP_vendor.c) 317 | 10. [0, 254] // DAP_Info / Get Packet Size 318 | 11. [17, 128, 150, 152, 0] // DAP_SWJ_Clock 319 | 12. [2, 0] // DAP_Connect Defaults 320 | 13. [17, 128, 150, 152, 0] // DAP_SWJ_Clock 321 | 14. [4, 0, 80, 0, 0, 0] // DAP_TransferConfigure 322 | 15. [19, 0] // DAP_SWD_Configure default 323 | 16. [18, 56, 255, 255, 255, 255, 255, 255, 255] // DAP_SWJ_Sequence 324 | 325 | 326 | ## Captured / Decoded USB Sequence from Makecode for v2.21 327 | 328 | 1. .then(() => device.selectConfiguration(1)) 329 | 2. .then(() => device.claimInterface(5)) 330 | 331 | 332 | 3. Transfer out 5, [5, 0, 4, 8, 0, 0, 0, 0, 1, 82, 0, 0, 35, 5, 240, 237, 0, 224, 13, 3, 0, 95, 160] 333 | ID_DAP_Transfer https://arm-software.github.io/CMSIS_5/DAP/html/group__DAP__Transfer.html 334 | index 0, transfer 4 335 | 8, 0, 0, 0, 0, 1, 82, 0, 0, 35, 5, 240, 237, 0, 224, 13, 3, 0, 95, 160 336 | https://arm-software.github.io/CMSIS_5/DAP/html/group__DAP__Transfer.html 337 | 338 | 339 | BYTE | BYTE *****| BYTE **********| BYTE *************| WORD *********| 340 | > 0x05 | DAP Index | Transfer Count | Transfer Request | Transfer Data | 341 | > 5, 0, 4, 342 | > 8: 0, 0, 0, 0 //write A3 Register Address bit 3. ??? 343 | > 1: 82, 0, 0, 35, write to access port 344 | > 5: 240, 237, 0, 224 a2 register write to AP ??? 345 | > 13:, 3, 0, 95, 160 a3 and a2 346 | 347 | 348 | 349 | 1. Transfer in 5, 64 350 | ID_DAP_Vendor0 ??? 351 | 6. Transfer out 5, [0,4] 352 | 1. ID_DAP_Info / 0x04 = Get the CMSIS-DAP Protocol Version (string). 353 | 7. Transfer in 5, 64 354 | 8. Transfer out 5,[128] 0x80? 355 | 1. 356 | 9. Transfer in 5, 64 357 | 10. Transfer out 5,[130, 0, 194, 1, 0] 0x82 358 | 11. Transfer in 5, 64 359 | 12. Transfer out 5,[0, 254] // Get the maximum Packet Count (BYTE). 360 | 13. Transfer in 5, 64 361 | 362 | 14. Transfer out 5,[17, 128, 150, 152, 0] //MMM 363 | 1. DAP_SWJ_Clock https://arm-software.github.io/CMSIS_5/DAP/html/group__DAP__SWJ__Clock.html 364 | 15. Transfer in 5, 64 365 | 16. Transfer out 5,[2, 0] 366 | 17. Transfer in 5, 64 367 | 368 | 18. Transfer out 5,[17, 128, 150, 152, 0] 369 | 1. ID_DAP_SWJ_Clock ... ??? 370 | 19. Transfer in 5, 64 371 | 20. Transfer out 5,[4, 0, 80, 0, 0, 0] 372 | 1. ID_DAP_TransferConfigure 373 | 2. 0 idle cyclles 374 | 3. 80, 0, wait retry 375 | 4. 00 00 match retry 376 | 21. Transfer in 5, 64 377 | 22. Transfer out 5,[19, 0] 378 | 1. DAP_SWD_Configure 379 | 23. Transfer in 5, 64 380 | 24. Transfer out 5,[18, 56, 255, 255, 255, 255, 255, 255, 255] 381 | 1. ID_DAP_SWJ_Sequence 382 | 25. Transfer in 5, 64 383 | 26. Transfer out 5,[18, 16, 158, 231] 384 | 1. ID_DAP_SWJ_Sequence 385 | 27. Transfer in 5, 64 386 | 28. Transfer out 5,[18, 56, 255, 255, 255, 255, 255, 255, 255] 387 | 29. Transfer in 5, 64 388 | 30. Transfer out 5,[18, 8, 0] 389 | 31. Transfer in 5, 64 390 | Connected 391 | Transfer out 5, [5, 0, 1, 2] 392 | Transfer out 5, [5, 0, 4, 0, 4, 0, 0, 0, 8, 0, 0, 0, 0, 4, 0, 0, 0, 80, 6] 393 | Transfer out 5, [5, 0, 4, 4, 0, 15, 0, 80, 8, 0, 0, 0, 0, 8, 240, 0, 0, 0, 15] 394 | Transfer out 5, [5, 0, 4, 8, 0, 0, 0, 0, 1, 82, 0, 0, 35, 5, 0, 32, 0, 224, 15] 395 | Breakpoints messqge 396 | Transfer out 5, [5, 0, 4, 8, 0, 0, 0, 0, 1, 82, 0, 0, 35, 5, 0, 32, 0, 224, 13, 2, 0, 0, 0] 397 | Transfer out 5, [5, 0, 4, 8, 0, 0, 0, 0, 1, 82, 0, 0, 35, 5, 8, 32, 0, 224, 13, 0, 0, 0, 0] 398 | Transfer out 5, [] 399 | Transfer out 5, [] 400 | Transfer out 5, [] 401 | Transfer out 5, [] 402 | Transfer out 5, [] 403 | Transfer out 5, [] 404 | Transfer out 5, [] 405 | 406 | // product id 516 407 | 408 | 409 | 6. Transfer out 5,[17, 128, 150, 152, 0] 410 | 6. Transfer out 5,[2, 0] 411 | 5. Transfer out 5,[19, 0] 412 | 6. Transfer out 5,[130, 0, 194, 1, 0] 413 | 414 | 415 | 416 | ok from here on 417 | 418 | 1. [130, 0, 194, 1, 0] 419 | Connecting... 420 | 7. [0,254] 421 | 8. [17, 128, 150, 152, 0] 422 | 9. [2,0] 423 | 10. [17, 128, 150, 152, 0] 424 | 11. [4, 0, 80, 0, 0, 0] 425 | 12. [19, 0] 426 | 13. [18, 56, 255, 255, 255, 255, 255, 255, 255] 427 | 14. [18, 16, 158, 23] 428 | 429 | 430 | 431 | 432 | -------------------------------------------------------------------------------- /style.css: -------------------------------------------------------------------------------- 1 | /* Based on https://stackoverflow.com/questions/90178/make-a-div-fill-the-height-of-the-remaining-screen-space/16960823 */ 2 | 3 | html, 4 | body { 5 | height: 99%; 6 | margin: 2px; 7 | } 8 | 9 | .box { 10 | display: flex; 11 | flex-flow: column; 12 | height: 100%; 13 | } 14 | 15 | .box .row { 16 | border: 1px dotted grey; 17 | } 18 | 19 | .box .row.header { 20 | flex: 0 1 auto; 21 | /* The above is shorthand for: 22 | flex-grow: 0, 23 | flex-shrink: 1, 24 | flex-basis: auto 25 | */ 26 | } 27 | 28 | .box .row.content { 29 | flex: 1 1 auto; 30 | } 31 | 32 | /* https://www.w3schools.com/css/css3_buttons.asp */ 33 | .button { 34 | background-color: #4CAF50; /* Green */ 35 | border: none; 36 | color: white; 37 | padding: 15px 32px; 38 | text-align: center; 39 | text-decoration: none; 40 | display: inline-block; 41 | font-size: 16px; 42 | width: 100%; 43 | } -------------------------------------------------------------------------------- /ubitwebusb.js: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * JavaScript functions for interacting with micro:bit microcontrollers over WebUSB 4 | * (Only works in Chrome browsers; Pages must be either HTTPS or local) 5 | */ 6 | 7 | 8 | const MICROBIT_VENDOR_ID = 0x0d28 9 | const MICROBIT_PRODUCT_ID = 0x0204 10 | 11 | /* 12 | Open and configure a selected device and then start the read-loop 13 | */ 14 | async function uBitOpenDevice(device, callback) { 15 | const transport = new DAPjs.WebUSB(device) 16 | const target = new DAPjs.DAPLink(transport) 17 | await target.connect() 18 | await target.setSerialBaudrate(115200) 19 | device.target = target; // Store the target in the device object (needed for write) 20 | device.callback = callback // Store the callback for the device 21 | callback("connected", device, null) 22 | 23 | // Cite: https://stackoverflow.com/questions/21647928/javascript-unicode-string-to-hex 24 | // String.prototype.hexEncode = function(){ 25 | // var hex, i; 26 | 27 | // var result = ""; 28 | // for (i=0; i { 37 | let firstNewline = buffer.indexOf("\n") 38 | if(firstNewline>=0) { 39 | let messageToNewline = buffer.slice(0,firstNewline) 40 | let now = new Date() 41 | // Deal with line 42 | // If it's a graph/series format, break it into parts 43 | let parseResult = parser.exec(messageToNewline) 44 | if(parseResult) { 45 | let graph = parseResult[1] 46 | let series = parseResult[2] 47 | let data = parseResult[3] 48 | let callbackType = "graph-event" 49 | // If data is numeric, it's a data message and should be sent as numbers 50 | if(!isNaN(data)) { 51 | callbackType = "graph-data" 52 | data = parseFloat(data) 53 | } 54 | // Build and send the bundle 55 | let dataBundle = { 56 | time: now, 57 | graph: graph, 58 | series: series, 59 | data: data 60 | } 61 | callback(callbackType, device, dataBundle) 62 | } else { 63 | // Not a graph format. Send it as a console bundle 64 | let dataBundle = {time: now, data: messageToNewline} 65 | callback("console", device, dataBundle) 66 | } 67 | buffer = buffer.slice(firstNewline+1) // Advance to after newline 68 | firstNewline = buffer.indexOf("\n") // See if there's more data 69 | // Schedule more parsing 70 | if(firstNewline>=0) { 71 | setTimeout(lineParser, 10) // If so, parse it 72 | } 73 | } 74 | 75 | } 76 | 77 | let buffer="" // Buffer of accumulated messages 78 | const parser = /([^.:]*)\.*([^:]+|):(.*)/ // Parser to identify time-series format (graph:info or graph.series:info) 79 | const ws = / *\r\n/g 80 | target.on(DAPjs.DAPLink.EVENT_SERIAL_DATA, data => { 81 | buffer += data; 82 | buffer = buffer.replace(ws, "\n") 83 | if(data.includes("\n")) 84 | setTimeout(lineParser, 10) 85 | }); 86 | target.startSerialRead(1) 87 | return Promise.resolve() 88 | } 89 | 90 | 91 | /** 92 | * Disconnect from a device 93 | * @param {USBDevice} device to disconnect from 94 | */ 95 | async function uBitDisconnect(device) { 96 | if(device) { 97 | try { 98 | await device.target.stopSerialRead() 99 | } catch(error) { 100 | // Failure may mean already stopped 101 | } 102 | try { 103 | await device.target.disconnect() 104 | } catch(error) { 105 | // Failure may mean already disconnected 106 | } 107 | try { 108 | await device.close() 109 | } catch(error) { 110 | // Failure may mean already closed 111 | } 112 | // Call the callback with notification of disconnect 113 | device.callback("disconnected", device, null) 114 | device.callback = null 115 | device.target = null 116 | } 117 | } 118 | 119 | /** 120 | * Send a string to a specific device 121 | * @param {USBDevice} device 122 | * @param {string} data to send (must not include newlines) 123 | */ 124 | function uBitSend(device, data) { 125 | if(!device.opened) 126 | return 127 | let fullLine = data+'\n' 128 | device.target.serialWrite(fullLine) 129 | } 130 | 131 | 132 | /** 133 | * Callback for micro:bit events 134 | * 135 | 136 | Event data varies based on the event string: 137 |
    138 |
  • "connection failure": null
  • 139 |
  • "connected": null
  • 140 |
  • "disconnected": null
  • 141 |
  • "error": error object
  • 142 |
  • "console": { "time":Date object "data":string}
  • 143 |
  • "graph-data": { "time":Date object "graph":string "series":string "data":number}
  • 144 |
  • "graph-event": { "time":Date object "graph":string "series":string "data":string}
  • 145 |
146 | 147 | * @callback uBitEventCallback 148 | * @param {string} event ("connection failure", "connected", "disconnected", "error", "console", "graph-data", "graph-event" ) 149 | * @param {USBDevice} device triggering the callback 150 | * @param {*} data (event-specific data object). See list above for variants 151 | * 152 | */ 153 | 154 | 155 | /** 156 | * Allow users to select a device to connect to. 157 | * 158 | * @param {uBitEventCallback} callback function for device events 159 | */ 160 | function uBitConnectDevice(callback) { 161 | navigator.usb.requestDevice({filters: [{ vendorId: MICROBIT_VENDOR_ID, productId: MICROBIT_PRODUCT_ID }]}) 162 | .then( d => { if(!d.opened) uBitOpenDevice(d, callback)} ) 163 | .catch( () => callback("connection failure", null, null)) 164 | 165 | } 166 | 167 | //stackoverflow.com/questions/5892845/how-to-load-one-javascript-file-from-another 168 | var newScript = document.createElement('script'); 169 | newScript.type = 'text/javascript'; 170 | newScript.src = 'dap.umd.js'; 171 | document.getElementsByTagName('head')[0].appendChild(newScript); 172 | 173 | navigator.usb.addEventListener('disconnect', (event) => { 174 | if("device" in event && "callback" in event.device && event.device.callback!=null && event.device.productName.includes("micro:bit")) { 175 | uBitDisconnect(event.device) 176 | } 177 | }) 178 | --------------------------------------------------------------------------------