tools.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import errToString from "./error";
  2. import {logs, promisify} from '../util'
  3. import {ab2hex} from "@/utils/ble/hex";
  4. function _onBluetoothAdapterStateChange(callback) {
  5. /* #ifndef H5 */
  6. uni.onBluetoothAdapterStateChange(res => {
  7. // 处理蓝牙开启与关闭问题
  8. callback(res)
  9. })
  10. /* #endif */
  11. }
  12. function _onBLEConnectionStateChange(callback) {
  13. /* #ifndef H5 */
  14. uni.onBLEConnectionStateChange(res => {
  15. // 该方法回调中可以用于处理连接意外断开等异常情况
  16. callback(res)
  17. })
  18. /* #endif */
  19. }
  20. function _onBLECharacteristicValueChange(callback) {
  21. /* #ifndef H5 */
  22. uni.onBLECharacteristicValueChange(res => {
  23. res.str = ab2hex(res.value)
  24. callback(res)
  25. })
  26. /* #endif */
  27. }
  28. function _openAdapter() {
  29. logs(`准备初始化蓝牙适配器...`);
  30. return uni.openBluetoothAdapter().then(
  31. (res) => {
  32. logs(`✔ 适配器初始化成功!`);
  33. return res;
  34. },
  35. (err) => {
  36. throw `初始化失败!${errToString(err)}`
  37. }
  38. );
  39. }
  40. /**
  41. * @param {Array<string>} services
  42. * @param { Int } interval
  43. */
  44. function _startSearch(data = {}) {
  45. logs(`准备搜寻附近的蓝牙外围设备...`);
  46. /* #ifndef H5 */
  47. return promisify(uni.startBluetoothDevicesDiscovery, Object.assign({
  48. interval: 10
  49. }, data)).then(
  50. (res) => {
  51. logs(`✔ 搜索成功!`);
  52. return res
  53. },
  54. (err) => {
  55. throw `搜索蓝牙失败!${errToString(err)}`
  56. }
  57. );
  58. /* #endif */
  59. }
  60. /**
  61. * 获取已发现的蓝牙设备
  62. * @returns {Promise<[null, undefined] | [(string|string), Object]>}
  63. * @private
  64. */
  65. function _getBluetoothDevices() {
  66. return promisify(uni.getBluetoothDevices).then(
  67. ({devices}) => {
  68. logs(`✔ 获取已发现的蓝牙设备成功!`);
  69. let list = devices.filter(function (obj) {
  70. return obj.advertisData; //这里过滤自己想要的设备
  71. })
  72. logs('已发现的蓝牙设备列表');
  73. return list
  74. },
  75. (err) => {
  76. throw `获取已发现的蓝牙设备失败!${errToString(err)}`
  77. }
  78. );
  79. }
  80. /**
  81. * @param {Array} devices 查找到设备数组
  82. * @param {int} count 计数器-嗅探2次
  83. */
  84. function _onBluetoothFound(maxCount = 3) {
  85. let devices = []
  86. let count = 0
  87. /* #ifdef H5 */
  88. return Promise.resolve(devices)
  89. /* #endif */
  90. return new Promise((resolve, reject) => {
  91. uni.onBluetoothDeviceFound(res => {
  92. devices.push(...res.devices)
  93. count++
  94. if (count > maxCount) {
  95. resolve(devices)
  96. }
  97. logs(`已嗅探蓝牙设备数:${devices.length}...`)
  98. }, err => {
  99. reject(err)
  100. })
  101. })
  102. }
  103. /**
  104. * 停止蓝牙搜索
  105. * @returns {PromiseLike<[null, any] | [(string|string), null]> | Promise<[null, any] | [(string|string), null]>}
  106. * @private
  107. */
  108. function _stopSearchBluetooth() {
  109. logs(`停止查找新设备...`);
  110. /* #ifdef H5 */
  111. throw `停止查询失败!H5不能操作`
  112. /* #endif */
  113. return uni.stopBluetoothDevicesDiscovery().then(
  114. (res) => {
  115. logs(`✔ 停止查找设备成功!`);
  116. return res
  117. },
  118. (err) => {
  119. throw `停止查询失败!${errToString(err)}`
  120. }
  121. );
  122. }
  123. /**
  124. * 连接设备
  125. * @param deviceId
  126. * @returns {Promise<[null, unknown] | [null, any] | [(string|string), null]>}
  127. * @private
  128. */
  129. function _connectBlue(deviceId) {
  130. logs(`准备连接设备...`);
  131. /* #ifndef H5 */
  132. return promisify(uni.createBLEConnection, {
  133. deviceId,
  134. }).then(
  135. (res) => {
  136. logs(`✔ 连接蓝牙成功!`);
  137. return true
  138. },
  139. (err) => {
  140. if (err.errCode == 10010) {
  141. logs(`✔ 连接蓝牙成功!`);
  142. return true
  143. } else {
  144. throw `连接蓝牙失败! ${errToString(err)}`
  145. }
  146. }
  147. );
  148. /* #endif */
  149. }
  150. /**
  151. * 关闭设备蓝牙
  152. * @param deviceId
  153. * @returns {Promise<[null, unknown] | [(string|string), null]>}
  154. * @private
  155. */
  156. function _closeBLEConnection(deviceId) {
  157. logs(`断开蓝牙连接...`)
  158. /* #ifndef H5 */
  159. return promisify(uni.closeBLEConnection, {
  160. deviceId,
  161. }).then(
  162. (res) => {
  163. logs(`✔ 断开蓝牙成功!`);
  164. return true
  165. },
  166. (err) => {
  167. throw `断开蓝牙连接失败! ${errToString(err)}`
  168. }
  169. );
  170. /* #endif */
  171. }
  172. /**
  173. * 关闭蓝牙
  174. * @returns {Promise<[null, unknown] | [(string|string), null]>}
  175. * @private
  176. */
  177. function _closeBLEAdapter() {
  178. logs(`释放蓝牙适配器...`)
  179. return promisify(uni.closeBluetoothAdapter).then(
  180. (res) => {
  181. logs(`✔ 释放适配器成功!`)
  182. return res
  183. },
  184. (err) => {
  185. throw `释放适配器失败! ${errToString(err)}`
  186. }
  187. );
  188. }
  189. /**
  190. * 获取设备服务列表
  191. * @param deviceId
  192. * @returns {Promise<[null, unknown] | [(string|string), null]>}
  193. * @private
  194. */
  195. function _getBLEServices(deviceId) {
  196. logs(`获取蓝牙设备所有服务...`)
  197. return promisify(uni.getBLEDeviceServices, {
  198. deviceId
  199. }).then(res => {
  200. logs(`✔ 获取service成功!`)
  201. return res
  202. }, err => {
  203. throw `获取service失败! ${errToString(err)}`
  204. })
  205. }
  206. /**
  207. * 获取服务通道
  208. * @param deviceId
  209. * @param serviceId
  210. * @returns {Promise<[null, unknown] | [(string|string), null]>}
  211. * @private
  212. */
  213. function _getCharacteristics(deviceId, serviceId) {
  214. logs(`开始获取特征值...`);
  215. return promisify(uni.getBLEDeviceCharacteristics, {
  216. deviceId,
  217. serviceId,
  218. }).then(
  219. (res) => {
  220. logs(`✔ 获取特征值成功!`);
  221. return res
  222. },
  223. (err) => {
  224. throw `获取特征值失败! ${errToString(err)}`
  225. }
  226. );
  227. }
  228. // 订阅特征值
  229. function _notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId) {
  230. return promisify(uni.notifyBLECharacteristicValueChange, {
  231. deviceId,
  232. serviceId,
  233. characteristicId,
  234. state: true
  235. }).then(res => {
  236. logs(`✔ 订阅notify成功!`)
  237. return true
  238. }, err => {
  239. throw `订阅notify失败! ${errToString(err)}`
  240. })
  241. }
  242. function _writeBLECharacteristicValue(deviceId, serviceId, characteristicId, buffer) {
  243. return promisify(uni.writeBLECharacteristicValue, {
  244. deviceId,
  245. serviceId,
  246. characteristicId,
  247. value: buffer,
  248. }).then(res => {
  249. return res
  250. }, err => {
  251. throw {
  252. code: err.errCode,
  253. msg: `写入数据失败! ${errToString(err)}`
  254. }
  255. })
  256. }
  257. export {
  258. _onBLEConnectionStateChange,
  259. _onBluetoothAdapterStateChange,
  260. _openAdapter,
  261. _getCharacteristics,
  262. _connectBlue,
  263. _getBLEServices,
  264. _closeBLEConnection,
  265. _closeBLEAdapter,
  266. _stopSearchBluetooth,
  267. _getBluetoothDevices,
  268. _notifyBLECharacteristicValueChange,
  269. _onBluetoothFound,
  270. _startSearch,
  271. _writeBLECharacteristicValue,
  272. _onBLECharacteristicValueChange,
  273. };