uniapp 小程序低功耗蓝牙配网 blefi配网 物联网

2024-05-09 06:44

本文主要是介绍uniapp 小程序低功耗蓝牙配网 blefi配网 物联网,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.获取蓝牙列表  bleList.vue

<template><view><button @touchstart="startSearch">获取蓝牙列表</button><scroll-view :scroll-top="scrollTop" scroll-y class="content-pop"><viewclass="bluetoothItem"v-for="(item, index) in bluetoohList":key="index"@click="openControl(item)"><view class="textItem">蓝牙:{{ item.name }}</view><view>{{ item.deviceId }}</view></view></scroll-view></view>
</template><script>
export default {data() {return {bluetoohList: [],};},onLoad: function (options) {this.startSearch();},methods: {// 连接蓝牙startSearch() {var that = this;uni.openBluetoothAdapter({success: (res) => {uni.getBluetoothAdapterState({success: (res) => {if (res.available) {if (res.discovering) {uni.stopBluetoothDevicesDiscovery({success: (res) => {},});} else {that.getBluetoothDevices();}that.checkPemission();} else {uni.showToast({title: "本机蓝牙不可用",mask: true,});}},});},fail: (err) => {that.openSetting();},});},openSetting() {uni.showModal({title: "检测到您没打开蓝牙权限,是否去设置打开?",confirmText: "确认",cancelText: "取消",cancelColor: "#999999", //取消按钮颜色confirmColor: "#00A0E9", //确定按钮颜色success: (res) => {if (res.confirm) {uni.openSetting({//opensetting是调起设置页面的success: (res) => {if (res.authSetting == true) {//判断res.authsetting的值是true还是falseuni.openBluetoothAdapter({success: (res) => {this.startSearch();},});}},});} else {// 取消return false;}},});},checkPemission() {//android 6.0以上需授权地理位置权限var that = this;const sys = uni.getSystemInfoSync();if (sys.platform == "ios") {that.getBluetoothDevices();} else if (sys.platform == "android") {console.log(app.getSystem().substring(app.getSystem().length - (app.getSystem().length - 8),app.getSystem().length - (app.getSystem().length - 8) + 1));if (app.globalData.getSystem().substring(app.globalData.getSystem().length -(app.globalData.getSystem().length - 8),app.globalData.getSystem().length -(app.globalData.getSystem().length - 8) +1) > 5) {uni.getSetting({success: (res) => {console.log(res);if (!res.authSetting["scope.userLocation"]) {uni.authorize({scope: "scope.userLocation",complete: (res) => {that.getBluetoothDevices();},});} else {that.getBluetoothDevices();}},});}}},//获取蓝牙设备信息getBluetoothDevices() {var that = this;uni.showLoading({title: "蓝牙搜索中",mask: true,});// 开始搜寻附近的蓝牙外围设备uni.startBluetoothDevicesDiscovery({success: (res) => {setTimeout(() => {// 获取搜索到的设备信息uni.getBluetoothDevices({success: (res) => {that.bluetoohList = [];var num = 0;for (var i = 0; i < res.devices.length; ++i) {if (res.devices[i].name != "未知设备") {that.bluetoohList[num] = res.devices[i];num++;}}uni.stopPullDownRefresh(); // 停止当前页面下拉刷新uni.stopBluetoothDevicesDiscovery({// 停止搜索蓝牙设备success: (res) => {uni.hideLoading();},});},});}, 5000);},});},// 连接蓝牙 跳转到连接页面openControl(item) {let params = {list: this.bluetoohList,info: item,};uni.redirectTo({url:"/pages/blefi/blefi?info=" +encodeURIComponent(JSON.stringify(params)),});},},
};
</script><style scoped>
.content-pop {width: 100vw;max-height: 55vh;padding: 0 30rpx;
}
.bluetoothItem {padding: 20rpx 0;font-weight: 400;font-size: 28rpx;border-bottom: 1rpx solid #f4f4f4;text-align: left;
}
.textItem {display: block;margin-bottom: 10rpx;
}
</style>

2.选择蓝牙进行连接  blefi.vue

<template><text>打印机正在连接中...</text>
</template><script>
export default {data() {return {bluInfo: {},services: [],serviceId: 0,writeCharacter: false,readCharacter: false,notifyCharacter: false,deviceId: "",notifyCharaterId: "",notifyServiceId: "",writeCharaterId: "",writeServiceId: "",readCharaterId: "",readServiceId: "",};},onLoad(option) {// 接收页面传递的数据this.bluInfo = JSON.parse(decodeURIComponent(option.info));this.bluetooh(this.bluInfo.info.deviceId);this.deviceId = this.bluInfo.info.deviceId;},methods: {bluetooh(deviceId) {var that = this;uni.stopBluetoothDevicesDiscovery({success: (res) => {},});uni.createBLEConnection({deviceId: deviceId,success: (res) => {that.getSeviceId();},fail: (e) => {that.bluetoothFail();},complete: (e) => {},});},// 连接成功后保存连接状态getSeviceId() {var that = this;uni.getBLEDeviceServices({deviceId: this.deviceId,success: (res) => {that.services = res.services;that.getCharacteristics();},fail: (e) => {that.bluetoothFail();},complete: (e) => {},});},getCharacteristics() {var that = this;var list = that.services;var num = that.serviceId;var write = that.writeCharacter;var read = that.readCharacter;var notify = that.notifyCharacter;uni.getBLEDeviceCharacteristics({deviceId: this.deviceId,serviceId: list[num].uuid,success: (res) => {for (var i = 0; i < res.characteristics.length; ++i) {var properties = res.characteristics[i].properties;var item = res.characteristics[i].uuid;if (!notify) {if (properties.notify) {this.notifyCharaterId = item;this.notifyServiceId = list[num].uuid;notify = true;}}if (!write) {if (properties.write) {this.writeCharaterId = item;this.writeServiceId = list[num].uuid;write = true;}}if (!read) {if (properties.read) {readServiceId.readCharaterId = item;readServiceId.readServiceId = list[num].uuid;read = true;}}}if (!write || !notify || !read) {num++;(that.writeCharacter = write),(that.readCharacter = read),(that.notifyCharacter = notify),(that.serviceId = num);if (num == list.length) {// console.log("找不到该读写的特征值")that.bluetoothFail();} else {that.getCharacteristics();}} else {that.bluetoothSuccess(res);}},fail: (e) => {that.bluetoothFail();},});},// 蓝牙连接打印机bluetoothSuccess(res) {let info = {deviceId: this.deviceId,notifyCharaterId: thid.notifyCharaterId,notifyServiceId: thid.notifyServiceId,writeCharaterId: thid.writeCharaterId,writeServiceId: thid.writeServiceId,readCharaterId: thid.readCharaterId,readServiceId: thid.readServiceId,};uni.setStorageSync("blefiInfo", info);uni.showModal({title: "连接成功",confirmText: "继续",confirmColor: "#00A0E9", //确定按钮颜色showCancel: false, //没有取消按钮的弹框success: (res) => {if (res.confirm) {// 蓝牙连接成功,跳转到下一页面uni.redirectTo({url: "/pages/blefi/blefiWifi",});}},});},bluetoothFail() {// 蓝牙连接失败,跳转到失败页面uni.redirectTo({url: "/pages/blefi/blefiFail",});},},
};
</script>

3. 低功耗蓝牙连接WiFi  blefiWifi.vue

<template><view><text>{{ wifiSSID }}</text><input type="text" placeholder="请输入WLAN密码" v-model="password" /><button @click="settiing">连接</button></view>
</template><script>
export default {data() {return {bleInfo: {},wifiSSID: "your SSID",password: "",bleSendSequence: 0,connected: true,wifiCountDown: 0,wifiCountInterval: null, // 定时器dataEnum: {PACKAGE_VALUE: 0x01,SUBTYPE_NEG: 0x00,SUBTYPE_STA_WIFI_BSSID: 0x01,SUBTYPE_STA_WIFI_SSID: 0x02,SUBTYPE_STA_WIFI_PASSWORD: 0x03,SUBTYPE_SOFTAP_WIFI_SSID: 0x04,SUBTYPE_SOFTAP_WIFI_PASSWORD: 0x05,SUBTYPE_SOFTAP_MAX_CONNECTION_COUNT: 0x06,SUBTYPE_SOFTAP_AUTH_MODE: 0x07,SUBTYPE_SOFTAP_CHANNEL: 0x08,SUBTYPE_USERNAME: 0x09,SUBTYPE_CA_CERTIFICATION: 0x0a,SUBTYPE_CLIENT_CERTIFICATION: 0x0b,SUBTYPE_SERVER_CERTIFICATION: 0x0c,SUBTYPE_CLIENT_PRIVATE_KEY: 0x0d,SUBTYPE_SERVER_PRIVATE_KEY: 0x0e,SUBTYPE_WIFI_CONNECTION_STATE: 0x0f,SUBTYPE_VERSION: 0x10,SUBTYPE_WIFI_LIST: 0x11,SUBTYPE_ERROR: 0x12,SUBTYPE_CUSTOM_DATA: 0x13,},controllEnum: {PACKAGE_VALUE: 0x00,SUBTYPE_ACK: 0x00,SUBTYPE_SET_SEC_MODE: 0x01,SUBTYPE_SET_OP_MODE: 0x02,SUBTYPE_CONNECT_WIFI: 0x03,SUBTYPE_DISCONNECT_WIFI: 0x04,SUBTYPE_GET_WIFI_STATUS: 0x05,SUBTYPE_DEAUTHENTICATE: 0x06,SUBTYPE_GET_VERSION: 0x07,SUBTYPE_CLOSE_CONNECTION: 0x08,SUBTYPE_GET_WIFI_LIST: 0x09,},};},// 二级页面清除onUnload() {wx.offBLEConnectionStateChange();if (this.wifiCountInterval) {clearInterval(this.wifiCountInterval);this.wifiCountInterval = null;}},onLoad(options) {this.bleInfo = uni.getStorageSync("blefiInfo");var that = this;wx.getBLEDeviceServices({deviceId: this.bleInfo.deviceId,success: function (res) {wx.getBLEDeviceCharacteristics({deviceId: this.bleInfo.deviceId,serviceId: this.bleInfo.notifyServiceId,success: function (res) {wx.notifyBLECharacteristicValueChange({state: true,deviceId: this.bleInfo.deviceId,serviceId: this.bleInfo.notifyServiceId,characteristicId: this.bleInfo.notifyCharaterId,success: function (res) {console.log("启用notify成功");},});},});},});wx.onBLEConnectionStateChange((res) => {that.connected = res.connected;if (!res.connected) {uni.hideLoading();// 蓝牙连接失败,跳转到失败页面uni.redirectTo({url: "/pages/blefi/blefiFail",});}});// 接收配网打印机回传的数据wx.onBLECharacteristicValueChange(function (res) {uni.hideLoading();var receive = that.ab2strt(res.value);console.log("接收到数据 receive : " + receive);// 处理接收的数据........});},methods: {// 将 ArrayBuffer 转换为16进度字符串ab2strt(buff) {var hexArr = Array.prototype.map.call(new Uint8Array(buff),function (bit) {return ("00" + bit.toString(16)).slice(-2);});return hexArr.join(" ");},settiing() {// 取消wifi连接成功/失败页面this.wifiCountDown = 30;this.startSMSTimer();uni.showLoading({title: "连接中",mask: true,});if (this.connected) {this.sendSSID();this.sendPASSWORD();this.notifyConnect();} else {uni.hideLoading();// 蓝牙连接失败,跳转到失败页面uni.redirectTo({url: "/pages/blefi/blefiFail",});}},startSMSTimer() {this.wifiCountInterval = setInterval(() => {this.wifiCountDown--;if (this.wifiCountDown <= 0) {clearInterval(this.wifiCountInterval);this.wifiCountInterval = null;uni.hideLoading();// 蓝牙连接wifi失败uni.redirectTo({url: "/pages/blefi/wifiFile",});}}, 1000);},sendSSID() {// SSID转UTF-8let password = this.utf16to8(this.wifiSSID);let u8buffer = new Uint8Array(password.length);for (var i = 0; i < password.length; i++) {u8buffer[i] = password.charCodeAt(i);}this.bleSendCMD(this.dataEnum.PACKAGE_VALUE,this.dataEnum.SUBTYPE_STA_WIFI_SSID,0,u8buffer);},utf16to8(str) {var out, i, len, c;out = "";len = str.length;for (i = 0; i < len; i++) {c = str.charCodeAt(i);if (c >= 0x0001 && c <= 0x007f) {out += str.charAt(i);} else if (c > 0x07ff) {out += String.fromCharCode(0xe0 | ((c >> 12) & 0x0f));out += String.fromCharCode(0x80 | ((c >> 6) & 0x3f));out += String.fromCharCode(0x80 | ((c >> 0) & 0x3f));} else {out += String.fromCharCode(0xc0 | ((c >> 6) & 0x1f));out += String.fromCharCode(0x80 | ((c >> 0) & 0x3f));}}return out;},sendPASSWORD() {let password = this.password;let u8buffer = new Uint8Array(password.length);for (var i = 0; i < password.length; i++) {u8buffer[i] = password.charCodeAt(i);}this.bleSendCMD(this.dataEnum.PACKAGE_VALUE,this.dataEnum.SUBTYPE_STA_WIFI_PASSWORD,0,u8buffer);},notifyConnect() {let password = this.password;let u8buffer = new Uint8Array(password.length);for (var i = 0; i < password.length; i++) {u8buffer[i] = password.charCodeAt(i);}this.bleSendCMD(this.controllEnum.PACKAGE_VALUE,this.controllEnum.SUBTYPE_CONNECT_WIFI,0,u8buffer);},//ESP32的蓝牙配网命令接口bleSendCMD(CMD, subCMD, frameControl, payload) {var newValue = new ArrayBuffer(payload.length + 6);var u8array = new Uint8Array(newValue);var LSB_Type = ((subCMD & 0x3f) << 2) | (CMD & 0x03);u8array[0] = LSB_Type;u8array[1] = frameControl;u8array[2] = this.bleSendSequence;u8array[3] = payload.length;for (let i = 0; i < payload.length; i++) {u8array[4 + i] = payload[i];}this.bleSendSequence++;if (this.connected) {wx.writeBLECharacteristicValue({deviceId: this.bleInfo.deviceId,serviceId: this.bleInfo.writeServiceId,characteristicId: this.bleInfo.writeCharaterId,value: newValue,});}},},
};
</script>

4. 手机连接蓝牙失败、蓝牙连接WiFi成功/失败(关闭蓝牙连接)

<script>
export default {onLoad() {let deviceId = uni.getStorageSync("blefiInfo").deviceIduni.closeBLEConnection({deviceId: deviceId,});},
};
</script>

这篇关于uniapp 小程序低功耗蓝牙配网 blefi配网 物联网的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/972671

相关文章

OpenHarmony鸿蒙开发( Beta5.0)无感配网详解

1、简介 无感配网是指在设备联网过程中无需输入热点相关账号信息,即可快速实现设备配网,是一种兼顾高效性、可靠性和安全性的配网方式。 2、配网原理 2.1 通信原理 手机和智能设备之间的信息传递,利用特有的NAN协议实现。利用手机和智能设备之间的WiFi 感知订阅、发布能力,实现了数字管家应用和设备之间的发现。在完成设备间的认证和响应后,即可发送相关配网数据。同时还支持与常规Sof

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

EMLOG程序单页友链和标签增加美化

单页友联效果图: 标签页面效果图: 源码介绍 EMLOG单页友情链接和TAG标签,友链单页文件代码main{width: 58%;是设置宽度 自己把设置成与您的网站宽度一样,如果自适应就填写100%,TAG文件不用修改 安装方法:把Links.php和tag.php上传到网站根目录即可,访问 域名/Links.php、域名/tag.php 所有模板适用,代码就不粘贴出来,已经打

跨系统环境下LabVIEW程序稳定运行

在LabVIEW开发中,不同电脑的配置和操作系统(如Win11与Win7)可能对程序的稳定运行产生影响。为了确保程序在不同平台上都能正常且稳定运行,需要从兼容性、驱动、以及性能优化等多个方面入手。本文将详细介绍如何在不同系统环境下,使LabVIEW开发的程序保持稳定运行的有效策略。 LabVIEW版本兼容性 LabVIEW各版本对不同操作系统的支持存在差异。因此,在开发程序时,尽量使用

CSP 2023 提高级第一轮 CSP-S 2023初试题 完善程序第二题解析 未完

一、题目阅读 (最大值之和)给定整数序列 a0,⋯,an−1,求该序列所有非空连续子序列的最大值之和。上述参数满足 1≤n≤105 和 1≤ai≤108。 一个序列的非空连续子序列可以用两个下标 ll 和 rr(其中0≤l≤r<n0≤l≤r<n)表示,对应的序列为 al,al+1,⋯,ar​。两个非空连续子序列不同,当且仅当下标不同。 例如,当原序列为 [1,2,1,2] 时,要计算子序列 [

这些心智程序你安装了吗?

原文题目:《为什么聪明人也会做蠢事(四)》 心智程序 大脑有两个特征导致人类不够理性,一个是处理信息方面的缺陷,一个是心智程序出了问题。前者可以称为“认知吝啬鬼”,前几篇文章已经讨论了。本期主要讲心智程序这个方面。 心智程序这一概念由哈佛大学认知科学家大卫•帕金斯提出,指个体可以从记忆中提取出的规则、知识、程序和策略,以辅助我们决策判断和解决问题。如果把人脑比喻成计算机,那心智程序就是人脑的

uniapp设置微信小程序的交互反馈

链接:uni.showToast(OBJECT) | uni-app官网 (dcloud.net.cn) 设置操作成功的弹窗: title是我们弹窗提示的文字 showToast是我们在加载的时候进入就会弹出的提示。 2.设置失败的提示窗口和标签 icon:'error'是设置我们失败的logo 设置的文字上限是7个文字,如果需要设置的提示文字过长就需要设置icon并给

基于SpringBoot的宠物服务系统+uniapp小程序+LW参考示例

系列文章目录 1.基于SSM的洗衣房管理系统+原生微信小程序+LW参考示例 2.基于SpringBoot的宠物摄影网站管理系统+LW参考示例 3.基于SpringBoot+Vue的企业人事管理系统+LW参考示例 4.基于SSM的高校实验室管理系统+LW参考示例 5.基于SpringBoot的二手数码回收系统+原生微信小程序+LW参考示例 6.基于SSM的民宿预订管理系统+LW参考示例 7.基于

Spring Roo 实站( 一 )部署安装 第一个示例程序

转自:http://blog.csdn.net/jun55xiu/article/details/9380213 一:安装 注:可以参与官网spring-roo: static.springsource.org/spring-roo/reference/html/intro.html#intro-exploring-sampleROO_OPTS http://stati

未来工作趋势:零工小程序在共享经济中的作用

经济在不断发展的同时,科技也在飞速发展。零工经济作为一种新兴的工作模式,正在全球范围内迅速崛起。特别是在中国,随着数字经济的蓬勃发展和共享经济模式的深入推广,零工小程序在促进就业、提升资源利用效率方面显示出了巨大的潜力和价值。 一、零工经济的定义及现状 零工经济是指通过临时性、自由职业或项目制的工作形式,利用互联网平台快速匹配供需双方的新型经济模式。这种模式打破了传统全职工作的界限,为劳动