bluetooth.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. class Bluetooth {
  2. constructor() {
  3. this.isOpenBle = false;
  4. this.deviceId = "";
  5. this.serviceId = "";
  6. this.writeId = "";
  7. this.notifyId = "";
  8. this.BluetoothConnectStatus = false this.printStatus = false this.init()
  9. }
  10. init() {
  11. this.closeBluetoothAdapter().then(() = >{
  12. console.log("init初始关闭蓝牙模块") this.openBluetoothAdapter().then(() = >{
  13. console.log("init初始化蓝牙模块") this.reconnect() //自动连接蓝牙设备
  14. })
  15. })
  16. }
  17. showToast(title) {
  18. uni.showToast({
  19. title: title,
  20. icon: 'none',
  21. 'duration': 2000
  22. });
  23. }
  24. openBluetoothAdapter() {
  25. return new Promise((resolve, reject) = >{
  26. uni.openBluetoothAdapter({
  27. success: res = >{
  28. this.isOpenBle = true;
  29. resolve(res);
  30. },
  31. fail: err = >{
  32. this.showToast(`蓝牙未打开`);
  33. reject(err);
  34. },
  35. });
  36. });
  37. }
  38. startBluetoothDevicesDiscovery() {
  39. if (!this.isOpenBle) {
  40. this.showToast(`初始化蓝牙模块失败`) return;
  41. }
  42. let self = this;
  43. uni.showLoading({
  44. title: '蓝牙搜索中'
  45. }) return new Promise((resolve, reject) = >{
  46. setTimeout(() = >{
  47. uni.startBluetoothDevicesDiscovery({
  48. success: res = >{
  49. resolve(res)
  50. },
  51. fail: res = >{
  52. self.showToast(`搜索设备失败` + JSON.stringify(err));
  53. reject(err);
  54. }
  55. })
  56. },
  57. 300);
  58. });
  59. }
  60. stopBluetoothDevicesDiscovery() {
  61. let self = this;
  62. return new Promise((resolve, reject) = >{
  63. uni.stopBluetoothDevicesDiscovery({
  64. success: e = >{
  65. uni.hideLoading();
  66. },
  67. fail: e = >{
  68. uni.hideLoading();
  69. self.showToast(`停止搜索蓝牙设备失败` + JSON.stringify(err));
  70. }
  71. })
  72. });
  73. }
  74. createBLEConnection() {
  75. //设备deviceId
  76. let deviceId = this.deviceId;
  77. let self = this;
  78. // uni.showLoading({
  79. // mask: true,
  80. // title: '设别连接中,请稍候...'
  81. // })
  82. console.log(this.deviceId);
  83. return new Promise((resolve, reject) = >{
  84. uni.createBLEConnection({
  85. deviceId,
  86. success: (res) = >{
  87. console.log("res:createBLEConnection " + JSON.stringify(res));
  88. resolve(res)
  89. },
  90. fail: err = >{
  91. uni.hideLoading();
  92. self.showToast(`停止搜索蓝牙设备失败` + JSON.stringify(err));
  93. reject(err);
  94. }
  95. })
  96. });
  97. }
  98. //获取蓝牙设备所有服务(service)
  99. getBLEDeviceServices() {
  100. let _serviceList = [];
  101. let deviceId = this.deviceId;
  102. let self = this;
  103. return new Promise((resolve, reject) = >{
  104. setTimeout(() = >{
  105. uni.getBLEDeviceServices({
  106. deviceId,
  107. success: res = >{
  108. for (let service of res.services) {
  109. if (service.isPrimary) {
  110. _serviceList.push(service);
  111. }
  112. }
  113. uni.hideLoading();
  114. console.log("_serviceList: " + JSON.stringify(_serviceList));
  115. resolve(_serviceList)
  116. },
  117. fail: err = >{
  118. uni.hideLoading();
  119. // self.showToast(`获取设备Services` + JSON.stringify(err));
  120. reject(err);
  121. },
  122. })
  123. },
  124. 500);
  125. });
  126. }
  127. //获取蓝牙设备某个服务中所有特征值(characteristic)
  128. getBLEDeviceCharacteristics() {
  129. // console.log("getBLEDeviceCharacteristics")
  130. let deviceId = this.deviceId;
  131. let serviceId = this.serviceId;
  132. let self = this;
  133. return new Promise((resolve, reject) = >{
  134. uni.getBLEDeviceCharacteristics({
  135. deviceId,
  136. serviceId,
  137. success: res = >{
  138. for (let _obj of res.characteristics) {
  139. //获取notify
  140. if (_obj.properties.notify) {
  141. self.notifyId = _obj.uuid;
  142. uni.setStorageSync('notifyId', self.notifyId);
  143. }
  144. //获取writeId
  145. if (_obj.properties.write) {
  146. self.writeId = _obj.uuid;
  147. uni.setStorageSync('writeId', self.writeId);
  148. }
  149. }
  150. //console.log("res:getBLEDeviceCharacteristics " + JSON.stringify(res));
  151. let result = {
  152. 'notifyId': self.notifyId,
  153. 'writeId': self.writeId
  154. };
  155. // self.showToast(`获取服务中所有特征值OK,${JSON.stringify(result)}`);
  156. this.BluetoothStatus = true resolve(result)
  157. },
  158. fail: err = >{
  159. self.showToast(`getBLEDeviceCharacteristics` + JSON.stringify(err));
  160. reject(err);
  161. }
  162. })
  163. });
  164. }
  165. //断开联链接
  166. closeBLEConnection() {
  167. let deviceId = this.deviceId;
  168. uni.closeBLEConnection({
  169. deviceId,
  170. success(res) {
  171. console.log("closeBLEConnection" + res)
  172. }
  173. })
  174. }
  175. notifyBLECharacteristicValue() {
  176. let deviceId = this.deviceId;
  177. let serviceId = this.serviceId;
  178. let characteristicId = this.notifyId;
  179. uni.notifyBLECharacteristicValueChange({
  180. state: true,
  181. // 启用 notify 功能
  182. deviceId,
  183. serviceId,
  184. characteristicId,
  185. success(res) {
  186. uni.onBLECharacteristicValueChange(function(res) {
  187. console.log('onBLECharacteristicValueChange', res);
  188. });
  189. },
  190. fail(res) {
  191. console.log('notifyBLECharacteristicValueChange failed:' + res.errMsg);
  192. }
  193. });
  194. }
  195. writeBLECharacteristicValue(buffer) {
  196. let deviceId = this.deviceId;
  197. let serviceId = this.serviceId;
  198. let characteristicId = this.writeId;
  199. // console.log(deviceId);
  200. // console.log(serviceId);
  201. // console.log(characteristicId);
  202. return new Promise((resolve, reject) = >{
  203. uni.writeBLECharacteristicValue({
  204. deviceId,
  205. serviceId,
  206. characteristicId,
  207. value: buffer,
  208. success(res) {
  209. // console.log('message发送成功', JSON.stringify(res));
  210. resolve(res);
  211. },
  212. fail(err) {
  213. // console.log('message发送失败', JSON.stringify(err));
  214. reject(err);
  215. }
  216. });
  217. });
  218. }
  219. closeBluetoothAdapter() {
  220. return new Promise((resolve, reject) = >{
  221. uni.closeBluetoothAdapter({
  222. success: res = >{
  223. resolve()
  224. }
  225. });
  226. })
  227. }
  228. //若APP在之前已有搜索过某个蓝牙设备,并成功建立连接,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备,无需进行搜索操作。
  229. reconnect() { (async() = >{
  230. try {
  231. this.deviceId = this.deviceId || uni.getStorageSync("deviceId");
  232. this.serviceId = this.serviceId || uni.getStorageSync("serviceId");
  233. console.log("this.deviceId", this.deviceId) console.log("this.serviceId", this.serviceId) let result1 = await this.createBLEConnection();
  234. console.log("createBLEConnection: " + JSON.stringify(result1));
  235. let result2 = await this.getBLEDeviceServices();
  236. console.log("getBLEDeviceServices: " + JSON.stringify(result2));
  237. let result3 = await this.getBLEDeviceCharacteristics();
  238. console.log("getBLEDeviceCharacteristics: " + JSON.stringify(result3));
  239. this.BluetoothConnectStatus = true this.showToast("蓝牙打印设备连接成功")
  240. // this.writeId = uni.getStorageSync("writeId");
  241. // this.notifyId = uni.getStorageSync("notifyId");
  242. } catch(err) {
  243. console.log("err: " + err);
  244. // this.showToast("蓝牙打印设备连接失败")
  245. }
  246. })();
  247. }
  248. }
  249. export default Bluetooth