taro-bluetooth-print 1.0.0

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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +201 -0
  3. package/dist/bluetooth/adapter.d.ts +31 -0
  4. package/dist/bluetooth/adapter.js +47 -0
  5. package/dist/bluetooth/adapter.js.map +1 -0
  6. package/dist/bluetooth/h5.d.ts +66 -0
  7. package/dist/bluetooth/h5.js +302 -0
  8. package/dist/bluetooth/h5.js.map +1 -0
  9. package/dist/bluetooth/harmony.d.ts +82 -0
  10. package/dist/bluetooth/harmony.js +342 -0
  11. package/dist/bluetooth/harmony.js.map +1 -0
  12. package/dist/bluetooth/index.d.ts +45 -0
  13. package/dist/bluetooth/index.js +175 -0
  14. package/dist/bluetooth/index.js.map +1 -0
  15. package/dist/bluetooth/rn.d.ts +35 -0
  16. package/dist/bluetooth/rn.js +368 -0
  17. package/dist/bluetooth/rn.js.map +1 -0
  18. package/dist/bluetooth/weapp.d.ts +16 -0
  19. package/dist/bluetooth/weapp.js +177 -0
  20. package/dist/bluetooth/weapp.js.map +1 -0
  21. package/dist/index.d.ts +16 -0
  22. package/dist/index.js +35 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/printer/commands.d.ts +28 -0
  25. package/dist/printer/commands.js +90 -0
  26. package/dist/printer/commands.js.map +1 -0
  27. package/dist/printer/image.d.ts +59 -0
  28. package/dist/printer/image.js +258 -0
  29. package/dist/printer/image.js.map +1 -0
  30. package/dist/printer/index.d.ts +87 -0
  31. package/dist/printer/index.js +362 -0
  32. package/dist/printer/index.js.map +1 -0
  33. package/dist/printer/template.d.ts +95 -0
  34. package/dist/printer/template.js +262 -0
  35. package/dist/printer/template.js.map +1 -0
  36. package/dist/utils/buffer.d.ts +35 -0
  37. package/dist/utils/buffer.js +96 -0
  38. package/dist/utils/buffer.js.map +1 -0
  39. package/dist/utils/encoding.d.ts +26 -0
  40. package/dist/utils/encoding.js +149 -0
  41. package/dist/utils/encoding.js.map +1 -0
  42. package/dist/utils/logger.d.ts +18 -0
  43. package/dist/utils/logger.js +91 -0
  44. package/dist/utils/logger.js.map +1 -0
  45. package/package.json +57 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Your Name
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,201 @@
1
+ # Taro 蓝牙打印库
2
+
3
+ 一个基于 Taro.js 的跨平台蓝牙打印库,支持微信小程序、H5、React Native 和鸿蒙等多平台,支持 ESC/POS 指令,可用于连接蓝牙打印机并发送打印数据。
4
+
5
+ ## 特性
6
+
7
+ - 支持多平台:微信小程序、H5、React Native、鸿蒙OS
8
+ - 支持 ESC/POS 打印指令
9
+ - 提供简洁易用的 API
10
+ - 支持打印文本、图片、条形码、二维码、收据等
11
+ - 支持文本格式化(对齐、加粗、下划线等)
12
+ - 支持打印模板系统,便于重用
13
+ - TypeScript 支持
14
+
15
+ ## 安装
16
+
17
+ ```bash
18
+ npm install taro-bluetooth-print --save
19
+ # 或
20
+ yarn add taro-bluetooth-print
21
+ ```
22
+
23
+ ## 使用示例
24
+
25
+ ### 基本使用
26
+
27
+ ```typescript
28
+ import Taro from '@tarojs/taro';
29
+ import TaroBluePrint from 'taro-bluetooth-print';
30
+
31
+ // 初始化打印库
32
+ const printer = new TaroBluePrint();
33
+
34
+ // 扫描并连接打印机
35
+ async function scanAndConnect() {
36
+ await printer.bluetooth.init();
37
+ await printer.bluetooth.startDiscovery();
38
+
39
+ Taro.showLoading({ title: '搜索打印机...' });
40
+
41
+ // 等待2秒钟搜索设备
42
+ await new Promise(resolve => setTimeout(resolve, 2000));
43
+
44
+ const devices = await printer.bluetooth.getDiscoveredDevices();
45
+ await printer.bluetooth.stopDiscovery();
46
+
47
+ Taro.hideLoading();
48
+
49
+ if (devices.length === 0) {
50
+ Taro.showToast({ title: '未找到打印机', icon: 'none' });
51
+ return;
52
+ }
53
+
54
+ // 显示设备列表让用户选择
55
+ const list = devices.map(device => ({
56
+ text: device.name || '未知设备',
57
+ value: device.deviceId
58
+ }));
59
+
60
+ Taro.showActionSheet({
61
+ itemList: list.map(item => item.text),
62
+ success: async (res) => {
63
+ const deviceId = list[res.tapIndex].value;
64
+
65
+ Taro.showLoading({ title: '连接中...' });
66
+ const connected = await printer.bluetooth.connect(deviceId);
67
+ Taro.hideLoading();
68
+
69
+ if (connected) {
70
+ Taro.showToast({ title: '连接成功' });
71
+
72
+ // 打印测试页
73
+ const printResult = await printer.printer.printTestPage();
74
+
75
+ if (printResult) {
76
+ Taro.showToast({ title: '打印成功' });
77
+ } else {
78
+ Taro.showToast({ title: '打印失败', icon: 'none' });
79
+ }
80
+
81
+ // 断开连接
82
+ await printer.bluetooth.disconnect();
83
+ } else {
84
+ Taro.showToast({ title: '连接失败', icon: 'none' });
85
+ }
86
+ }
87
+ });
88
+ }
89
+
90
+ // 调用扫描并连接
91
+ scanAndConnect();
92
+ ```
93
+
94
+ ### 打印文本
95
+
96
+ ```typescript
97
+ await printer.printer.printText('Hello, World!', {
98
+ align: 'center',
99
+ bold: true,
100
+ doubleHeight: true
101
+ });
102
+ ```
103
+
104
+ ### 打印图片
105
+
106
+ ```typescript
107
+ await printer.printer.printImage('https://example.com/logo.png', {
108
+ maxWidth: 300,
109
+ dithering: true
110
+ });
111
+
112
+ // 或打印Base64图片
113
+ await printer.printer.printImage('data:image/png;base64,...', {
114
+ maxWidth: 300
115
+ });
116
+ ```
117
+
118
+ ### 打印收据
119
+
120
+ ```typescript
121
+ await printer.printer.printReceipt({
122
+ title: '收据',
123
+ merchant: '示例商店',
124
+ items: [
125
+ { name: '商品1', price: 10.5, quantity: 2 },
126
+ { name: '商品2', price: 5.0, quantity: 1 }
127
+ ],
128
+ total: 26.0,
129
+ date: '2023-09-28 15:30:45',
130
+ footer: '感谢您的惠顾,欢迎再次光临!',
131
+ logo: 'https://example.com/logo.png' // 可选
132
+ });
133
+ ```
134
+
135
+ ### 打印条形码
136
+
137
+ ```typescript
138
+ await printer.printer.printBarcode('123456789', {
139
+ height: 80,
140
+ align: 'center'
141
+ });
142
+ ```
143
+
144
+ ### 打印二维码
145
+
146
+ ```typescript
147
+ await printer.printer.printQRCode('https://example.com', {
148
+ size: 8,
149
+ align: 'center'
150
+ });
151
+ ```
152
+
153
+ ### 使用打印模板
154
+
155
+ ```typescript
156
+ import { ReceiptTemplate } from 'taro-bluetooth-print/dist/printer/template';
157
+
158
+ // 创建收据模板
159
+ const receiptTemplate = new ReceiptTemplate({
160
+ title: '收据',
161
+ merchant: '示例商店',
162
+ items: [
163
+ { name: '商品1', price: 10.5, quantity: 2 },
164
+ { name: '商品2', price: 5.0, quantity: 1 }
165
+ ],
166
+ total: 26.0,
167
+ date: '2023-09-28 15:30:45',
168
+ footer: '感谢您的惠顾,欢迎再次光临!'
169
+ });
170
+
171
+ // 构建模板命令
172
+ const commands = await receiptTemplate.build();
173
+
174
+ // 发送打印命令
175
+ await printer.printer.sendCommands(commands);
176
+ ```
177
+
178
+ ## API 文档
179
+
180
+ 请查看完整的API文档以了解更多详情:[API文档](https://github.com/yourusername/taro-bluetooth-print/blob/main/docs/API.md)
181
+
182
+ ## 平台支持
183
+
184
+ | 功能 | 微信小程序 | H5 | React Native | 鸿蒙OS |
185
+ | --- | --- | --- | --- | --- |
186
+ | 设备扫描 | ✓ | ✓* | ✓ | ✓ |
187
+ | 设备连接 | ✓ | ✓* | ✓ | ✓ |
188
+ | 文本打印 | ✓ | ✓ | ✓ | ✓ |
189
+ | 图片打印 | ✓ | ✓ | ✓ | ✓ |
190
+ | 条码打印 | ✓ | ✓ | ✓ | ✓ |
191
+ | 二维码打印 | ✓ | ✓ | ✓ | ✓ |
192
+
193
+ *注意:H5 环境需要支持 Web Bluetooth API 的浏览器。目前 Chrome、Edge、Opera 等基于 Chromium 的浏览器支持此功能,且需要在 HTTPS 环境下使用。
194
+
195
+ ## 许可证
196
+
197
+ MIT
198
+
199
+ ## 贡献
200
+
201
+ 欢迎提交 Issue 和 PR!
@@ -0,0 +1,31 @@
1
+ export declare enum Platform {
2
+ WEAPP = "weapp",
3
+ H5 = "h5",
4
+ RN = "rn",
5
+ HARMONY = "harmony"
6
+ }
7
+ export interface BluetoothDevice {
8
+ deviceId: string;
9
+ name: string;
10
+ RSSI?: number;
11
+ advertisData?: ArrayBuffer;
12
+ deviceName?: string;
13
+ localName?: string;
14
+ }
15
+ export interface BluetoothAdapter {
16
+ init(): Promise<boolean>;
17
+ getAdapterState(): Promise<any>;
18
+ startDiscovery(): Promise<boolean>;
19
+ stopDiscovery(): Promise<boolean>;
20
+ getDiscoveredDevices(): Promise<BluetoothDevice[]>;
21
+ connect(deviceId: string): Promise<boolean>;
22
+ disconnect(deviceId?: string): Promise<boolean>;
23
+ getServices(deviceId: string): Promise<any>;
24
+ getCharacteristics(deviceId: string, serviceId: string): Promise<any>;
25
+ write(deviceId: string, serviceId: string, characteristicId: string, data: ArrayBuffer): Promise<boolean>;
26
+ read(deviceId: string, serviceId: string, characteristicId: string): Promise<ArrayBuffer>;
27
+ notifyCharacteristicValueChange(deviceId: string, serviceId: string, characteristicId: string, state: boolean): Promise<boolean>;
28
+ destroy(): Promise<boolean>;
29
+ }
30
+ export declare function getCurrentPlatform(): Platform;
31
+ export declare function getAdapter(): BluetoothAdapter;
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getAdapter = exports.getCurrentPlatform = exports.Platform = void 0;
4
+ var Platform;
5
+ (function (Platform) {
6
+ Platform["WEAPP"] = "weapp";
7
+ Platform["H5"] = "h5";
8
+ Platform["RN"] = "rn";
9
+ Platform["HARMONY"] = "harmony";
10
+ })(Platform = exports.Platform || (exports.Platform = {}));
11
+ function getCurrentPlatform() {
12
+ if (process.env.TARO_ENV === 'weapp') {
13
+ return Platform.WEAPP;
14
+ }
15
+ else if (process.env.TARO_ENV === 'h5') {
16
+ return Platform.H5;
17
+ }
18
+ else if (process.env.TARO_ENV === 'rn') {
19
+ return Platform.RN;
20
+ }
21
+ else if (process.env.TARO_ENV === 'harmony') {
22
+ return Platform.HARMONY;
23
+ }
24
+ throw new Error('不支持的平台');
25
+ }
26
+ exports.getCurrentPlatform = getCurrentPlatform;
27
+ function getAdapter() {
28
+ const platform = getCurrentPlatform();
29
+ switch (platform) {
30
+ case Platform.WEAPP:
31
+ const { WeappBluetoothAdapter } = require('./weapp');
32
+ return new WeappBluetoothAdapter();
33
+ case Platform.H5:
34
+ const { H5BluetoothAdapter } = require('./h5');
35
+ return new H5BluetoothAdapter();
36
+ case Platform.RN:
37
+ const { RNBluetoothAdapter } = require('./rn');
38
+ return new RNBluetoothAdapter();
39
+ case Platform.HARMONY:
40
+ const { HarmonyBluetoothAdapter } = require('./harmony');
41
+ return new HarmonyBluetoothAdapter();
42
+ default:
43
+ throw new Error('不支持的平台');
44
+ }
45
+ }
46
+ exports.getAdapter = getAdapter;
47
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.js","sourceRoot":"","sources":["../../src/bluetooth/adapter.ts"],"names":[],"mappings":";;;AAEA,IAAY,QAKX;AALD,WAAY,QAAQ;IAClB,2BAAe,CAAA;IACf,qBAAS,CAAA;IACT,qBAAS,CAAA;IACT,+BAAmB,CAAA;AACrB,CAAC,EALW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAKnB;AAoDD,SAAgB,kBAAkB;IAChC,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,OAAO,EAAE;QACpC,OAAO,QAAQ,CAAC,KAAK,CAAC;KACvB;SAAM,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,IAAI,EAAE;QACxC,OAAO,QAAQ,CAAC,EAAE,CAAC;KACpB;SAAM,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,IAAI,EAAE;QACxC,OAAO,QAAQ,CAAC,EAAE,CAAC;KACpB;SAAM,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,SAAS,EAAE;QAC7C,OAAO,QAAQ,CAAC,OAAO,CAAC;KACzB;IACD,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,CAAC;AAC5B,CAAC;AAXD,gDAWC;AAED,SAAgB,UAAU;IACxB,MAAM,QAAQ,GAAG,kBAAkB,EAAE,CAAC;IAEtC,QAAQ,QAAQ,EAAE;QAChB,KAAK,QAAQ,CAAC,KAAK;YACjB,MAAM,EAAE,qBAAqB,EAAE,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;YACrD,OAAO,IAAI,qBAAqB,EAAE,CAAC;QACrC,KAAK,QAAQ,CAAC,EAAE;YACd,MAAM,EAAE,kBAAkB,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;YAC/C,OAAO,IAAI,kBAAkB,EAAE,CAAC;QAClC,KAAK,QAAQ,CAAC,EAAE;YACd,MAAM,EAAE,kBAAkB,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;YAC/C,OAAO,IAAI,kBAAkB,EAAE,CAAC;QAClC,KAAK,QAAQ,CAAC,OAAO;YACnB,MAAM,EAAE,uBAAuB,EAAE,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;YACzD,OAAO,IAAI,uBAAuB,EAAE,CAAC;QACvC;YACE,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,CAAC;KAC7B;AACH,CAAC;AAnBD,gCAmBC"}
@@ -0,0 +1,66 @@
1
+ import { BluetoothAdapter, BluetoothDevice } from './adapter';
2
+ declare global {
3
+ interface Navigator {
4
+ bluetooth?: {
5
+ requestDevice(options?: any): Promise<any>;
6
+ getAvailability(): Promise<boolean>;
7
+ };
8
+ }
9
+ interface BluetoothRemoteGATTServer {
10
+ connected: boolean;
11
+ device: any;
12
+ connect(): Promise<BluetoothRemoteGATTServer>;
13
+ disconnect(): void;
14
+ getPrimaryServices(service?: BluetoothServiceUUID): Promise<BluetoothRemoteGATTService[]>;
15
+ }
16
+ interface BluetoothRemoteGATTService {
17
+ uuid: string;
18
+ device: any;
19
+ isPrimary: boolean;
20
+ getCharacteristics(characteristic?: BluetoothCharacteristicUUID): Promise<BluetoothRemoteGATTCharacteristic[]>;
21
+ }
22
+ interface BluetoothRemoteGATTCharacteristic {
23
+ uuid: string;
24
+ service: BluetoothRemoteGATTService;
25
+ properties: {
26
+ broadcast: boolean;
27
+ read: boolean;
28
+ writeWithoutResponse: boolean;
29
+ write: boolean;
30
+ notify: boolean;
31
+ indicate: boolean;
32
+ authenticatedSignedWrites: boolean;
33
+ reliableWrite: boolean;
34
+ writableAuxiliaries: boolean;
35
+ };
36
+ readValue(): Promise<DataView>;
37
+ writeValue(value: BufferSource): Promise<void>;
38
+ startNotifications(): Promise<BluetoothRemoteGATTCharacteristic>;
39
+ stopNotifications(): Promise<BluetoothRemoteGATTCharacteristic>;
40
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
41
+ removeEventListener(type: string, callback: EventListenerOrEventListenerObject, options?: EventListenerOptions | boolean): void;
42
+ }
43
+ type BluetoothServiceUUID = string | number;
44
+ type BluetoothCharacteristicUUID = string | number;
45
+ }
46
+ export declare class H5BluetoothAdapter implements BluetoothAdapter {
47
+ private bluetooth;
48
+ private device;
49
+ private gattServer;
50
+ private services;
51
+ private characteristics;
52
+ private eventListeners;
53
+ init(): Promise<boolean>;
54
+ getAdapterState(): Promise<any>;
55
+ startDiscovery(): Promise<boolean>;
56
+ stopDiscovery(): Promise<boolean>;
57
+ getDiscoveredDevices(): Promise<BluetoothDevice[]>;
58
+ connect(deviceId: string): Promise<boolean>;
59
+ disconnect(deviceId?: string): Promise<boolean>;
60
+ getServices(deviceId: string): Promise<any>;
61
+ getCharacteristics(deviceId: string, serviceId: string): Promise<any>;
62
+ write(deviceId: string, serviceId: string, characteristicId: string, data: ArrayBuffer): Promise<boolean>;
63
+ read(deviceId: string, serviceId: string, characteristicId: string): Promise<ArrayBuffer>;
64
+ notifyCharacteristicValueChange(deviceId: string, serviceId: string, characteristicId: string, state: boolean): Promise<boolean>;
65
+ destroy(): Promise<boolean>;
66
+ }
@@ -0,0 +1,302 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.H5BluetoothAdapter = void 0;
4
+ const logger_1 = require("../utils/logger");
5
+ class H5BluetoothAdapter {
6
+ constructor() {
7
+ this.bluetooth = null;
8
+ this.device = null;
9
+ this.gattServer = null;
10
+ this.services = new Map();
11
+ this.characteristics = new Map();
12
+ this.eventListeners = new Map();
13
+ }
14
+ async init() {
15
+ try {
16
+ if (!navigator.bluetooth) {
17
+ throw new Error('当前浏览器不支持Web Bluetooth API');
18
+ }
19
+ // 检查蓝牙是否可用
20
+ const available = await navigator.bluetooth.getAvailability();
21
+ if (!available) {
22
+ throw new Error('蓝牙不可用');
23
+ }
24
+ this.bluetooth = navigator.bluetooth;
25
+ return true;
26
+ }
27
+ catch (error) {
28
+ logger_1.logger.error('初始化蓝牙模块失败', error);
29
+ return false;
30
+ }
31
+ }
32
+ async getAdapterState() {
33
+ var _a;
34
+ try {
35
+ if (!this.bluetooth) {
36
+ throw new Error('蓝牙模块未初始化');
37
+ }
38
+ const available = await ((_a = navigator.bluetooth) === null || _a === void 0 ? void 0 : _a.getAvailability());
39
+ return { available: available || false };
40
+ }
41
+ catch (error) {
42
+ logger_1.logger.error('获取蓝牙适配器状态失败', error);
43
+ throw error;
44
+ }
45
+ }
46
+ async startDiscovery() {
47
+ try {
48
+ if (!this.bluetooth) {
49
+ await this.init();
50
+ }
51
+ // 打印机通常使用的服务 (这些值可能需要根据具体打印机调整)
52
+ const printerServices = [
53
+ '000018f0-0000-1000-8000-00805f9b34fb',
54
+ '49535343-fe7d-4ae5-8fa9-9fafd205e455',
55
+ '00001101-0000-1000-8000-00805f9b34fb',
56
+ '0000180a-0000-1000-8000-00805f9b34fb' // 设备信息服务
57
+ ];
58
+ // Web Bluetooth API使用requestDevice方法触发设备选择
59
+ this.device = await this.bluetooth.requestDevice({
60
+ // 过滤器用于找到打印机设备
61
+ filters: [
62
+ { services: printerServices },
63
+ { namePrefix: 'Printer' },
64
+ { namePrefix: 'printer' },
65
+ { namePrefix: 'POS' },
66
+ { namePrefix: 'pos' },
67
+ { namePrefix: 'BT' }
68
+ ],
69
+ // 添加可选服务以便于访问
70
+ optionalServices: printerServices
71
+ });
72
+ if (this.device) {
73
+ return true;
74
+ }
75
+ return false;
76
+ }
77
+ catch (error) {
78
+ logger_1.logger.error('开始搜索蓝牙设备失败', error);
79
+ return false;
80
+ }
81
+ }
82
+ async stopDiscovery() {
83
+ // Web Bluetooth API没有停止搜索的方法,因为搜索已经在设备选择完成后结束
84
+ return true;
85
+ }
86
+ async getDiscoveredDevices() {
87
+ if (!this.device) {
88
+ return [];
89
+ }
90
+ return [{
91
+ deviceId: this.device.id,
92
+ name: this.device.name || '未知设备',
93
+ deviceName: this.device.name
94
+ }];
95
+ }
96
+ async connect(deviceId) {
97
+ var _a;
98
+ try {
99
+ if (!this.device || this.device.id !== deviceId) {
100
+ logger_1.logger.error('设备未找到或ID不匹配');
101
+ return false;
102
+ }
103
+ // 连接到GATT服务器
104
+ this.gattServer = await this.device.gatt.connect();
105
+ // 连接后自动发现服务
106
+ if (this.gattServer) {
107
+ await this.getServices(deviceId);
108
+ }
109
+ return ((_a = this.gattServer) === null || _a === void 0 ? void 0 : _a.connected) || false;
110
+ }
111
+ catch (error) {
112
+ logger_1.logger.error('连接蓝牙设备失败', error);
113
+ return false;
114
+ }
115
+ }
116
+ async disconnect(deviceId) {
117
+ try {
118
+ if (this.gattServer && this.gattServer.connected) {
119
+ this.gattServer.disconnect();
120
+ this.services.clear();
121
+ this.characteristics.clear();
122
+ }
123
+ return true;
124
+ }
125
+ catch (error) {
126
+ logger_1.logger.error('断开蓝牙连接失败', error);
127
+ return false;
128
+ }
129
+ }
130
+ async getServices(deviceId) {
131
+ try {
132
+ if (!this.gattServer) {
133
+ throw new Error('未连接到GATT服务器');
134
+ }
135
+ const services = await this.gattServer.getPrimaryServices();
136
+ const result = { services: [] };
137
+ for (const service of services) {
138
+ this.services.set(service.uuid, service);
139
+ result.services.push({
140
+ uuid: service.uuid,
141
+ isPrimary: service.isPrimary
142
+ });
143
+ // 自动获取每个服务的特征值
144
+ await this.getCharacteristics(deviceId, service.uuid);
145
+ }
146
+ return result;
147
+ }
148
+ catch (error) {
149
+ logger_1.logger.error('获取服务失败', error);
150
+ throw error;
151
+ }
152
+ }
153
+ async getCharacteristics(deviceId, serviceId) {
154
+ try {
155
+ const service = this.services.get(serviceId);
156
+ if (!service) {
157
+ throw new Error(`服务${serviceId}未找到`);
158
+ }
159
+ const characteristics = await service.getCharacteristics();
160
+ const result = { characteristics: [] };
161
+ if (!this.characteristics.has(serviceId)) {
162
+ this.characteristics.set(serviceId, new Map());
163
+ }
164
+ const serviceChars = this.characteristics.get(serviceId);
165
+ for (const char of characteristics) {
166
+ serviceChars.set(char.uuid, char);
167
+ result.characteristics.push({
168
+ uuid: char.uuid,
169
+ properties: {
170
+ read: char.properties.read,
171
+ write: char.properties.write,
172
+ notify: char.properties.notify,
173
+ writeWithoutResponse: char.properties.writeWithoutResponse
174
+ }
175
+ });
176
+ }
177
+ return result;
178
+ }
179
+ catch (error) {
180
+ logger_1.logger.error('获取特征值失败', error);
181
+ throw error;
182
+ }
183
+ }
184
+ async write(deviceId, serviceId, characteristicId, data) {
185
+ try {
186
+ if (!this.characteristics.has(serviceId)) {
187
+ await this.getCharacteristics(deviceId, serviceId);
188
+ }
189
+ const serviceChars = this.characteristics.get(serviceId);
190
+ if (!serviceChars) {
191
+ throw new Error(`服务${serviceId}的特征值未找到`);
192
+ }
193
+ const characteristic = serviceChars.get(characteristicId);
194
+ if (!characteristic) {
195
+ throw new Error(`特征值${characteristicId}未找到`);
196
+ }
197
+ await characteristic.writeValue(data);
198
+ return true;
199
+ }
200
+ catch (error) {
201
+ logger_1.logger.error('写入数据失败', error);
202
+ return false;
203
+ }
204
+ }
205
+ async read(deviceId, serviceId, characteristicId) {
206
+ try {
207
+ if (!this.characteristics.has(serviceId)) {
208
+ await this.getCharacteristics(deviceId, serviceId);
209
+ }
210
+ const serviceChars = this.characteristics.get(serviceId);
211
+ if (!serviceChars) {
212
+ throw new Error(`服务${serviceId}的特征值未找到`);
213
+ }
214
+ const characteristic = serviceChars.get(characteristicId);
215
+ if (!characteristic) {
216
+ throw new Error(`特征值${characteristicId}未找到`);
217
+ }
218
+ const value = await characteristic.readValue();
219
+ return value.buffer;
220
+ }
221
+ catch (error) {
222
+ logger_1.logger.error('读取数据失败', error);
223
+ throw error;
224
+ }
225
+ }
226
+ async notifyCharacteristicValueChange(deviceId, serviceId, characteristicId, state) {
227
+ try {
228
+ if (!this.characteristics.has(serviceId)) {
229
+ await this.getCharacteristics(deviceId, serviceId);
230
+ }
231
+ const serviceChars = this.characteristics.get(serviceId);
232
+ if (!serviceChars) {
233
+ throw new Error(`服务${serviceId}的特征值未找到`);
234
+ }
235
+ const characteristic = serviceChars.get(characteristicId);
236
+ if (!characteristic) {
237
+ throw new Error(`特征值${characteristicId}未找到`);
238
+ }
239
+ if (state) {
240
+ await characteristic.startNotifications();
241
+ // 创建并存储事件监听器,以便以后可以移除
242
+ const listenerKey = `${deviceId}_${serviceId}_${characteristicId}`;
243
+ // 创建类型安全的事件监听器
244
+ const listener = function (event) {
245
+ // 安全地转换类型
246
+ if (event.target && event.target instanceof EventTarget) {
247
+ // Web Bluetooth API中,值在characteristicvaluechanged事件中
248
+ if ('readValue' in event.target) {
249
+ try {
250
+ const characteristic = event.target;
251
+ characteristic.readValue().then((dataView) => {
252
+ logger_1.logger.debug('特征值变化:', new Uint8Array(dataView.buffer));
253
+ });
254
+ }
255
+ catch (error) {
256
+ logger_1.logger.error('读取特征值变化失败', error);
257
+ }
258
+ }
259
+ }
260
+ };
261
+ this.eventListeners.set(listenerKey, listener);
262
+ // 添加通知事件监听器
263
+ characteristic.addEventListener('characteristicvaluechanged', this.eventListeners.get(listenerKey));
264
+ }
265
+ else {
266
+ await characteristic.stopNotifications();
267
+ // 获取并移除事件监听器
268
+ const listenerKey = `${deviceId}_${serviceId}_${characteristicId}`;
269
+ const listener = this.eventListeners.get(listenerKey);
270
+ if (listener) {
271
+ characteristic.removeEventListener('characteristicvaluechanged', listener);
272
+ this.eventListeners.delete(listenerKey);
273
+ }
274
+ }
275
+ return true;
276
+ }
277
+ catch (error) {
278
+ logger_1.logger.error('监听特征值变化失败', error);
279
+ return false;
280
+ }
281
+ }
282
+ async destroy() {
283
+ try {
284
+ if (this.gattServer && this.gattServer.connected) {
285
+ this.gattServer.disconnect();
286
+ }
287
+ // 清除所有事件监听器
288
+ this.eventListeners.clear();
289
+ this.device = null;
290
+ this.gattServer = null;
291
+ this.services.clear();
292
+ this.characteristics.clear();
293
+ return true;
294
+ }
295
+ catch (error) {
296
+ logger_1.logger.error('销毁蓝牙适配器失败', error);
297
+ return false;
298
+ }
299
+ }
300
+ }
301
+ exports.H5BluetoothAdapter = H5BluetoothAdapter;
302
+ //# sourceMappingURL=h5.js.map