bluetooth.js 7.0 KB

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