-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathindex.js
136 lines (110 loc) · 2.79 KB
/
index.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
'use strict';
var util = require('util');
var stream = require('stream');
var DEFAULT_FILTERS = [
{ 'vendorId': 0x2341, 'productId': 0x8036 }, // Arduino Leonardo
{ 'vendorId': 0x2341, 'productId': 0x8037 }, // Arduino Micro
{ 'vendorId': 0x239a, 'productId': 0x8011 } // Adafruit Circuit Playground
];
function WebUSBSerialPort(options) {
var self = this;
options = options || {};
self.filters = options.filters || DEFAULT_FILTERS;
function handleDevice(device) {
self.device = device;
var readLoop = function(){
self.device.transferIn(5, 64).then(function(result){
self.emit('data', new Buffer(result.data.buffer));
readLoop();
}, function(error){
self.emit('emit', error);
});
};
self.device.open()
.then(function(){
return self.device.configuration;
})
.then(function(config){
if (config.configurationValue == 1) {
return {};
} else {
throw new Error("Need to setConfiguration(1).");
}
})
.catch(function(error){
return self.device.setConfiguration(1);
})
.then(function(){
return self.device.claimInterface(2);
})
.then(function(){
return self.device.controlTransferOut({
'requestType': 'class',
'recipient': 'interface',
'request': 0x22,
'value': 0x01,
'index': 0x02});
})
.then(function() {
self.emit('open');
readLoop();
});
}
if(options.device) {
handleDevice(options.device);
}
else{
navigator.usb.requestDevice({filters: self.filters })
.then(handleDevice)
.catch(function(err){
self.emit('error', err);
});
}
}
util.inherits(WebUSBSerialPort, stream.Stream);
WebUSBSerialPort.prototype.open = function (callback) {
this.emit('open');
if (callback) {
callback();
}
};
WebUSBSerialPort.prototype.write = function (data, callback) {
this.device.transferOut(4, data)
.then(function(){
if(callback){
callback(null);
}
})
.catch(function(error){
if(callback){
callback(error);
}
});
};
WebUSBSerialPort.prototype.close = function (callback) {
var self = this;
self.device.controlTransferOut({
'requestType': 'class',
'recipient': 'interface',
'request': 0x22,
'value': 0x00,
'index': 0x02})
.then(function(){
self.device.close();
if(callback){
callback();
}
});
};
WebUSBSerialPort.prototype.flush = function (callback) {
if(callback){
callback();
}
};
WebUSBSerialPort.prototype.drain = function (callback) {
if(callback){
callback();
}
};
WebUSBSerialPort.DEFAULT_FILTERS = DEFAULT_FILTERS;
module.exports = WebUSBSerialPort;