-
Notifications
You must be signed in to change notification settings - Fork 15
/
transports.js
589 lines (518 loc) · 16.8 KB
/
transports.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
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
207
208
209
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
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
344
345
346
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
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
504
505
506
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
/*
* SPDX-FileCopyrightText: 2024 Volodymyr Shymanskyy
* SPDX-License-Identifier: MIT
*
* The software is provided "as is", without any warranties or guarantees (explicit or implied).
* This includes no assurances about being fit for any specific purpose.
*/
import { sleep, Mutex, report } from './utils.js'
export class Transport {
constructor() {
if (this.constructor === Transport) {
throw new Error("Cannot instantiate abstract class Transport")
}
this.mutex = new Mutex()
this.inTransaction = false
this.receivedData = ''
this.activityCallback = () => {}
this.receiveCallback = () => {}
this.disconnectCallback = () => {}
this.writeChunk = 128
this.emit = false
this.info = {}
}
async requestAccess() {
throw new Error("Method 'requestAccess()' must be implemented.")
}
async connect() {
throw new Error("Method 'connect()' must be implemented.")
}
async getInfo() {
return this.info
}
async disconnect() {
throw new Error("Method 'disconnect()' must be implemented.")
}
async write(data) {
const encoder = new TextEncoder()
const value = encoder.encode(data)
try {
let offset = 0
while (offset < value.byteLength) {
const chunk = value.slice(offset, offset + this.writeChunk)
await this.writeBytes(chunk)
this.activityCallback()
offset += this.writeChunk
}
} catch (err) {
report("Write error", err) // TODO
}
}
onActivity(callback) {
this.activityCallback = callback
}
onReceive(callback) {
this.receiveCallback = callback
}
onDisconnect(callback) {
this.disconnectCallback = callback
}
/*
* Transaction API
*/
async startTransaction() {
const release = await this.mutex.acquire()
this.prevRecvCbk = this.receiveCallback
this.inTransaction = true
this.receivedData = ''
this.receiveCallback = (data) => {
this.receivedData += data
if (this.emit && this.prevRecvCbk) { this.prevRecvCbk(data) }
}
return () => {
if (this.prevRecvCbk) {
this.receiveCallback = this.prevRecvCbk
this.receiveCallback(this.receivedData)
}
this.receivedData = null
this.inTransaction = false
release()
}
}
async flushInput() {
if (!this.inTransaction) {
throw new Error('Not in transaction')
}
this.receivedData = ''
/*while (1) {
const { value, done } = await reader.read()
console.log(value, done)
if (done) { break }
if (value.length == 0) { break }
}*/
}
async readExactly(n, timeout=5000) {
if (!this.inTransaction) {
throw new Error('Not in transaction')
}
let endTime = Date.now() + timeout
while (timeout <= 0 || (Date.now() < endTime)) {
if (this.receivedData.length >= n) {
const res = this.receivedData.substring(0, n)
this.receivedData = this.receivedData.substring(n)
return res
}
const prev_avail = this.receivedData.length
await sleep(10)
if (this.receivedData.length > prev_avail) {
endTime = Date.now() + timeout
}
}
throw new Error('Timeout')
}
async readUntil(ending, timeout=5000) {
if (!this.inTransaction) {
throw new Error('Not in transaction')
}
let endTime = Date.now() + timeout
while (timeout <= 0 || (Date.now() < endTime)) {
const idx = this.receivedData.indexOf(ending) + ending.length
if (idx >= ending.length) {
const res = this.receivedData.substring(0, idx)
this.receivedData = this.receivedData.substring(idx)
return res
}
const prev_avail = this.receivedData.length
await sleep(10)
if (this.receivedData.length > prev_avail) {
endTime = Date.now() + timeout
}
}
throw new Error('Timeout reached before finding the ending sequence')
}
}
/*
* USB / Serial
*/
export class WebSerial extends Transport {
constructor(serial=null) {
super()
this.port = null
this.reader = null
this.writer = null
if (serial) {
this.serial = serial
} else {
if (typeof navigator.serial === 'undefined') {
throw new Error('WebSerial not available')
}
this.serial = navigator.serial
}
}
async requestAccess() {
this.port = await this.serial.requestPort()
try {
const pi = this.port.getInfo()
this.info = {
vid: pi.usbVendorId.toString(16).padStart(4, '0'),
pid: pi.usbProductId.toString(16).padStart(4, '0'),
}
} catch(err) {}
}
async connect() {
await this.port.open({ baudRate: 115200 })
this.reader = this.port.readable.getReader()
this.writer = this.port.writable.getWriter()
this.listen()
}
async disconnect() {
await this.reader.cancel()
await this.port.forget()
}
async writeBytes(data) {
await this.writer.write(data)
}
async listen() {
const decoder = new TextDecoder()
try {
while (true) {
const { value, done } = await this.reader.read()
if (done) break
this.receiveCallback(decoder.decode(value))
this.activityCallback()
}
} catch (err) {
this.disconnectCallback()
}
}
}
/*
* Bluetooth
*/
const NUS_SERVICE = '6e400001-b5a3-f393-e0a9-e50e24dcca9e'
const NUS_TX = '6e400002-b5a3-f393-e0a9-e50e24dcca9e'
const NUS_RX = '6e400003-b5a3-f393-e0a9-e50e24dcca9e'
const NUS_TX_LIMIT = 241
const ADA_NUS_SERVICE = 'adaf0001-4369-7263-7569-74507974686e'
const ADA_NUS_TX = 'adaf0002-4369-7263-7569-74507974686e'
const ADA_NUS_RX = 'adaf0003-4369-7263-7569-74507974686e'
const ADA_VER = 'adaf0100-4669-6c65-5472-616e73666572'
const ADA_FT = 'adaf0200-4669-6c65-5472-616e73666572'
const ADA_NUS_TX_LIMIT = 20
export class WebBluetooth extends Transport {
constructor() {
super()
this.device = null
this.server = null
this.service = null
this.rx = null
this.tx = null
this.tx_limit = 20
if (typeof navigator.bluetooth === 'undefined') {
throw new Error('WebBluetooth not available')
}
}
async requestAccess() {
this.device = await navigator.bluetooth.requestDevice({
filters: [
{ services: [NUS_SERVICE] },
{ namePrefix: 'mpy-' },
{ services: [ 0xfebb ] },
{ namePrefix: 'CIRCUITPY' },
],
//acceptAllDevices: true,
optionalServices: [NUS_SERVICE, ADA_NUS_SERVICE, 0xfebb],
})
this.device.addEventListener("gattserverdisconnected", () => {
this.disconnectCallback()
})
try {
this.info = {
name: this.device.name,
}
} catch(err) {}
}
async connect() {
this.server = await this.device.gatt.connect()
this.service = null
const services = await this.server.getPrimaryServices()
for (let service of services) {
if (service.uuid === NUS_SERVICE) {
this.service = service
this.rx = await service.getCharacteristic(NUS_RX)
this.tx = await service.getCharacteristic(NUS_TX)
this.tx_limit = NUS_TX_LIMIT
} else if (service.uuid === ADA_NUS_SERVICE) {
this.service = service
this.rx = await service.getCharacteristic(ADA_NUS_RX)
this.tx = await service.getCharacteristic(ADA_NUS_TX)
this.tx_limit = ADA_NUS_TX_LIMIT
// Check version
const ada_fts = await this.server.getPrimaryService(0xfebb)
const versionChar = await ada_fts.getCharacteristic(ADA_VER)
const version = (await versionChar.readValue()).getUint32(0, true)
if (version != 4) {
throw new Error(`Unsupported version: ${version}`)
}
// Register file transfer char
const ft = await ada_fts.getCharacteristic(ADA_FT)
//ft.removeEventListener('characteristicvaluechanged', () => {})
ft.addEventListener('characteristicvaluechanged', () => {})
await ft.startNotifications()
}
if (this.service) {
await this.rx.startNotifications()
this.rx.addEventListener('characteristicvaluechanged', this.handleNotifications.bind(this))
return
}
}
throw new Error('No compatible NUS service found')
}
async disconnect() {
if (this.device && this.device.gatt.connected) {
await this.device.gatt.disconnect();
}
}
async writeBytes(data) {
//await this.tx.writeValueWithoutResponse(data)
await this.tx.writeValue(data)
}
handleNotifications(event) {
const decoder = new TextDecoder()
const value = event.target.value
this.receiveCallback(decoder.decode(value))
this.activityCallback()
}
}
/*
* WebSocket
*/
export class WebSocketREPL extends Transport {
constructor(url) {
super()
if (!url) {
throw new Error("WebSocket URL is required")
}
this.url = url
this.socket = null
this.last_activity = 0
this.info = {
url: this.url
}
}
onPasswordRequest(callback) {
this._passReqCallback = callback
}
async requestAccess() {
}
async connect() {
function _conn(url) {
return new Promise(function(resolve, reject) {
const ws = new WebSocket(url)
let finished = false
ws.onopen = async function() {
await sleep(300) // TODO: find a better way
if (!finished) {
finished = true
resolve(ws)
}
}
ws.onerror = function(err) {
reject(err)
}
ws.onclose = function(ev) {
if (!finished) {
finished = true
reject(new Error(ev.reason))
}
}
})
}
this.socket = await _conn(this.url)
this.socket.binaryType = 'arraybuffer'
this.hbeat = setInterval(() => {
// Send empty data frame
const now = Date.now()
if (this.socket && (now - this.last_activity > 55*1000)) {
this.socket.send('')
this.last_activity = now
}
}, 10*1000)
this.socket.onmessage = (event) => {
if (event.data instanceof ArrayBuffer) {
const decoder = new TextDecoder()
this.receiveCallback(decoder.decode(event.data))
} else {
this.receiveCallback(event.data)
}
this.activityCallback()
this.last_activity = Date.now()
}
this.socket.onclose = (ev) => {
this.disconnectCallback()
}
const release = await this.startTransaction()
try {
try {
await this.readUntil('Password:', 1000)
} catch (err) {
return
}
const pass = await this._passReqCallback()
if (!pass) {
throw new Error("Password is required")
}
await this.write(pass + '\n')
await this.readUntil('\n') // skip echo
const rsp = (await this.readUntil('\n')).trim()
if (rsp == "WebREPL connected") {
// All good!
} else if (rsp == "Access denied") {
throw new Error("Invalid password")
} else {
throw new Error(rsp)
}
} finally {
release()
}
}
async disconnect() {
if (this.socket) {
clearInterval(this.hbeat)
this.socket.close()
this.socket = null
this.hbeat = null
}
}
async write(value) {
if (!this.socket) { return; }
try {
let offset = 0
while (offset < value.length) {
const chunk = value.slice(offset, offset + this.writeChunk)
this.socket.send(chunk)
this.activityCallback()
offset += this.writeChunk
if (offset < value.length) {
await sleep(150)
}
}
this.last_activity = Date.now()
} catch (err) {
report("Write error", err) // TODO
}
}
}
/*
* P2P / WebRTC
*/
import { Peer } from 'peerjs'
export class WebRTCTransport extends Transport {
constructor(peerId = null, myId = null) {
super();
this.peerId = peerId
this.myId = myId
}
onConnect(callback) {
this.connectCallback = callback
}
async requestAccess() {
let iceServers = [
{
urls: [
'stun:stun.l.google.com:19302',
'stun:stun1.l.google.com:19302',
'stun:stun2.l.google.com:19302',
'stun:stun3.l.google.com:19302',
'stun:stun4.l.google.com:19302',
'stun:stun.cloudflare.com:3478',
'stun:stun.nextcloud.com:3478',
]
}
]
const controller = new AbortController()
const timeout = setTimeout(() => {
controller.abort()
}, 3000);
try {
const ice = await (await fetch('https://hub.viper-ide.org/ice.json', {
cache: "no-store",
signal: controller.signal,
})).json()
iceServers.push(...ice)
} catch (err) {
} finally {
clearTimeout(timeout)
}
iceServers.push(...[
{
urls: [
'turn:eu-0.turn.peerjs.com:3478',
'turn:us-0.turn.peerjs.com:3478',
],
username: "peerjs",
credential: "peerjsp"
}, {
url: 'turn:hub.viper-ide.org:3478?transport=udp',
username: 'viper-ide',
credential: 'K70h5k>6ni/a',
}
]);
this.peer = new Peer(this.myId, {
secure: true,
config: { iceServers }
})
this.connection = null
this.connectCallback = () => {}
this.peer.on('connection', (conn) => {
this.peerId = conn.peer
this._setup_conn(conn)
this.connectCallback()
})
// Generate a unique ID if not provided
if (!this.peer.id) {
await new Promise((resolve) => this.peer.on('open', resolve))
}
this.info = { id: this.peer.id }
console.log('My P2P ID:', this.peer.id)
}
_setup_conn(conn) {
conn.on('data', (data) => {
const decoder = new TextDecoder()
this.receiveCallback(decoder.decode(data))
this.activityCallback()
})
conn.on('close', () => {
this.disconnectCallback()
})
this.connection = conn
}
connect() {
return new Promise((resolve, reject) => {
this.peer.on('error', reject)
const conn = this.peer.connect(this.peerId, {
serialization: 'binary',
reliable: true,
})
conn.on('error', reject)
conn.on('open', () => {
this._setup_conn(conn)
resolve()
})
});
}
async disconnect() {
if (this.connection) {
this.connection.close();
this.connection = null;
}
}
async write(data) {
const encoder = new TextEncoder()
const value = encoder.encode(data)
if (this.connection && this.connection.open) {
this.connection.send(value)
await sleep(50) // TODO find a better way
}
}
}