微信小程序蓝牙连接(uniapp版本)

1.安卓和ios差异
微信小程序项目是扫码获取蓝牙连接设备的信息,可以拿到设备的deviceId,但是安卓和IOS的deviceId格式不一样,最好是通过蓝牙名字查 询获取deviceId
2.代码

<template>
	<view class="index-container">
		<!-- 蓝牙已连接 -->
		<block v-if="hasConnectBTFlag">
			<!-- 充电中显示 -->
			<view class="charging" v-if="hasChargeFlag">
				<view class="charing-animate"></view>
				<view class="charge-text">充电中</view>
			</view>
			<!-- 待机显示 其他状态-->
			<view class="errStatus" v-if="pileErrorFlag && !hasChargeFlag">
				<view class="ring">故障中</view>
			</view>
			<view class="otherStatus" v-if="!pileErrorFlag && !hasChargeFlag">
				<view class="ring">待机中</view>
			</view>
		</block>
		<!-- 蓝牙未连接有设备-->
		<block v-if="!hasConnectBTFlag && hasEquipFlag">
			<view class="ont-connected">
				<view class="rings">蓝牙断开连接</view>
			</view>
		</block>
		<!-- 蓝牙未连接无设备 -->
		<block v-if="!hasConnectBTFlag && !hasEquipFlag">
			<view class="ont-connected">
				<view class="rings">暂无设备</view>
			</view>
		</block>
		<!-- 蓝牙连接成功按钮 -->
		<block v-if="hasConnectBTFlag">
			<!-- 开始充电按钮   蓝牙模式显示 chargeMode =='00'蓝牙模式   equipBaseInfo.chargeMode =='01' 充电模式-->
			<view class="startCharge" v-if="equipBaseInfo.chargeMode =='00' && !hasChargeFlag"
				@click="$u.throttle(startCharge,3000)">
				<view></view>
			</view>
			<!-- 停止充电按钮    蓝牙模式显示-->
			<view class="offCharge" v-if="equipBaseInfo.chargeMode =='00' && hasChargeFlag"
				@click="$u.throttle(offCharge,3000)">
				<view></view>
			</view>
			<!-- 即插即充模式占位 -->
			<view style="height: 150rpx;margin: 106rpx auto 0;" v-if="equipBaseInfo.chargeMode =='01'"></view>
		</block>
		<!-- 蓝牙连接失败按钮 -->
		<block v-if="!hasConnectBTFlag && hasEquipFlag">
			<view class="toContect" @click="$u.throttle(restContect, 6000)">
				<view></view>
			</view>
			<view class="contect-text">
				<view style="margin-right: 10rpx;">
					<tui-icon name="about" size="16"></tui-icon>
				</view>
				<view>请确保您在设备附近,点击按钮重新连接</view>
			</view>
		</block>
		<!-- 未绑定设备去绑定设备 -->
		<block v-if="!hasConnectBTFlag && !hasEquipFlag">
			<view class="toContect" @click="goBind">
				<view></view>
			</view>
			<view class="contect-text">
				<view style="margin-right: 10rpx;">
					<tui-icon name="about" size="16"></tui-icon>
				</view>
				<view>点击按钮绑定设备</view>
			</view>
		</block>
		<!-- 操作面板 -->
		<view :class="[hasConnectBTFlag?'marg100':'marg75','panel']">
			<view class="btn">
				<view class="switch" @click="$u.throttle(switchType,3000)">
					<view :class="[equipBaseInfo.chargeMode =='00'? 'blueThtooth':'plug']"></view>
					<view :class="[equipBaseInfo.chargeMode =='00'? 'cutA':'cutB','cut']">切换</view>
					<view class="switch_describe">{
    
    {
    
    equipBaseInfo.chargeMode =='00' ?'蓝牙充电模式':'即插即充模式'}}</view>
				</view>
				<view class="device" @click="goDeviceDetail">
					<view :class="[equipBaseInfo.chargeMode =='00' ?'device_item':'device_items']"></view>
					<view class="device_describe">设备详情</view>
				</view>
			</view>
			<view class="tips">
				<view>
					<view>{
    
    {
    
    formatChargeVal(equipBaseInfo.powerCount)}}<text class="smallFont">KW</text></view>
					<view class="marg">实时功率</view>
				</view>
				<view class="center-tips">
					<view>{
    
    {
    
    formatChargeVal(equipBaseInfo.currentChargeIVal)}}<text class="smallFont">A</text></view>
					<view class="marg">实时电流</view>
				</view>
				<view>
					<view>{
    
    {
    
    formatChargeVal(equipBaseInfo.chargeV)}}<text class="smallFont">V</text></view>
					<view class="marg">实时电压</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import blueteeth from '../../libs/blueteeth.js';
	import tuiSwipeAction from "@/components/tui-swipe-action/tui-swipe-action.vue"
	import blueteethCmd from '../../libs/blueteeth-cmd.js';
	import store from '../../libs/store.js';
	import utils from '../../libs/utils.js';
	import config from '../../libs/config.js';
	import {
    
    
		throttle
	} from "../../libs/throttle.js"; //引入节流函数
	export default {
    
    
		data() {
    
    
			return {
    
    
				hasEquipFlag: false, //是否绑桩
				hasConnectBTFlag: false, //有没有连上蓝牙Flag
				hasChargeFlag: false, //是否充电中
				equipBaseInfo: {
    
    
					// chargeMode: '00'
				}, //设备信息
				deviceId: '',
				deviceName: '',
				canUseBlueteethFlag: false, //能否使用蓝牙
				serviceId: "0000FFF0-0000-1000-8000-00805F9B34FB", // 服务ID
				readCharacteristicId: "0000FFF1-0000-1000-8000-00805F9B34FB",
				writeCharacteristicId: "0000FFF2-0000-1000-8000-00805F9B34FB",
				statusLooper: null, //轮训查询桩状态定时器
				mode: 1, //模式   1蓝牙模式 2 即插即充模式
				charging: 1, //     1充电中 2 其他状态
				pileErrorFlag: false, //设备故障
				waitChargeFlag: false, //充电等待中
				wirte0032CodeMsgId: '', // 写入的消息ID
				wirte0041CodeMsgId: '', // 写入的消息ID
			}
		},
		onShow() {
    
    
			if (!uni.getStorageSync('hasLogin') == true) {
    
    
				uni.reLaunch({
    
    
					url: '/pages/login/index'
				})
			} else {
    
    
				uni.setNavigationBarTitle({
    
    
					title: uni.getStorageSync('EQUIP_BASE_INFO_KEY').personalityName
				});
				this.bluetoothJudgment()
			}

		},
		onHide() {
    
    
			clearTimeout(this.statusLooper)
			this.statusLooper = null;
		},
		onUnload() {
    
    
			clearTimeout(this.statusLooper)
			this.statusLooper = null;
		},
		methods: {
    
    
			/*判断用户有没有授权蓝牙*/
			bluetoothJudgment() {
    
    
				let _ = this;
				wx.getSetting({
    
    
					success(res) {
    
    
						let authSetting = res.authSetting;
						if (authSetting['scope.bluetooth']) {
    
     //已授权
							_.pageInitFun()
						} else if (authSetting['scope.bluetooth'] === false) {
    
    
							wx.showModal({
    
    
								title: '您未开启蓝牙授权',
								content: '请在系统设置中打开蓝牙授权,以便我们为您提供更好的服务',
								success: (res) => {
    
    
									if (res.confirm) {
    
    
										wx.openSetting()
									}
								}
							})
						} else {
    
    
							wx.authorize({
    
    
								scope: 'scope.bluetooth',
								success: () => {
    
    
									_.pageInitFun()
								},
								fail: () => {
    
    
									wx.showModal({
    
    
										title: '您未开启蓝牙授权',
										content: '请在系统设置中打开蓝牙授权,以便我们为您提供更好的服务',
										success: (res) => {
    
    
											if (res.confirm) {
    
    
												wx.openSetting()
											}
										}
									})
								}
							})
						}
					}
				})
			},
			/* 页面初始化*/
			pageInitFun() {
    
    
				console.log('页面初始化')
				let that = this;
				this.hasEquipFlag = false;
				// this.hasConnectBTFlag = false;
				this.checkCurEquipInfo();

			},
			/*判断是否有设备*/
			checkCurEquipInfo() {
    
    
				let that = this;
				this.hasEquipFlag = false;
				// let obj = store.getEquipBaseInfo() || {}
				if (uni.getStorageSync('hasConnectBTFlag')) {
    
     //缓存有值
					this.equipBaseInfo = store.getEquipBaseInfo()
					this.hasEquipFlag = true;
					this.checkBlueteethFun();
				} else {
    
    
					that.$u.api.getDeviceList({
    
    
						accessType: 'app',
						data: {
    
    
							userId: uni.getStorageSync('userId')
						}
					}).then(res => {
    
    
						console.log(res.data)
						if (res.data.length > 0) {
    
     //有设备
							that.equipBaseInfo = res.data[0]

							store.setEquipBaseInfo(res.data[0]);
							that.hasEquipFlag = true;
							that.deviceId = that.equipBaseInfo.deviceId
							that.deviceName = that.equipBaseInfo.deviceName
							console.log('this.deviceId')
							console.log(that.deviceId)

							that.checkBlueteethFun();
						} else {
    
     //无设备
							that.hasConnectBTFlag = false;
							store.setEquipBaseInfo({
    
    })
						}
					}).catch(err => {
    
    
						uni.reLaunch({
    
    
							url: '/pages/login/index'
						})
					})
				}

				// 查看设备信息
				// this.equipBaseInfo = store.getEquipBaseInfo() || {};
				// console.log('this.equipBaseInfo')
				// console.log(this.equipBaseInfo)

				// if (this.equipBaseInfo.deviceId) {
    
    
				// 	this.hasEquipFlag = true;
				// 	this.deviceId = this.equipBaseInfo.deviceId
				// 	this.deviceName = this.equipBaseInfo.deviceName
				// 	console.log('this.deviceId')
				// 	console.log(this.deviceId)

				// 	this.checkBlueteethFun();
				// } else {
    
    
				// 	this.hasConnectBTFlag = false;
				// }
			},
			/*蓝牙初始化*/
			checkBlueteethFun() {
    
    
				let _ = this;
				_.canUseBlueteethFlag = false;

				uni.openBluetoothAdapter({
    
    
					success(e) {
    
    
						console.log(e)
						_.canUseBlueteethFlag = true;

						wx.getBluetoothDevices({
    
     //判断是否已经连接设备
							success: function(res) {
    
    
								console.log('bbbccc')
								console.log(res.devices.length)
								console.log('bbbccc')
								if (res.devices.length == 0) {
    
     //未连接设备
									uni.showLoading({
    
    
										title: '蓝牙连接中...',
										mask: true
									})
									console.log('无设备连接')
									_.hasConnectBTFlag = false;
									uni.setStorageSync('hasConnectBTFlag', false)
									// _.closeDeviceConnect()
									if (uni.getSystemInfoSync().platform === 'android') {
    
    
										uni.setStorageSync('currentDeviceId', _.equipBaseInfo
											.deviceId)
										_.toConnectEquip();
									} else {
    
    
										_.find()
									}
								} else {
    
     //有设备连接
									console.log('有设备连接')
									_.hasConnectBTFlag = true;
									uni.setStorageSync('hasConnectBTFlag', true);
									_.equipBaseInfo = store.getEquipBaseInfo() || {
    
    };
									_.deviceId = uni.getStorageSync('currentDeviceId');
									_.serviceId = uni.getStorageSync('currentServiceId');
									uni.hideLoading()
									_.notifyBLECharacter()
									_.writePileStatusCode()
								}
							}
						})




					},
					fail(err) {
    
    
						utils.errMsg('请打开手机蓝牙后重试')
						_.canUseBlueteethFlag = false;
					}
				})
			},
			/*---------测试查找蓝牙设备----------*/
			find() {
    
    
				let _ = this;
				console.log('蓝牙开始查找')
				wx.startBluetoothDevicesDiscovery({
    
    
					services: [],
					success: function() {
    
    
						console.log('开始搜索蓝牙')
						wx.onBluetoothDeviceFound(function(res) {
    
    
							console.log(res, '搜索蓝牙相关设备')
							for (let i = 0; i < res.devices.length; i++) {
    
    
								// app.globalData.bleConfig.name 这里提前就获取了设备的name
								if (res.devices[i].name == _.deviceName) {
    
    
									var deviceId = res.devices[i].deviceId
									console.log('找到设备')
									console.log(res.devices[i])
									_.deviceId = res.devices[i].deviceId
									// _.equipBaseInfo.deviceId = _.deviceId;
									uni.setStorageSync('currentDeviceId', _.deviceId)
									// if (_.equipBaseInfo.serviceId == '') {
    
    
									// 	store.setEquipBaseInfo(_.equipBaseInfo);
									// }
									console.log('找到设备')
									// ios搜索出目标设备后,将停止搜索,否则影响手机性能
									wx.stopBluetoothDevicesDiscovery({
    
    
										success: function() {
    
    
											_.toConnectEquip()
										}
									})
								}
							}
						})
					},
					fail: function() {
    
    
						wx.stopBluetoothDevicesDiscovery({
    
    
							success: function() {
    
    }
						})
					}
				})
			},
			/*连接蓝牙设备*/
			toConnectEquip() {
    
    
				let _ = this;
				console.log('deviceId=' + _.deviceId)
				uni.createBLEConnection({
    
    
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: _.deviceId,
					success(res) {
    
    
						console.log('连接蓝牙成功==suc')
						_.getEquipServices();
					},
					fail(err) {
    
    
						console.log('连接蓝牙失败==fail')

						_.connectErrorFun();
					},
					complete(err) {
    
    
						console.log(err)
					}
				})

			},
			/*获取服务信息*/
			getEquipServices() {
    
    
				let _ = this;
				uni.getBLEDeviceServices({
    
    
					deviceId: this.deviceId, // 设备ID,在上一步【4】里获取
					success(res) {
    
    
						_.serviceId = res.services[0].uuid;
						uni.setStorageSync('currentServiceId', _.serviceId)
						console.log('serviceId=' + _.serviceId)
						// _.equipBaseInfo.serviceId = _.serviceId;
						// store.setEquipBaseInfo(_.equipBaseInfo);
						if (_.serviceId) {
    
    
							_.getEquipCharacteristics();
						}
					},
					fail(err) {
    
    
						_.connectErrorFun();
					}
				})
			},
			/*获取特征值*/
			getEquipCharacteristics() {
    
    
				let _ = this;
				uni.getBLEDeviceCharacteristics({
    
    
					deviceId: _.deviceId, // 设备ID,在【4】里获取到
					serviceId: _.serviceId, // 服务UUID,在【6】里能获取到
					success(res) {
    
    
						console.log('获取服务特征值成功')
						console.log(res)
						console.log('获取服务特征值成功')
						_.notifyEquip();
					},
					fail(err) {
    
    
						_.connectErrorFun();
					}
				})
			},
			/*开启监听蓝牙传值*/
			notifyEquip() {
    
    
				let _ = this;

				if (uni.getSystemInfoSync().platform === 'android') {
    
    
					uni.setBLEMTU({
    
    
						deviceId: _.deviceId, // 设备ID,在【4】里获取到
						mtu: 512, // 服务UUID,在【6】里能获取到
						success(res) {
    
    
							console.log('设置mtu成功')
						},
						fail(err) {
    
    
							console.error(err)
						}
					})
				}
				_.notifyBLECharacter()
			},
			notifyBLECharacter() {
    
    
				let _ = this;
				uni.notifyBLECharacteristicValueChange({
    
    
					deviceId: _.deviceId, // 设备ID,在【4】里获取到
					serviceId: _.serviceId, // 服务UUID,在【6】里能获取到
					characteristicId: _.readCharacteristicId, // 特征值,在【7】里能获取到
					state: true,
					success(res) {
    
    
						_.hasConnectBTFlag = true;
						uni.hideLoading()
						uni.setStorageSync('hasConnectBTFlag', true)
						// 下发获取充电桩状态数据
						_.listenValueChange();
						// 接受消息的方法
						_.looperGetPileStatusFun()
					},
					fail(err) {
    
    
						_.connectErrorFun();
					}
				})
			},
			/*处理桩返回的值*/
			listenValueChange() {
    
    
				let _ = this;

				uni.onBLECharacteristicValueChange(res => {
    
    
					// 结果里有个value值,该值为 ArrayBuffer 类型,所以在控制台无法用肉眼观察到,必须将该值转换为16进制
					let resHex = _.ab2hex(res.value);
					_.handleEquipNotifyBackCode(resHex);
				})
			},
			/*处理桩上传的信息*/
			handleEquipNotifyBackCode(notifyCode) {
    
    
				let _ = this;
				let startIndex = notifyCode.indexOf('7e');
				let endIndex = notifyCode.lastIndexOf('7e');

				if (startIndex >= 0 && endIndex > 0) {
    
    
					const cmdCodeType = notifyCode.substring(startIndex + 2, startIndex + 6);
					console.log(cmdCodeType)

					// 状态查询回调
					if ('8051' == cmdCodeType) {
    
    
						_.hasConnectBTFlag = true;
						uni.hideLoading();
						uni.setStorageSync('hasConnectBTFlag', true)
						_.hasChargeFlag = false;
						_.waitChargeFlag = false;
						_.pileErrorFlag = false;
						const pileStatusObj = blueteethCmd.parse8051Cmd(notifyCode)
						if (Object.keys(pileStatusObj).length === 0) {
    
     //异常数据就取缓存里的值
							_.hasChargeFlag = uni.getStorageSync('hasChargeFlags')
							this.equipBaseInfo = store.getEquipBaseInfo()
							console.log('空对象使用缓存数据');
							return
						}
						if (pileStatusObj.chargeStatusStr == '05') {
    
     //正在充电中
							_.hasChargeFlag = true;
							uni.setStorageSync('hasChargeFlags', true)
						} else if (pileStatusObj.chargeStatusStr == '04') {
    
    
							_.waitChargeFlag = true;
							uni.setStorageSync('hasChargeFlags', false)
						} else if (pileStatusObj.chargeStatusStr == '01') {
    
     //故障
							_.pileErrorFlag = true;
							uni.setStorageSync('hasChargeFlags', false)
						} else {
    
    
							uni.setStorageSync('hasChargeFlags', false)
						}
						console.log(pileStatusObj)
						this.equipBaseInfo.chargeMode = ('1' == pileStatusObj.chargeMode ? '01' : '00')
						uni.setStorageSync('chargeModes', this.equipBaseInfo.chargeMode)
						this.equipBaseInfo.chargeModeName = ('01' == this.equipBaseInfo.chargeMode ? '即插即充模式' : '蓝牙模式')
						uni.setStorageSync('chargeModeNames', this.equipBaseInfo.chargeModeName)
						this.equipBaseInfo.chargeV = pileStatusObj.chargeV; //电压
						this.equipBaseInfo.chargeI = pileStatusObj.chargeI || 0; //电流
						this.equipBaseInfo.currentChargeIVal = pileStatusObj.currentChargeIVal; //实时电流
						this.equipBaseInfo.powerCount = (this.equipBaseInfo.currentChargeIVal * this.equipBaseInfo
								.chargeV) /
							1000; //功率
						this.equipBaseInfo.chargePower = pileStatusObj.chargeI; //电流
						this.equipBaseInfo.chargePowerName = pileStatusObj.chargeI + 'A';
						let obj = store.getEquipBaseInfo()
						obj.chargeMode = this.equipBaseInfo.chargeMode;
						store.setEquipBaseInfo(obj)
						uni.setStorageSync('MaxChargePowerName', pileStatusObj.chargeI)
					} else if ('8032' == cmdCodeType) {
    
    
						_.wirte0032CodeMsgId = '';
						// 充电回调
						const chargeRes = blueteethCmd.parse8032Cmd(notifyCode)
						if (_.hasChargeFlag) {
    
    
							utils.sucMsg('结束成功')
							_.hasChargeFlag = false;
						} else {
    
    
							utils.sucMsg('充电成功')
							_.hasChargeFlag = true;
						}

					} else if ('8041' == cmdCodeType) {
    
    
						_.wirte0041CodeMsgId = '';
						// 设置回调
						// const chargeRes = blueteethCmd.parse8041Cmd(notifyCode)
						uni.hideLoading();
						_.writePileStatusCode()
						utils.sucMsg('模式切换成功')
					}
				}

			},
			/*往桩里面写入数据*/
			writeDataToEquip(msg) {
    
    
				let _ = this;

				function hexStringToArrayBuffer(str) {
    
    
					if (!str) {
    
    
						return new ArrayBuffer(0);
					}
					var buffer = new ArrayBuffer(str.length / 2);
					let dataView = new DataView(buffer)
					let ind = 0;
					for (var i = 0, len = str.length / 2; i < len; i += 1) {
    
    
						let code = parseInt(str.substr(2 * i, 2), 16)

						console.log(code)
						dataView.setUint8(ind, code)
						ind++
					}
					return buffer;
				}

				function hexStringToArrayBuffer1(str) {
    
    
					if (!str) {
    
    
						return new ArrayBuffer(0);
					}
					var buffer = new ArrayBuffer(str.length);
					let dataView = new DataView(buffer)
					let ind = 0;
					for (var i = 0, len = str.length; i < len; i += 2) {
    
    
						let code = parseInt(str.substr(i, 2), 16)

						console.log(code)
						dataView.setUint8(ind, code)
						ind++
					}
					return buffer;
				}
				const bufferNew = hexStringToArrayBuffer(msg)

				console.log(bufferNew)

				uni.writeBLECharacteristicValue({
    
    
					deviceId: _.deviceId, // 设备ID,在【4】里获取到
					serviceId: _.serviceId, // 服务UUID,在【6】里能获取到
					characteristicId: _.writeCharacteristicId, // 特征值,在【7】里能获取到
					value: bufferNew,
					success(res) {
    
    
						console.log('写入指令成功===' + msg)
					},
					fail(err) {
    
    
						console.error(err)
						utils.errMsg('指令写入失败,请重新连接');
						uni.hideLoading()
						// 断开连接,重新连接
						_.closeDeviceConnect();
					}
				})
			},
			/*ArrayBuffer转16进度字符串示例*/
			ab2hex(buffer) {
    
    
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
    
    
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			/*轮训查询桩的信息*/
			looperGetPileStatusFun() {
    
    
				let _ = this;
				clearTimeout(this.statusLooper)
				// 连接上设备再去查状态
				if (_.hasConnectBTFlag) {
    
    
					_.writePileStatusCode();
					this.statusLooper = setTimeout(() => {
    
    
						_.looperGetPileStatusFun();
					}, 5000)
				}
			},
			/*0051获取桩状态数据*/
			writePileStatusCode() {
    
    
				// 获取桩状态
				const cmdCode = blueteethCmd.gen0051Cmd();
				this.writeDataToEquip(cmdCode)
			},
			/*接受设备蓝牙传值*/
			listenValueChange() {
    
    
				let _ = this;

				uni.onBLECharacteristicValueChange(res => {
    
    
					// 结果里有个value值,该值为 ArrayBuffer 类型,所以在控制台无法用肉眼观察到,必须将该值转换为16进制
					let resHex = _.ab2hex(res.value);
					_.handleEquipNotifyBackCode(resHex);
				})
			},
			/*蓝牙连接失败*/
			connectErrorFun() {
    
    
				uni.hideLoading();
				utils.errMsg('蓝牙连接失败,请靠近充电桩后重试')
				this.closeDeviceConnect();
				// this.continueConnectEquipFun();
			},
			/*关闭蓝牙连接*/
			closeDeviceConnect() {
    
    
				let _ = this;
				this.hasConnectBTFlag = false;
				uni.setStorageSync('hasConnectBTFlag', false)
				this.hasChargeFlag = false;
				// uni.hideLoading()
				let deviceId = _.deviceId;
				uni.closeBLEConnection({
    
    
					deviceId: deviceId,
					success(res) {
    
    
						console.log(res)
					},
					fail(err) {
    
    
						console.log(err)
					}
				})
			},
			/*模式切换   蓝牙和即插即充模式切换*/
			switchType() {
    
    
				let that = this;
				wx.vibrateLong();
				if (this.hasChargeFlag) {
    
    
					utils.errMsg('充电中,无法修改');
					return;
				}
				if (!this.hasConnectBTFlag) {
    
    
					utils.errMsg('请先连接蓝牙');
					return;
				}
				if (!this.hasEquipFlag) {
    
    
					utils.errMsg('请先绑桩');
					return;
				}

				let tempChargeMode = ''
				if (this.equipBaseInfo.chargeMode == '00') {
    
    
					tempChargeMode = '01'
				} else {
    
    
					tempChargeMode = '00'
				}
				uni.showLoading({
    
    
					title: '加载中...',
					mask: true
				})
				let newChargeModeName = ('00' == tempChargeMode ? '蓝牙模式' : '即插即充模式')
				// 设置即插即充模式
				const chargePower = this.equipBaseInfo.chargePower;
				const jcjcCmdCode = blueteethCmd.gen0041Cmd(tempChargeMode, chargePower)
				this.writeDataToEquip(jcjcCmdCode);
				this.wirte0041CodeMsgId = utils.genUUID();

				setTimeout(() => {
    
    
					uni.hideLoading()
					if (this.wirte0041CodeMsgId) {
    
    
						// utils.errMsg('写入失败,请重试!')
						this.wirte0041CodeMsgId = '';
					} else {
    
    
						that.equipBaseInfo.chargeMode = tempChargeMode
						store.setEquipBaseInfo(that.equipBaseInfo);
						that.$u.api.setEditDevice({
    
    
							accessType: 'app',
							data: {
    
    
								chargePointMac: that.equipBaseInfo.equipBaseInfo,
								chargeMode: tempChargeMode
							},
						}).then(res => {
    
    
							console.log('充电模式变更成功')
						}).catch(err => {
    
    })
					}
				}, 3000)
			},
			/*开始充电*/
			startCharge() {
    
    
				if (this.waitChargeFlag) {
    
    
					utils.errMsg('充电等待中')
					return;
				}
				if (this.pileErrorFlag) {
    
    
					utils.errMsg('设备故障')
					return;
				}
				uni.showLoading({
    
    
					title: '加载中...',
					mask: true
				})
				wx.vibrateLong() //手机震动
				// 开始充电
				const cmdCode = blueteethCmd.gen0032Cmd('01');
				this.wirte0032CodeMsgId = utils.genUUID();
				this.writeDataToEquip(cmdCode);
				setTimeout(() => {
    
    
					uni.hideLoading()
					if (this.wirte0032CodeMsgId) {
    
    
						// utils.errMsg('写入失败,请重试!')
						this.wirte0032CodeMsgId = '';
						uni.setStorageSync('hasChargeFlags', true)
					}
				}, 3000)
			},
			/*结束充电*/
			offCharge() {
    
    
				wx.vibrateLong() //手机震动
				uni.showLoading({
    
    
					title: '加载中...',
					mask: true
				})
				const cmdCode = blueteethCmd.gen0032Cmd('00');
				this.wirte0032CodeMsgId = utils.genUUID();
				this.writeDataToEquip(cmdCode);
				setTimeout(() => {
    
    
					uni.hideLoading()
					if (this.wirte0032CodeMsgId) {
    
    
						// utils.errMsg('写入失败,请重试!')
						this.wirte0032CodeMsgId = '';
						uni.setStorageSync('hasChargeFlags', false)
					}
				}, 3000)
			},
			/*重新连接蓝牙 10秒节流*/
			restContect() {
    
    
				let that = this;
				console.log('点了重新连接')
				this.hasConnectBTFlag = false;
				uni.setStorageSync('hasConnectBTFlag', false)
				wx.vibrateLong({
    
    
					success(res) {
    
    
						console.log('震动了')
					},
					fail(err) {
    
    
						console.log('未震动')
					}
				})
				//先断开之前的连接
				let deviceId = uni.getStorageSync('currentDeviceId')
				console.log(deviceId)
				// that.pageInitFun()
				wx.closeBluetoothAdapter({
    
    
					success(res) {
    
    
						console.log('断开了连接开始重新连接')
						that.pageInitFun()
					},
					complete() {
    
    

					}
				})
			},
			/*设备详情*/
			goDeviceDetail() {
    
    
				// if (!this.hasEquipFlag) {
    
    
				// 	utils.errMsg('请先绑桩');
				// 	return;
				// }
				uni.navigateTo({
    
    
					url: '/pages/device-details/index'
				})
			},
			/*绑定设备*/
			goBind() {
    
    
				uni.navigateTo({
    
    
					url: '/pages/index/index'
				})
			},
			/*格式化电流电压和功率的format函数*/
			formatChargeVal(val) {
    
    
				if (val) {
    
    
					val = parseFloat(val)
					return parseFloat(val.toFixed(2))
				}
				return 0;
			},
		}
	}
</script>

<style lang="less">
	page {
    
    
		background-color: #F8FAFF;
	}

	.index-container {
    
    
		width: 100%;
	}

	.charging {
    
    
		width: 400rpx;
		height: 400rpx;
		margin: 48rpx auto 0;
		position: relative;

		.charge-text {
    
    
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			color: #FFFFFF;
			font-size: 48rpx;
		}

		.charing-animate {
    
    
			width: 400rpx;
			height: 400rpx;
			border-radius: 50%;
			position: relative;
			border-radius: 42% 58% 62% 40%;
			background-color: rgba(54, 207, 201, .7);
			animation: rotates 5s reverse linear infinite;

			// background: radial-gradient(circle, #36CFC9 0%, #67f5ee 100%);
			// color: #ffffff;
			// text-align: center;
			// line-height: 400rpx;
			// font-size: 48rpx;
			// box-shadow: 0px 2px 10px 10px rgba(57, 221, 197, 0.25);
			// animation: fadenum 3s ease-in-out infinite;
			&::before {
    
    
				content: '';
				position: absolute;
				top: 0;
				left: 0;
				width: 400rpx;
				height: 400rpx;
				background-color: rgba(54, 207, 201, 1);
				border-radius: 32% 48% 52% 40%;
				animation: rotates 5s infinite linear;
			}
		}
	}



	.otherStatus {
    
    
		width: 400rpx;
		height: 400rpx;
		border-radius: 50%;
		background: #3291F8;
		margin: 48rpx auto 0;
		display: flex;
		justify-content: center;
		align-items: center;

		.ring {
    
    
			width: 360rpx;
			height: 360rpx;
			border-radius: 50%;
			background: #FFFFFF;
			color: #3291F8;
			line-height: 360rpx;
			text-align: center;
			font-size: 48rpx;
		}
	}

	.errStatus {
    
    
		width: 400rpx;
		height: 400rpx;
		border-radius: 50%;
		background: #ff4d40;
		margin: 48rpx auto 0;
		display: flex;
		justify-content: center;
		align-items: center;

		.ring {
    
    
			width: 360rpx;
			height: 360rpx;
			border-radius: 50%;
			background: #FFFFFF;
			color: #ff4d40;
			line-height: 360rpx;
			text-align: center;
			font-size: 48rpx;
		}
	}

	.ont-connected {
    
    
		width: 400rpx;
		height: 400rpx;
		border-radius: 50%;
		background: #BFBFBF;
		margin: 48rpx auto 0;
		display: flex;
		justify-content: center;
		align-items: center;

		.rings {
    
    
			width: 360rpx;
			height: 360rpx;
			border-radius: 50%;
			background: #FFFFFF;
			color: #BFBFBF;
			line-height: 360rpx;
			text-align: center;
			font-size: 48rpx;
		}
	}

	.startCharge {
    
    
		width: 150rpx;
		height: 150rpx;
		border-radius: 50%;
		background: #1890FF;
		margin: 106rpx auto 0;
		display: flex;
		justify-content: center;
		align-items: center;

		>view {
    
    
			width: 102rpx;
			height: 102rpx;
			background: url('https://img.cdn.wxzhida.cn/lingpao-ui/kaiguan.png');
			background-size: cover;
		}
	}

	.offCharge {
    
    
		width: 150rpx;
		height: 150rpx;
		border-radius: 50%;
		background: #FFC069;
		margin: 106rpx auto 0;
		display: flex;
		justify-content: center;
		align-items: center;

		>view {
    
    
			width: 102rpx;
			height: 102rpx;
			background: url('https://img.cdn.wxzhida.cn/lingpao-ui/%E5%BC%80%E5%85%B3.png');
			background-size: cover;
		}
	}

	.toContect {
    
    
		width: 150rpx;
		height: 150rpx;
		border-radius: 50%;
		background: #BFBFBF;
		margin: 86rpx auto 0;
		display: flex;
		justify-content: center;
		align-items: center;

		>view {
    
    
			width: 102rpx;
			height: 102rpx;
			background: url('https://img.cdn.wxzhida.cn/lingpao-ui/vvvvxx.png');
			background-size: cover;
		}


	}

	.contect-text {
    
    
		font-size: 28rpx;
		color: #C1C3C3;
		height: 50rpx;
		display: flex;
		align-items: center;
		width: 100%;
		justify-content: center;
		margin-top: 20rpx;
	}

	.marg100 {
    
    
		margin: 100rpx auto 0;
	}

	.marg75 {
    
    
		margin: 75rpx auto 0;
	}

	.panel {
    
    
		width: 90%;
		border-radius: 60rpx;
		overflow: hidden;
		background: #ffffff;
		// margin: 100rpx auto 0;
		box-shadow: 0px 2px 20px 3px rgba(169, 169, 169, 0.39);

		.btn {
    
    
			display: flex;
			height: 266rpx;
			border-bottom: 4rpx solid #F8FAFF;

			>view {
    
    
				flex: 1;
			}

			.switch {
    
    
				border-right: 4rpx solid #F8FAFF;
				// display: flex;
				// justify-content: center;
				// align-items: center;
				position: relative;
			}

			.switch_describe {
    
    
				color: #C1C3C3;
				position: absolute;
				width: 80%;
				top: 70%;
				left: 50%;
				text-align: center;
				transform: translateX(-50%);
			}

			.cut {
    
    
				position: absolute;
				top: 0;
				width: 150rpx;
				height: 48rpx;
				border-bottom-right-radius: 60rpx;
				text-align: center;
				line-height: 48rpx;
			}

			.cutA {
    
    
				background: #BAE7FF;
				color: #2B9AFF;
			}

			.cutB {
    
    
				background: #D9F7BE;
				color: #52C41A;
			}

			//蓝牙模式
			.blueThtooth {
    
    
				width: 64rpx;
				height: 64rpx;
				background: url('https://img.cdn.wxzhida.cn/lingpao-ui/%E8%93%9D%E7%89%99%20%281%29.png');
				background-size: 100% 100%;
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
			}

			//即插即充模式
			.plug {
    
    
				width: 64rpx;
				height: 64rpx;
				background: url('https://img.cdn.wxzhida.cn/lingpao-ui/%E5%9B%BE%E6%A0%87-%E6%8F%92%E5%A4%B4.png');
				background-size: 100% 100%;
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
			}

			.device {
    
    
				position: relative;

				.device_item {
    
    
					width: 64rpx;
					height: 64rpx;
					background: url('https://img.cdn.wxzhida.cn/lingpao-ui/%E8%AE%BE%E5%A4%87.png');
					background-size: 100% 100%;
					background-color: #1890FF;
					position: absolute;
					top: 50%;
					left: 50%;
					transform: translate(-50%, -50%);
				}

				.device_items {
    
    
					width: 64rpx;
					height: 64rpx;
					background: url('https://img.cdn.wxzhida.cn/lingpao-ui/%E8%AE%BE%E5%A4%87.png');
					background-size: 100% 100%;
					background-color: #1ED56D;
					position: absolute;
					top: 50%;
					left: 50%;
					transform: translate(-50%, -50%);
				}

				.device_describe {
    
    
					color: #C1C3C3;
					position: absolute;
					top: 70%;
					left: 50%;
					transform: translateX(-50%);
				}
			}
		}

		.tips {
    
    
			display: flex;
			height: 266rpx;
			box-sizing: border-box;

			>view {
    
    
				flex: 1;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: flex-end;
			}

			.center-tips {
    
    
				border-right: 4rpx solid #F8FAFF;
				border-left: 4rpx solid #F8FAFF;
			}

			.marg {
    
    
				margin-bottom: 50rpx;
				margin-top: 20rpx;
				color: #C1C3C3;
			}

			.smallFont {
    
    
				font-size: 24rpx;
			}
		}
	}

	@keyframes fadenum {
    
    

		/*设置内容由显示变为隐藏*/
		0% {
    
    
			opacity: 0.8;
			transform: scale(.9);
		}

		50% {
    
    
			opacity: 1.0;
			transform: scale(1);
		}

		100% {
    
    
			opacity: 0.8;
			transform: scale(0.9);
		}
	}

	@keyframes rotates {
    
    
		50% {
    
    
			border-radius: 80% 70% 58% 70%;
		}

		100% {
    
    
			transform: rotate(-720deg);
		}
	}
</style>



在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44705979/article/details/132273909