Commit 8693b0fd by 姜雷

添加重连

parent 49cc78c0
...@@ -165,4 +165,9 @@ ...@@ -165,4 +165,9 @@
color: #ec2929; color: #ec2929;
} }
} }
.Connect-relink {
width: 226rpx;
height: 60rpx;
margin: 0 42rpx 62rpx;
}
} }
...@@ -3,11 +3,7 @@ import { ComponentClass } from 'react'; ...@@ -3,11 +3,7 @@ import { ComponentClass } from 'react';
import { View, Text, Button, ScrollView, Image } from '@tarojs/components'; import { View, Text, Button, ScrollView, Image } from '@tarojs/components';
import { getPayOrder } from '../../api/Order/pay'; import { getPayOrder } from '../../api/Order/pay';
import { connect } from '@tarojs/redux'; import { connect } from '@tarojs/redux';
import { import { Device } from '../../types/Device/Device';
Device,
DeviceRefundMode,
OnlyBluetooth,
} from '../../types/Device/Device';
import PrepayConfig from '../../types/Order/Order'; import PrepayConfig from '../../types/Order/Order';
import { Customer } from '../../types/Customer/Customer'; import { Customer } from '../../types/Customer/Customer';
import AES from 'crypto-js/aes'; import AES from 'crypto-js/aes';
...@@ -22,6 +18,8 @@ import selectIcon from '../../images/select_icon1@2x.png'; ...@@ -22,6 +18,8 @@ import selectIcon from '../../images/select_icon1@2x.png';
import selectedIcon from '../../images/selected_icon1@2x.png'; import selectedIcon from '../../images/selected_icon1@2x.png';
import select2Icon from '../../images/select_icon2@2x.png'; import select2Icon from '../../images/select_icon2@2x.png';
import selected2Icon from '../../images/selected_icon2@2x.png'; import selected2Icon from '../../images/selected_icon2@2x.png';
import reconnectIcon from '../../images/re_link@2x.png';
import { formatDate } from '@/utils/time';
enum ContorlCode { enum ContorlCode {
using = '1', using = '1',
...@@ -83,6 +81,7 @@ type PageState = { ...@@ -83,6 +81,7 @@ type PageState = {
messageQueue: Message[]; messageQueue: Message[];
lastMessage: string; lastMessage: string;
canPay: boolean; canPay: boolean;
errorState: boolean;
}; };
type PageOwnProps = {}; type PageOwnProps = {};
...@@ -137,6 +136,7 @@ class Connect extends Component { ...@@ -137,6 +136,7 @@ class Connect extends Component {
messageQueue: [], messageQueue: [],
lastMessage: '', lastMessage: '',
canPay: false, canPay: false,
errorState: false,
}; };
} }
...@@ -158,11 +158,11 @@ class Connect extends Component { ...@@ -158,11 +158,11 @@ class Connect extends Component {
} }
componentWillUnmount() { componentWillUnmount() {
// this.closeBluetooth();
// this.closeDeviceSocket();
msgList = []; msgList = [];
msgindex = 0; msgindex = 0;
currentThis = null; currentThis = null;
this.closeBluetooth();
this.closeDeviceSocket();
} }
connectDeviceSocket() { connectDeviceSocket() {
...@@ -262,6 +262,7 @@ class Connect extends Component { ...@@ -262,6 +262,7 @@ class Connect extends Component {
console.log('socked关闭', e, reConnectting, timer); console.log('socked关闭', e, reConnectting, timer);
this.setState({ this.setState({
sockedDone: false, sockedDone: false,
errorState: true,
}); });
liveTimer && clearInterval(liveTimer); liveTimer && clearInterval(liveTimer);
socketTask = null; socketTask = null;
...@@ -325,22 +326,7 @@ class Connect extends Component { ...@@ -325,22 +326,7 @@ class Connect extends Component {
sendDeviceCode() { sendDeviceCode() {
const { sockedDone, deviceDone } = this.state; const { sockedDone, deviceDone } = this.state;
// const { device } = this.props;
console.log('socket状态:', sockedDone, '蓝牙状态:', deviceDone); console.log('socket状态:', sockedDone, '蓝牙状态:', deviceDone);
// if (sockedDone && socketTask && deviceDone) {
// let deviceData = '{<' + device.code + '>}';
// console.log('<---发送设备编号:', deviceData);
// socketTask.send({
// data: str2ab(deviceData),
// success: msg => {
// console.log('发送设备编号:', msg, '--->');
// },
// fail: err => {
// console.log('发送设备编号:', err, '--->');
// },
// });
// }
} }
closeDeviceSocket() { closeDeviceSocket() {
...@@ -396,7 +382,16 @@ class Connect extends Component { ...@@ -396,7 +382,16 @@ class Connect extends Component {
}); });
Taro.showModal({ Taro.showModal({
title: '温馨提示', title: '温馨提示',
content: '为了更好的体验本次服务,请打开手机蓝牙!', content: '本次服务需要进行蓝牙连接,请打开手机蓝牙!',
confirmText: '重连',
}).then(res => {
if (res.confirm) {
this.reConnect();
} else {
this.setState({
errorState: true,
});
}
}); });
console.error(err); console.error(err);
Taro.onBluetoothAdapterStateChange(res => { Taro.onBluetoothAdapterStateChange(res => {
...@@ -435,10 +430,15 @@ class Connect extends Component { ...@@ -435,10 +430,15 @@ class Connect extends Component {
} }
closeBluetooth() { closeBluetooth() {
return Taro.closeBluetoothAdapter(); return Taro.closeBluetoothAdapter().catch(err => {
console.log(err);
});
} }
warnBluetoothOpen() { warnBluetoothOpen() {
this.setState({
errorState: true,
});
return Taro.showModal({ return Taro.showModal({
title: '警告', title: '警告',
content: '为保障正常使用,请打开蓝牙功能', content: '为保障正常使用,请打开蓝牙功能',
...@@ -491,32 +491,15 @@ class Connect extends Component { ...@@ -491,32 +491,15 @@ class Connect extends Component {
} }
Taro.hideLoading(); Taro.hideLoading();
console.error('startBluetoothDevicesDiscovery: ', err); console.error('startBluetoothDevicesDiscovery: ', err);
// if (err.msg === BlueToothError.DeviceNotFound) {
Taro.stopBluetoothDevicesDiscovery(); Taro.stopBluetoothDevicesDiscovery();
// this.sendStartShower(); this.setState({
errorState: true,
});
throw err; throw err;
// } else {
// return this.warnBluetoothOpen();
// }
}); });
} else { } else {
Taro.hideLoading(); Taro.hideLoading();
return this.warnBluetoothOpen().then(res => { return this.warnBluetoothOpen().then(res => {
if (res.confirm) {
// const { isOnlyBluetooth } = this.props.bluetoothDevice;
// if (!isOnlyBluetooth) {
// Taro.showLoading({
// title: '开启中',
// mask: true,
// });
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// this.sendStartShower();
// reject();
// }, 5000);
// });
// }
}
throw BlueToothError.BlueToothNotOpen; throw BlueToothError.BlueToothNotOpen;
}); });
} }
...@@ -533,11 +516,12 @@ class Connect extends Component { ...@@ -533,11 +516,12 @@ class Connect extends Component {
let abStr = ''; let abStr = '';
Taro.onBLECharacteristicValueChange(res => { Taro.onBLECharacteristicValueChange(res => {
console.log( console.log(
`characteristic ${res.characteristicId} has changed, now is ${res.value}` `characteristic ${res.characteristicId} has changed, now is ${res.value}`,
formatDate(new Date())
); );
console.log(res.value); console.log(res.value);
let datastr = ab2str(res.value); let datastr = ab2str(res.value);
console.log('获取bluetooth消息: ', datastr); console.log('获取bluetooth消息: ', datastr, formatDate(new Date()));
if (datastr === '<>') { if (datastr === '<>') {
console.log('结束蓝牙以及socket: ', datastr); console.log('结束蓝牙以及socket: ', datastr);
// this.closeDeviceSocket(); // this.closeDeviceSocket();
...@@ -560,7 +544,12 @@ class Connect extends Component { ...@@ -560,7 +544,12 @@ class Connect extends Component {
socketTask.send({ socketTask.send({
data: str2ab(JSON.stringify(sendData)), data: str2ab(JSON.stringify(sendData)),
success: msg => { success: msg => {
console.log('发送完整数据:', msg, '--->'); console.log(
'发送完整数据:',
msg,
'--->',
formatDate(new Date())
);
}, },
fail: err => { fail: err => {
console.log('发送完整数据:', err, '--->'); console.log('发送完整数据:', err, '--->');
...@@ -785,11 +774,6 @@ class Connect extends Component { ...@@ -785,11 +774,6 @@ class Connect extends Component {
}); });
this.addConnectMsg(); this.addConnectMsg();
this.sendDeviceCode(); this.sendDeviceCode();
// if (!reConnect) {
// setTimeout(() => {
// this.sendStartShower();
// }, 2000);
// }
}) })
.catch(err => { .catch(err => {
console.error(err); console.error(err);
...@@ -797,35 +781,6 @@ class Connect extends Component { ...@@ -797,35 +781,6 @@ class Connect extends Component {
}); });
} }
sendStartShower() {
console.log('开启洗浴');
// const { code } = this.props.device;
// const { userinfo } = this.props;
// startShowerEquipment({
// deviceCode: code,
// customerId: userinfo.customerId.toString(),
// customerName: userinfo.customerName,
// customerPhone: userinfo.customerPhone,
// })
// .then(res => {
// console.log(res);
// Taro.showToast({
// title: '开启成功!',
// });
// this.setState({
// showerState: true,
// });
// })
// .catch(err => {
// console.error(err);
// Taro.showToast({
// title: err.msg || '开启失败!',
// icon: 'none',
// });
// this.closeBluetoothConnection();
// });
}
selectPayConfig(id: number) { selectPayConfig(id: number) {
if (id === this.state.payId) return; if (id === this.state.payId) return;
this.setState( this.setState(
...@@ -1023,6 +978,42 @@ class Connect extends Component { ...@@ -1023,6 +978,42 @@ class Connect extends Component {
}); });
} }
reConnect() {
const { deviceInfo } = this.state;
msgList = [];
this.setState({
errorState: false,
messageQueue: [],
lastMessage: '',
});
console.log(socketTask);
let closeHandle;
closeHandle = socketTask
? new Promise((resolve, reject) => {
socketTask &&
socketTask.close({
code: StopCode,
success: res => resolve(res),
fail: res => reject(res),
});
})
: Promise.resolve();
closeHandle
.then(() => {
return Taro.closeBLEConnection({
deviceId: deviceInfo.deviceId,
});
})
.then(() => {
this.checkBluetoothAndWs();
})
.catch(err => {
console.log('in close err', err);
this.checkBluetoothAndWs();
});
}
render() { render() {
const { device, prepayConfig, addprepayConfig, userinfo } = this.props; const { device, prepayConfig, addprepayConfig, userinfo } = this.props;
const { const {
...@@ -1032,8 +1023,8 @@ class Connect extends Component { ...@@ -1032,8 +1023,8 @@ class Connect extends Component {
lastMessage, lastMessage,
canPay, canPay,
payMoney, payMoney,
errorState,
} = this.state; } = this.state;
console.log(canPay, device.isOnlyBluetooth);
return ( return (
<View className="Connect"> <View className="Connect">
...@@ -1157,6 +1148,12 @@ class Connect extends Component { ...@@ -1157,6 +1148,12 @@ class Connect extends Component {
</View> </View>
))} ))}
</ScrollView> </ScrollView>
{errorState && (
<Image
className="Connect-relink"
src={reconnectIcon}
onClick={this.reConnect}></Image>
)}
<View className="Connect-tip2"> <View className="Connect-tip2">
说明:如果在1分钟内没有跳转到支付页面,请开启手机蓝牙后再次微信扫码。 说明:如果在1分钟内没有跳转到支付页面,请开启手机蓝牙后再次微信扫码。
</View> </View>
......
export function formatDate(date: string | Date, fmt = 'yyyy-MM-dd hh:mm:ss') {
if (!date) {
return '无';
}
if (typeof date === 'string') {
date = new Date(date);
// date = new Date(date.replace('-', '/'));
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
(date.getFullYear() + '').substr(4 - RegExp.$1.length)
);
}
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds(),
};
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + '';
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length === 1 ? str : padLeftZero(str)
);
}
}
return fmt;
}
function padLeftZero(str: string) {
return ('00' + str).substr(str.length);
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment