index.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. <template>
  2. <view style="height: 100vh">
  3. <view v-if="!connected">
  4. <scroll-view class="main-container" scroll-y="true"
  5. :refresher-enabled="false">
  6. <view v-for="(item, index) in deviceListDataShow" :key="item.id" class="list-item" hover-class="list-item-hover"
  7. hover-start-time="0" hover-stay-time="100" @click="listViewTap(item.id)">
  8. <image v-if="item.manufacturer==='eciot'" src="/static/img/ecble.png" class="list-item-img"></image>
  9. <image v-else src="/static/img/ble.png" class="list-item-img"></image>
  10. <text class="list-item-name">{{item.name}}</text>
  11. <image v-if="item.rssi >= -41" src="/static/img/s5.png" mode="aspectFit" class="list-item-rssi-img"></image>
  12. <image v-else-if="item.rssi >= -55" src="/static/img/s4.png" mode="aspectFit" class="list-item-rssi-img"></image>
  13. <image v-else-if="item.rssi >= -65" src="/static/img/s3.png" mode="aspectFit" class="list-item-rssi-img"></image>
  14. <image v-else-if="item.rssi >= -75" src="/static/img/s2.png" mode="aspectFit" class="list-item-rssi-img"></image>
  15. <image v-else="item.rssi < -75" src="/static/img/s1.png" mode="aspectFit" class="list-item-rssi-img"></image>
  16. <text class="list-item-rssi">{{item.rssi}}</text>
  17. <view class="list-item-line"></view>
  18. </view>
  19. <u-popup :show="showSendData" >
  20. <view class="slot-content">
  21. <view>
  22. <u--input
  23. :placeholder="i18('请输入值')"
  24. border="surround"
  25. v-model="sendData"
  26. ></u--input>
  27. </view>
  28. <view style="margin:10px;text-decoration: underline;margin-bottom: 0px" @click="sendLanyaData">
  29. <u-button>发送</u-button>
  30. </view>
  31. </view>
  32. </u-popup>
  33. <view v-if="deviceListDataShow.length==0" class="notice"> - {{ $t('buletooth.nodevice') }} -</view>
  34. <view class="gap"></view>
  35. </scroll-view>
  36. </view>
  37. <view v-if="connected">
  38. <view class="text-area">
  39. <u--form style="width: 100%;"
  40. labelPosition="left"
  41. ref="uForm"
  42. >
  43. <u-form-item
  44. label="WIFI名称:"
  45. borderBottom
  46. labelWidth="auto"
  47. @click="openChooseWifi"
  48. ref="item1"
  49. >
  50. <u--input
  51. v-model="SSID"
  52. disabled
  53. disabledColor="#ffffff"
  54. placeholder="请选择wifi:"
  55. border="none"
  56. ></u--input>
  57. <u-icon
  58. slot="right"
  59. name="arrow-right"
  60. ></u-icon>
  61. </u-form-item>
  62. <u-form-item
  63. label="密码:"
  64. borderBottom
  65. ref="item1"
  66. >
  67. <u--input
  68. v-model="password"
  69. border="none"
  70. ></u--input>
  71. </u-form-item>
  72. <u-form-item
  73. label="二维码ID:"
  74. borderBottom
  75. ref="item1"
  76. labelWidth="auto"
  77. >
  78. <u--input
  79. v-model="qrcodeid"
  80. border="none"
  81. ></u--input>
  82. </u-form-item>
  83. <u-form-item
  84. @click="showProductList = true"
  85. label="产品类型:"
  86. borderBottom
  87. ref="item1"
  88. labelWidth="auto"
  89. >
  90. <u--input
  91. v-model="productName"
  92. border="none"
  93. ></u--input>
  94. </u-form-item>
  95. </u--form>
  96. </view>
  97. <view style="margin:10px">
  98. <u-button text="开始配网" @click="doConnect" size="small" type="primary"></u-button>
  99. </view>
  100. <u-picker @cancel="showWiftList=false" @confirm="chooseWifi" :show="showWiftList" :columns="wifiList"></u-picker>
  101. <u-picker @cancel="showProductList=false" keyName="text" @confirm="chooseProduct" :show="showProductList" :columns="chooseProductList"></u-picker>
  102. </view>
  103. </view>
  104. </template>
  105. <script>
  106. // #ifdef APP
  107. import ecUI from '@/utils/ecUI.js'
  108. import ecBLE from '@/utils/ecBLE/ecBLE.js'
  109. // #endif
  110. // #ifdef MP
  111. const ecUI = require('@/utils/ecUI.js')
  112. const ecBLE = require('@/utils/ecBLE/ecBLE.js')
  113. // #endif
  114. import i18 from '@/utils/i18.js'
  115. let ctx
  116. let deviceListData = []
  117. export default {
  118. data() {
  119. return {
  120. showProductList:false,
  121. showPwd:false,
  122. rightPwd:"",
  123. pwd:"",
  124. timer:"",
  125. buleid:"",
  126. deviceListDataShow: [],
  127. showTimer:null,
  128. connected:false,
  129. uuid:"",
  130. showDeviceNo:false,
  131. inputDeviceNo:"",
  132. commonCode:"",
  133. showSendData:false,
  134. sendData:"",
  135. qrcodeid:"",
  136. productName:"",
  137. deviceno:"",
  138. SSID:"",
  139. password:"",
  140. showWiftList:false,
  141. productId:56,
  142. chooseProductList:[[ {
  143. id:56,text:"3"
  144. },
  145. {
  146. id:56,text:"4"
  147. },
  148. {
  149. id:57,text:"5"
  150. }
  151. ]],
  152. wifiList: [
  153. []
  154. ],
  155. }
  156. },
  157. onLoad() {
  158. uni.setNavigationBarTitle({
  159. title: "蓝牙配网"
  160. })
  161. this.deviceno = this.generateTimestamp();
  162. ecUI.showLoading("正在初始化蓝牙模块")
  163. ctx = this
  164. clearInterval(this.timer);
  165. this.timer = setInterval(() => {
  166. ctx.deviceListDataShow = JSON.parse(JSON.stringify(deviceListData))
  167. }, 800)
  168. console.log(this.commonCode)
  169. this.productName = this.chooseProductList[0][0].text;
  170. },
  171. onUnload(){
  172. ecBLE.stopBluetoothDevicesDiscovery();
  173. ecBLE.closeBLEConnection()
  174. },
  175. onShow() {
  176. if(this.showTimer!= null){
  177. clearTimeout(this.showTimer);
  178. }
  179. this.showTimer = setTimeout(() => {
  180. ctx.openBluetoothAdapter()
  181. }, 100)
  182. },
  183. methods: {
  184. chooseProduct(e){
  185. this.productId = e.value[0].id;
  186. this.productName = e.value[0].text;
  187. this.showProductList= false;
  188. },
  189. generateTimestamp() {
  190. const date = new Date();
  191. const year = date.getFullYear().toString().substr(2);
  192. const month = date.getMonth() + 1;
  193. const day = date.getDate();
  194. const hours = date.getHours();
  195. const minutes = date.getMinutes();
  196. // 生成6位随机数字
  197. const randomNum = Math.floor(Math.random() * 900000) + 100000;
  198. // 将数字拼接成字符串
  199. const timestamp = `${year}${month < 10 ? '0' + month : month}${day < 10 ? '0' + day : day}${hours}${minutes < 10 ? '0' + minutes : minutes}${randomNum}`;
  200. return timestamp;
  201. },
  202. getAuth(){
  203. wx.getSetting({
  204. success(res) {
  205. if (!res.authSetting['scope.userLocation']) {
  206. wx.authorize({
  207. scope: 'scope.userLocation',
  208. success () {
  209. // 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问
  210. }
  211. })
  212. }
  213. }
  214. })
  215. },
  216. chooseWifi(e){
  217. this.SSID = e.value[0];
  218. this.showWiftList= false;
  219. },
  220. openChooseWifi(){
  221. if(this.wifiList[0].length == 0){
  222. this.getWifiList();
  223. }else{
  224. this.showWiftList = true;
  225. }
  226. },
  227. openWifi(){
  228. let self = this;
  229. // #ifdef MP-WEIXIN
  230. wx.startWifi({
  231. success(res) {
  232. console.log(res);
  233. // self.getWifiList();
  234. },
  235. fail(res) {
  236. console.log(res)
  237. uni.showToast({
  238. title: '请打开WIFI',
  239. icon: 'none',
  240. duration: 3000
  241. });
  242. },
  243. })
  244. // #endif
  245. },
  246. getWifi(){
  247. // #ifdef MP-WEIXIN
  248. var that = this
  249. wx.getConnectedWifi({
  250. success(res) {
  251. console.log(res)
  252. that.BSSID = res.wifi.BSSID
  253. that.WIFIName = res.wifi.SSID
  254. },
  255. fail(res) {
  256. console.log(res)
  257. //报错的相关处理
  258. },
  259. })
  260. // #endif
  261. },
  262. getWifiList(){
  263. // #ifdef MP-WEIXIN
  264. var that = this
  265. uni.showLoading();
  266. wx.getWifiList({
  267. success(res) {
  268. console.log(res)
  269. wx.onGetWifiList(function(res) {
  270. that.showWiftList = true;
  271. uni.hideLoading();
  272. console.log("获取wifi列表");
  273. that.wifiList = [[]];
  274. console.log(res.wifiList); //在这里提取列表数据
  275. //通过遍历将WIFI名字存入集合,以便下卡框等组件使用
  276. for (var i = 0; i < res.wifiList.length; i++) {
  277. that.wifiList[0].push(res.wifiList[i].SSID)
  278. }
  279. })
  280. },
  281. fail(res) {
  282. console.log(res)
  283. uni.showToast({
  284. title: '获取wifi失败,请检查wifi',
  285. icon: 'none',
  286. duration: 2000
  287. });
  288. },
  289. })
  290. // #endif
  291. },
  292. doConnect(){
  293. if(this.SSID == ""){
  294. uni.showToast({
  295. title: '请选择WIFI',
  296. icon: 'none',
  297. duration: 3000
  298. });
  299. return;
  300. }
  301. if(this.password == ""){
  302. uni.showToast({
  303. title: '请输入wifi密码',
  304. icon: 'none',
  305. duration: 3000
  306. });
  307. return;
  308. }
  309. if(this.qrcodeid == ""){
  310. uni.showToast({
  311. title: '请输入二维码ID',
  312. icon: 'none',
  313. duration: 3000
  314. });
  315. return;
  316. }
  317. if(this.deviceno == ""){
  318. uni.showToast({
  319. title: '请输入设备编号',
  320. icon: 'none',
  321. duration: 3000
  322. });
  323. return;
  324. }
  325. /**
  326. * ID:XXX+回车换行(设备编号)
  327. * QR:XXXX+回车换行(二维码ID)
  328. * ssid:WiFi名字+回车换行
  329. * psd:wifi密码+回车换行
  330. * 最后+OK
  331. */
  332. let self = this;
  333. let endStr = "$$";
  334. ecUI.showLoading("正在配置网络信息")
  335. setTimeout(function(){
  336. self.sendBlueData("ID:"+self.deviceno+endStr);
  337. },200);
  338. setTimeout(function(){
  339. self.sendBlueData("QR:"+self.qrcodeid+endStr);
  340. },400);
  341. setTimeout(function(){
  342. self.sendBlueData("ssid:"+self.SSID+endStr);
  343. },600);
  344. setTimeout(function(){
  345. self.sendBlueData("psd:"+self.password+endStr);
  346. },800);
  347. setTimeout(function(){
  348. self.sendBlueData("pid:"+self.productId+endStr);
  349. },1000);
  350. setTimeout(function(){
  351. self.sendBlueData("OK");
  352. },1200);
  353. },
  354. stringToHex(str) {
  355. let hex = '';
  356. for (let i = 0; i < str.length; i++) {
  357. const char = str.charCodeAt(i);
  358. const hexChar = char.toString(16).padStart(2, '0');
  359. hex += hexChar;
  360. }
  361. return hex;
  362. },
  363. doByTime(func,time){
  364. setTimeout(function (){
  365. func();
  366. },time);
  367. },
  368. sendLanyaData(){
  369. this.$modal.showToast("正在发送");
  370. this.sendBlueData(this.sendData);
  371. },
  372. i18(text){
  373. return text;
  374. },
  375. cancel(){
  376. this.showPwd = false;
  377. uni.navigateBack({
  378. });
  379. },
  380. resetPwd(){
  381. let self = this;
  382. if(!this.inputDeviceNo){
  383. self.$modal.showToast("请输入序列号");
  384. return;
  385. }
  386. let uuidRight = false;
  387. if(this.inputDeviceNo == this.commonCode || this.uuid == this.inputDeviceNo){
  388. uuidRight = true;
  389. }
  390. if(!uuidRight){
  391. self.$modal.showToast("序列号有误");
  392. return;
  393. }
  394. if(uuidRight){
  395. this.$modal.confirm("密码将被重置为123456").then(res=>{
  396. setPwd("123456")
  397. self.$modal.showToast("密码修改成功");
  398. this.rightPwd = "123456";
  399. self.loginSuccess();
  400. });
  401. }
  402. },
  403. getBeijingTime() {
  404. const date = new Date();
  405. const utcTime = date.getTime() + (date.getTimezoneOffset() * 60 * 1000);
  406. const beijingTime = new Date(utcTime + (8 * 60 * 60 * 1000));
  407. return beijingTime;
  408. },
  409. generateUniqueNumber(date) {
  410. let dateString = date.toISOString().slice(0, 10).replace(/-/g, '');
  411. console.log(dateString)
  412. let hash = w_md5.hex_md5_32(dateString);
  413. console.log(hash);//32位小写
  414. let str = "";
  415. for (let i = 0; i < 6; i++) {
  416. const c = hash.charCodeAt(i);
  417. str = str+""+c+""
  418. }
  419. return str.substr(0,6);
  420. },
  421. goBack(){
  422. uni.navigateBack({
  423. });
  424. },
  425. $t(title){
  426. return title;
  427. },
  428. inputPwd(){
  429. if(!this.pwd ){
  430. this.$modal.showToast(this.$t('buletooth.errpwd'));
  431. }else{
  432. if(this.rightPwd && this.rightPwd === this.pwd){
  433. this.loginSuccess();
  434. }else{
  435. this.$modal.showToast(this.$t('buletooth.errpwd'));
  436. }
  437. }
  438. },
  439. loginSuccess(){
  440. this.showPwd = false;
  441. this.showDeviceNo = false;
  442. uni.setStorageSync("pwd",this.rightPwd);
  443. uni.setStorageSync('blueid', this.buleid);
  444. this.pwd = "";
  445. ecBLE.stopBluetoothDevicesDiscovery();
  446. uni.navigateTo({
  447. url: '/pages/weitiandi/bluetooth/status'
  448. });
  449. },
  450. getLocalPwd(){
  451. let pwd = uni.getStorageSync("pwd");
  452. return pwd;
  453. },
  454. sendBlueData(tempSendData){
  455. tempSendData = this.stringToHex(tempSendData);
  456. let data = tempSendData
  457. .replace(/\s*/g, '')
  458. .replace(/\n/g, '')
  459. .replace(/\r/g, '')
  460. console.log("写入数据:"+data);
  461. ecBLE.writeBLECharacteristicValue(data, true)
  462. },
  463. listViewTap(id){
  464. let self = this;
  465. ecUI.showLoading("正在连接蓝牙")
  466. ecBLE.onBLEConnectionStateChange(res => {
  467. console.log(res);
  468. if (res.ok) {
  469. self.connected = true;
  470. self.openWifi();
  471. ecUI.hideLoading()
  472. self.showSendData = true;
  473. ecBLE.stopBluetoothDevicesDiscovery();
  474. //
  475. } else {
  476. ecUI.hideLoading()
  477. this.$modal.showToast("请检查是否配置成功");
  478. }
  479. });
  480. //receive data
  481. ecBLE.onBLECharacteristicValueChange((str, strHex) => {
  482. console.log("数据来了")
  483. let isCheckRevHex = true;
  484. let data =
  485. (isCheckRevHex ? strHex.replace(/[0-9a-fA-F]{2}/g, ' $&') : str)
  486. console.log(data)
  487. self.$modal.closeLoading();
  488. data = parseDataObj(data);
  489. })
  490. self.connected = false;
  491. ecBLE.createBLEConnection(id);
  492. setTimeout(function (){
  493. if(!self.connected){
  494. self.$modal.showToast(i18('连接失败'));
  495. self.startBluetoothDevicesDiscovery()
  496. }
  497. },10000);
  498. },
  499. showInputPwd(){
  500. this.showPwd = true;
  501. },
  502. messageCallback(data){
  503. let self = this;
  504. console.log(data);
  505. let type = data.type;
  506. let real_data = data.real_data;
  507. if(type == 253){
  508. self.$modal.closeLoading();
  509. self.uuid = real_data.substr(0,6);
  510. }
  511. self.$forceUpdate();
  512. console.log('收到服务器内容:' + JSON.stringify(data));
  513. },
  514. forgetPwd(){
  515. this.$modal.loading("正在读取设备ID");
  516. getUUID()
  517. this.showDeviceNo = true;
  518. },
  519. openBluetoothAdapter() {
  520. let self = this;
  521. ecBLE.onBluetoothAdapterStateChange(res => {
  522. ecUI.hideLoading()
  523. if (res.ok) {
  524. ctx.startBluetoothDevicesDiscovery()
  525. } else {
  526. ecUI.showModal(
  527. this.$t('buletooth.tip'),
  528. `Bluetooth adapter error | ${res.errCode} | ${res.errMsg}`,
  529. () => {
  530. }
  531. )
  532. }
  533. })
  534. ecBLE.openBluetoothAdapter()
  535. },
  536. startBluetoothDevicesDiscovery() {
  537. ecBLE.stopBluetoothDevicesDiscovery();
  538. console.log('start search')
  539. ecBLE.onBluetoothDeviceFound(res => {
  540. let isRight = true;
  541. // if(res.name.startsWith('BT_') || res.name.startsWith('FC41D')){
  542. // isRight = true;
  543. // }
  544. if(!isRight){
  545. return;
  546. }
  547. for (const item of deviceListData) {
  548. if (item.id === res.id) {
  549. item.name = res.name
  550. item.rssi = res.rssi
  551. return
  552. }
  553. }
  554. let manufacturer = ''
  555. if (res.name.length === 11 && res.name.startsWith('@')) {
  556. manufacturer = 'eciot'
  557. }
  558. if (res.name.length === 15 && res.name.startsWith('BT_')) {
  559. manufacturer = 'eciot'
  560. }
  561. manufacturer = 'eciot'
  562. deviceListData.push({
  563. id: res.id,
  564. name: res.name,
  565. rssi: res.rssi,
  566. manufacturer,
  567. })
  568. })
  569. ecBLE.startBluetoothDevicesDiscovery()
  570. },
  571. }
  572. }
  573. </script>
  574. <style>
  575. .main-container {
  576. height: 100vh;
  577. }
  578. .list-item {
  579. height: 57px;
  580. position: relative;
  581. }
  582. .list-item-hover {
  583. background-color: #e5e4e9;
  584. }
  585. .list-item-img {
  586. position: absolute;
  587. width: 36px;
  588. height: 36px;
  589. left: 20px;
  590. top: 10px;
  591. }
  592. .list-item-name {
  593. position: absolute;
  594. font-size: 22px;
  595. left: 76px;
  596. top: 0px;
  597. line-height: 56px;
  598. }
  599. .list-item-rssi-img {
  600. position: absolute;
  601. width: 20px;
  602. height: 20px;
  603. right: 20px;
  604. top: 13px;
  605. }
  606. .list-item-rssi {
  607. position: absolute;
  608. width: 40px;
  609. height: 20px;
  610. right: 10px;
  611. top: 33px;
  612. font-size: 12px;
  613. font-weight: bold;
  614. display: flex;
  615. justify-content: center;
  616. }
  617. .list-item-line {
  618. position: absolute;
  619. height: 1px;
  620. width: 100vw;
  621. left: 20px;
  622. top: 56px;
  623. background-color: #c6c6c8;
  624. }
  625. .notice {
  626. display: flex;
  627. justify-content: center;
  628. align-items: center;
  629. margin-top: 10px;
  630. font-size: 13px;
  631. color: #909399;
  632. }
  633. .gap {
  634. height: 57px;
  635. }
  636. .text-area {
  637. display: flex;
  638. justify-content: center;
  639. background: white;
  640. width: 100%;
  641. height: 100%;
  642. }
  643. </style>