index.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. <template>
  2. <view class="container">
  3. <!-- 头部区域 -->
  4. <BluetoothHeader
  5. @ble-data-received="handleBleDataReceived"
  6. />
  7. <!-- 主要内容区域 -->
  8. <view class="main-content">
  9. <!-- 显示区域 -->
  10. <view class="display-area">
  11. <view class="display-window">
  12. <view
  13. v-for="(item, index) in deviceListDataShow"
  14. :key="item.id"
  15. :class="['list-item', { 'list-item-selected': item.id === selectedDeviceId }]"
  16. hover-class="list-item-hover"
  17. hover-start-time="0"
  18. hover-stay-time="100"
  19. @click="selectblue(item.id)"
  20. >
  21. <image v-if="item.manufacturer==='eciot'" src="/static/img/ecble.png" class="list-item-img"></image>
  22. <text class="list-item-name">{{item.id}}:{{ item.name }}&nbsp;</text>
  23. <image v-if="item.rssi >= -41" src="/static/img/s5.png" mode="aspectFit" class="list-item-rssi-img"></image>
  24. <image v-else-if="item.rssi >= -55" src="/static/img/s4.png" mode="aspectFit"
  25. class="list-item-rssi-img"></image>
  26. <image v-else-if="item.rssi >= -65" src="/static/img/s3.png" mode="aspectFit"
  27. class="list-item-rssi-img"></image>
  28. <image v-else-if="item.rssi >= -75" src="/static/img/s2.png" mode="aspectFit"
  29. class="list-item-rssi-img"></image>
  30. <image v-else="item.rssi < -75" src="/static/img/s1.png" mode="aspectFit"
  31. class="list-item-rssi-img"></image>
  32. </view>
  33. </view>
  34. </view>
  35. <!-- 控制按钮区域 -->
  36. <view class="control-area">
  37. <!-- 蓝牙控制行 -->
  38. <view class="control-row">
  39. <u-button type="info" size="medium" class="control-btn" @click="closeBlue()">断开蓝牙</u-button>
  40. <u-button type="info" size="medium" class="control-btn" @click="openBluetoothAdapter()">搜索蓝牙</u-button>
  41. <u-button type="info" size="medium" class="control-btn" @click="listViewTap()">连接蓝牙</u-button>
  42. <u-button type="info" size="medium" class="control-btn" @click="readAddress()">读取地址</u-button>
  43. <u-button type="info" size="medium" class="control-btn" @click="readOldValue()">ORead</u-button>
  44. </view>
  45. <!-- 设备地址行 -->
  46. <u-row gutter="10" customStyle="margin-bottom: 10px">
  47. <u-col span="3">
  48. <view class="label-box">设备地址:</view>
  49. </u-col>
  50. <u-col span="5">
  51. <u-input v-model="deviceAddress" type="number" class="address-input"></u-input>
  52. </u-col>
  53. <u-col span="4">
  54. <u-button type="info" size="medium" class="control-btn" @click="updataAddress()">更新通讯地址</u-button>
  55. </u-col>
  56. </u-row>
  57. <!-- 新设备地址行 -->
  58. <u-row gutter="10" customStyle="margin-bottom: 10px">
  59. <u-col span="3">
  60. <view class="label-box">设备新地址:</view>
  61. </u-col>
  62. <u-col span="5">
  63. <u-input v-model="newDeviceAddress" type="number" placeholder="" class="address-input"></u-input>
  64. </u-col>
  65. <u-col span="4">
  66. <u-button type="info" size="medium" class="control-btn" @click="writeAddress()">写地址</u-button>
  67. </u-col>
  68. </u-row>
  69. <!-- 新设备地址行 -->
  70. <u-row gutter="10" customStyle="margin-bottom: 10px">
  71. <u-col span="3">
  72. <view class="label-box">ODev:</view>
  73. </u-col>
  74. <u-col span="5">
  75. <u-input v-model="oldValue" type="number" placeholder="" class="address-input"></u-input>
  76. </u-col>
  77. </u-row>
  78. </view>
  79. <DeviceStatusInfo/>
  80. </view>
  81. </view>
  82. </template>
  83. <script>
  84. import BluetoothHeader from '@/pages/components/header.vue';
  85. import DeviceStatusInfo from '@/pages/components/DeviceStatusInfo.vue';
  86. import {ecBLE,ecUI,initBLE,writeRegister,startHeartbeat,stopHeartbeat,setGlobalSlaveAddress,getGlobalSlaveAddress,setAgreement,getConnected} from '@/utils/modbus.js';
  87. import i18 from '@/utils/i18.js';
  88. import {setTime} from "../../../utils/modbus";
  89. let deviceListData = [];
  90. let ctx;
  91. export default {
  92. components: {
  93. BluetoothHeader,
  94. DeviceStatusInfo
  95. },
  96. data() {
  97. return {
  98. step:"",
  99. editStatus: false,
  100. oldValue: "",
  101. selectedDeviceId: null, //选中的设备
  102. timer: "", //设备列表数据定时刷新
  103. deviceListDataShow: [
  104. {
  105. id: 1,
  106. name: "设备1",
  107. rssi: -55
  108. },
  109. {
  110. id: 2,
  111. name: "设备2",
  112. rssi: -55
  113. },
  114. ], //蓝牙设备列表
  115. showTimer: null,
  116. connected: false,
  117. sendData: "",
  118. newDeviceAddress:'',
  119. deviceAddress:'',
  120. communicationLink_one: false,
  121. communicationTimer: null, // 添加这一行用于保存定时器 ID
  122. readOldValueStatus:false,
  123. }
  124. },
  125. onLoad() {
  126. uni.setNavigationBarTitle({
  127. title: "蓝牙配网"
  128. })
  129. ecUI.showLoading("正在初始化蓝牙模块")
  130. ctx = this;
  131. clearInterval(this.timer);
  132. this.timer = setInterval(() => {
  133. // 在添加或更新设备后对数组进行排序
  134. deviceListData.sort((a, b) => b.rssi - a.rssi);
  135. ctx.deviceListDataShow = JSON.parse(JSON.stringify(deviceListData))
  136. }, 800)
  137. initBLE();
  138. },
  139. onUnload() {
  140. ecBLE.stopBluetoothDevicesDiscovery();
  141. ecBLE.closeBLEConnection()
  142. },
  143. onShow() {
  144. if (this.showTimer != null) {
  145. clearTimeout(this.showTimer);
  146. }
  147. this.showTimer = setTimeout(() => {
  148. ctx.openBluetoothAdapter()
  149. }, 100)
  150. },
  151. methods: {
  152. // 处理从子组件传递过来的蓝牙数据
  153. handleBleDataReceived(data) {
  154. console.log('在父组件中接收到蓝牙数据:', data);
  155. this.updateSensorData(data);
  156. },
  157. agreementTypeSelect(e){
  158. this.agreementTypeName = e.name;
  159. setAgreement(this.agreementTypeName);
  160. },
  161. async readAddress(){
  162. try {
  163. // 发送读取地址指令
  164. writeRegister("GET_ADDRESS", null);
  165. // 等待地址响应,最多3秒
  166. const data = await this.waitForAddressResponse(3000);
  167. console.log('接收到的数据地址:', data.Addres_23);
  168. this.deviceAddress = data.Addres_23;
  169. // 如果有地址则更新通讯地址
  170. if (this.deviceAddress != null && this.deviceAddress != '') {
  171. this.updataAddress();
  172. }
  173. return data;
  174. } catch (error) {
  175. console.error('读取地址失败:', error);
  176. this.$modal.showToast("读取地址超时");
  177. throw error;
  178. }
  179. },
  180. async readOldValue() {
  181. this.readOldValueStatus = true;
  182. ecUI.showLoading("正在获取旧地址");
  183. // 读取旧值
  184. writeRegister("WRITE_ADDRESS_OLD", null);
  185. let that = this;
  186. setTimeout(() => {
  187. if (that.readOldValueStatus){
  188. ecUI.hideLoading();
  189. }
  190. }, 3000);
  191. },
  192. closeBlue(){
  193. ecUI.showLoading("正在断开并重新扫描");
  194. ecBLE.closeBLEConnection();
  195. stopHeartbeat();
  196. // 重新开始蓝牙扫描以获取设备列表
  197. deviceListData = []; // 清空当前设备列表
  198. this.startBluetoothDevicesDiscovery(); // 开始重新扫描
  199. // 可选:在一段时间后隐藏加载提示
  200. setTimeout(() => {
  201. this.communicationLink_one = false
  202. ecUI.hideLoading();
  203. }, 2000);
  204. },
  205. updateSensorData(data){
  206. console.log('接收到的数据地址:', data.Addres_23);
  207. if (data.Addres_23 != null && data.Addres_23 !== ''){
  208. this.deviceAddress = data.Addres_23;
  209. }
  210. if (data.oldAddressValue != null && data.oldAddressValue !== ''){
  211. this.oldValue = data.oldAddressValue;
  212. }
  213. },
  214. updataAddress(){
  215. if (this.deviceAddress == null || this.deviceAddress === '') {
  216. this.$modal.showToast("请输入通讯地址");
  217. return;
  218. }
  219. let value = parseInt(this.deviceAddress, 10);
  220. setGlobalSlaveAddress(value);
  221. startHeartbeat();
  222. },
  223. writeAddress(){
  224. ecUI.showLoading("正在写入地址,请稍后!")
  225. stopHeartbeat();
  226. setTimeout(() => {
  227. writeRegister("WRITE_ADDRESS",this.newDeviceAddress);
  228. }, 1000);
  229. setTimeout(() => {
  230. this.communicationLink_one = false
  231. ecUI.hideLoading();
  232. }, 2000);
  233. },
  234. i18(text){
  235. return text;
  236. },
  237. $t(title) {
  238. return title;
  239. },
  240. selectblue(id){ //选中需要连接的蓝牙
  241. this.selectedDeviceId = id;
  242. },
  243. listViewTap(){ //连接蓝牙
  244. const id = this.selectedDeviceId;
  245. // 校验设备ID
  246. if (!id) {
  247. this.$modal.showToast("请选择一个设备");
  248. return;
  249. }
  250. // 清除旧的连接状态
  251. this.connected = false;
  252. ecUI.showLoading("正在连接蓝牙");
  253. // 建立连接
  254. ecBLE.createBLEConnection(id);
  255. // 设置连接超时
  256. setTimeout(() => {
  257. this.handleConnectionTimeout();
  258. }, 5000);
  259. },
  260. // 超时处理函数
  261. handleConnectionTimeout() {
  262. this.connected = getConnected();
  263. ecUI.hideLoading();
  264. if (!this.connected) {
  265. this.$modal.showToast(i18('连接失败'));
  266. this.startBluetoothDevicesDiscovery();
  267. }
  268. },
  269. openBluetoothAdapter() { //打开蓝牙
  270. ecBLE.onBluetoothAdapterStateChange(res => {
  271. ecUI.hideLoading()
  272. if (res.ok) {
  273. ctx.startBluetoothDevicesDiscovery()
  274. } else {
  275. ecUI.showModal(
  276. this.$t('buletooth.tip'),
  277. `Bluetooth adapter error | ${res.errCode} | ${res.errMsg}`,
  278. () => {
  279. }
  280. )
  281. }
  282. })
  283. ecBLE.openBluetoothAdapter()
  284. },
  285. startBluetoothDevicesDiscovery() {
  286. ecBLE.stopBluetoothDevicesDiscovery();
  287. console.log('start search')
  288. ecBLE.onBluetoothDeviceFound(res => {
  289. let isRight = true;
  290. if (!isRight) {
  291. return;
  292. }
  293. for (const item of deviceListData) {
  294. if (item.id === res.id) {
  295. item.name = res.name
  296. item.rssi = res.rssi
  297. return
  298. }
  299. }
  300. let manufacturer = ''
  301. if (res.name.length === 11 && res.name.startsWith('@')) {
  302. manufacturer = 'eciot'
  303. }
  304. if (res.name.length === 15 && res.name.startsWith('BT_')) {
  305. manufacturer = 'eciot'
  306. }
  307. manufacturer = 'eciot'
  308. deviceListData.push({
  309. id: res.id,
  310. name: res.name,
  311. rssi: res.rssi,
  312. manufacturer,
  313. })
  314. })
  315. ecBLE.startBluetoothDevicesDiscovery()
  316. },
  317. async autoLinkList() {
  318. // 获取前五个设备进行配网通讯
  319. for (let i = 0; i < Math.min(5, this.deviceListDataShow.length); i++) {
  320. const device = this.deviceListDataShow[i];
  321. try {
  322. this.step = `正在处理设备 ${i+1}/${Math.min(5, this.deviceListDataShow.length)}: 断开当前连接`;
  323. if (getConnected()){
  324. // 断开蓝牙
  325. ecBLE.closeBLEConnection();
  326. // 等待断开连接(等待connected为false)
  327. const isDisconnected = await this.waitForBluetoothState(false, 2000);
  328. if (!isDisconnected) {
  329. this.step = `设备 ${device.name} 断开连接失败,跳过该设备`;
  330. continue;
  331. }
  332. }
  333. // 连接蓝牙
  334. this.step = `正在连接设备: ${device.name}`;
  335. ecUI.showLoading(`正在连接 ${device.name}`);
  336. // 建立连接
  337. ecBLE.createBLEConnection(device.id);
  338. // 等待连接建立(等待connected为true)
  339. const isConnected = await this.waitForBluetoothState(true, 5000);
  340. if (isConnected) {
  341. this.step = `连接成功,正在读取设备地址信息`;
  342. // 获取设备地址并等待响应
  343. try {
  344. const addressData = await this.readAddress();
  345. this.step = `设备地址读取成功: ${this.deviceAddress}`;
  346. // 进行其他通讯操作
  347. // ...
  348. this.step = `设备 ${device.name} 处理完成`;
  349. } catch (error) {
  350. console.error('读取设备地址失败:', error);
  351. this.step = `读取设备 ${device.name} 地址失败,跳过该设备`;
  352. }
  353. } else {
  354. this.step = `连接 ${device.name} 失败,跳过该设备`;
  355. }
  356. ecUI.hideLoading();
  357. // 设备间间隔1秒
  358. await this.sleep(1000);
  359. } catch (error) {
  360. console.error(`处理设备 ${device.name} 时出错:`, error);
  361. this.step = `处理设备 ${device.name} 出错,跳过`;
  362. await this.sleep(1000);
  363. }
  364. }
  365. this.step = "批量连接处理已完成";
  366. },
  367. // 通用的等待状态方法
  368. waitForBluetoothState(targetState, timeout = 2000, interval = 200) {
  369. return new Promise((resolve) => {
  370. const startTime = Date.now();
  371. const checkState = () => {
  372. const currentState = getConnected();
  373. const isTargetState = currentState === targetState;
  374. // 如果达到目标状态或者超时,则resolve
  375. if (isTargetState || (Date.now() - startTime) >= timeout) {
  376. resolve(isTargetState);
  377. } else {
  378. // 继续检查
  379. setTimeout(checkState, interval);
  380. }
  381. };
  382. checkState();
  383. });
  384. },
  385. // 延时方法
  386. sleep(ms) {
  387. return new Promise(resolve => setTimeout(resolve, ms));
  388. },
  389. waitForAddressResponse(timeout = 3000) {
  390. return new Promise((resolve, reject) => {
  391. // 保存原始的 handleBleDataReceived 方法
  392. const originalHandler = this.handleBleDataReceived;
  393. let timeoutId;
  394. // 创建新的处理函数
  395. const newHandler = (data) => {
  396. // 检查是否包含地址数据
  397. if (data && data.Addres_23 !== undefined) {
  398. clearTimeout(timeoutId);
  399. // 恢复原始处理函数
  400. this.handleBleDataReceived = originalHandler;
  401. resolve(data);
  402. } else {
  403. // 如果不是地址数据,调用原始处理函数
  404. originalHandler.call(this, data);
  405. }
  406. };
  407. // 替换处理函数
  408. this.handleBleDataReceived = newHandler;
  409. // 设置超时
  410. timeoutId = setTimeout(() => {
  411. this.handleBleDataReceived = originalHandler;
  412. reject(new Error('等待地址响应超时'));
  413. }, timeout);
  414. });
  415. },
  416. }
  417. }
  418. </script>
  419. <style lang="scss" >
  420. .container {
  421. height: calc(100vh - 100px);
  422. background-color: #f5f5f5;
  423. display: flex;
  424. flex-direction: column;
  425. }
  426. // 主要内容区域
  427. .main-content {
  428. flex: 1;
  429. padding: 15px;
  430. display: flex;
  431. flex-direction: column;
  432. gap: 20px;
  433. height: 100%;
  434. }
  435. // 显示区域
  436. .display-area {
  437. .display-window {
  438. width: 100%;
  439. height: 250px;
  440. background-color: #000;
  441. border: 2px solid #ddd;
  442. border-radius: 8px;
  443. overflow: auto;
  444. }
  445. }
  446. // 控制区域
  447. .control-area {
  448. display: flex;
  449. flex-direction: column;
  450. gap: 15px;
  451. margin-top: 10px;
  452. }
  453. .control-row {
  454. display: flex;
  455. align-items: center;
  456. gap: 10px;
  457. margin-bottom: 10px;
  458. .control-btn {
  459. flex: 1;
  460. background-color: white;
  461. color: #333;
  462. border: 1px solid #ddd;
  463. border-radius: 6px;
  464. font-size: 14px;
  465. height: 40px;
  466. font-size: 13px;
  467. }
  468. .label-box {
  469. width: 80px;
  470. }
  471. .address-input {
  472. flex: 1;
  473. background-color: white;
  474. border: 1px solid #ddd;
  475. border-radius: 6px;
  476. height: 40px;
  477. padding: 0 12px;
  478. }
  479. }
  480. .list-item {
  481. height: 40px;
  482. background-color: #000;
  483. color: #fff;
  484. position: relative;
  485. }
  486. .list-item-selected {
  487. background-color: #767a82;
  488. color: #000;
  489. }
  490. .list-item-name {
  491. position: absolute;
  492. font-size: 16px;
  493. left: 20px;
  494. top: 0px;
  495. line-height: 40px;
  496. color: #fff;
  497. max-width: 80%;
  498. overflow-x: hidden;
  499. }
  500. .list-item-rssi-img {
  501. position: absolute;
  502. width: 20px;
  503. height: 20px;
  504. right: 20px;
  505. top: 13px;
  506. }
  507. .list-item-rssi {
  508. position: absolute;
  509. width: 40px;
  510. height: 40px;
  511. right: 0px;
  512. font-size: 12px;
  513. font-weight: bold;
  514. display: flex;
  515. justify-content: center;
  516. color: white;
  517. line-height: 50px;
  518. }
  519. .list-item-line {
  520. position: absolute;
  521. height: 1px;
  522. width: 100vw;
  523. left: 20px;
  524. background-color: #c6c6c8;
  525. }
  526. ::v-deep .u-button--medium{
  527. font-size: 13px !important;
  528. }
  529. </style>