当前位置:   article > 正文

项目记录:uni-app+vue3项目,门锁小程序:使用蓝牙插件,对接电子门锁各项功能。_vue-bluetooth

vue-bluetooth

1、项目需求:

  使用uni-app开发门锁小程序,主要功能有:门锁添加、远程开锁、蓝牙开锁、密码管理、指纹管理。

2、项目重点:

  前端需要调用厂家提供的设备文档来进行设备的添加、设备钥匙(密码、指纹)的添加、设备的开锁。

3、项目前期配置

  微信平台配置好插件:在项目的manifest.json导入该插件:

4、具体页面流程:

设备api进行二次封装方便使用:

创建detectingBluetooth.ts文件,使用class创建对象并将设备api二次封装方便后续使用。

  1. declare const wx: any;
  2. // 门锁各类方法
  3. export class HandlerBluetooth {
  4. /**
  5. *@function 处理检测蓝牙开启
  6. * @returns true为开启 fsle为关闭
  7. */
  8. async handleGetSetting() {
  9. return new Promise<boolean>((resolve, reject) => {
  10. uni.getSetting({
  11. success(res) {
  12. if (!res.authSetting['scope.bluetooth']) {
  13. uni.showModal({
  14. title: '提示',
  15. content: '当前小程序未开启蓝牙授权,是否前往授权?',
  16. success(res) {
  17. if (res.confirm) {
  18. wx.openBluetoothAdapter();
  19. resolve(true);
  20. } else if (res.cancel) {
  21. resolve(false);
  22. }
  23. },
  24. });
  25. } else {
  26. uni.openBluetoothAdapter({
  27. success: (res) => {
  28. resolve(true);
  29. },
  30. fail: (res) => {
  31. //如果手机上的蓝牙没有打开,可以提醒用户
  32. resolve(false);
  33. uni.showModal({
  34. title: '提示',
  35. content: '请打开手机蓝牙',
  36. showCancel: false,
  37. });
  38. uni.closeBluetoothAdapter({});
  39. },
  40. });
  41. }
  42. },
  43. });
  44. });
  45. }
  46. /**
  47. * @function 处理添加蓝牙设备
  48. * @param plugin plugin对象
  49. * @returns 成功返回蓝牙对象,失败返回失败对象
  50. */
  51. async handleAddBluetoothDevice(plugin: any) {
  52. return new Promise<any>((resolve, reject) => {
  53. // 监听“初始化完成”事件
  54. plugin.on('ready', function (plugin) {
  55. console.info('plugin is on ready', plugin);
  56. plugin
  57. .addBluetoothDevice()
  58. .then(function (res) {
  59. uni.hideLoading();
  60. resolve(res);
  61. })
  62. .catch(function (err) {
  63. uni.hideLoading();
  64. reject(err);
  65. });
  66. });
  67. // 监听“运行错误”事件
  68. plugin.on('error', function (err) {
  69. console.info('plugin is on error -->', err);
  70. });
  71. });
  72. }
  73. /**
  74. * @function 处理蓝牙开锁
  75. * @param plugin plugin对象
  76. * @returns 开锁成功或者失败
  77. */
  78. async handleOpenLock(plugin: any) {
  79. return new Promise<any>((resolve, reject) => {
  80. plugin
  81. .openLock()
  82. .then((res) => {
  83. resolve(res);
  84. })
  85. .catch((err) => {
  86. reject(err);
  87. });
  88. });
  89. }
  90. /**
  91. * @function 添加蓝牙钥匙
  92. * @param type 添加方式 :0:按指定的钥匙类型添加;1:按内容添加
  93. * @param keyType 钥匙类型:0: 指纹 1:密码 2:卡片 3:遥控 4:二维码 5:机械钥匙 6:人脸 7:App
  94. * @param keyGroupId 用户组 ID:901
  95. * @param plugin plugin对象
  96. */
  97. async handleAddkeyKey(type: number, keyType: number, keyGroupId: number, plugin: any, key?: string) {
  98. return new Promise<any>((resolve, reject) => {
  99. let params: any = {
  100. type,
  101. keyType,
  102. keyGroupId,
  103. lockKeyId: 0,
  104. validEndTime: '',
  105. validStartTime: '',
  106. usageCount: 255,
  107. validTimeMode: 0, // 时间模式为有效期类型
  108. };
  109. if (key) {
  110. params.key = key;
  111. }
  112. console.log('params--->', params);
  113. plugin
  114. .addKey(params)
  115. .then((res) => {
  116. resolve(res);
  117. })
  118. .catch((err) => {
  119. console.log('err--->', err);
  120. resolve(err);
  121. uni.hideLoading();
  122. });
  123. });
  124. }
  125. /**
  126. * @function 更新钥匙
  127. * @param newPassword 新密码
  128. * @param lockKeyId 门锁中钥匙的唯一 Id
  129. * @param plugin plugin对象
  130. * @returns
  131. */
  132. async handleUpdateKey(newPassword: string, lockKeyId: number, plugin: any) {
  133. return new Promise<any>((resolve, reject) => {
  134. plugin
  135. .updatePassword({ newPassword, lockKeyId })
  136. .then((res) => {
  137. resolve(res);
  138. })
  139. .catch((err) => {
  140. reject(err);
  141. });
  142. });
  143. }
  144. /**
  145. * @function 校验门锁初始信息
  146. * @param plugin plugin对象
  147. * @returns 返回成功或失败对象
  148. */
  149. async handleValidateLockInitialInfo(plugin: any) {
  150. return new Promise<any>((resolve, reject) => {
  151. plugin.validateLockInitialInfo({ isSuccess: true }).then((res) => {
  152. const options = {
  153. openMode: 2,
  154. volumeEnable: 1,
  155. antiLockEnable: 2,
  156. };
  157. plugin
  158. .setSystemInfo(options)
  159. .then((res) => {
  160. resolve(res);
  161. })
  162. .catch((err) => {
  163. resolve(err);
  164. });
  165. });
  166. });
  167. }
  168. }

添加设备:

初始化设备并连接:

  1. import { HandlerBluetooth } from '../../utils/detectingBluetooth';
  2. declare const requirePlugin: any;
  3. const detectingBluetoothObj = new HandlerBluetooth();
  4. const createPlugin = requirePlugin('BLELockSDK'); // 使用蓝牙插件
  5. const Plugin = createPlugin();
  6. let plugin: any;
  7. // 定义数据
  8. var config = {
  9. keyGroupId: ‘’, // 由业务服务器返回
  10. };
  11. // 添加门锁
  12. function insertDoorLock() {
  13. detectingBluetoothObj.handleGetSetting().then((res) => {
  14. if (res) {
  15. uni.showLoading({
  16. title: '连接中...',
  17. mask: true,
  18. });
  19. // 初始化时调用方式
  20. plugin = new Plugin({
  21. keyGroupId: config.keyGroupId,
  22. });
  23. detectingBluetoothObj.handleAddBluetoothDevice(plugin).then((res) => {
  24. const data = JSON.parse(JSON.stringify(res));
  25. Object.assign(options.form.extAttrMap, data.data.DNAInfo); // 后面对接后端需要的数据
  26. options.form.deviceInfo.deviceCode = data.data.DNAInfo.lockMac;// 后面对接后端需要的数据
  27. isShow.value = true;
  28. });
  29. }
  30. });
  31. }

校验门锁初始信息、设置设备参数、对接后端新增设备:

  1. function submitInsert() {
  2. const submitData = {
  3. spaceId: options.form.spaceId,
  4. deviceInfo: options.form.deviceInfo,
  5. extAttrMap: options.form.extAttrMap,
  6. };
  7. //校验门锁初始信息、设置设备参数
  8. detectingBluetoothObj.handleValidateLockInitialInfo(plugin).then((res) => {
  9. if (res) {
  10. const data = JSON.parse(JSON.stringify(res));
  11. if (data.errCode === '01') {
  12. iotAccess.insert4LockDevice(submitData).then((res) => {
  13. // 对接后端
  14. if (res) {
  15. uni.hideLoading();
  16. util.showToast('添加设备成功', 'success');
  17. setTimeout(() => {
  18. uni.navigateBack({
  19. delta: 1,
  20. });
  21. }, 1500);
  22. }
  23. });
  24. }
  25. }
  26. });
  27. }

 设备详情:

 蓝牙开锁 远程开锁:

  1. import util from '../../utils/util';
  2. import { HandlerBluetooth } from '../../utils/detectingBluetooth';
  3. // #region 蓝牙所需参数
  4. declare const requirePlugin: any;
  5. const detectingBluetoothObj = new HandlerBluetooth();
  6. const createPlugin = requirePlugin('BLELockSDK');
  7. const Plugin = createPlugin();
  8. let plugin: any;
  9. // 定义数据
  10. var config = {
  11. keyGroupId: '', // 由业务服务器返回
  12. lockMac: '',
  13. aesKey: '',
  14. authCode: '',
  15. };
  16. // #endregion
  17. // #region 蓝牙开锁+远程开锁
  18. function handleOpenDoor(type: 'bluetooth' | 'remote') {
  19. switch (type) {
  20. // 蓝牙
  21. case 'bluetooth':
  22. uni.showLoading({
  23. title: '蓝牙开锁中...',
  24. mask: true,
  25. });
  26. handle();
  27. break;
  28. // 远程
  29. case 'remote':
  30. uni.showLoading({
  31. title: '远程开锁中...',
  32. mask: true,
  33. });
  34. iotAccess.openDoor(doorInfo.id).then((res) => {
  35. if (res) {
  36. uni.hideLoading();
  37. util.showToast('开锁成功', 'success');
  38. }
  39. });
  40. break;
  41. }
  42. }
  43. function handle() {
  44. if (options.flag) {
  45. return;
  46. }
  47. options.flag = true;
  48. setTimeout(() => {
  49. options.flag = false;
  50. }, 1000); // 防止开锁连点
  51. detectingBluetoothObj.handleGetSetting().then((res) => {
  52. if (res) {
  53. if (options.isFirst) { // 第一次开锁需要初始化设备速度会慢,后面开锁速度就会
  54. plugin = new Plugin({
  55. authCode: config.authCode,
  56. aesKey: config.aesKey,
  57. lockMac: config.lockMac,
  58. keyGroupId: config.keyGroupId,
  59. });
  60. plugin.on('ready', function () {
  61. openLock();
  62. });
  63. options.isFirst = false;
  64. } else {
  65. openLock();
  66. }
  67. }
  68. });
  69. }
  70. function openLock() {
  71. detectingBluetoothObj
  72. .handleOpenLock(plugin)
  73. .then(() => {
  74. const params = {
  75. device: { id: doorInfo.id },
  76. user: { id: authorInfo.userId },
  77. identifyMode: 'Bluetooth',
  78. status: 'Success',
  79. };
  80. iotAccess
  81. .insertAcessRecordPage(params)
  82. .then((res) => {
  83. uni.hideLoading();
  84. if (res) {
  85. util.showToast('开锁成功', 'success');
  86. }
  87. })
  88. .catch(() => {
  89. uni.hideLoading();
  90. util.showToast('开锁失败', 'none');
  91. });
  92. })
  93. .catch(() => {
  94. uni.hideLoading();
  95. util.showToast('开锁失败', 'success');
  96. });
  97. }

密码管理

  1. import { HandlerBluetooth } from '../../utils/detectingBluetooth';
  2. // #region 蓝牙所需参数
  3. declare const requirePlugin: any;
  4. const detectingBluetoothObj = new HandlerBluetooth();
  5. const createPlugin = requirePlugin('BLELockSDK');
  6. const Plugin = createPlugin();
  7. let plugin: any;
  8. // 定义数据
  9. var config = {
  10. keyGroupId: '', // 由业务服务器返回
  11. lockMac: '',
  12. aesKey: '',
  13. authCode: '',
  14. };
  15. // #endregion
  16. function handleConfirmSearch() {
  17. uni.showLoading({
  18. title: '加载中....',
  19. mask: true,
  20. });
  21. handlerBluetooth.handleGetSetting().then((res) => {
  22. if (res) {
  23. if (options.isFirst) {
  24. plugin = new Plugin({
  25. authCode: config.authCode,
  26. aesKey: config.aesKey,
  27. lockMac: config.lockMac,
  28. keyGroupId: config.keyGroupId,
  29. });
  30. plugin.on('ready', function () {
  31. console.log('ready====>');
  32. handleAddkeyOrUpdateKey();
  33. });
  34. options.isFirst = false;
  35. } else {
  36. handleAddkeyOrUpdateKey();
  37. }
  38. }
  39. });
  40. }
  41. // 不存在密码时添加钥匙、存在密码时修改密码
  42. function handleAddkeyOrUpdateKey() {
  43. if (options.isPassword) { // 页面初始化根据id查询设备是否有密码,存在则调用修改,不存在则调用添加
  44. console.log('添加密码');
  45. handlerBluetooth
  46. .handleAddkeyKey(1, 1, config.keyGroupId, plugin, form.submitPassword)
  47. .then((res) => {
  48. handleUpdateLockPassword(doorInfo.id, form.submitPassword, res.data.lockKeyId);
  49. })
  50. .catch((err) => {
  51. handleShowToast('失败,请重试', 'none');
  52. });
  53. } else {
  54. console.log('修改密码');
  55. handlerBluetooth
  56. .handleUpdateKey(form.submitPassword, Number(doorInfo.passwordLockKeyId), plugin)
  57. .then((res) => {
  58. handleUpdateLockPassword(doorInfo.id, form.submitPassword, res.data.lockKeyId);
  59. })
  60. .catch(() => {
  61. uni.hideLoading();
  62. handleShowToast('失败,请重试', 'none');
  63. });
  64. }
  65. }
  66. function handleUpdateLockPassword(deviceId: string, password: string, passwordLockKeyId: number) {
  67. iotAccess
  68. .updateLockPassword(deviceId, password, passwordLockKeyId)
  69. .then((res) => {
  70. if (res) {
  71. uni.hideLoading();
  72. handleShowToast('密码修改成功', 'success');
  73. setTimeout(() => {
  74. uni.navigateBack();
  75. }, 1500);
  76. }
  77. })
  78. .catch((err) => {
  79. uni.hideLoading();
  80. handleShowToast(err.description, 'none');
  81. });
  82. }

指纹管理:

  1. import { HandlerBluetooth } from '../../utils/detectingBluetooth';
  2. // #region 蓝牙所需参数
  3. declare const requirePlugin: any;
  4. const detectingBluetoothObj = new HandlerBluetooth();
  5. const createPlugin = requirePlugin('BLELockSDK');
  6. const Plugin = createPlugin();
  7. let plugin: any;
  8. // 定义数据
  9. var config = {
  10. keyGroupId: '', // 由业务服务器返回
  11. lockMac: '',
  12. aesKey: '',
  13. authCode: '',
  14. };
  15. // #endregion
  16. // #region 方法
  17. function handleGetDeviceInfo() {
  18. //根据id查询设备详细信息
  19. iotAccess.getDevice(doorInfo.id).then((res) => {
  20. if (res) {
  21. const data = JSON.parse(JSON.stringify(res.data.data));
  22. config.lockMac = data.device.extAttrMap.lockMac;
  23. config.aesKey = data.device.extAttrMap.aesKey;
  24. config.authCode = data.device.extAttrMap.generalAuthCode;
  25. handleGetSetting();
  26. }
  27. });
  28. }
  29. function handleGetSetting() {
  30. if (!options.isOpen) { // 标识符判断手机蓝牙是否开启
  31. detectingBluetoothObj.handleGetSetting().then((res) => {
  32. options.isOpen = res;
  33. if (res) {
  34. uni.showLoading({
  35. title: '正在读取设备...',
  36. mask: true,
  37. });
  38. handleSetPlugin();
  39. }
  40. });
  41. } else {
  42. handleSetPlugin();
  43. }
  44. }
  45. function handleSetPlugin() {
  46. if (options.isFirst) {
  47. plugin = new Plugin({
  48. authCode: config.authCode,
  49. aesKey: config.aesKey,
  50. lockMac: config.lockMac,
  51. keyGroupId: config.keyGroupId,
  52. });
  53. plugin.on('ready', function (ready) {
  54. console.log('ready--->', ready);
  55. detectingBluetoothObj.handleAddkeyKey(0, 0, config.keyGroupId, plugin);
  56. });
  57. plugin.on('report:addKey', (res) => {
  58. // 监听设备指纹的添加
  59. console.log('监听指纹---->');
  60. if (res.errCode == '01') {
  61. const params = {
  62. deviceInfo: { id: doorInfo.id },
  63. lockKeyId: res.data.lockKeyId,
  64. lockKeyName: '未命名',
  65. lockKeyType: '1',
  66. };
  67. iotAccess.addLockUserKey(params).then((res) => {
  68. if (res) {
  69. const data = JSON.parse(JSON.stringify(res.data.data));
  70. uni.redirectTo({
  71. url: '', // 跳转页面对接后端将指纹添加到该设备上
  72. });
  73. }
  74. });
  75. }
  76. });
  77. options.isFirst = false;
  78. } else {
  79. detectingBluetoothObj.handleAddkeyKey(0, 0, config.keyGroupId, plugin);
  80. }
  81. }
  82. // #endregion

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/481400
推荐阅读
相关标签
  

闽ICP备14008679号