| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585 |
- <template>
- <view class="container">
- <!-- 头部区域 -->
- <BluetoothHeader
- @ble-data-received="handleBleDataReceived"
- />
- <!-- 主要内容区域 -->
- <view class="main-content">
- <!-- 显示区域 -->
- <view class="display-area">
- <view class="display-window">
- <view
- v-for="(item, index) in deviceListDataShow"
- :key="item.id"
- :class="['list-item', { 'list-item-selected': item.id === selectedDeviceId }]"
- hover-class="list-item-hover"
- hover-start-time="0"
- hover-stay-time="100"
- @click="selectblue(item.id)"
- >
- <image v-if="item.manufacturer==='eciot'" src="/static/img/ecble.png" class="list-item-img"></image>
- <text class="list-item-name">{{item.id}}:{{ item.name }} </text>
- <image v-if="item.rssi >= -41" src="/static/img/s5.png" mode="aspectFit" class="list-item-rssi-img"></image>
- <image v-else-if="item.rssi >= -55" src="/static/img/s4.png" mode="aspectFit"
- class="list-item-rssi-img"></image>
- <image v-else-if="item.rssi >= -65" src="/static/img/s3.png" mode="aspectFit"
- class="list-item-rssi-img"></image>
- <image v-else-if="item.rssi >= -75" src="/static/img/s2.png" mode="aspectFit"
- class="list-item-rssi-img"></image>
- <image v-else="item.rssi < -75" src="/static/img/s1.png" mode="aspectFit"
- class="list-item-rssi-img"></image>
- </view>
- </view>
- </view>
- <!-- 控制按钮区域 -->
- <view class="control-area">
- <!-- 蓝牙控制行 -->
- <view class="control-row">
- <u-button type="info" size="medium" class="control-btn" @click="closeBlue()">断开蓝牙</u-button>
- <u-button type="info" size="medium" class="control-btn" @click="openBluetoothAdapter()">搜索蓝牙</u-button>
- <u-button type="info" size="medium" class="control-btn" @click="listViewTap()">连接蓝牙</u-button>
- <u-button type="info" size="medium" class="control-btn" @click="readAddress()">读取地址</u-button>
- <u-button type="info" size="medium" class="control-btn" @click="readOldValue()">ORead</u-button>
- </view>
- <!-- 设备地址行 -->
- <u-row gutter="10" customStyle="margin-bottom: 10px">
- <u-col span="3">
- <view class="label-box">设备地址:</view>
- </u-col>
- <u-col span="5">
- <u-input v-model="deviceAddress" type="number" class="address-input"></u-input>
- </u-col>
- <u-col span="4">
- <u-button type="info" size="medium" class="control-btn" @click="updataAddress()">更新通讯地址</u-button>
- </u-col>
- </u-row>
- <!-- 新设备地址行 -->
- <u-row gutter="10" customStyle="margin-bottom: 10px">
- <u-col span="3">
- <view class="label-box">设备新地址:</view>
- </u-col>
- <u-col span="5">
- <u-input v-model="newDeviceAddress" type="number" placeholder="" class="address-input"></u-input>
- </u-col>
- <u-col span="4">
- <u-button type="info" size="medium" class="control-btn" @click="writeAddress()">写地址</u-button>
- </u-col>
- </u-row>
- <!-- 新设备地址行 -->
- <u-row gutter="10" customStyle="margin-bottom: 10px">
- <u-col span="3">
- <view class="label-box">ODev:</view>
- </u-col>
- <u-col span="5">
- <u-input v-model="oldValue" type="number" placeholder="" class="address-input"></u-input>
- </u-col>
- </u-row>
- </view>
- <DeviceStatusInfo/>
- </view>
- </view>
- </template>
- <script>
- import BluetoothHeader from '@/pages/components/header.vue';
- import DeviceStatusInfo from '@/pages/components/DeviceStatusInfo.vue';
- import {ecBLE,ecUI,initBLE,writeRegister,startHeartbeat,stopHeartbeat,setGlobalSlaveAddress,getGlobalSlaveAddress,setAgreement,getConnected} from '@/utils/modbus.js';
- import i18 from '@/utils/i18.js';
- import {setTime} from "../../../utils/modbus";
- let deviceListData = [];
- let ctx;
- export default {
- components: {
- BluetoothHeader,
- DeviceStatusInfo
- },
- data() {
- return {
- step:"",
- editStatus: false,
- oldValue: "",
- selectedDeviceId: null, //选中的设备
- timer: "", //设备列表数据定时刷新
- deviceListDataShow: [
- {
- id: 1,
- name: "设备1",
- rssi: -55
- },
- {
- id: 2,
- name: "设备2",
- rssi: -55
- },
- ], //蓝牙设备列表
- showTimer: null,
- connected: false,
- sendData: "",
- newDeviceAddress:'',
- deviceAddress:'',
- communicationLink_one: false,
- communicationTimer: null, // 添加这一行用于保存定时器 ID
- readOldValueStatus:false,
- }
- },
- onLoad() {
- uni.setNavigationBarTitle({
- title: "蓝牙配网"
- })
- ecUI.showLoading("正在初始化蓝牙模块")
- ctx = this;
- clearInterval(this.timer);
- this.timer = setInterval(() => {
- // 在添加或更新设备后对数组进行排序
- deviceListData.sort((a, b) => b.rssi - a.rssi);
- ctx.deviceListDataShow = JSON.parse(JSON.stringify(deviceListData))
- }, 800)
- initBLE();
- },
- onUnload() {
- ecBLE.stopBluetoothDevicesDiscovery();
- ecBLE.closeBLEConnection()
- },
- onShow() {
- if (this.showTimer != null) {
- clearTimeout(this.showTimer);
- }
- this.showTimer = setTimeout(() => {
- ctx.openBluetoothAdapter()
- }, 100)
- },
- methods: {
- // 处理从子组件传递过来的蓝牙数据
- handleBleDataReceived(data) {
- console.log('在父组件中接收到蓝牙数据:', data);
- this.updateSensorData(data);
- },
- agreementTypeSelect(e){
- this.agreementTypeName = e.name;
- setAgreement(this.agreementTypeName);
- },
- async readAddress(){
- try {
- // 发送读取地址指令
- writeRegister("GET_ADDRESS", null);
- // 等待地址响应,最多3秒
- const data = await this.waitForAddressResponse(3000);
- console.log('接收到的数据地址:', data.Addres_23);
- this.deviceAddress = data.Addres_23;
- // 如果有地址则更新通讯地址
- if (this.deviceAddress != null && this.deviceAddress != '') {
- this.updataAddress();
- }
- return data;
- } catch (error) {
- console.error('读取地址失败:', error);
- this.$modal.showToast("读取地址超时");
- throw error;
- }
- },
- async readOldValue() {
- this.readOldValueStatus = true;
- ecUI.showLoading("正在获取旧地址");
- // 读取旧值
- writeRegister("WRITE_ADDRESS_OLD", null);
- let that = this;
- setTimeout(() => {
- if (that.readOldValueStatus){
- ecUI.hideLoading();
- }
- }, 3000);
- },
- closeBlue(){
- ecUI.showLoading("正在断开并重新扫描");
- ecBLE.closeBLEConnection();
- stopHeartbeat();
- // 重新开始蓝牙扫描以获取设备列表
- deviceListData = []; // 清空当前设备列表
- this.startBluetoothDevicesDiscovery(); // 开始重新扫描
- // 可选:在一段时间后隐藏加载提示
- setTimeout(() => {
- this.communicationLink_one = false
- ecUI.hideLoading();
- }, 2000);
- },
- updateSensorData(data){
- console.log('接收到的数据地址:', data.Addres_23);
- if (data.Addres_23 != null && data.Addres_23 !== ''){
- this.deviceAddress = data.Addres_23;
- }
- if (data.oldAddressValue != null && data.oldAddressValue !== ''){
- this.oldValue = data.oldAddressValue;
- }
- },
- updataAddress(){
- if (this.deviceAddress == null || this.deviceAddress === '') {
- this.$modal.showToast("请输入通讯地址");
- return;
- }
- let value = parseInt(this.deviceAddress, 10);
- setGlobalSlaveAddress(value);
- startHeartbeat();
- },
- writeAddress(){
- ecUI.showLoading("正在写入地址,请稍后!")
- stopHeartbeat();
- setTimeout(() => {
- writeRegister("WRITE_ADDRESS",this.newDeviceAddress);
- }, 1000);
- setTimeout(() => {
- this.communicationLink_one = false
- ecUI.hideLoading();
- }, 2000);
- },
- i18(text){
- return text;
- },
- $t(title) {
- return title;
- },
- selectblue(id){ //选中需要连接的蓝牙
- this.selectedDeviceId = id;
- },
- listViewTap(){ //连接蓝牙
- const id = this.selectedDeviceId;
- // 校验设备ID
- if (!id) {
- this.$modal.showToast("请选择一个设备");
- return;
- }
- // 清除旧的连接状态
- this.connected = false;
- ecUI.showLoading("正在连接蓝牙");
- // 建立连接
- ecBLE.createBLEConnection(id);
- // 设置连接超时
- setTimeout(() => {
- this.handleConnectionTimeout();
- }, 5000);
- },
- // 超时处理函数
- handleConnectionTimeout() {
- this.connected = getConnected();
- ecUI.hideLoading();
- if (!this.connected) {
- this.$modal.showToast(i18('连接失败'));
- this.startBluetoothDevicesDiscovery();
- }
- },
- openBluetoothAdapter() { //打开蓝牙
- ecBLE.onBluetoothAdapterStateChange(res => {
- ecUI.hideLoading()
- if (res.ok) {
- ctx.startBluetoothDevicesDiscovery()
- } else {
- ecUI.showModal(
- this.$t('buletooth.tip'),
- `Bluetooth adapter error | ${res.errCode} | ${res.errMsg}`,
- () => {
- }
- )
- }
- })
- ecBLE.openBluetoothAdapter()
- },
- startBluetoothDevicesDiscovery() {
- ecBLE.stopBluetoothDevicesDiscovery();
- console.log('start search')
- ecBLE.onBluetoothDeviceFound(res => {
- let isRight = true;
- if (!isRight) {
- return;
- }
- for (const item of deviceListData) {
- if (item.id === res.id) {
- item.name = res.name
- item.rssi = res.rssi
- return
- }
- }
- let manufacturer = ''
- if (res.name.length === 11 && res.name.startsWith('@')) {
- manufacturer = 'eciot'
- }
- if (res.name.length === 15 && res.name.startsWith('BT_')) {
- manufacturer = 'eciot'
- }
- manufacturer = 'eciot'
- deviceListData.push({
- id: res.id,
- name: res.name,
- rssi: res.rssi,
- manufacturer,
- })
- })
- ecBLE.startBluetoothDevicesDiscovery()
- },
- async autoLinkList() {
- // 获取前五个设备进行配网通讯
- for (let i = 0; i < Math.min(5, this.deviceListDataShow.length); i++) {
- const device = this.deviceListDataShow[i];
- try {
- this.step = `正在处理设备 ${i+1}/${Math.min(5, this.deviceListDataShow.length)}: 断开当前连接`;
- if (getConnected()){
- // 断开蓝牙
- ecBLE.closeBLEConnection();
- // 等待断开连接(等待connected为false)
- const isDisconnected = await this.waitForBluetoothState(false, 2000);
- if (!isDisconnected) {
- this.step = `设备 ${device.name} 断开连接失败,跳过该设备`;
- continue;
- }
- }
- // 连接蓝牙
- this.step = `正在连接设备: ${device.name}`;
- ecUI.showLoading(`正在连接 ${device.name}`);
- // 建立连接
- ecBLE.createBLEConnection(device.id);
- // 等待连接建立(等待connected为true)
- const isConnected = await this.waitForBluetoothState(true, 5000);
- if (isConnected) {
- this.step = `连接成功,正在读取设备地址信息`;
- // 获取设备地址并等待响应
- try {
- const addressData = await this.readAddress();
- this.step = `设备地址读取成功: ${this.deviceAddress}`;
- // 进行其他通讯操作
- // ...
- this.step = `设备 ${device.name} 处理完成`;
- } catch (error) {
- console.error('读取设备地址失败:', error);
- this.step = `读取设备 ${device.name} 地址失败,跳过该设备`;
- }
- } else {
- this.step = `连接 ${device.name} 失败,跳过该设备`;
- }
- ecUI.hideLoading();
- // 设备间间隔1秒
- await this.sleep(1000);
- } catch (error) {
- console.error(`处理设备 ${device.name} 时出错:`, error);
- this.step = `处理设备 ${device.name} 出错,跳过`;
- await this.sleep(1000);
- }
- }
- this.step = "批量连接处理已完成";
- },
- // 通用的等待状态方法
- waitForBluetoothState(targetState, timeout = 2000, interval = 200) {
- return new Promise((resolve) => {
- const startTime = Date.now();
- const checkState = () => {
- const currentState = getConnected();
- const isTargetState = currentState === targetState;
- // 如果达到目标状态或者超时,则resolve
- if (isTargetState || (Date.now() - startTime) >= timeout) {
- resolve(isTargetState);
- } else {
- // 继续检查
- setTimeout(checkState, interval);
- }
- };
- checkState();
- });
- },
- // 延时方法
- sleep(ms) {
- return new Promise(resolve => setTimeout(resolve, ms));
- },
- waitForAddressResponse(timeout = 3000) {
- return new Promise((resolve, reject) => {
- // 保存原始的 handleBleDataReceived 方法
- const originalHandler = this.handleBleDataReceived;
- let timeoutId;
- // 创建新的处理函数
- const newHandler = (data) => {
- // 检查是否包含地址数据
- if (data && data.Addres_23 !== undefined) {
- clearTimeout(timeoutId);
- // 恢复原始处理函数
- this.handleBleDataReceived = originalHandler;
- resolve(data);
- } else {
- // 如果不是地址数据,调用原始处理函数
- originalHandler.call(this, data);
- }
- };
- // 替换处理函数
- this.handleBleDataReceived = newHandler;
- // 设置超时
- timeoutId = setTimeout(() => {
- this.handleBleDataReceived = originalHandler;
- reject(new Error('等待地址响应超时'));
- }, timeout);
- });
- },
- }
- }
- </script>
- <style lang="scss" >
- .container {
- height: calc(100vh - 100px);
- background-color: #f5f5f5;
- display: flex;
- flex-direction: column;
- }
- // 主要内容区域
- .main-content {
- flex: 1;
- padding: 15px;
- display: flex;
- flex-direction: column;
- gap: 20px;
- height: 100%;
- }
- // 显示区域
- .display-area {
- .display-window {
- width: 100%;
- height: 250px;
- background-color: #000;
- border: 2px solid #ddd;
- border-radius: 8px;
- overflow: auto;
- }
- }
- // 控制区域
- .control-area {
- display: flex;
- flex-direction: column;
- gap: 15px;
- margin-top: 10px;
- }
- .control-row {
- display: flex;
- align-items: center;
- gap: 10px;
- margin-bottom: 10px;
- .control-btn {
- flex: 1;
- background-color: white;
- color: #333;
- border: 1px solid #ddd;
- border-radius: 6px;
- font-size: 14px;
- height: 40px;
- font-size: 13px;
- }
- .label-box {
- width: 80px;
- }
- .address-input {
- flex: 1;
- background-color: white;
- border: 1px solid #ddd;
- border-radius: 6px;
- height: 40px;
- padding: 0 12px;
- }
- }
- .list-item {
- height: 40px;
- background-color: #000;
- color: #fff;
- position: relative;
- }
- .list-item-selected {
- background-color: #767a82;
- color: #000;
- }
- .list-item-name {
- position: absolute;
- font-size: 16px;
- left: 20px;
- top: 0px;
- line-height: 40px;
- color: #fff;
- max-width: 80%;
- overflow-x: hidden;
- }
- .list-item-rssi-img {
- position: absolute;
- width: 20px;
- height: 20px;
- right: 20px;
- top: 13px;
- }
- .list-item-rssi {
- position: absolute;
- width: 40px;
- height: 40px;
- right: 0px;
- font-size: 12px;
- font-weight: bold;
- display: flex;
- justify-content: center;
- color: white;
- line-height: 50px;
- }
- .list-item-line {
- position: absolute;
- height: 1px;
- width: 100vw;
- left: 20px;
- background-color: #c6c6c8;
- }
- ::v-deep .u-button--medium{
- font-size: 13px !important;
- }
- </style>
|