index.vue 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. <template>
  2. <view class="content">
  3. <view class="cz-box" @click="toFindDev">
  4. <u-image width="150rpx" height="150rpx" src="/static/chengzhong.png"></u-image>
  5. <view class="tits">{{statusStr}}</view>
  6. </view>
  7. </view>
  8. </template>
  9. <script>
  10. export default {
  11. data() {
  12. return {
  13. deviceList:[], // 设备列表
  14. deviceId: '',
  15. connectedDeviceId: '',
  16. services: [],
  17. notifyCharacteristicsId:'',
  18. notifyServicweId: '',
  19. writeDatas: '',
  20. balanceData: '',
  21. hexstr: '',
  22. statusStr: '投放称重'
  23. }
  24. },
  25. methods: {
  26. toFindDev(){
  27. let _this = this
  28. const res = uni.getSystemInfoSync();
  29. // 初始化蓝牙模块
  30. uni.openBluetoothAdapter({
  31. success(res) {
  32. console.log(res)
  33. _this.statusStr = '初始化蓝牙模块成功'
  34. /* 获取本机的蓝牙状态 */
  35. setTimeout(() => {
  36. _this.init()
  37. }, 1000)
  38. }
  39. })
  40. // 监听蓝牙适配器状态变化事件
  41. uni.onBluetoothAdapterStateChange(function (res) {
  42. console.log(res,'适配器变化')
  43. })
  44. if(!res.bluetoothEnabled){
  45. uni.showModal({
  46. title:'提示',
  47. content:'请开启手机蓝牙',
  48. complete(e) {
  49. console.log(e)
  50. _this.statusStr = '请开启手机蓝牙'
  51. }
  52. })
  53. }
  54. },
  55. // 初始化蓝牙
  56. init(){
  57. let _this = this
  58. uni.getBluetoothAdapterState({
  59. success(res) {
  60. console.log(res)
  61. _this.statusStr = 'adapterState changed, now is'
  62. // 开始搜寻附近的蓝牙外围设备
  63. _this.startBluetoothDevicesDiscovery()
  64. },
  65. fail(res) {
  66. console.log(res)
  67. }
  68. })
  69. },
  70. startBluetoothDevicesDiscovery(){
  71. let _this = this
  72. uni.startBluetoothDevicesDiscovery({
  73. services: [],
  74. success(res) {
  75. console.log(res)
  76. // 监听寻找到新设备的事件
  77. uni.onBluetoothDeviceFound(function (res) {
  78. _this.deviceList = res.devices
  79. let devices = _this.deviceList.filter(item => item.name == 'FAYA')
  80. console.dir(devices,'devices list')
  81. if(devices.length == 1){
  82. _this.statusStr = '发现设备'
  83. _this.deviceId = devices[0].deviceId
  84. _this.createBLEConnection()
  85. }
  86. else if(devices.length > 1){
  87. }
  88. else{
  89. _this.statusStr = '没有找到电子秤'
  90. }
  91. })
  92. }
  93. })
  94. },
  95. // 开始连接指定设备
  96. createBLEConnection(){
  97. let _this = this
  98. uni.createBLEConnection({
  99. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  100. deviceId:this.deviceId,
  101. success(res) {
  102. console.log(res)
  103. _this.statusStr = '连接设备成功'
  104. _this.connectedDeviceId = _this.deviceId
  105. // 获取连接设备的service服务
  106. setTimeout(()=>{
  107. _this.getBLEDeviceServices()
  108. },1000)
  109. }
  110. })
  111. },
  112. // 获取连接设备的service服务
  113. getBLEDeviceServices(){
  114. let _this = this
  115. uni.getBLEDeviceServices({
  116. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  117. deviceId: _this.deviceId,
  118. success(res) {
  119. console.log('device services:', res.services)
  120. _this.statusStr = '获取连接设备的service服务成功'
  121. _this.services = res.services
  122. /* 获取连接设备的所有特征值 */
  123. setTimeout(()=>{
  124. _this.getBLEDeviceCharacteristics()
  125. },500)
  126. // 停止搜索
  127. uni.stopBluetoothDevicesDiscovery({
  128. success: function(res) {
  129. console.log(res, '停止搜索')
  130. },
  131. fail(res) {
  132. }
  133. })
  134. }
  135. })
  136. },
  137. // 获取连接设备的所有特征值
  138. getBLEDeviceCharacteristics(){
  139. let _this = this
  140. this.notifyServicweId = this.services[1].uuid
  141. uni.getBLEDeviceCharacteristics({
  142. deviceId: this.connectedDeviceId,
  143. serviceId: this.notifyServicweId,
  144. success: function(res) {
  145. console.log(res)
  146. _this.statusStr = '获取连接设备的所有特征值成功'
  147. for (let i = 0; i < res.characteristics.length; i++) {
  148. if ((res.characteristics[i].properties.notify || res.characteristics[i].properties.indicate) &&
  149. (res.characteristics[i].properties.read && res.characteristics[i].properties.write)) {
  150. console.log(res.characteristics[i].uuid, '蓝牙特征值 ==========')
  151. /* 获取蓝牙特征值 */
  152. _this.notifyCharacteristicsId = res.characteristics[i].uuid
  153. // 启用低功耗蓝牙设备特征值变化时的 notify 功能
  154. setTimeout(()=>{
  155. _this.notifyBLECharacteristicValueChange()
  156. },500)
  157. }
  158. }
  159. },
  160. fail: function(res) {
  161. console.log(res)
  162. }
  163. })
  164. },
  165. // 启用低功耗蓝牙设备特征值变化时的 notify 功能
  166. notifyBLECharacteristicValueChange() {
  167. let that = this;
  168. console.log(that.connectedDeviceId,that.notifyServicweId,that.notifyCharacteristicsId)
  169. uni.notifyBLECharacteristicValueChange({
  170. state: true,
  171. deviceId: that.connectedDeviceId,
  172. serviceId: that.notifyServicweId,
  173. // characteristicId: that.notifyCharacteristicsId,
  174. characteristicId: '49535343-1E4D-4BD9-BA61-23C647249616',
  175. success(res) {
  176. console.log(res,'notifyBLECharacteristicValueChange')
  177. that.statusStr = '启用低功耗蓝牙设备特征值变化成功'
  178. /*用来监听手机蓝牙设备的数据变化*/
  179. uni.onBLECharacteristicValueChange(function(res) {
  180. console.log(res,'read data')
  181. that.balanceData = that.buf2string(res.value)
  182. // that.hexstr = that.receiveData(res.value)
  183. })
  184. },
  185. fail(res) {
  186. console.log(res, '启用低功耗蓝牙设备监听失败')
  187. }
  188. })
  189. },
  190. /*转换成需要的格式*/
  191. buf2string(buffer) {
  192. let arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
  193. return arr.map((char, i) => {
  194. return String.fromCharCode(char);
  195. }).join('');
  196. },
  197. receiveData(buf) {
  198. return this.hexCharCodeToStr(this.ab2hex(buf))
  199. },
  200. /*转成二进制*/
  201. ab2hex (buffer) {
  202. let hexArr = Array.prototype.map.call(
  203. new Uint8Array(buffer), function (bit) {
  204. return ('00' + bit.toString(16)).slice(-2)
  205. }
  206. )
  207. return hexArr.join('')
  208. },
  209. /*转成可展会的文字*/
  210. hexCharCodeToStr(hexCharCodeStr) {
  211. let trimedStr = hexCharCodeStr.trim();
  212. let rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;
  213. let len = rawStr.length;
  214. let curCharCode;
  215. let resultStr = [];
  216. for (let i = 0; i < len; i = i + 2) {
  217. curCharCode = parseInt(rawStr.substr(i, 2), 16);
  218. resultStr.push(String.fromCharCode(curCharCode));
  219. }
  220. return resultStr.join('');
  221. },
  222. // 发送数据
  223. sendData(str) {
  224. let that = this;
  225. let dataBuffer = new ArrayBuffer(3)
  226. let dataView = new DataView(dataBuffer)
  227. // for (let i = 0; i < str.length; i++) {
  228. // dataView.setUint8(i, str.charAt(i).charCodeAt())
  229. // }
  230. dataView.setUint8(0, 0x02)
  231. dataView.setUint8(1, 0x42)
  232. dataView.setUint8(2, 0x03)
  233. let dataHex = that.ab2hex(dataBuffer);
  234. this.writeDatas = that.hexCharCodeToStr(dataHex);
  235. uni.writeBLECharacteristicValue({
  236. deviceId: that.connectedDeviceId,
  237. serviceId: that.notifyServicweId,
  238. characteristicId: that.notifyCharacteristicsId,
  239. // characteristicId: '49535343-1E4D-4BD9-BA61-23C647249616',
  240. value: dataBuffer,
  241. success: function (res) {
  242. console.log('发送的数据:' + that.writeDatas)
  243. console.log('message发送成功')
  244. },
  245. fail: function (res) {
  246. console.log('发送失败:' + res)
  247. },
  248. complete: function (res) {
  249. }
  250. })
  251. },
  252. // 断开设备连接
  253. closeConnect() {
  254. let that = this;
  255. if (that.connectedDeviceId) {
  256. uni.closeBLEConnection({
  257. deviceId: that.connectedDeviceId,
  258. success: function(res) {
  259. that.closeBluetoothAdapter()
  260. },
  261. fail(res) {
  262. }
  263. })
  264. } else {
  265. that.closeBluetoothAdapter()
  266. }
  267. },
  268. // 关闭蓝牙模块
  269. closeBluetoothAdapter() {
  270. let that = this;
  271. uni.closeBluetoothAdapter({
  272. success: function(res) {
  273. that.statusStr = '关闭蓝牙模块'
  274. that.balanceData = ''
  275. console.log(res,'closeBluetoothAdapter')
  276. },
  277. fail: function(err) {
  278. }
  279. })
  280. },
  281. },
  282. onUnload() {
  283. this.closeConnect()
  284. }
  285. }
  286. </script>
  287. <style>
  288. .content{
  289. display: flex;
  290. align-items: center;
  291. justify-content: center;
  292. height: 100vh;
  293. width: 100%;
  294. }
  295. .cz-box{
  296. text-align: center;
  297. background-color: #FFFFFF;
  298. padding: 50rpx 50rpx 30rpx;
  299. border-radius: 300rpx;
  300. box-shadow: 2rpx 2rpx 5rpx #eee;
  301. width: 300rpx;
  302. height: 300rpx;
  303. display: flex;
  304. align-items: center;
  305. justify-content: center;
  306. flex-direction: column;
  307. }
  308. .tits{
  309. padding: 20rpx 0;
  310. }
  311. </style>