@alexgyver/ble 1.0.0 → 1.0.1

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.
@@ -0,0 +1,3 @@
1
+ {
2
+ "liveServer.settings.port": 5501
3
+ }
package/README.md CHANGED
@@ -4,7 +4,11 @@
4
4
  - Буферизация отправки
5
5
  - Буферизация приёма, разделение текста по разделителю
6
6
 
7
- > npm i @alexgyver/ble
7
+ [demo](https://gyverlibs.github.io/BLE.js/test/)
8
+
9
+ > **Browser**: https://gyverlibs.github.io/BLE.js/BLE.min.js
10
+
11
+ > **Node**: npm i @alexgyver/ble
8
12
 
9
13
  ## Дока
10
14
  ```js
package/ble2.js ADDED
@@ -0,0 +1,192 @@
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 ADDED
@@ -0,0 +1,165 @@
1
+ export default class BLEJS {
2
+ static State = {
3
+ Closed: 'closed',
4
+ Opening: 'opening',
5
+ Open: 'open',
6
+ Closing: 'closing',
7
+ };
8
+
9
+ //#region handlers
10
+ onbin = null;
11
+
12
+ onopen() { }
13
+ onclose() { }
14
+ onchange(s) { }
15
+ onselect(name) { }
16
+ onerror(e) { }
17
+
18
+ //#region constructor
19
+ constructor(params = {}) {
20
+ const def = {
21
+ serviceUUID: '0000ffe0-0000-1000-8000-00805f9b34fb',
22
+ rxUUID: '0000ffe1-0000-1000-8000-00805f9b34fb',
23
+ txUUID: '0000ffe2-0000-1000-8000-00805f9b34fb',
24
+ auto_open: false,
25
+ reconnect: 1000,
26
+ };
27
+ this.cfg = { ...def, ...params };
28
+ }
29
+
30
+ //#region methods
31
+ config(params = {}) {
32
+ this.cfg = { ...this.cfg, ...params };
33
+ }
34
+
35
+ static supported() {
36
+ return 'bluetooth' in navigator;
37
+ }
38
+
39
+ opened() {
40
+ return this._state === BLEJS.State.Open;
41
+ }
42
+
43
+ selected() {
44
+ return !!this._device;
45
+ }
46
+
47
+ getName() {
48
+ return this._device ? this._device.name : null;
49
+ }
50
+
51
+ async select() {
52
+ try {
53
+ await this.close();
54
+ if (this._device) this._device.removeEventListener('gattserverdisconnected', this._disconnect_h);
55
+ this._device = await navigator.bluetooth.requestDevice({
56
+ filters: [{ services: [this.cfg.serviceUUID] }],
57
+ optionalServices: [this.cfg.serviceUUID]
58
+ });
59
+ this._device.addEventListener("gattserverdisconnected", this._disconnect_h);
60
+ } catch (e) {
61
+ this._error(e);
62
+ this._device = null;
63
+ }
64
+
65
+ this.onselect(this.getName());
66
+ if (this.cfg.auto_open) this.open();
67
+ return this.selected();
68
+ }
69
+
70
+ async open() {
71
+ if (!this._device) {
72
+ this._error("No device");
73
+ return;
74
+ }
75
+ if (this.opened()) return;
76
+
77
+ if (this.cfg.reconnect) this.retry = true;
78
+ await this._open();
79
+ }
80
+
81
+ async _open() {
82
+ if (this._state != BLEJS.State.Closed) return;
83
+
84
+ this._change(BLEJS.State.Opening);
85
+ try {
86
+ const server = await this._device.gatt.connect();
87
+ const service = await server.getPrimaryService(this.cfg.serviceUUID);
88
+
89
+ this._rx = await service.getCharacteristic(this.cfg.rxUUID);
90
+ this._tx = await service.getCharacteristic(this.cfg.txUUID);
91
+
92
+ await this._tx.startNotifications();
93
+ this._tx.addEventListener("characteristicvaluechanged", this._data_h);
94
+
95
+ this._change(BLEJS.State.Open);
96
+ } catch (e) {
97
+ this._error(e);
98
+ this._change(BLEJS.State.Closed);
99
+ if (this.retry) sleep(this.cfg.reconnect).then(() => this._open());
100
+ }
101
+ }
102
+
103
+ async close() {
104
+ this.retry = false;
105
+ if (this._device?.gatt?.connected) await this._close();
106
+ }
107
+
108
+ async _close() {
109
+ this._change(BLEJS.State.Closing);
110
+ try {
111
+ if (this._device?.gatt?.connected) this._device.gatt.disconnect();
112
+ else this._disconnect();
113
+ } catch (e) {
114
+ this._error(e);
115
+ }
116
+ }
117
+
118
+ async sendBin(data, fast = true) {
119
+ try {
120
+ if (fast) await this._rx.writeValueWithoutResponse(data);
121
+ else await this._rx.writeValueWithResponse(data);
122
+ } catch (e) {
123
+ this._error(e);
124
+ }
125
+ }
126
+
127
+ //#region private
128
+ _state = BLEJS.State.Closed;
129
+ _device = null;
130
+ _rx = null;
131
+ _tx = null;
132
+
133
+ async _disconnect(e) {
134
+ this._change(BLEJS.State.Closed);
135
+ if (this._tx) this._tx.removeEventListener('characteristicvaluechanged', this._data_h);
136
+
137
+ this._rx = null;
138
+ this._tx = null;
139
+
140
+ if (this.retry) sleep(this.cfg.reconnect).then(() => this._open());
141
+ await sleep(50);
142
+ }
143
+ _disconnect_h = this._disconnect.bind(this);
144
+
145
+ _data(e) {
146
+ const dv = e.target.value;
147
+ const value = new Uint8Array(dv.buffer, dv.byteOffset, dv.byteLength);
148
+ if (this.onbin) this.onbin(value);
149
+ }
150
+ _data_h = this._data.bind(this);
151
+
152
+ _error(e) {
153
+ this.onerror('[BLE] ' + e);
154
+ }
155
+ _change(s) {
156
+ this._state = s;
157
+ this.onchange(s);
158
+ switch (s) {
159
+ case BLEJS.State.Open: this.onopen(); break;
160
+ case BLEJS.State.Closed: this.onclose(); break;
161
+ }
162
+ }
163
+ }
164
+
165
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexgyver/ble",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Web BLE Serial",
5
5
  "main": "./ble.js",
6
6
  "module": "./ble.js",
@@ -14,14 +14,15 @@
14
14
  "url": "git+https://github.com/GyverLibs/ble.js.git"
15
15
  },
16
16
  "devDependencies": {
17
- "webpack": "^5.103.0",
17
+ "css-loader": "^7.1.3",
18
+ "style-loader": "^4.0.0",
19
+ "webpack": "^5.105.1",
18
20
  "webpack-cli": "^6.0.1",
19
- "webpack-dev-server": "^5.2.2",
20
- "html-webpack-plugin": "^5.6.5"
21
+ "webpack-dev-server": "^5.2.3"
21
22
  },
22
23
  "dependencies": {
23
24
  "@alexgyver/utils": "^1.2.4"
24
25
  },
25
26
  "author": "AlexGyver <alex@alexgyver.ru>",
26
27
  "license": "MIT"
27
- }
28
+ }
package/test/index.html CHANGED
@@ -3,8 +3,7 @@
3
3
 
4
4
  <head>
5
5
  <meta charset="UTF-8">
6
- <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
7
- <script src="script.js" type="module" defer="defer"></script>
6
+ <script src="./script.js" type="module"></script>
8
7
  <title>BLE test</title>
9
8
  </head>
10
9
 
package/test/script.js CHANGED
@@ -1,17 +1,25 @@
1
1
  import BLEJS from "https://gyverlibs.github.io/BLE.js/ble.min.js";
2
+ // import BLEJS from "../ble2light.js";
2
3
 
3
4
  let i = 0;
4
- let ble = new BLEJS({ auto_open: true, eol: '' });
5
+ let ble = new BLEJS({ auto_open: true });
5
6
 
6
7
  // control
7
8
  select_b.onclick = () => ble.select();
8
9
  open_b.onclick = () => ble.open();
9
10
  close_b.onclick = () => ble.close();
10
- send_b.onclick = () => ble.sendText('Hello ' + i++);
11
+ send_b.onclick = async () => {
12
+ ble.sendBin(new TextEncoder().encode('Hello ' + i++));
13
+ }
14
+
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
+ }
11
19
 
12
20
  // read
13
- // ble.onbin = b => console.log(b);
14
- ble.ontext = t => console.log(t);
21
+ ble.onbin = b => console.log(new TextDecoder().decode(b));
22
+ // ble.ontext = t => console.log(t);
15
23
 
16
24
  // state
17
25
  // ble.onopen = () => {
@@ -1,39 +1,24 @@
1
1
  const path = require('path');
2
- const PACKAGE = require('./package.json');
3
- const HtmlWebpackPlugin = require('html-webpack-plugin');
4
2
 
5
3
  module.exports = {
6
- entry: {
7
- index: './test_dev/script.js',
8
- },
9
-
4
+ entry: './test/script.js',
10
5
  output: {
11
6
  filename: 'script.js',
12
- path: path.resolve(__dirname, 'dev'),
13
- clean: true,
7
+ path: path.resolve(__dirname, 'test'),
8
+ clean: false,
9
+ },
10
+ module: {
11
+ rules: [
12
+ {
13
+ test: /\.css$/,
14
+ use: ['style-loader', 'css-loader'],
15
+ }
16
+ ]
14
17
  },
15
-
16
- plugins: [
17
- new HtmlWebpackPlugin({
18
- template: `./test_dev/index.html`,
19
- filename: `index.html`,
20
- inject: true,
21
- minify: false,
22
- version: PACKAGE.version,
23
- title: PACKAGE.title,
24
- }),
25
- ],
26
-
27
18
  devServer: {
28
- watchFiles: ['test_dev/*.html'],
29
- static: path.resolve(__dirname, './dev'),
19
+ static: path.resolve(__dirname, 'test'),
30
20
  hot: true,
31
21
  open: true,
32
22
  },
33
-
34
- watchOptions: {
35
- poll: 1000,
36
- },
37
-
38
23
  mode: 'development',
39
24
  };
@@ -1,18 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
-
4
- <head>
5
- <meta charset="UTF-8">
6
- <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
7
- <script src="script.js" type="module" defer="defer"></script>
8
- <title>BLE test</title>
9
- </head>
10
-
11
- <body>
12
- <button id="select_b">select</button>
13
- <button id="open_b">open</button>
14
- <button id="close_b">close</button>
15
- <button id="send_b">send</button>
16
- </body>
17
-
18
- </html>
@@ -1,31 +0,0 @@
1
- import BLEJS from "../ble";
2
-
3
- let i = 0;
4
- let ble = new BLEJS({ auto_open: true, eol: '' });
5
-
6
- // control
7
- select_b.onclick = () => ble.select();
8
- open_b.onclick = () => ble.open();
9
- close_b.onclick = () => ble.close();
10
- send_b.onclick = () => ble.sendText('Hello ' + i++);
11
-
12
- // read
13
- // ble.onbin = b => console.log(b);
14
- ble.ontext = t => console.log(t);
15
-
16
- // state
17
- // ble.onopen = () => {
18
- // console.log('Opened', ble.getName());
19
- // }
20
- // ble.onclose = () => {
21
- // console.log('Closed');
22
- // }
23
- ble.onchange = s => {
24
- console.log(s);
25
- }
26
- ble.onerror = e => {
27
- console.log(e);
28
- }
29
- ble.onselect = (d) => {
30
- console.log('select', d);
31
- }