wangfukang 2 weeks ago
parent
commit
071e68557b
  1. 15
      App.vue
  2. 147
      components/print/bluetooth.js
  3. 22
      components/print/index.js
  4. 8
      components/tab-bar/myCenter.vue
  5. 42
      pages/login/login.vue
  6. 108
      pages/myCenter/setPrint.vue

15
App.vue

@ -23,6 +23,7 @@
genTestUserSig genTestUserSig
} from './debug/GenerateTestUserSig.js'; } from './debug/GenerateTestUserSig.js';
import printer from './components/print/index.js'; // app.js import printer from './components/print/index.js'; // app.js
import Bluetooth from './components/print/bluetooth.js';
// const aegis = new Aegis({ // const aegis = new Aegis({
// id: 'iHWefAYqKznuxWjLnr', // key // id: 'iHWefAYqKznuxWjLnr', // key
// reportApiSpeed: true, // // reportApiSpeed: true, //
@ -208,6 +209,7 @@
this.globalData.GaoDeKey_amapkey = '52de86da47be2ea547c37dd382025a0c' this.globalData.GaoDeKey_amapkey = '52de86da47be2ea547c37dd382025a0c'
// #endif // #endif
if(uni.getStorageSync('peisongyuan')) return; if(uni.getStorageSync('peisongyuan')) return;
this.autoConnectPrinter()
if (!uni.getStorageSync('bluetoothDeviceId')) { if (!uni.getStorageSync('bluetoothDeviceId')) {
uni.showModal({ uni.showModal({
title: '提示', title: '提示',
@ -230,6 +232,15 @@
}, },
}, },
methods: { methods: {
autoConnectPrinter() {
if (!uni.getStorageSync('bluetoothDeviceId')) return;
const bluetooth = new Bluetooth({
autoOpen: false
});
bluetooth.connectSavedDevice({
silent: true
}).catch(() => {});
},
processPrintQueue() { processPrintQueue() {
if (this.globalData.printData.length === 0) { if (this.globalData.printData.length === 0) {
this.globalData.isPrinting = false this.globalData.isPrinting = false
@ -330,8 +341,8 @@
}, },
getRegistrationID() { //registerID getRegistrationID() { //registerID
jpushModule.getRegistrationID(result => { jpushModule.getRegistrationID(result => {
let registerID = result.registerID let registerID = result && (result.registerID || result.registrationID)
if (result && result.registerID) { if (registerID) {
this.globalData.registrationID = registerID this.globalData.registrationID = registerID
uni.setStorageSync("registerID", registerID) uni.setStorageSync("registerID", registerID)
} }

147
components/print/bluetooth.js

@ -1,6 +1,6 @@
class Bluetooth { class Bluetooth {
constructor() { constructor(options = {}) {
this.isOpenBle = false; this.isOpenBle = false;
this.deviceId = ""; this.deviceId = "";
this.serviceId = ""; this.serviceId = "";
@ -8,7 +8,11 @@ class Bluetooth {
this.notifyId = ""; this.notifyId = "";
this.num = 0; this.num = 0;
this.serviceList = []; this.serviceList = [];
this.openBluetoothAdapter(); if (options.autoOpen !== false) {
this.openBluetoothAdapter({
silent: true
}).catch(() => {});
}
} }
showToast(title) { showToast(title) {
@ -19,7 +23,8 @@ class Bluetooth {
}); });
} }
openBluetoothAdapter() { openBluetoothAdapter(options = {}) {
const silent = options.silent === true;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
uni.openBluetoothAdapter({ uni.openBluetoothAdapter({
success: res => { success: res => {
@ -28,7 +33,9 @@ class Bluetooth {
resolve(res); resolve(res);
}, },
fail: err => { fail: err => {
this.showToast('蓝牙状态读取失败,请检查是否打开蓝牙'); if (!silent) {
this.showToast('蓝牙状态读取失败,请检查是否打开蓝牙');
}
reject(err); reject(err);
}, },
}); });
@ -52,7 +59,7 @@ class Bluetooth {
success: res => { success: res => {
resolve(res) resolve(res)
}, },
fail: res => { fail: err => {
self.showToast(`搜索设备失败` + JSON.stringify(err)); self.showToast(`搜索设备失败` + JSON.stringify(err));
reject(err); reject(err);
} }
@ -68,7 +75,7 @@ class Bluetooth {
success: e => { success: e => {
uni.hideLoading(); uni.hideLoading();
}, },
fail: e => { fail: err => {
uni.hideLoading(); uni.hideLoading();
self.showToast(`停止搜索蓝牙设备失败` + JSON.stringify(err)); self.showToast(`停止搜索蓝牙设备失败` + JSON.stringify(err));
} }
@ -76,14 +83,71 @@ class Bluetooth {
}); });
} }
createBLEConnection(deviceId) { saveDevice(deviceId, deviceName = '') {
if (!deviceId) return;
uni.setStorageSync('bluetoothDeviceId', deviceId);
if (deviceName) {
uni.setStorageSync('bluetoothDeviceName', deviceName);
}
}
removeSavedDevice() {
uni.removeStorageSync('bluetoothDeviceId');
uni.removeStorageSync('bluetoothDeviceName');
uni.removeStorageSync('serviceId');
uni.removeStorageSync('notifyId');
uni.removeStorageSync('writeId');
}
resetConnectionInfo() {
this.serviceId = "";
this.writeId = "";
this.notifyId = "";
this.num = 0;
this.serviceList = [];
}
async connectDevice(deviceId, options = {}) {
if (!deviceId) {
return Promise.reject('设备ID不能为空');
}
await this.openBluetoothAdapter(options);
this.deviceId = deviceId;
this.resetConnectionInfo();
await this.createBLEConnection(deviceId, options);
this.serviceList = await this.getBLEDeviceServices(options);
await this.getBLEDeviceCharacteristics(options);
this.saveDevice(deviceId, options.deviceName);
return {
deviceId: this.deviceId,
serviceId: this.serviceId,
notifyId: this.notifyId,
writeId: this.writeId
};
}
connectSavedDevice(options = {}) {
const deviceId = uni.getStorageSync('bluetoothDeviceId');
if (!deviceId) {
return Promise.resolve(null);
}
return this.connectDevice(deviceId, {
...options,
deviceName: options.deviceName || uni.getStorageSync('bluetoothDeviceName')
});
}
createBLEConnection(deviceId, options = {}) {
//设备deviceId //设备deviceId
let self = this; let self = this;
const silent = options.silent === true;
uni.showLoading({ if (!silent) {
mask: true, uni.showLoading({
title: '设别连接中,请稍候...' mask: true,
}) title: '设备连接中,请稍候...'
})
}
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
uni.createBLEConnection({ uni.createBLEConnection({
deviceId, deviceId,
@ -97,24 +161,29 @@ class Bluetooth {
return true; return true;
} }
if (err.errCode == 10012) { if (err.errCode == 10012) {
self.showToast(`蓝牙连接超时`); if (!silent) {
} else { self.showToast(`蓝牙连接超时`);
self.showToast(`停止搜索蓝牙设备失败` + JSON.stringify(err)); }
} else if (!silent) {
self.showToast(`蓝牙连接失败` + JSON.stringify(err));
} }
reject(err); reject(err);
}, },
complete() { complete() {
uni.hideLoading(); if (!silent) {
uni.hideLoading();
}
} }
}) })
}); });
} }
//获取蓝牙设备所有服务(service) //获取蓝牙设备所有服务(service)
getBLEDeviceServices() { getBLEDeviceServices(options = {}) {
let _serviceList = []; let _serviceList = [];
let deviceId = this.deviceId; let deviceId = this.deviceId;
let self = this; let self = this;
const silent = options.silent === true;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
setTimeout(() => { setTimeout(() => {
uni.getBLEDeviceServices({ uni.getBLEDeviceServices({
@ -125,12 +194,16 @@ class Bluetooth {
_serviceList.push(service); _serviceList.push(service);
} }
} }
uni.hideLoading(); if (!silent) {
uni.hideLoading();
}
resolve(_serviceList) resolve(_serviceList)
}, },
fail: err => { fail: err => {
uni.hideLoading(); if (!silent) {
self.showToast(`获取设备Services` + JSON.stringify(err)); uni.hideLoading();
self.showToast(`获取设备Services` + JSON.stringify(err));
}
reject(err); reject(err);
}, },
}) })
@ -139,10 +212,14 @@ class Bluetooth {
} }
//获取蓝牙设备某个服务中所有特征值(characteristic) //获取蓝牙设备某个服务中所有特征值(characteristic)
getBLEDeviceCharacteristics() { getBLEDeviceCharacteristics(options = {}) {
let self = this; let self = this;
let deviceId = self.deviceId; let deviceId = self.deviceId;
let service = self.serviceList; let service = self.serviceList;
const silent = options.silent === true;
if (!service || !service[self.num]) {
return Promise.reject('找不到该读写的服务');
}
var uuid = service[self.num].uuid; var uuid = service[self.num].uuid;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
uni.getBLEDeviceCharacteristics({ uni.getBLEDeviceCharacteristics({
@ -167,10 +244,12 @@ class Bluetooth {
reject('找不到该读写的特征值'); reject('找不到该读写的特征值');
return false; return false;
} else { } else {
self.getBLEDeviceCharacteristics() self.getBLEDeviceCharacteristics(options).then(resolve).catch(reject);
return;
} }
} else { } else {
self.serviceId = uuid; self.serviceId = uuid;
uni.setStorageSync('serviceId', self.serviceId);
} }
let result = { let result = {
'notifyId': self.notifyId, 'notifyId': self.notifyId,
@ -180,7 +259,9 @@ class Bluetooth {
resolve(result) resolve(result)
}, },
fail: err => { fail: err => {
self.showToast(`getBLEDeviceCharacteristics` + JSON.stringify(err)); if (!silent) {
self.showToast(`getBLEDeviceCharacteristics` + JSON.stringify(err));
}
reject(err); reject(err);
} }
}) })
@ -188,8 +269,8 @@ class Bluetooth {
} }
//断开联链接 //断开联链接
closeBLEConnection() { closeBLEConnection(deviceId = this.deviceId) {
let deviceId = this.deviceId; if (!deviceId) return;
uni.closeBLEConnection({ uni.closeBLEConnection({
deviceId, deviceId,
success(res) { success(res) {
@ -248,23 +329,7 @@ class Bluetooth {
//若APP在之前已有搜索过某个蓝牙设备,并成功建立连接,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备,无需进行搜索操作。 //若APP在之前已有搜索过某个蓝牙设备,并成功建立连接,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备,无需进行搜索操作。
reconnect() { reconnect() {
(async () => { return this.connectSavedDevice();
try {
this.deviceId = this.deviceId || uni.getStorageSync("deviceId");
this.serviceId = this.serviceId || uni.getStorageSync("serviceId");
let result1 = await this.createBLEConnection();
let result2 = await this.getBLEDeviceServices();
let result3 = await this.getBLEDeviceCharacteristics();
} catch (err) {
}
})();
} }
} }

22
components/print/index.js

@ -61,26 +61,8 @@ export default {
async bindViewTap(deviceId, state, onDone) { async bindViewTap(deviceId, state, onDone) {
var _this = this; var _this = this;
try { try {
await bluetooth.createBLEConnection(deviceId).then((res) => { await bluetooth.connectDevice(deviceId);
bluetooth.deviceId = deviceId; this.pickUpOnce(onDone)
}).catch((e) => {
throw e;
});
let server = [];
await bluetooth.getBLEDeviceServices().then((res) => {
bluetooth.notifyId = '';
bluetooth.writeId = '';
bluetooth.num = 0;
bluetooth.serviceList = res
}).catch((e) => {
throw e;
});
let result3 = await bluetooth.getBLEDeviceCharacteristics().then(res => {
uni.setStorageSync('bluetoothDeviceId', deviceId);
this.pickUpOnce(onDone)
}).catch((e) => {
throw e;
});
} catch (e) { } catch (e) {
if (typeof onDone === 'function') onDone(); if (typeof onDone === 'function') onDone();
} }

8
components/tab-bar/myCenter.vue

@ -148,9 +148,11 @@
}, },
getRegistrationID() { //registerID getRegistrationID() { //registerID
jpushModule.getRegistrationID(result => { jpushModule.getRegistrationID(result => {
let registerID = result.registerID let registerID = result && (result.registerID || result.registrationID)
if (registerID) {
uni.setStorageSync("registerID", registerID) getApp().globalData.registrationID = registerID
uni.setStorageSync("registerID", registerID)
}
}) })
}, },

42
pages/login/login.vue

@ -68,6 +68,9 @@
<script> <script>
const app = getApp(); const app = getApp();
// #ifdef APP-PLUS
const jpushModule = uni.requireNativePlugin("JG-JPush");
// #endif
// import { // import {
// genTestUserSig // genTestUserSig
// } from '@/debug/GenerateTestUserSig.js'; // } from '@/debug/GenerateTestUserSig.js';
@ -122,7 +125,7 @@
}, },
onLoad(option) { onLoad(option) {
this.top = getApp().globalData.top + 20 this.top = getApp().globalData.top + 20
// this.setregisterID() this.getRegistrationID()
this.getCaptchaImg(); this.getCaptchaImg();
}, },
computed: { computed: {
@ -161,12 +164,40 @@
}) })
}, },
setregisterID(info) { setregisterID(info) {
const clientId = getApp().globalData.registrationID || uni.getStorageSync('registerID') const clientId = this.getStoredClientId()
this.NB.sendRequest('/worker/admin/editApp', { this.NB.sendRequest('/worker/admin/editApp', {
workerId: info.workerId, workerId: info.workerId,
clientId: clientId clientId: clientId
}, false, 'POST') }, false, 'POST')
}, },
getStoredClientId() {
return app.globalData.registrationID || uni.getStorageSync('registerID') || ''
},
saveClientId(clientId) {
if (!clientId) return;
app.globalData.registrationID = clientId;
uni.setStorageSync('registerID', clientId);
},
getRegistrationID() {
const cachedClientId = this.getStoredClientId();
if (cachedClientId) {
return Promise.resolve(cachedClientId);
}
// #ifdef APP-PLUS
return new Promise(resolve => {
jpushModule.getRegistrationID(result => {
const clientId = result && (result.registerID || result.registrationID);
this.saveClientId(clientId);
resolve(clientId || '');
});
});
// #endif
// #ifndef APP-PLUS
return Promise.resolve('');
// #endif
},
chooseCountry() { chooseCountry() {
uni.navigateTo({ uni.navigateTo({
url: 'country' url: 'country'
@ -357,7 +388,7 @@
this.type = type this.type = type
this.$refs.popup.open(type) this.$refs.popup.open(type)
}, },
submit() { async submit() {
if (this.enabled && this.loginType) { if (this.enabled && this.loginType) {
uni.showToast({ uni.showToast({
title: '请输入手机号和验证码后登录', title: '请输入手机号和验证码后登录',
@ -373,6 +404,7 @@
return; return;
} }
uni.setStorageSync('yanzhengma', this.code) uni.setStorageSync('yanzhengma', this.code)
const clientId = await this.getRegistrationID()
let url; let url;
let data; let data;
@ -383,7 +415,7 @@
code: this.codes, code: this.codes,
saveLogin: true, saveLogin: true,
type: this.wayValue, type: this.wayValue,
clientId: uni.getStorageSync('registerID') clientId: clientId
}; };
} else { } else {
url = `/auth/login`; url = `/auth/login`;
@ -394,7 +426,7 @@
code: this.code, code: this.code,
saveLogin: true, saveLogin: true,
type: 0, type: 0,
clientId: uni.getStorageSync('registerID') clientId: clientId
}; };
} }
let that = this; let that = this;

108
pages/myCenter/setPrint.vue

@ -1,12 +1,16 @@
<template> <template>
<view class=""> <view class="">
<view class="btn"> <view class="btn">
<view class="connected-printer" v-if="savedDeviceId">
<text>{{okAddress ? '已连接设备' : (linkAddress == savedDeviceId ? '正在自动连接' : '已保存设备')}}</text>
<text class="connected-printer-name">{{connectedDeviceName || savedDeviceId}}</text>
</view>
<button type="primary" :loading="isSearching" v-if="isSearching == false" @tap="startSearch(true)" <button type="primary" :loading="isSearching" v-if="isSearching == false" @tap="startSearch(true)"
text="">搜索蓝牙设备 text="">搜索蓝牙设备
</button> </button>
<button type="primary" :loading="isSearching" v-if="isSearching == true" @tap="stopSearch" text="">搜索蓝牙设备 <button type="primary" :loading="isSearching" v-if="isSearching == true" @tap="stopSearch" text="">搜索蓝牙设备
</button> </button>
<button type="primary" style="margin-top: 40rpx;" v-if="okAddress !=''" @tap="endSearch(true)" <button type="primary" style="margin-top: 40rpx;" v-if="savedDeviceId !=''" @tap="endSearch(true)"
text="">删除已连接蓝牙设备 text="">删除已连接蓝牙设备
</button> </button>
<button type="primary" style="margin-top: 40rpx;font-size: 32rpx;" :loading="isPrint" v-if="okAddress" <button type="primary" style="margin-top: 40rpx;font-size: 32rpx;" :loading="isPrint" v-if="okAddress"
@ -41,6 +45,8 @@
return { return {
isSearching: false, isSearching: false,
list: [], list: [],
savedDeviceId: '',
connectedDeviceName: '',
okAddress: '', okAddress: '',
linkAddress: '', linkAddress: '',
data: { data: {
@ -83,27 +89,43 @@
// bluetooth.closeBLEConnection(); // bluetooth.closeBLEConnection();
// bluetooth.closeBluetoothAdapter(); // bluetooth.closeBluetoothAdapter();
// }, // },
//,, //,
onLoad() { onLoad() {},
uni.getLocation({
type: 'wgs84',
success: function(res) {
}
});
// this.getData()
},
onShow() { onShow() {
this.initSavedPrinter()
}, },
methods: { methods: {
endSearch(){ endSearch(){
uni.hideLoading() uni.hideLoading()
bluetooth.closeBLEConnection(); bluetooth.closeBLEConnection();
bluetooth.closeBluetoothAdapter(); bluetooth.closeBluetoothAdapter();
bluetooth.removeSavedDevice();
this.savedDeviceId = ''
this.connectedDeviceName = ''
this.okAddress = '' this.okAddress = ''
this.linkAddress = ''
},
initSavedPrinter() {
const deviceId = uni.getStorageSync('bluetoothDeviceId');
const deviceName = uni.getStorageSync('bluetoothDeviceName');
this.savedDeviceId = deviceId || '';
this.connectedDeviceName = deviceName || '';
if (!deviceId) {
this.okAddress = '';
this.linkAddress = '';
return;
}
this.linkAddress = deviceId;
bluetooth.connectSavedDevice({
silent: true
}).then(res => {
if (!res) return;
this.okAddress = deviceId;
this.linkAddress = '';
}).catch(() => {
this.okAddress = '';
this.linkAddress = '';
});
}, },
getData() { getData() {
var that = this; var that = this;
@ -111,6 +133,7 @@
}, },
async bindViewTap(deviceId, state) { async bindViewTap(deviceId, state) {
var _this = this; var _this = this;
const device = this.list.find(item => item.deviceId == deviceId);
_this.okAddress = ''; _this.okAddress = '';
_this.linkAddress = deviceId; _this.linkAddress = deviceId;
@ -118,33 +141,17 @@
_this.isSearching = false _this.isSearching = false
} }
try { try {
//1. if (_this.savedDeviceId && _this.savedDeviceId != deviceId) {
await bluetooth.createBLEConnection(deviceId).then((res) => { bluetooth.closeBLEConnection(_this.savedDeviceId);
bluetooth.deviceId = deviceId; }
}).catch((e) => { await bluetooth.connectDevice(deviceId, {
throw e; deviceName: device && device.name
});
let server = [];
//2.
await bluetooth.getBLEDeviceServices().then((res) => {
bluetooth.notifyId = '';
bluetooth.writeId = '';
bluetooth.num = 0;
bluetooth.serviceList = res
}).catch((e) => {
throw e;
});
//3.
let result3 = await bluetooth.getBLEDeviceCharacteristics().then(res => {
_this.okAddress = deviceId;
_this.linkAddress = '';
uni.setStorageSync('bluetoothDeviceId', deviceId);
}).catch((e) => {
throw e;
}); });
_this.okAddress = deviceId;
_this.savedDeviceId = deviceId;
_this.connectedDeviceName = device && device.name ? device.name : uni.getStorageSync('bluetoothDeviceName');
_this.linkAddress = '';
_this.stopSearch();
} catch (e) { } catch (e) {
_this.okAddress = ''; _this.okAddress = '';
_this.linkAddress = ''; _this.linkAddress = '';
@ -244,7 +251,7 @@
that.list = arr.concat(devices); that.list = arr.concat(devices);
}); });
}, },
fail: res => { fail: err => {
uni.hideLoading(); uni.hideLoading();
uni.showToast({ uni.showToast({
title: `搜索设备失败` + JSON.stringify(err) title: `搜索设备失败` + JSON.stringify(err)
@ -275,6 +282,25 @@
padding: 40rpx; padding: 40rpx;
} }
.connected-printer {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 30rpx;
padding: 24rpx 30rpx;
border-radius: 16rpx;
background: #fff;
font-size: 28rpx;
color: #333;
}
.connected-printer-name {
max-width: 420rpx;
color: #3769FF;
text-align: right;
word-break: break-all;
}
.content { .content {
padding: 40rpx; padding: 40rpx;

Loading…
Cancel
Save