-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathubitwebusb.js
177 lines (155 loc) · 5.89 KB
/
ubitwebusb.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/*
* JavaScript functions for interacting with micro:bit microcontrollers over WebUSB
* (Only works in Chrome browsers; Pages must be either HTTPS or local)
*/
const MICROBIT_VENDOR_ID = 0x0d28
const MICROBIT_PRODUCT_ID = 0x0204
/*
Open and configure a selected device and then start the read-loop
*/
async function uBitOpenDevice(device, callback) {
const transport = new DAPjs.WebUSB(device)
const target = new DAPjs.DAPLink(transport)
await target.connect()
await target.setSerialBaudrate(115200)
device.target = target; // Store the target in the device object (needed for write)
device.callback = callback // Store the callback for the device
callback("connected", device, null)
// Cite: https://stackoverflow.com/questions/21647928/javascript-unicode-string-to-hex
// String.prototype.hexEncode = function(){
// var hex, i;
// var result = "";
// for (i=0; i<this.length; i++) {
// hex = this.charCodeAt(i).toString(16);
// result += ("000"+hex).slice(-4);
// }
// return result
// }
let lineParser = () => {
let firstNewline = buffer.indexOf("\n")
if(firstNewline>=0) {
let messageToNewline = buffer.slice(0,firstNewline)
let now = new Date()
// Deal with line
// If it's a graph/series format, break it into parts
let parseResult = parser.exec(messageToNewline)
if(parseResult) {
let graph = parseResult[1]
let series = parseResult[2]
let data = parseResult[3]
let callbackType = "graph-event"
// If data is numeric, it's a data message and should be sent as numbers
if(!isNaN(data)) {
callbackType = "graph-data"
data = parseFloat(data)
}
// Build and send the bundle
let dataBundle = {
time: now,
graph: graph,
series: series,
data: data
}
callback(callbackType, device, dataBundle)
} else {
// Not a graph format. Send it as a console bundle
let dataBundle = {time: now, data: messageToNewline}
callback("console", device, dataBundle)
}
buffer = buffer.slice(firstNewline+1) // Advance to after newline
firstNewline = buffer.indexOf("\n") // See if there's more data
// Schedule more parsing
if(firstNewline>=0) {
setTimeout(lineParser, 10) // If so, parse it
}
}
}
let buffer="" // Buffer of accumulated messages
const parser = /([^.:]*)\.*([^:]+|):(.*)/ // Parser to identify time-series format (graph:info or graph.series:info)
const ws = / *\r\n/g
target.on(DAPjs.DAPLink.EVENT_SERIAL_DATA, data => {
buffer += data;
buffer = buffer.replace(ws, "\n")
if(data.includes("\n"))
setTimeout(lineParser, 10)
});
target.startSerialRead(1)
return Promise.resolve()
}
/**
* Disconnect from a device
* @param {USBDevice} device to disconnect from
*/
async function uBitDisconnect(device) {
if(device) {
try {
await device.target.stopSerialRead()
} catch(error) {
// Failure may mean already stopped
}
try {
await device.target.disconnect()
} catch(error) {
// Failure may mean already disconnected
}
try {
await device.close()
} catch(error) {
// Failure may mean already closed
}
// Call the callback with notification of disconnect
device.callback("disconnected", device, null)
device.callback = null
device.target = null
}
}
/**
* Send a string to a specific device
* @param {USBDevice} device
* @param {string} data to send (must not include newlines)
*/
function uBitSend(device, data) {
if(!device.opened)
return
let fullLine = data+'\n'
device.target.serialWrite(fullLine)
}
/**
* Callback for micro:bit events
*
Event data varies based on the event string:
<ul>
<li>"connection failure": null</li>
<li>"connected": null</li>
<li>"disconnected": null</li>
<li>"error": error object</li>
<li>"console": { "time":Date object "data":string}</li>
<li>"graph-data": { "time":Date object "graph":string "series":string "data":number}</li>
<li>"graph-event": { "time":Date object "graph":string "series":string "data":string}</li>
</ul>
* @callback uBitEventCallback
* @param {string} event ("connection failure", "connected", "disconnected", "error", "console", "graph-data", "graph-event" )
* @param {USBDevice} device triggering the callback
* @param {*} data (event-specific data object). See list above for variants
*
*/
/**
* Allow users to select a device to connect to.
*
* @param {uBitEventCallback} callback function for device events
*/
function uBitConnectDevice(callback) {
navigator.usb.requestDevice({filters: [{ vendorId: MICROBIT_VENDOR_ID, productId: MICROBIT_PRODUCT_ID }]})
.then( d => { if(!d.opened) uBitOpenDevice(d, callback)} )
.catch( () => callback("connection failure", null, null))
}
//stackoverflow.com/questions/5892845/how-to-load-one-javascript-file-from-another
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'dap.umd.js';
document.getElementsByTagName('head')[0].appendChild(newScript);
navigator.usb.addEventListener('disconnect', (event) => {
if("device" in event && "callback" in event.device && event.device.callback!=null && event.device.productName.includes("micro:bit")) {
uBitDisconnect(event.device)
}
})