uniapp 连接蓝牙 并下发命令

1:创建ly.js 文件

// import { TextDecoder } from 'text-encoding-utf-8';
let bluetoothOpen = false; // 手机蓝牙是否打开
let bluetoothConnect = false; // 设备和蓝牙是否连接
let isHaveDevice = false; // 是否查找到设备
let deviceId = null; // 设备id
let serviceId = null; // 服务id
let notify = null; // 监听uuid
let writeId = null; // 写入uuid
/**
 * 获取手机蓝牙是否打开
 */
const getBluetoothState = () => {
	// 主机模式
	return new Promise((resolve, reject) => {
		// mode: 'central',
		uni.openBluetoothAdapter({
			success: (r) => {
				console.log("蓝牙初始化成功");
				// 获取蓝牙的匹配状态
				uni.getBluetoothAdapterState({
					success: function(row) {
						console.log('蓝牙状态:', row.available);
						if (row.available) {
							bluetoothOpen = true;
							resolve();
						} else {
							// 请开启蓝牙
							uni.showToast({
								title: '请打开蓝牙3',
								icon: 'none'
							})
							bluetoothOpen = false;
							bluetoothConnect = false;

							reject();
						}
					},
					fail: function(err) {
						// 请开启蓝牙
						uni.showToast({
							title: '请打开蓝牙2',
							icon: 'none'
						})
						bluetoothOpen = false;
						bluetoothConnect = false;
						reject();
					}
				})
			},
			fail: () => {
				// 请开启蓝牙
				uni.showToast({
					title: '请打开蓝牙1',
					icon: 'none'
				})
				bluetoothOpen = false;
				bluetoothConnect = false;
				reject();
			}
		});
	});
};
/**
 * 开始搜索蓝牙设备
 */
const discoveryBluetooth = () => {
	return new Promise((resolve) => {
		uni.startBluetoothDevicesDiscovery({
			success(res) {
				console.log('搜索蓝牙外围设备完成', res)
				setTimeout(() => {
					resolve();
				}, 2000);
			}
		});
	})
};
// 关闭蓝牙搜索
const stopDiscoveryBluetooth = () => {
	uni.stopBluetoothDevicesDiscovery({
		success(r) {
			console.log("停止搜索蓝牙设备", r);
		}
	});
};
/**
 * 获取搜索到的设备信息
 */
const getBluetoothDevices = (deviceName) => {
	return new Promise((resolve, reject) => {
		uni.getBluetoothDevices({
			success(res) {
				console.log('获取搜索到的设备信息', res.devices);

				bluetoothConnect = false;
				// 过滤掉name为空或者未知设备的设备
				let devices = res.devices.filter(function(obj) {
					return obj.name !== "" && obj.name !== "未知设备"
				});
				console.log('有名称蓝牙列表', devices, deviceName);
				devices && devices.forEach(item => {
					if (item.name && item.name === deviceName) {
						deviceId = item.deviceId;
						isHaveDevice = true;
						resolve(isHaveDevice);
						console.log('设备ID', deviceId, item);
					}
				});
			},
			fail: function() {
				console.log('搜索蓝牙设备失败');
				bluetoothConnect = false;
				isHaveDevice = false;
				reject(isHaveDevice);
			},
			complete: function() {
				console.log("蓝牙搜索完成");
				// // 是否具有当前设备
				// if (deviceId) {
				// 	isHaveDevice = true;
				// } else {
				// 	isHaveDevice = false;
				// }
				// resolve(isHaveDevice);
			}
		});
	});
}
/**
 * 连接蓝牙
 * deviceId 蓝牙设备id
 */
const connectBluetooth = () => {
	return new Promise((resolve, reject) => {
		uni.createBLEConnection({
			deviceId: deviceId, // 设备id
			success() {
				bluetoothConnect = true;
				console.log('连接蓝牙成功', deviceId);
				// 蓝牙连接成功后关闭蓝牙搜索
				stopDiscoveryBluetooth();
				resolve();
				// 获取服务id
				getServiceId();
			},
			fail() {
				bluetoothConnect = false;
				console.log("蓝牙连接失败");
				reject();
			}
		});
	});
};
// 获取服务id
const getServiceId = () => {
	uni.getBLEDeviceServices({
		deviceId: deviceId,
		success(res) {
			console.log("获取服务Id", res)
			let model = res.services[0];
			serviceId = model.uuid;

			// 调用蓝牙监听和写入功能
			getCharacteId();
		}
	})
};
// 获取蓝牙低功耗设备某个服务中所有特征
const getCharacteId = () => {
	uni.getBLEDeviceCharacteristics({
		deviceId: deviceId, // 蓝牙设备id
		serviceId: serviceId, // 蓝牙服务UUID
		success(res) {
			console.log('数据监听', res);
			res.characteristics.forEach(item => {
				// 003
				if (item.properties.notify === true) {
					// 监听
					notify = item.uuid;
					startNotice();
				}
				// 002
				if (item.properties.write === true) {
					// 写入
					let writeId = item.uuid;
					uni.setStorageSync("writeId", item.uuid);
				}
			});
		},
		fail(err) {
			console.log("数据监听失败", err)
		}
	})
};
// 启用低功耗蓝牙设备特征值变化时的notify功能
const startNotice = () => {
	uni.notifyBLECharacteristicValueChange({
		characteristicId: notify,
		deviceId: deviceId,
		serviceId: serviceId,
		state: true,
		success(res) {
			// 监听低功耗蓝牙设备的特征值变化
			uni.onBLECharacteristicValueChange(result => {
				console.log("监听低功耗蓝牙设备的特征值变化", result);
				if (result.value) {
					let decoder = new TextDecoder('utf-8');
					let data = decoder.decode(result.value);
					// let data = result.value;
					console.log('帽子返回数据', data)
				}
			})
		}
	});
};
// 蓝牙发送数据
const writeData = (buffer) => {
	return new Promise((resolve, reject) => {
		uni.writeBLECharacteristicValue({
			characteristicId: uni.getStorageSync("writeId"),
			deviceId: deviceId,
			serviceId: serviceId,
			value: buffer,
			success(res) {
				console.log("writeBLECharacteristicValue success", res);
				resolve();
			},
			fail(err) {
				console.log("报错了", err);
				reject();
			}
		});
	});
};
const createBlec = () => {
	uni.createBLEConnection({
		deviceId:deviceId,
		success(res) {
			console.log(res, '断开成功')
		},
		fail(err) {
			console.log("断开失败", err);
		}
	})
}

// closeBLEConnection  deviceId  断开蓝牙
export default {
	getBluetoothState,
	discoveryBluetooth,
	stopDiscoveryBluetooth,
	getBluetoothDevices,
	connectBluetooth,
	getServiceId,
	getCharacteId,
	startNotice,
	writeData,
	createBlec
};

2:在你需要用到vue页面中引入 ly.js

import bluetooth from '@/uilts/ly.js';

3:连接蓝牙并下发命令 

<template>
  <view class="device_container"> </view>
</template>

<script>
import bluetooth from "../bluetooth.js";
export default {
  data() {
    return {
      bluetoothStatus: false, // 蓝牙连接状态
    };
  },
  methods: {
    // 获取蓝牙和设备是否已连接
    initBluetooth() {
      let _this = this;
      // 初始化蓝牙
      bluetooth.getBluetoothState().then(
        () => {
          // 搜索外围蓝牙设备
          bluetooth.discoveryBluetooth().then(() => {
            this.discoveryLoading = true;
            // 获取蓝牙设备
            bluetooth.getBluetoothDevices().then(
              (isHaveDevice) => {
                if (isHaveDevice) {
                  // 搜索到指定设备,连接蓝牙
                  bluetooth.connectBluetooth().then(
                    () => {
                      _this.bluetoothStatus = true;
                    },
                    () => {
                      _this.bluetoothStatus = false;
                    }
                  );
                } else {
                  // 未搜到设备
                  _this.bluetoothStatus = false;
                }
              },
              () => {
                // 蓝牙搜索失败
                _this.bluetoothStatus = false;
              }
            );
          });
        },
        () => {
          // 未开启蓝牙
          _this.bluetoothStatus = false;
        }
      );
    },
    // 向设备发送数据
    writeBlueData() {
      //针头=0xAA55   T=0x01 - 0xFF L=0x01 – 0xFF  V=0x00 - N
      let v = ["AA", "55", "01", "01", "00"];

      //转16进制
      let list = v.map((v) => {
        return parseInt(v, 16);
      });

      //我们是TLV命令协议转成 list == [170, 85, 1, 1, 0]

      let buffer = this.arr2ab(list);
      bluetooth.writeData(buffer);
    },
    // buffer 数据拼接
    arr2ab(arr) {
      const buffer = new ArrayBuffer(arr.length);
      const dataView = new DataView(buffer);
      for (var i = 0; i < arr.length; i++) {
        dataView.setUint8(i, arr[i]);
      }
      return buffer;
    },
  },
  onShow() {
    // 获取蓝牙和设备连接状态
    this.initBluetooth();
  },
};
</script>

<style lang="scss">
page {
  height: 100%;
}
</style>

  • 14
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值