BleActivateDevice.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. const SERVER_UUID = "0000AB00-0000-1000-8000-00805F9B34FB";
  2. const DISSCONNECTED = 0
  3. const CONNECTING = 1
  4. const CONNECTED = 2
  5. const DISSCONNECTING = 3
  6. let callback = null
  7. let deviceId = null
  8. let writeCharacteristicId = null
  9. let configTimeout = null
  10. let state = DISSCONNECTED
  11. /**
  12. * 连接ble设备
  13. * @param {string} mac 设备mac地址
  14. * @param {function} cb 连接的回调
  15. */
  16. function connectBle(mac, cb) {
  17. if (state === DISSCONNECTED) {
  18. deviceId = mac
  19. callback = cb
  20. state = CONNECTING
  21. uni.createBLEConnection({
  22. deviceId,
  23. success(res) {
  24. console.log('ble连接成功')
  25. state = CONNECTED
  26. //获取服务
  27. getBleDeviceServices()
  28. },
  29. fail(err) {
  30. console.log(`ble连接失败 code :${err.errCode}`)
  31. state = DISSCONNECTED
  32. callback(err)
  33. }
  34. })
  35. }
  36. }
  37. /**
  38. * 获取ble的特征
  39. * @param {string} deviceId 设备mac地址
  40. */
  41. function getBleDeviceServices() {
  42. setTimeout(() => {
  43. uni.getBLEDeviceServices({
  44. deviceId,
  45. success(res) {
  46. console.log('ble获取服务成功')
  47. //let SERVER_UUID = res.services[0].uuid
  48. //getBLEDeviceCharacteristics()
  49. for (let service of res.services) {
  50. console.log(service)
  51. if (SERVER_UUID.toUpperCase() == service.uuid.toUpperCase()) {
  52. //获取特征
  53. getBLEDeviceCharacteristics(service.uuid)
  54. return
  55. }
  56. }
  57. },
  58. fail(err) {
  59. console.log(`ble获取服务失败 code :${err.errCode}`)
  60. closeBLEConnection()
  61. callback(err)
  62. }
  63. })
  64. }, 200)
  65. }
  66. /**
  67. * 获取特征
  68. */
  69. function getBLEDeviceCharacteristics(serverId) {
  70. //setTimeout(() => {
  71. uni.getBLEDeviceCharacteristics({
  72. deviceId,
  73. serviceId: serverId,
  74. success(res) {
  75. console.log(`ble获取特征成功`);
  76. for (let characteristic of res.characteristics) {
  77. console.log(characteristic.properties);
  78. // console.log(characteristic.properties.notify);
  79. if (characteristic.properties.notify) {
  80. console.warn(`NOTIFY ${characteristic.uuid}`);
  81. notifyBLECharacteristicValueChange(characteristic.uuid)
  82. } else {
  83. writeCharacteristicId = characteristic.uuid
  84. startAcivateDevice(characteristic.uuid)
  85. }
  86. }
  87. },
  88. fail(err) {
  89. console.log(`获取特征失败 code :${err.errCode}`);
  90. //console.log(err);
  91. //closeBLEConnection()
  92. callback(err)
  93. }
  94. })
  95. //}, 1000)
  96. }
  97. /**
  98. * 监听设备发送过来的数据
  99. * @param {string} characteristicId 特征的uuid
  100. */
  101. function notifyBLECharacteristicValueChange(nofifyCharacteristicId) {
  102. setTimeout(() => {
  103. //设置一个超时配网的时间
  104. configTimeout = setTimeout(() => {
  105. closeBLEConnection()
  106. if (callback) {
  107. callback({ errCode: -100 })
  108. }
  109. }, 60 * 1000)
  110. uni.notifyBLECharacteristicValueChange({
  111. state: true,
  112. deviceId,
  113. serviceId: SERVER_UUID,
  114. characteristicId: nofifyCharacteristicId,
  115. })
  116. //监听设备发送过来的数据
  117. uni.onBLECharacteristicValueChange(function(res) {
  118. let buf = Buffer.from(res.value);
  119. let receiveStr = buf.toString()
  120. console.log(`收到数据:${receiveStr}`);
  121. if (receiveStr.indexOf('ID0:') >= 0) {
  122. //获取id1
  123. let buffer = Buffer.from('getID1:').buffer
  124. setTimeout(() => { sendCongifCmd(writeCharacteristicId, buffer) }, 500)
  125. } else if (receiveStr.indexOf('ID1:') >= 0) {
  126. let data = "E2E7A1A90C89E81A62BACA5DD386F2A8ADD1192C5F3400F4D4D5B2FBF32B3B60B1209598A82C679D30C4604726D30DC09A31E241B716258CC2887FE6395D6181B9D55476A4F8F4C3D11A850BE4FE10BC42F126D74053F7A1B9FB44F76FE79B9903F48B0C5FB38746E6CDCA35121C785F46FC66460C56A8382D7656FBE4D0DB3A363149E0BCF94C05C69D2120241A98C83C8D05BA409C6F981F3491226AFBB7ACF987BD8E72E7B53AE77CFFE51E8CDE6F787BA7641B4F601BC5744FB99C50E7AC"
  127. setTimeout(() => { sendLongData(writeCharacteristicId, data) }, 500)
  128. }
  129. })
  130. }, 200)
  131. }
  132. function startAcivateDevice(characteristicId) {
  133. setTimeout(() => {
  134. //获取id0
  135. let buf = Buffer.from('getID0:').buffer
  136. setTimeout(() => { sendCongifCmd(characteristicId, buf) }, 500)
  137. }, 800)
  138. }
  139. /**
  140. * 发送数据给设备
  141. * @param {string} characteristicId 特征uuid
  142. * @param {ArrayBuffer} buffer 发送的数据
  143. */
  144. function sendCongifCmd(characteristicId, buffer) {
  145. let count = Math.ceil(buffer.byteLength / 20)
  146. //拆分成的ArrayBuffer数组,每个ArrayBuffer不超过20个字节
  147. let buffers = []
  148. for (var i = 0; i < count; i++) {
  149. let size = Math.min(20, buffer.byteLength - i * 20)
  150. let buf = buffer.slice(i * 20, size + i * 20)
  151. buffers.push(buf)
  152. }
  153. //返回的是一个promise对象
  154. function sendData(buffer) {
  155. return uni.writeBLECharacteristicValue({
  156. deviceId,
  157. serviceId: SERVER_UUID,
  158. characteristicId,
  159. value: buffer,
  160. })
  161. };
  162. (async() => {
  163. for (let b of buffers) {
  164. let res = await sendData(b)
  165. //console.log(res);
  166. console.log(`发送的数据为:${Buffer.from(b)} errorCode: ${res[res.length - 1].errCode}`);
  167. }
  168. // let promises = buffers.map((b) => sendData(b))
  169. // let res = await Promise.all(promises)
  170. })();
  171. }
  172. function sendLongData(characteristicId, dataStr) {
  173. let buffer = Buffer.from(dataStr)
  174. //每个包20个字节 间隔200毫秒
  175. //0x54 + 0x3a +pack_count(总数)+pack_index(包号)+data_len+data(长度最长15位)
  176. let count = Math.ceil(buffer.byteLength / 15)
  177. let buffers = []
  178. for (var i = 0; i < count; i++) {
  179. let size = Math.min(15, buffer.byteLength - i * 15)
  180. let buf = buffer.slice(i * 15, size + i * 15)
  181. let pkgBuf = Buffer.allocUnsafe(size + 5)
  182. pkgBuf.writeUInt8(0x54, 0) //固定0x54
  183. pkgBuf.writeUInt8(0x3a, 1) //固定0x54
  184. pkgBuf.writeUInt8(count, 2) //pack_count(包总数)
  185. pkgBuf.writeUInt8(i, 3) //pack_index(包号)
  186. pkgBuf.writeUInt8(size, 4) //data_len
  187. pkgBuf.write(buf.toString(), 5) //data
  188. //console.log(pkgBuf);
  189. buffers.push(pkgBuf.buffer)
  190. }
  191. // for (let b of buffers) {
  192. // console.warn(Buffer.from(b));
  193. // }
  194. //返回的是一个promise对象
  195. function sendData(buffer) {
  196. return uni.writeBLECharacteristicValue({
  197. deviceId,
  198. serviceId: SERVER_UUID,
  199. characteristicId,
  200. value: buffer,
  201. })
  202. };
  203. (async() => {
  204. for (let b of buffers) {
  205. let res = await sendData(b)
  206. //console.log(res);
  207. console.log(Buffer.from(b));
  208. console.log(`errorCode: ${res[res.length - 1].errCode}`);
  209. await sleep(200)
  210. }
  211. })();
  212. }
  213. function sleep(time) {
  214. return new Promise((resolve) => setTimeout(resolve, time))
  215. }
  216. /**
  217. * 关闭ble连接
  218. */
  219. function closeBLEConnection() {
  220. if (state !== DISSCONNECTED) {
  221. state = DISSCONNECTING
  222. uni.closeBLEConnection({
  223. deviceId,
  224. success(res) {
  225. state = DISSCONNECTED
  226. console.log('ble关闭连接成功');
  227. },
  228. fail(err) {
  229. console.log(`ble关闭连接失败 code :${err.errCode}`);
  230. }
  231. })
  232. clearTimeout(configTimeout)
  233. }
  234. }
  235. module.exports = { closeBLEConnection, connectBle, sendLongData };