@alexgyver/ble 1.0.4 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ble.js CHANGED
@@ -1,4 +1,4 @@
1
- import { sleep, ShiftBuffer, StreamSplitter } from "@alexgyver/utils";
1
+ import { sleep, SerialExecutor } from "@alexgyver/utils";
2
2
 
3
3
  export default class BLEJS {
4
4
  static State = {
@@ -8,36 +8,29 @@ export default class BLEJS {
8
8
  Closing: 'closing',
9
9
  };
10
10
 
11
- //#region handlers
12
- onbin = null;
13
- ontext = null;
14
-
11
+ onbin(b) { }
15
12
  onopen() { }
16
13
  onclose() { }
17
14
  onchange(s) { }
18
15
  onselect(name) { }
19
16
  onerror(e) { }
20
17
 
21
- //#region constructor
22
18
  constructor(params = {}) {
23
19
  const def = {
24
- eol: /\r?\n/,
25
20
  serviceUUID: '0000ffe0-0000-1000-8000-00805f9b34fb',
26
- charxUUID: '0000ffe1-0000-1000-8000-00805f9b34fb',
21
+ rxUUID: '0000ffe1-0000-1000-8000-00805f9b34fb',
22
+ txUUID: '0000ffe2-0000-1000-8000-00805f9b34fb',
27
23
  auto_open: false,
28
- max_tx: 20,
29
24
  reconnect: 1000,
25
+ chunkSize: 500,
26
+ chunkDelay: 0,
30
27
  };
31
- this.cfg = { ...def, ...params };
32
28
 
33
- this.splitter = new StreamSplitter(this.cfg.eol);
34
- this.splitter.ontext = (t) => this.ontext(t);
29
+ this.cfg = { ...def, ...params };
35
30
  }
36
31
 
37
- //#region methods
38
32
  config(params = {}) {
39
33
  this.cfg = { ...this.cfg, ...params };
40
- this.splitter.eol = this.cfg.eol;
41
34
  }
42
35
 
43
36
  static supported() {
@@ -59,113 +52,221 @@ export default class BLEJS {
59
52
  async select() {
60
53
  try {
61
54
  await this.close();
62
- if (this._device) this._device.removeEventListener('gattserverdisconnected', this._disconnect_h);
55
+
56
+ if (this._device) {
57
+ this._device.removeEventListener(
58
+ 'gattserverdisconnected',
59
+ this._disconnect_h
60
+ );
61
+ }
62
+
63
63
  this._device = await navigator.bluetooth.requestDevice({
64
64
  filters: [{ services: [this.cfg.serviceUUID] }],
65
- optionalServices: [this.cfg.serviceUUID]
65
+ optionalServices: [this.cfg.serviceUUID],
66
66
  });
67
- this._device.addEventListener("gattserverdisconnected", this._disconnect_h);
67
+
68
+ this._device.addEventListener(
69
+ 'gattserverdisconnected',
70
+ this._disconnect_h
71
+ );
68
72
  } catch (e) {
69
73
  this._error(e);
70
74
  this._device = null;
71
75
  }
76
+
72
77
  this.onselect(this.getName());
78
+
73
79
  if (this.cfg.auto_open) this.open();
80
+
74
81
  return this.selected();
75
82
  }
76
83
 
77
84
  async open() {
78
- if (!this._device) return;
79
- if (this.opened()) return;
85
+ return this._lifecycle.runNothrow(async () => {
86
+ if (!this._device) {
87
+ this._error('No device');
88
+ return false;
89
+ }
90
+
91
+ if (this.opened()) return true;
92
+
93
+ if (this.cfg.reconnect) this.retry = true;
94
+
95
+ await this._open();
80
96
 
81
- if (this.cfg.reconnect) this.retry = true;
82
- await this._open();
97
+ return this.opened();
98
+ });
83
99
  }
84
100
 
85
101
  async _open() {
86
- if (this._state != BLEJS.State.Closed) return;
102
+ if (this._state !== BLEJS.State.Closed) return;
87
103
 
88
104
  this._change(BLEJS.State.Opening);
105
+
89
106
  try {
90
107
  const server = await this._device.gatt.connect();
91
108
  const service = await server.getPrimaryService(this.cfg.serviceUUID);
92
- this._charx = await service.getCharacteristic(this.cfg.charxUUID);
93
- await this._charx.startNotifications();
94
- this._charx.addEventListener("characteristicvaluechanged", this._data_h);
95
- this._buffer.clear();
109
+
110
+ this._rx = await service.getCharacteristic(this.cfg.rxUUID);
111
+ this._tx = await service.getCharacteristic(this.cfg.txUUID);
112
+
113
+ await this._tx.startNotifications();
114
+ this._tx.addEventListener(
115
+ 'characteristicvaluechanged',
116
+ this._data_h
117
+ );
118
+
119
+ this._sender.reset();
96
120
  this._change(BLEJS.State.Open);
97
121
  } catch (e) {
98
122
  this._error(e);
123
+ this._sender.reset();
99
124
  this._change(BLEJS.State.Closed);
100
- if (this.retry) sleep(this.cfg.reconnect).then(() => this._open());
125
+
126
+ if (this.retry) {
127
+ sleep(this.cfg.reconnect).then(() => {
128
+ this._lifecycle.runNothrow(() => this._open());
129
+ });
130
+ }
101
131
  }
102
132
  }
103
133
 
104
134
  async close() {
105
- this.retry = false;
106
- if (this.opened()) await this._close();
135
+ return this._lifecycle.runNothrow(async () => {
136
+ this.retry = false;
137
+ this._sender.reset();
138
+
139
+ if (this._state !== BLEJS.State.Closed) {
140
+ await this._close();
141
+ }
142
+
143
+ return true;
144
+ });
107
145
  }
108
146
 
109
147
  async _close() {
148
+ if (this._state === BLEJS.State.Closed) return;
149
+
110
150
  this._change(BLEJS.State.Closing);
111
- try { this._device.gatt.disconnect(); }
112
- catch (e) { this._error(e); }
151
+
152
+ try {
153
+ if (this._device?.gatt?.connected) {
154
+ this._device.gatt.disconnect();
155
+ } else {
156
+ await this._disconnect();
157
+ }
158
+ } catch (e) {
159
+ this._error(e);
160
+ await this._disconnect();
161
+ }
113
162
  }
114
163
 
115
- async sendText(text) {
116
- await this.sendBin((new TextEncoder()).encode(text));
164
+ async sendText(text, fast = true) {
165
+ await this.sendBin((new TextEncoder()).encode(text), fast);
117
166
  }
118
167
 
119
- async sendBin(data) {
120
- this._buffer.push(data);
121
- this._send();
168
+ async sendBin(data, fast = true) {
169
+ if (!this.opened() || !this._rx) return false;
170
+
171
+ return this._sender.runNothrow(async () => {
172
+ if (!this.opened() || !this._rx) return false;
173
+
174
+ const chunkSize = this.cfg.chunkSize;
175
+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
176
+
177
+ for (let i = 0; i < bytes.length; i += chunkSize) {
178
+ if (!this.opened() || !this._rx) return false;
179
+
180
+ const chunk = bytes.slice(i, i + chunkSize);
181
+
182
+ if (fast) {
183
+ await this._rx.writeValueWithoutResponse(chunk);
184
+ } else {
185
+ await this._rx.writeValueWithResponse(chunk);
186
+ }
187
+
188
+ if (this.cfg.chunkDelay > 0) {
189
+ await sleep(this.cfg.chunkDelay);
190
+ }
191
+ }
192
+
193
+ return true;
194
+ });
122
195
  }
123
196
 
124
- //#region private
125
- _device = null;
126
- _charx = null;
127
197
  _state = BLEJS.State.Closed;
128
- _buffer = new ShiftBuffer();
129
- _decoder = new TextDecoder();
198
+ _device = null;
199
+ _rx = null;
200
+ _tx = null;
201
+
202
+ retry = false;
203
+
204
+ _sender = new SerialExecutor();
205
+ _lifecycle = new SerialExecutor();
130
206
 
131
207
  async _disconnect(e) {
208
+ this._sender.reset();
209
+
210
+ if (this._tx) {
211
+ try {
212
+ this._tx.removeEventListener(
213
+ 'characteristicvaluechanged',
214
+ this._data_h
215
+ );
216
+ } catch (e) { }
217
+ }
218
+
219
+ this._rx = null;
220
+ this._tx = null;
221
+
132
222
  this._change(BLEJS.State.Closed);
133
- if (this._charx) this._charx.removeEventListener('characteristicvaluechanged', this._data_h);
134
- this._charx = null;
135
- if (this.retry) sleep(this.cfg.reconnect).then(() => this._open());
223
+
224
+ if (this.retry) {
225
+ sleep(this.cfg.reconnect).then(() => {
226
+ this._lifecycle.runNothrow(() => this._open());
227
+ });
228
+ }
229
+
136
230
  await sleep(50);
137
231
  }
232
+
138
233
  _disconnect_h = this._disconnect.bind(this);
139
234
 
140
235
  _data(e) {
141
- const dv = e.target.value;
142
- const value = new Uint8Array(dv.buffer, dv.byteOffset, dv.byteLength);
143
- if (this.onbin) this.onbin(value);
144
- if (this.ontext) this.splitter.write(this._decoder.decode(value, { stream: true }));
145
- }
146
- _data_h = this._data.bind(this);
236
+ try {
237
+ const dv = e.target.value;
238
+ const value = new Uint8Array(
239
+ dv.buffer,
240
+ dv.byteOffset,
241
+ dv.byteLength
242
+ );
147
243
 
148
- async _send() {
149
- if (this._busy) return;
150
- this._busy = true;
151
- while (this._buffer.length && this._charx) {
152
- let d = this._buffer.shift(this.cfg.max_tx);
153
- try {
154
- if (d.length) await this._charx.writeValueWithoutResponse(d);
155
- } catch (e) { }
244
+ this.onbin(value);
245
+ } catch (e) {
246
+ this._error(e);
156
247
  }
157
- this._busy = false;
158
248
  }
159
249
 
250
+ _data_h = this._data.bind(this);
251
+
160
252
  _error(e) {
161
253
  this.onerror('[BLE] ' + e);
162
254
  }
255
+
163
256
  _change(s) {
257
+ if (this._state === s) return;
258
+
164
259
  this._state = s;
165
260
  this.onchange(s);
261
+
166
262
  switch (s) {
167
- case BLEJS.State.Open: this.onopen(); break;
168
- case BLEJS.State.Closed: this.onclose(); break;
263
+ case BLEJS.State.Open:
264
+ this.onopen();
265
+ break;
266
+
267
+ case BLEJS.State.Closed:
268
+ this.onclose();
269
+ break;
169
270
  }
170
271
  }
171
272
  }
package/ble.min.js CHANGED
@@ -1 +1 @@
1
- const t=t=>new Promise(e=>setTimeout(e,t));class e{ontext=null;constructor(t=/\r?\n/,e=!1){this.eol=t,this.skip=e}reset(){this._buf=""}write(t){if(!this.ontext)return;if(!this.eol)return void this.ontext(t);this._buf+=t;let e=this._buf.split(this.eol);1!=e.length&&(e[e.length-1].length?this._buf=e.pop():(this._buf="",e.pop()),this.skip&&(e.shift(),this.skip=!1),e.forEach(t=>this.ontext(t)))}_buf=""}class s{constructor(){this.chunks=[],this.length=0}clear(){this.chunks=[],this.length=0}push(t){return!(!t||0===t.length||(this.chunks.push(t),this.length+=t.length,0))}shift(t){if(!this.length||!t)return new Uint8Array(0);t>this.length&&(t=this.length);const e=new Uint8Array(t);let s=0;for(;s<t&&this.chunks.length>0;){const i=this.chunks[0];if(!i||0===i.length){this.chunks.shift();continue}const h=Math.min(i.length,t-s);e.set(i.subarray(0,h),s),s+=h,h===i.length?this.chunks.shift():this.chunks[0]=i.subarray(h),this.length-=h}return e}shiftAll(){return this.shift(this.length)}}class i{static State={Closed:"closed",Opening:"opening",Open:"open",Closing:"closing"};onbin=null;ontext=null;onopen(){}onclose(){}onchange(t){}onselect(t){}onerror(t){}constructor(t={}){this.cfg={eol:/\r?\n/,serviceUUID:"0000ffe0-0000-1000-8000-00805f9b34fb",charxUUID:"0000ffe1-0000-1000-8000-00805f9b34fb",auto_open:!1,max_tx:20,reconnect:1e3,...t},this.splitter=new e(this.cfg.eol),this.splitter.ontext=t=>this.ontext(t)}config(t={}){this.cfg={...this.cfg,...t},this.splitter.eol=this.cfg.eol}static supported(){return"bluetooth"in navigator}opened(){return this._state===i.State.Open}selected(){return!!this._device}getName(){return this._device?this._device.name:null}async select(){try{await this.close(),this._device&&this._device.removeEventListener("gattserverdisconnected",this._disconnect_h),this._device=await navigator.bluetooth.requestDevice({filters:[{services:[this.cfg.serviceUUID]}],optionalServices:[this.cfg.serviceUUID]}),this._device.addEventListener("gattserverdisconnected",this._disconnect_h)}catch(t){this._error(t),this._device=null}return this.onselect(this.getName()),this.cfg.auto_open&&this.open(),this.selected()}async open(){this._device&&(this.opened()||(this.cfg.reconnect&&(this.retry=!0),await this._open()))}async _open(){if(this._state==i.State.Closed){this._change(i.State.Opening);try{const t=await this._device.gatt.connect(),e=await t.getPrimaryService(this.cfg.serviceUUID);this._charx=await e.getCharacteristic(this.cfg.charxUUID),await this._charx.startNotifications(),this._charx.addEventListener("characteristicvaluechanged",this._data_h),this._buffer.clear(),this._change(i.State.Open)}catch(e){this._error(e),this._change(i.State.Closed),this.retry&&t(this.cfg.reconnect).then(()=>this._open())}}}async close(){this.retry=!1,this.opened()&&await this._close()}async _close(){this._change(i.State.Closing);try{this._device.gatt.disconnect()}catch(t){this._error(t)}}async sendText(t){await this.sendBin((new TextEncoder).encode(t))}async sendBin(t){this._buffer.push(t),this._send()}_device=null;_charx=null;_state=i.State.Closed;_buffer=new s;_decoder=new TextDecoder;async _disconnect(e){this._change(i.State.Closed),this._charx&&this._charx.removeEventListener("characteristicvaluechanged",this._data_h),this._charx=null,this.retry&&t(this.cfg.reconnect).then(()=>this._open()),await t(50)}_disconnect_h=this._disconnect.bind(this);_data(t){const e=t.target.value,s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this.onbin&&this.onbin(s),this.ontext&&this.splitter.write(this._decoder.decode(s,{stream:!0}))}_data_h=this._data.bind(this);async _send(){if(!this._busy){for(this._busy=!0;this._buffer.length&&this._charx;){let t=this._buffer.shift(this.cfg.max_tx);try{t.length&&await this._charx.writeValueWithoutResponse(t)}catch(t){}}this._busy=!1}}_error(t){this.onerror("[BLE] "+t)}_change(t){switch(this._state=t,this.onchange(t),t){case i.State.Open:this.onopen();break;case i.State.Closed:this.onclose()}}}export{i as default};
1
+ const t=t=>new Promise(e=>setTimeout(e,t));class e{constructor(){this._session=0,this.reset()}run(t){const e=this._session,s=this._queue.then(()=>{if(e!==this._session)throw new Error("Queue empty");return t()});return this._queue=s.catch(()=>{}),s}runNothrow(t){return this.run(t).catch(()=>null)}reset(){this._session++,this._queue=Promise.resolve()}}class s{static State={Closed:"closed",Opening:"opening",Open:"open",Closing:"closing"};onbin(t){}onopen(){}onclose(){}onchange(t){}onselect(t){}onerror(t){}constructor(t={}){this.cfg={serviceUUID:"0000ffe0-0000-1000-8000-00805f9b34fb",rxUUID:"0000ffe1-0000-1000-8000-00805f9b34fb",txUUID:"0000ffe2-0000-1000-8000-00805f9b34fb",auto_open:!1,reconnect:1e3,chunkSize:500,chunkDelay:0,...t}}config(t={}){this.cfg={...this.cfg,...t}}static supported(){return"bluetooth"in navigator}opened(){return this._state===s.State.Open}selected(){return!!this._device}getName(){return this._device?this._device.name:null}async select(){try{await this.close(),this._device&&this._device.removeEventListener("gattserverdisconnected",this._disconnect_h),this._device=await navigator.bluetooth.requestDevice({filters:[{services:[this.cfg.serviceUUID]}],optionalServices:[this.cfg.serviceUUID]}),this._device.addEventListener("gattserverdisconnected",this._disconnect_h)}catch(t){this._error(t),this._device=null}return this.onselect(this.getName()),this.cfg.auto_open&&this.open(),this.selected()}async open(){return this._lifecycle.runNothrow(async()=>this._device?!!this.opened()||(this.cfg.reconnect&&(this.retry=!0),await this._open(),this.opened()):(this._error("No device"),!1))}async _open(){if(this._state===s.State.Closed){this._change(s.State.Opening);try{const t=await this._device.gatt.connect(),e=await t.getPrimaryService(this.cfg.serviceUUID);this._rx=await e.getCharacteristic(this.cfg.rxUUID),this._tx=await e.getCharacteristic(this.cfg.txUUID),await this._tx.startNotifications(),this._tx.addEventListener("characteristicvaluechanged",this._data_h),this._sender.reset(),this._change(s.State.Open)}catch(e){this._error(e),this._sender.reset(),this._change(s.State.Closed),this.retry&&t(this.cfg.reconnect).then(()=>{this._lifecycle.runNothrow(()=>this._open())})}}}async close(){return this._lifecycle.runNothrow(async()=>(this.retry=!1,this._sender.reset(),this._state!==s.State.Closed&&await this._close(),!0))}async _close(){if(this._state!==s.State.Closed){this._change(s.State.Closing);try{this._device?.gatt?.connected?this._device.gatt.disconnect():await this._disconnect()}catch(t){this._error(t),await this._disconnect()}}}async sendText(t,e=!0){await this.sendBin((new TextEncoder).encode(t),e)}async sendBin(e,s=!0){return!(!this.opened()||!this._rx)&&this._sender.runNothrow(async()=>{if(!this.opened()||!this._rx)return!1;const i=this.cfg.chunkSize,n=e instanceof Uint8Array?e:new Uint8Array(e);for(let e=0;e<n.length;e+=i){if(!this.opened()||!this._rx)return!1;const c=n.slice(e,e+i);s?await this._rx.writeValueWithoutResponse(c):await this._rx.writeValueWithResponse(c),this.cfg.chunkDelay>0&&await t(this.cfg.chunkDelay)}return!0})}_state=s.State.Closed;_device=null;_rx=null;_tx=null;retry=!1;_sender=new e;_lifecycle=new e;async _disconnect(e){if(this._sender.reset(),this._tx)try{this._tx.removeEventListener("characteristicvaluechanged",this._data_h)}catch(e){}this._rx=null,this._tx=null,this._change(s.State.Closed),this.retry&&t(this.cfg.reconnect).then(()=>{this._lifecycle.runNothrow(()=>this._open())}),await t(50)}_disconnect_h=this._disconnect.bind(this);_data(t){try{const e=t.target.value,s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);this.onbin(s)}catch(t){this._error(t)}}_data_h=this._data.bind(this);_error(t){this.onerror("[BLE] "+t)}_change(t){if(this._state!==t)switch(this._state=t,this.onchange(t),t){case s.State.Open:this.onopen();break;case s.State.Closed:this.onclose()}}}export{s as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexgyver/ble",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "Web BLE Serial",
5
5
  "main": "./ble.js",
6
6
  "module": "./ble.js",
@@ -21,7 +21,7 @@
21
21
  "webpack-dev-server": "^5.2.4"
22
22
  },
23
23
  "dependencies": {
24
- "@alexgyver/utils": "^1.2.7"
24
+ "@alexgyver/utils": "^1.2.8"
25
25
  },
26
26
  "author": "AlexGyver <alex@alexgyver.ru>",
27
27
  "license": "MIT"
package/test/script.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import BLEJS from "https://gyverlibs.github.io/BLE.js/ble.min.js";
2
- // import BLEJS from "../ble2light.js";
2
+ // import BLEJS from "../ble.js";
3
3
 
4
4
  let i = 0;
5
5
  let ble = new BLEJS({ auto_open: true });
@@ -8,14 +8,15 @@ let ble = new BLEJS({ auto_open: true });
8
8
  select_b.onclick = () => ble.select();
9
9
  open_b.onclick = () => ble.open();
10
10
  close_b.onclick = () => ble.close();
11
+
11
12
  send_b.onclick = async () => {
12
13
  ble.sendBin(new TextEncoder().encode('Hello ' + i++));
13
14
  }
14
15
 
15
- async function send(hex) {
16
- const data = new Uint8Array(hex.trim().split(/\s+/).map(x => parseInt(x, 16)));
17
- await ble.sendBin(data);
18
- }
16
+ // async function send(hex) {
17
+ // const data = new Uint8Array(hex.trim().split(/\s+/).map(x => parseInt(x, 16)));
18
+ // await ble.sendBin(data);
19
+ // }
19
20
 
20
21
  // read
21
22
  ble.onbin = b => console.log(new TextDecoder().decode(b));
package/ble2.js DELETED
@@ -1,192 +0,0 @@
1
- import { sleep, ShiftBuffer, StreamSplitter } from "@alexgyver/utils";
2
-
3
- export default class BLEJS {
4
- static State = {
5
- Closed: 'closed',
6
- Opening: 'opening',
7
- Open: 'open',
8
- Closing: 'closing',
9
- };
10
-
11
- //#region handlers
12
- onbin = null;
13
- ontext = null;
14
-
15
- onopen() { }
16
- onclose() { }
17
- onchange(s) { }
18
- onselect(name) { }
19
- onerror(e) { }
20
-
21
- //#region constructor
22
- constructor(params = {}) {
23
- const def = {
24
- eol: /\r?\n/,
25
- serviceUUID: '0000ffe0-0000-1000-8000-00805f9b34fb',
26
- rxUUID: '0000ffe1-0000-1000-8000-00805f9b34fb',
27
- txUUID: '0000ffe2-0000-1000-8000-00805f9b34fb',
28
- auto_open: false,
29
- max_tx: 20,
30
- reconnect: 1000,
31
- };
32
- this.cfg = { ...def, ...params };
33
-
34
- this.splitter = new StreamSplitter(this.cfg.eol);
35
- this.splitter.ontext = (t) => this.ontext && this.ontext(t);
36
- }
37
-
38
- //#region methods
39
- config(params = {}) {
40
- this.cfg = { ...this.cfg, ...params };
41
- this.splitter.eol = this.cfg.eol;
42
- }
43
-
44
- static supported() {
45
- return 'bluetooth' in navigator;
46
- }
47
-
48
- opened() {
49
- return this._state === BLEJS.State.Open;
50
- }
51
-
52
- selected() {
53
- return !!this._device;
54
- }
55
-
56
- getName() {
57
- return this._device ? this._device.name : null;
58
- }
59
-
60
- async select() {
61
- try {
62
- await this.close();
63
- if (this._device) this._device.removeEventListener('gattserverdisconnected', this._disconnect_h);
64
- this._device = await navigator.bluetooth.requestDevice({
65
- filters: [{ services: [this.cfg.serviceUUID] }],
66
- optionalServices: [this.cfg.serviceUUID]
67
- });
68
- this._device.addEventListener("gattserverdisconnected", this._disconnect_h);
69
- } catch (e) {
70
- this._error(e);
71
- this._device = null;
72
- }
73
- this.onselect(this.getName());
74
- if (this.cfg.auto_open) this.open();
75
- return this.selected();
76
- }
77
-
78
- async open() {
79
- if (!this._device) return;
80
- if (this.opened()) return;
81
-
82
- if (this.cfg.reconnect) this.retry = true;
83
- await this._open();
84
- }
85
-
86
- async _open() {
87
- if (this._state != BLEJS.State.Closed) return;
88
-
89
- this._change(BLEJS.State.Opening);
90
- try {
91
- const server = await this._device.gatt.connect();
92
- const service = await server.getPrimaryService(this.cfg.serviceUUID);
93
-
94
- this._rx = await service.getCharacteristic(this.cfg.rxUUID);
95
- this._tx = await service.getCharacteristic(this.cfg.txUUID);
96
-
97
- await this._tx.startNotifications();
98
- this._tx.addEventListener("characteristicvaluechanged", this._data_h);
99
-
100
- this._buffer.clear();
101
- this._change(BLEJS.State.Open);
102
- this._decoder = new TextDecoder();
103
- this.splitter.reset();
104
- } catch (e) {
105
- this._error(e);
106
- this._change(BLEJS.State.Closed);
107
- if (this.retry) sleep(this.cfg.reconnect).then(() => this._open());
108
- }
109
- }
110
-
111
- async close() {
112
- this.retry = false;
113
- if (this._device?.gatt?.connected) await this._close();
114
- }
115
-
116
- async _close() {
117
- this._change(BLEJS.State.Closing);
118
- try {
119
- if (this._device?.gatt?.connected) this._device.gatt.disconnect();
120
- else this._disconnect();
121
- } catch (e) {
122
- this._error(e);
123
- }
124
- }
125
-
126
- async sendText(text) {
127
- await this.sendBin((new TextEncoder()).encode(text));
128
- }
129
-
130
- async sendBin(data) {
131
- this._buffer.push(data);
132
- this._send();
133
- }
134
-
135
- //#region private
136
- _device = null;
137
- _rx = null;
138
- _tx = null;
139
- _state = BLEJS.State.Closed;
140
- _buffer = new ShiftBuffer();
141
- _decoder = new TextDecoder();
142
-
143
- async _disconnect(e) {
144
- this._change(BLEJS.State.Closed);
145
- if (this._tx) this._tx.removeEventListener('characteristicvaluechanged', this._data_h);
146
-
147
- this._rx = null;
148
- this._tx = null;
149
-
150
- if (this.retry) sleep(this.cfg.reconnect).then(() => this._open());
151
- await sleep(50);
152
- }
153
- _disconnect_h = this._disconnect.bind(this);
154
-
155
- _data(e) {
156
- const dv = e.target.value;
157
- const value = new Uint8Array(dv.buffer, dv.byteOffset, dv.byteLength);
158
- if (this.onbin) this.onbin(value);
159
- if (this.ontext) this.splitter.write(this._decoder.decode(value, { stream: true }));
160
- }
161
- _data_h = this._data.bind(this);
162
-
163
- async _send() {
164
- if (this._busy) return;
165
- this._busy = true;
166
-
167
- while (this._buffer.length && this._rx) {
168
- let d = this._buffer.shift(this.cfg.max_tx);
169
-
170
- try {
171
- if (d.length) await this._rx.writeValueWithoutResponse(d);
172
- // await this._rx.writeValueWithResponse(d);
173
- } catch (e) {
174
- this._error(e);
175
- }
176
- }
177
-
178
- this._busy = false;
179
- }
180
-
181
- _error(e) {
182
- this.onerror('[BLE] ' + e);
183
- }
184
- _change(s) {
185
- this._state = s;
186
- this.onchange(s);
187
- switch (s) {
188
- case BLEJS.State.Open: this.onopen(); break;
189
- case BLEJS.State.Closed: this.onclose(); break;
190
- }
191
- }
192
- }
package/ble2light.js DELETED
@@ -1,253 +0,0 @@
1
- import { sleep, SerialExecutor } from "@alexgyver/utils";
2
-
3
- export default class BLEJS {
4
- static State = {
5
- Closed: 'closed',
6
- Opening: 'opening',
7
- Open: 'open',
8
- Closing: 'closing',
9
- };
10
-
11
- onbin(b) { }
12
- onopen() { }
13
- onclose() { }
14
- onchange(s) { }
15
- onselect(name) { }
16
- onerror(e) { }
17
-
18
- constructor(params = {}) {
19
- const def = {
20
- serviceUUID: '0000ffe0-0000-1000-8000-00805f9b34fb',
21
- rxUUID: '0000ffe1-0000-1000-8000-00805f9b34fb',
22
- txUUID: '0000ffe2-0000-1000-8000-00805f9b34fb',
23
- auto_open: false,
24
- reconnect: 1000,
25
- };
26
-
27
- this.cfg = { ...def, ...params };
28
- }
29
-
30
- config(params = {}) {
31
- this.cfg = { ...this.cfg, ...params };
32
- }
33
-
34
- static supported() {
35
- return 'bluetooth' in navigator;
36
- }
37
-
38
- opened() {
39
- return this._state === BLEJS.State.Open;
40
- }
41
-
42
- selected() {
43
- return !!this._device;
44
- }
45
-
46
- getName() {
47
- return this._device ? this._device.name : null;
48
- }
49
-
50
- async select() {
51
- try {
52
- await this.close();
53
-
54
- if (this._device) {
55
- this._device.removeEventListener(
56
- 'gattserverdisconnected',
57
- this._disconnect_h
58
- );
59
- }
60
-
61
- this._device = await navigator.bluetooth.requestDevice({
62
- filters: [{ services: [this.cfg.serviceUUID] }],
63
- optionalServices: [this.cfg.serviceUUID],
64
- });
65
-
66
- this._device.addEventListener(
67
- 'gattserverdisconnected',
68
- this._disconnect_h
69
- );
70
- } catch (e) {
71
- this._error(e);
72
- this._device = null;
73
- }
74
-
75
- this.onselect(this.getName());
76
-
77
- if (this.cfg.auto_open) this.open();
78
-
79
- return this.selected();
80
- }
81
-
82
- async open() {
83
- return this._lifecycle.runNothrow(async () => {
84
- if (!this._device) {
85
- this._error('No device');
86
- return false;
87
- }
88
-
89
- if (this.opened()) return true;
90
-
91
- if (this.cfg.reconnect) this.retry = true;
92
-
93
- await this._open();
94
-
95
- return this.opened();
96
- });
97
- }
98
-
99
- async _open() {
100
- if (this._state !== BLEJS.State.Closed) return;
101
-
102
- this._change(BLEJS.State.Opening);
103
-
104
- try {
105
- const server = await this._device.gatt.connect();
106
- const service = await server.getPrimaryService(this.cfg.serviceUUID);
107
-
108
- this._rx = await service.getCharacteristic(this.cfg.rxUUID);
109
- this._tx = await service.getCharacteristic(this.cfg.txUUID);
110
-
111
- await this._tx.startNotifications();
112
- this._tx.addEventListener(
113
- 'characteristicvaluechanged',
114
- this._data_h
115
- );
116
-
117
- this._sender.reset();
118
- this._change(BLEJS.State.Open);
119
- } catch (e) {
120
- this._error(e);
121
- this._sender.reset();
122
- this._change(BLEJS.State.Closed);
123
-
124
- if (this.retry) {
125
- sleep(this.cfg.reconnect).then(() => {
126
- this._lifecycle.runNothrow(() => this._open());
127
- });
128
- }
129
- }
130
- }
131
-
132
- async close() {
133
- return this._lifecycle.runNothrow(async () => {
134
- this.retry = false;
135
- this._sender.reset();
136
-
137
- if (this._state !== BLEJS.State.Closed) {
138
- await this._close();
139
- }
140
-
141
- return true;
142
- });
143
- }
144
-
145
- async _close() {
146
- if (this._state === BLEJS.State.Closed) return;
147
-
148
- this._change(BLEJS.State.Closing);
149
-
150
- try {
151
- if (this._device?.gatt?.connected) {
152
- this._device.gatt.disconnect();
153
- } else {
154
- await this._disconnect();
155
- }
156
- } catch (e) {
157
- this._error(e);
158
- await this._disconnect();
159
- }
160
- }
161
-
162
- async sendBin(data, fast = true) {
163
- if (!this.opened() || !this._rx) return false;
164
-
165
- return this._sender.runNothrow(async () => {
166
- if (!this.opened() || !this._rx) return false;
167
-
168
- if (fast) {
169
- await this._rx.writeValueWithoutResponse(data);
170
- } else {
171
- await this._rx.writeValueWithResponse(data);
172
- }
173
-
174
- return true;
175
- });
176
- }
177
-
178
- _state = BLEJS.State.Closed;
179
- _device = null;
180
- _rx = null;
181
- _tx = null;
182
-
183
- retry = false;
184
-
185
- _sender = new SerialExecutor();
186
- _lifecycle = new SerialExecutor();
187
-
188
- async _disconnect(e) {
189
- this._sender.reset();
190
-
191
- if (this._tx) {
192
- try {
193
- this._tx.removeEventListener(
194
- 'characteristicvaluechanged',
195
- this._data_h
196
- );
197
- } catch (e) { }
198
- }
199
-
200
- this._rx = null;
201
- this._tx = null;
202
-
203
- this._change(BLEJS.State.Closed);
204
-
205
- if (this.retry) {
206
- sleep(this.cfg.reconnect).then(() => {
207
- this._lifecycle.runNothrow(() => this._open());
208
- });
209
- }
210
-
211
- await sleep(50);
212
- }
213
-
214
- _disconnect_h = this._disconnect.bind(this);
215
-
216
- _data(e) {
217
- try {
218
- const dv = e.target.value;
219
- const value = new Uint8Array(
220
- dv.buffer,
221
- dv.byteOffset,
222
- dv.byteLength
223
- );
224
-
225
- this.onbin(value);
226
- } catch (e) {
227
- this._error(e);
228
- }
229
- }
230
-
231
- _data_h = this._data.bind(this);
232
-
233
- _error(e) {
234
- this.onerror('[BLE] ' + e);
235
- }
236
-
237
- _change(s) {
238
- if (this._state === s) return;
239
-
240
- this._state = s;
241
- this.onchange(s);
242
-
243
- switch (s) {
244
- case BLEJS.State.Open:
245
- this.onopen();
246
- break;
247
-
248
- case BLEJS.State.Closed:
249
- this.onclose();
250
- break;
251
- }
252
- }
253
- }