This commit is contained in:
weipengfei 2024-05-18 18:15:57 +08:00
parent 43292d0563
commit 2c55e72f39
17 changed files with 1056 additions and 59 deletions

View File

@ -1,5 +1,6 @@
<script setup>
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app"
import { inUpdate } from "@/utils/update.js"
const isHaveNetwork = ()=> {
uni.getNetworkType({
success: res => {
@ -26,6 +27,7 @@
}
onLaunch(() => {
console.log('App Launch')
inUpdate()
})
onShow(() => {
console.log('App Show')

View File

@ -134,8 +134,10 @@ function searchDevices(address = '', vlist1 = [], vlist2 = []) {
} else {
BleDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
const name = BleDevice.getName();
const n_address = BleDevice.getAddress();
console.log('====<<<', name, n_address);
//判断是否配对
if (BleDevice.getBondState() === bdevice.BOND_NONE) {
if (BleDevice.getBondState() === bdevice.BOND_NONE && name=='T58') {
//参数如果跟取得的mac地址一样就配对
if (address === BleDevice.getAddress()) {
if (BleDevice.createBond()) { //配对命令.createBond()
@ -144,32 +146,44 @@ function searchDevices(address = '', vlist1 = [], vlist2 = []) {
// main.unregisterReceiver(receiver);//取消监听
uni.hideLoading(); //
}
} else {
if (name !== null && name !== on) { //判断防止重复添加
if (name !== null && name !== on && n_address == BleDevice.getAddress()) { //判断防止重复添加
on = name || '未知设备';
vlist1.push({ name: on, address: BleDevice.getAddress() })
uni.hideLoading();
if (on === 'T58') { //判断连接到T58打印机
uni.$emit('connect', 'T58');
}
// if (name === 'T58') { //判断连接到T58打印机
// uni.$emit('connect', {
// name: 'T58',
// address: BleDevice.getAddress()
// });
// }
}
}
} else {
if (name !== un) { //判断防止重复添加
if (name !== un && address == BleDevice.getAddress()) { //判断防止重复添加
un = name;
vlist1.push({ name: un, address: BleDevice.getAddress() });
vlist2.push({ name: un, address: BleDevice.getAddress() });
console.log('=========', vlist1);
uni.hideLoading();
if (address) {
if (address === BleDevice.getAddress()) {
BAdapter.cancelDiscovery(); //取消扫描
}
if (un === 'T58') { //判断连接到T58打印机
uni.$emit('connect', 'T58');
}
}
if (name === 'T58') {
connect(n_address, (e)=>{
// console.log('连接T58', n_address);
if(e) {
uni.$emit('connect', {
name: 'T58',
address: n_address
});
BAdapter.cancelDiscovery();
}
})
}
}
@ -183,6 +197,33 @@ function searchDevices(address = '', vlist1 = [], vlist2 = []) {
main.registerReceiver(receiver, filter); //注册监听
}
const connect = (mac_address, callback)=>{
main = plus.android.runtimeMainActivity();
BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
UUID = plus.android.importClass("java.util.UUID");
uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BAdapter = BluetoothAdapter.getDefaultAdapter();
device = BAdapter.getRemoteDevice(mac_address);
plus.android.importClass(device);
bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
plus.android.importClass(bluetoothSocket);
if (!bluetoothSocket.isConnected()) {
bluetoothSocket.connect();
}
setTimeout(()=>{
if (bluetoothSocket.isConnected()) {
console.log('已连接=====', mac_address);
callback(true);
}
else {
console.log('未连接', mac_address);
callback(false);
}
bluetoothSocket.close();
}, 300)
}
//开始连接打印
function print(mac_address, data, callback) {
if (!mac_address) {
@ -193,7 +234,6 @@ function print(mac_address, data, callback) {
});
return;
}
main = plus.android.runtimeMainActivity();
BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
UUID = plus.android.importClass("java.util.UUID");
@ -206,6 +246,7 @@ function print(mac_address, data, callback) {
// const isConnected = bluetoothSocket.isConnected();
// console.log('设备是否连接,',bluetoothSocket.isConnected());
console.log('蓝牙', bluetoothSocket.isConnected());
if (!bluetoothSocket.isConnected()) {
uni.showToast({
title: '正在打印小票, 请耐心等待',

View File

@ -6,6 +6,24 @@
"navigationBarTitleText": "uni-app"
}
}
,{
"path": "uni_modules/guyue-updater/pages/updater",
"style": {
"app-plus": {
"animationDuration": 200,
"animationType": "fade-in",
"background": "transparent",
"backgroundColorTop": "transparent",
"bounce": "none",
"popGesture": "none",
"scrollIndicator": false,
"titleNView": false
},
"backgroundColor": "transparent",
"disableScroll": true,
"navigationStyle": "custom"
}
}
],
"globalStyle": {
"navigationBarTextStyle": "white",

View File

@ -62,16 +62,20 @@
})
console.log('打印内容', stringData);
let deviceId = uni.getStorageSync('deviceId');
if(!deviceId) {
let obj = state.deviceData.find(item=>item.name=='T58');
if(!obj) return uni.showToast({
if(!deviceId) return uni.showToast({
title: '蓝牙未连接到T58打印机, 请检查是否已配对T58打印机',
icon: 'exception'
})
else {
deviceId = obj.address;
}
}
// if(!deviceId) {
// let obj = state.deviceData.find(item=>item.name=='T58');
// if(!obj) return uni.showToast({
// title: 'T58, T58',
// icon: 'exception'
// })
// else {
// deviceId = obj.address;
// }
// }
console.log('打印机地址=>', deviceId);
print(deviceId, stringData, () => {
uni.showToast({
@ -97,15 +101,25 @@
}
}
else if(e.detail?.data[0]?.type=='connect') {
searchDevices('',state.deviceData);
uni.$off('connect');
state.deviceData = [];
searchDevices("");
// searchDevices('',state.deviceData);
uni.removeStorageSync("deviceId");
uni.$once('connect', (e)=>{
uni.hideLoading();
if(e.name!='T58'||!e.address) return uni.showToast({
title: '未找到T58打印机'
})
let obj = {
type: 'connect',
data: '打印机已连接'
data: {
title: '打印机已连接',
address: e.address
}
console.log('连接成功',t++);
}
console.log('连接成功',e);
uni.setStorageSync('deviceId', e.address);
vw.value.evalJS(`receiveData('${JSON.stringify(obj)}')`);
})
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -0,0 +1,6 @@
## 1.0.22023-06-02
修复部分bug新增条件编译仅限app平台调用
## 1.0.12023-06-02
去除ts使用js进行开发兼容性更好
## 1.0.02023-05-04
完成初始功能支持apk安装以及wgt升级支持显示弹窗升级、静默更新以及强制更新支持进度显示支持覆盖原生tabbar、原生导航栏

View File

@ -0,0 +1,24 @@
import { download, install } from "./updater";
export default class Updater {
static update(options ) {
// #ifdef APP-PLUS
// 静默更新
if (options.quiet) {
download({
url: options.downUrl,
onSuccess(filePath) {
install(filePath, false);
},
});
} else if (options.downUrl) {
uni.navigateTo({
url: `/uni_modules/guyue-updater/pages/updater?data=${encodeURIComponent(JSON.stringify(options))}`,
animationType: "fade-in",
animationDuration: 200,
});
}
// #endif
}
}

View File

@ -0,0 +1,12 @@
export type UpdateParams = {
content: string; // 必填,更新内容,内容中使用 \n 进行换行
downUrl: string; // 必填wgt热更新请给出 .wgt 的文件地址APK整包更新请设置下载apk地址ios请设置苹果商店的连接地址;
title?: string; // 用于显示弹窗标题,默认 发现新版本
versionName?: string; // 版本名,用于显示更新版本,如 1.0.0
quiet?: boolean; // 是否是静默更新开启后不会有弹窗会在后台下载更新文件在下次启动APP时使用更新
force?: boolean; // 是否是强制更新,开启后,弹窗无法被关闭,必须更新
updateBtnText?: string; // 升级按钮文字,默认 立即升级
downMsgTip?: string; // 仅android默认 下载中,请稍后
downSucTip?: string; // 仅android默认 下载完成,安装中
downErrorTip?: string; // 仅android默认 下载失败,请重试
}

View File

@ -0,0 +1,82 @@
{
"id": "guyue-updater",
"displayName": "App版本升级弹框和进度提示",
"version": "1.0.2",
"description": "app热更新模块支持apk安装以及wgt升级支持显示弹窗升级、静默更新以及强制更新支持进度显示支持覆盖原生tabar原生导航栏",
"keywords": [
"热更新",
"进度提示",
"版本升级",
"app自动升级",
"wgt自动升级"
],
"repository": "",
"engines": {
"HBuilderX": "^3.4.9"
},
"dcloudext": {
"type": "sdk-js",
"sale": {
"regular": {
"price": "9.98"
},
"sourcecode": {
"price": "16.80"
}
},
"contact": {
"qq": "2292550932"
},
"declaration": {
"ads": "无",
"data": "插件不采集任何数据",
"permissions": "无"
},
"npmurl": ""
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y"
},
"client": {
"Vue": {
"vue2": "y",
"vue3": "y"
},
"App": {},
"H5-mobile": {
"Safari": "n",
"Android Browser": "n",
"微信浏览器(Android)": "n",
"QQ浏览器(Android)": "n"
},
"H5-pc": {
"Chrome": "n",
"IE": "n",
"Edge": "n",
"Firefox": "n",
"Safari": "n"
},
"小程序": {
"微信": "n",
"阿里": "n",
"百度": "n",
"字节跳动": "n",
"QQ": "n",
"钉钉": "n",
"快手": "n",
"飞书": "n",
"京东": "n"
},
"快应用": {
"华为": "n",
"联盟": "n"
}
}
}
}
}

View File

@ -0,0 +1,315 @@
<template>
<view class="container">
<view class="main" @click.stop="">
<view class="header">
<image src="../assets/bg1.png" class="bg1" />
<image src="../assets/bg2.png" class="bg2" />
<view class="version-title">{{ updateParams.title }}</view>
<view class="version-name" v-if="updateParams.versionName">V{{ updateParams.versionName }}</view>
</view>
<view class="title">更新内容</view>
<view class="content" >
<rich-text :nodes="content" />
</view>
<view class="progress" v-if="downloading">
<view class="slider">
<view class="active-slider" :style="{ width: `${progress}%` }">
<view class="bar" />
<view class="dot">
<view class="text">{{ progress }}%</view>
<view class="circle" />
</view>
</view>
</view>
</view>
<view class="button" :class="{'active': !downloading || downloadError}" @click="handleButton">
{{ downloadText }}
</view>
</view>
<view class="bottom" v-if="!updateParams.force" @click="back">
<view class="line"/>
<image src="../assets/close.png" class="close" />
</view>
</view>
</template>
<script>
import { download, install } from "../updater";
export default {
data() {
const data = {
updateParams: {},
progress: 0,
downloading: false,
downloadSucc: false,
downloadError: false,
};
return data;
},
computed: {
content() {
return (this.updateParams.content || '').replace(/[\r\n]/gim, '<br/>');
},
downloadText () {
if (this.downloadSucc) {
return this.updateParams.downSucTip;
}
if (this.downloadError) {
return this.updateParams.downErrorTip;
}
if (this.downloading) {
return this.updateParams.downMsgTip;
}
return this.updateParams.updateBtnText;
},
},
onLoad(params) {
const data = {
title: '发现新版本',
updateBtnText: '立即升级',
downMsgTip: '下载中,请稍后',
downSucTip: '下载完成,安装中',
downErrorTip: '下载失败,请重试',
quiet: false,
force: false,
...(JSON.parse(decodeURIComponent(params.data)))
};
this.updateParams = data;
},
onBackPress() {
return this.updateParams.force;
},
methods: {
back() {
if (!this.updateParams.force) {
uni.navigateBack();
}
},
//
start() {
if (!this.updateParams.downUrl) {
return;
}
// ios appstore.apk.wgt
const isResource = ['.apk', '.wgt'].some(ext => this.updateParams.downUrl.toLocaleLowerCase().includes(ext));
if (plus.os.name !== "Android" || !isResource) {
plus.runtime.openURL(this.updateParams.downUrl);
return;
}
this.downloading = true;
const self = this;
download({
url: self.updateParams.downUrl,
onProgress(progress) {
self.progress = progress;
},
onSuccess(filePath) {
self.downloadSucc = true;
self.downloadError = false;
install(filePath, true);
},
onFail() {
self.downloading = false;
self.downloadSucc = false;
self.downloadError = true;
},
});
},
handleButton() {
if (!this.downloading) {
return this.start();
}
if (this.downloadError) {
this.progress = 0;
this.downloading = false;
this.downloadSucc = false;
this.downloadError = true;
return this.start();
}
},
},
};
</script>
<style lang="less">
page {
width: 100%;
height: 100%;
background: transparent;
}
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.3);
}
.main {
width: 75%;
background-color: #fff;
border-radius: 8rpx;
padding-bottom: 10rpx;
}
.header {
position: relative;
.bg1 {
width: 100%;
height: calc(100vw * 0.375);
border-top-left-radius: 8rpx;
border-top-right-radius: 8rpx;
}
.bg2 {
position: absolute;
top: -40%;
right: 13%;
width: 35.9%;
height: calc(100vw * 0.5441);
}
.version-title {
position: absolute;
top: 13%;
left: 8%;
color: #961c00;
font-size: 40rpx;
}
.version-name {
position: absolute;
top: 36%;
left: 24%;
background-color: #e54139;
color: #fff;
font-size: 26rpx;
line-height: 26rpx;
padding: 8rpx 20rpx;
border-radius: 20rpx;
}
}
.title {
background-color: #ff6d42;
color: #fff;
display: inline-block;
margin-top: 12rpx;
margin-left: 30rpx;
font-size: 26rpx;
line-height: 26rpx;
padding: 8rpx 20rpx;
border-radius: 8rpx;
}
.content {
margin-top: 12rpx;
margin-left: 30rpx;
font-size: 28rpx;
line-height: 2;
max-height: 240rpx;
overflow-y: auto;
}
.button {
margin: 20rpx 30rpx;
background-color: #ffaa00;
color: #fff;
font-size: 30rpx;
text-align: center;
padding: 20rpx 0;
border-radius: 14rpx;
opacity: 0.5;
pointer-events: none;
&:active {
opacity: 0.6;
}
&.active {
opacity: 1;
pointer-events: initial;
}
}
.progress {
padding: 50rpx 50rpx 18rpx;
.slider {
position: relative;
width: 100%;
height: 10rpx;
border-radius: 5rpx;
background-color: #e2e2e2;
.active-slider {
display: flex;
flex-direction: row;
align-items: center;
position: absolute;
left: 0;
top: 0;
width: 0%;
height: 10rpx;
border-radius: 5rpx;
.bar {
flex: 1;
height: 100%;
background-color: #e84116;
border-top-left-radius: 5rpx;
border-bottom-left-radius: 5rpx;
}
.dot {
position: relative;
margin-left: -12rpx;
.text {
position: absolute;
top: -34rpx;
left: -50%;
color: #e84116;
font-size: 24rpx;
font-weight: 500;
}
.circle {
width: 12rpx;
height: 12rpx;
border: 6rpx solid #e84116;
border-radius: 50%;
background-color: #fff;
}
}
}
}
}
.bottom {
display: flex;
flex-direction: column;
align-items: center;
.line {
width: 3rpx;
height: 50rpx;
background-color: #fff;
}
.close {
width: 64rpx;
height: 64rpx;
margin-top: -4rpx;
}
}
</style>

View File

@ -0,0 +1,65 @@
# App热更新
App热更新模块支持apk安装以及wgt升级支持显示弹窗升级、静默更新以及强制更新支持进度显示支持覆盖原生tabbar、原生导航栏。
可用于自建热更新渠道,不依赖于云服务,无云服务费用支出,也可以适配官方更新中心。
## 使用说明
### 1.将此项目导入自己的项目工程
### 2.在page.json中注册页面如下
```javascript
{
"path": "uni_modules/guyue-updater/pages/updater",
"style": {
"navigationStyle": "custom",
"backgroundColor": "transparent",
"disableScroll": true,
"app-plus": {
"backgroundColorTop": "transparent",
"background": "transparent",
"scrollIndicator": false,
"titleNView": false,
"popGesture": "none",
"bounce": "none",
"animationType": "fade-in",
"animationDuration": 200
}
}
}
```
### 3.将版本检测函数导入需要使用的页面
一般在App.vue中的onLaunch导入或者首页导入需要自行完成热更新检查一般在APP启动时发起一个请求获取热更新数据数据获取后可以调用该组件完成更新。
```javascript
import Updater from '@/uni_modules/guyue-updater/index';
// 仅在app平台有效其他平台调用无效
Updater.update({
title: '发现新版本',
content: '1. 我们更新了新的UI设计\n2. 我们更新了新的UI设计\n3. 我们更新了新的UI设计\n4. 我们更新了新的UI设计\n',
versionName: '1.3.6',
downUrl: 'https://cdn.xxx.cn/mp/__UNI__1F29D65.wgt',
force: false,
})
```
## 参数说明
```javascript
export type UpdateParams = {
content: string; // 必填,更新内容,内容中使用 \n 进行换行
downUrl: string; // 必填wgt热更新请给出 .wgt 的文件地址APK整包更新请设置下载apk地址ios请设置苹果商店的连接地址;
title?: string; // 用于显示弹窗标题,默认 发现新版本
versionName?: string; // 版本名,用于显示更新版本,如 1.0.0
quiet?: boolean; // 是否是静默更新开启后不会有弹窗会在后台下载更新文件在下次启动APP时使用更新
force?: boolean; // 是否是强制更新,开启后,弹窗无法被关闭,必须更新
updateBtnText?: string; // 升级按钮文字,默认 立即升级
downMsgTip?: string; // 仅android默认 下载中,请稍后
downSucTip?: string; // 仅android默认 下载完成,安装中
downErrorTip?: string; // 仅android默认 下载失败,请重试
}
```
## Android如何跳转到应用市场更新
downUrl 设置为应用市场的地址即可,如: market://details?id={这里写你的应用包名}
## iOS 如何跳转到AppStore
downUrl 设置为AppStore的地址即可 itms-apps://itunes.apple.com/cn/app/hello-uni-app/id1417078253

View File

@ -0,0 +1,30 @@
export const download = ({ url, onProgress, onSuccess, onFail }) => {
const task = uni.downloadFile({
url,
success(res) {
if (res.statusCode === 200) {
onSuccess && onSuccess(res.tempFilePath);
}
},
fail() {
onFail && onFail();
}
});
task.onProgressUpdate(res => {
onProgress && onProgress(res.progress);
});
};
export const install = (filePath, restart = false) => {
plus.runtime.install(filePath, {
force: true
}, () => {
console.log('install success...');
if (restart) {
plus.runtime.restart();
}
}, (e) => {
console.error('install fail...', e);
});
};

View File

@ -2,7 +2,7 @@
;(function(){
let u=void 0,isReady=false,onReadyCallbacks=[],isServiceReady=false,onServiceReadyCallbacks=[];
const __uniConfig = {"pages":[],"globalStyle":{"backgroundColor":"#FFFFFF","pageOrientation":"landscape","titleView":false,"navigationBar":{"backgroundColor":"#007AFF","titleText":"uni-app","style":"custom","type":"default","titleColor":"#ffffff"},"isNVue":false},"nvue":{"compiler":"uni-app","styleCompiler":"uni-app","flex-direction":"column"},"renderer":"auto","appname":"采购收银系统","splashscreen":{"alwaysShowBeforeRender":true,"autoclose":true},"compilerVersion":"4.15","entryPagePath":"pages/index/index","entryPageQuery":"","realEntryPagePath":"","networkTimeout":{"request":60000,"connectSocket":60000,"uploadFile":60000,"downloadFile":60000},"locales":{},"darkmode":false,"themeConfig":{}};
const __uniRoutes = [{"path":"pages/index/index","meta":{"isQuit":true,"isEntry":true,"navigationBar":{"titleText":"uni-app","type":"default"},"isNVue":false}}].map(uniRoute=>(uniRoute.meta.route=uniRoute.path,__uniConfig.pages.push(uniRoute.path),uniRoute.path='/'+uniRoute.path,uniRoute));
const __uniRoutes = [{"path":"pages/index/index","meta":{"isQuit":true,"isEntry":true,"navigationBar":{"titleText":"uni-app","type":"default"},"isNVue":false}},{"path":"uni_modules/guyue-updater/pages/updater","meta":{"backgroundColor":"transparent","disableScroll":true,"animationDuration":200,"animationType":"fade-in","background":"transparent","backgroundColorTop":"transparent","bounce":"none","scrollIndicator":false,"titleNView":false,"navigationBar":{"style":"custom","type":"default"},"isNVue":false}}].map(uniRoute=>(uniRoute.meta.route=uniRoute.path,__uniConfig.pages.push(uniRoute.path),uniRoute.path='/'+uniRoute.path,uniRoute));
__uniConfig.styles=[];//styles
__uniConfig.onReady=function(callback){if(__uniConfig.ready){callback()}else{onReadyCallbacks.push(callback)}};Object.defineProperty(__uniConfig,"ready",{get:function(){return isReady},set:function(val){isReady=val;if(!isReady){return}const callbacks=onReadyCallbacks.slice(0);onReadyCallbacks.length=0;callbacks.forEach(function(callback){callback()})}});
__uniConfig.onServiceReady=function(callback){if(__uniConfig.serviceReady){callback()}else{onServiceReadyCallbacks.push(callback)}};Object.defineProperty(__uniConfig,"serviceReady",{get:function(){return isServiceReady},set:function(val){isServiceReady=val;if(!isServiceReady){return}const callbacks=onServiceReadyCallbacks.slice(0);onServiceReadyCallbacks.length=0;callbacks.forEach(function(callback){callback()})}});

View File

@ -165,7 +165,9 @@ if (uni.restoreGlobal) {
} else {
BleDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
const name = BleDevice.getName();
if (BleDevice.getBondState() === bdevice.BOND_NONE) {
const n_address = BleDevice.getAddress();
formatAppLog("log", "at js_sdk/wangqingzhou311-android-blueTooth/searchDevices.js:138", "====<<<", name, n_address);
if (BleDevice.getBondState() === bdevice.BOND_NONE && name == "T58") {
if (address === BleDevice.getAddress()) {
if (BleDevice.createBond()) {
vlist2.push({ name, address: BleDevice.getAddress() });
@ -173,29 +175,33 @@ if (uni.restoreGlobal) {
uni.hideLoading();
}
} else {
if (name !== null && name !== on) {
if (name !== null && name !== on && n_address == BleDevice.getAddress()) {
on = name || "未知设备";
vlist1.push({ name: on, address: BleDevice.getAddress() });
uni.hideLoading();
if (on === "T58") {
uni.$emit("connect", "T58");
}
}
}
} else {
if (name !== un) {
if (name !== un && address == BleDevice.getAddress()) {
un = name;
vlist1.push({ name: un, address: BleDevice.getAddress() });
vlist2.push({ name: un, address: BleDevice.getAddress() });
formatAppLog("log", "at js_sdk/wangqingzhou311-android-blueTooth/searchDevices.js:164", "=========", vlist1);
uni.hideLoading();
if (address) {
if (address === BleDevice.getAddress()) {
BAdapter.cancelDiscovery();
}
if (un === "T58") {
uni.$emit("connect", "T58");
}
}
if (name === "T58") {
connect(n_address, (e) => {
if (e) {
uni.$emit("connect", {
name: "T58",
address: n_address
});
BAdapter.cancelDiscovery();
}
});
}
}
}
@ -207,6 +213,30 @@ if (uni.restoreGlobal) {
filter.addAction(BluetoothAdapter2.ACTION_ACL_DISCONNECTED);
main.registerReceiver(receiver, filter);
}
const connect = (mac_address, callback) => {
plus.android.runtimeMainActivity();
BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
UUID = plus.android.importClass("java.util.UUID");
uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BAdapter = BluetoothAdapter.getDefaultAdapter();
device = BAdapter.getRemoteDevice(mac_address);
plus.android.importClass(device);
bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
plus.android.importClass(bluetoothSocket);
if (!bluetoothSocket.isConnected()) {
bluetoothSocket.connect();
}
setTimeout(() => {
if (bluetoothSocket.isConnected()) {
formatAppLog("log", "at js_sdk/wangqingzhou311-android-blueTooth/searchDevices.js:216", "已连接=====", mac_address);
callback(true);
} else {
formatAppLog("log", "at js_sdk/wangqingzhou311-android-blueTooth/searchDevices.js:220", "未连接", mac_address);
callback(false);
}
bluetoothSocket.close();
}, 300);
};
function print(mac_address, data, callback) {
if (!mac_address) {
uni.showToast({
@ -225,6 +255,7 @@ if (uni.restoreGlobal) {
plus.android.importClass(device);
bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
plus.android.importClass(bluetoothSocket);
formatAppLog("log", "at js_sdk/wangqingzhou311-android-blueTooth/searchDevices.js:249", "蓝牙", bluetoothSocket.isConnected());
if (!bluetoothSocket.isConnected()) {
uni.showToast({
title: "正在打印小票, 请耐心等待",
@ -263,7 +294,7 @@ if (uni.restoreGlobal) {
}
return target;
};
const _sfc_main$1 = {
const _sfc_main$2 = {
__name: "index",
setup(__props) {
const vw = vue.ref(null);
@ -301,18 +332,12 @@ if (uni.restoreGlobal) {
});
formatAppLog("log", "at pages/index/index.vue:63", "打印内容", stringData);
let deviceId = uni.getStorageSync("deviceId");
if (!deviceId) {
let obj = state.deviceData.find((item) => item.name == "T58");
if (!obj)
if (!deviceId)
return uni.showToast({
title: "蓝牙未连接到T58打印机, 请检查是否已配对T58打印机",
icon: "exception"
});
else {
deviceId = obj.address;
}
}
formatAppLog("log", "at pages/index/index.vue:75", "打印机地址=>", deviceId);
formatAppLog("log", "at pages/index/index.vue:79", "打印机地址=>", deviceId);
print(deviceId, stringData, () => {
uni.showToast({
title: "打印成功",
@ -321,24 +346,33 @@ if (uni.restoreGlobal) {
uni.setStorageSync("deviceId", deviceId);
});
};
let t = 1;
const onmessage = (e) => {
var _a, _b, _c, _d, _e, _f, _g, _h;
formatAppLog("log", "at pages/index/index.vue:93", "收到消息", e);
formatAppLog("log", "at pages/index/index.vue:97", "收到消息", e);
if (((_b = (_a = e.detail) == null ? void 0 : _a.data[0]) == null ? void 0 : _b.type) == "print") {
if ((_d = (_c = e.detail) == null ? void 0 : _c.data[0]) == null ? void 0 : _d.content) {
onPrintClick((_f = (_e = e.detail) == null ? void 0 : _e.data[0]) == null ? void 0 : _f.content);
}
} else if (((_h = (_g = e.detail) == null ? void 0 : _g.data[0]) == null ? void 0 : _h.type) == "connect") {
searchDevices("", state.deviceData);
uni.$off("connect");
state.deviceData = [];
searchDevices("");
uni.removeStorageSync("deviceId");
uni.$once("connect", (e2) => {
uni.hideLoading();
if (e2.name != "T58" || !e2.address)
return uni.showToast({
title: "未找到T58打印机"
});
let obj = {
type: "connect",
data: "打印机已连接"
data: {
title: "打印机已连接",
address: e2.address
}
};
formatAppLog("log", "at pages/index/index.vue:108", "连接成功", t++);
formatAppLog("log", "at pages/index/index.vue:121", "连接成功", e2);
uni.setStorageSync("deviceId", e2.address);
vw.value.evalJS(`receiveData('${JSON.stringify(obj)}')`);
});
}
@ -357,8 +391,297 @@ if (uni.restoreGlobal) {
};
}
};
const PagesIndexIndex = /* @__PURE__ */ _export_sfc(_sfc_main$1, [["__file", "D:/里海数字乡村/cashier-paid/pages/index/index.vue"]]);
const PagesIndexIndex = /* @__PURE__ */ _export_sfc(_sfc_main$2, [["__file", "D:/里海数字乡村/cashier-paid/pages/index/index.vue"]]);
const download = ({ url, onProgress, onSuccess, onFail }) => {
const task = uni.downloadFile({
url,
success(res) {
if (res.statusCode === 200) {
onSuccess && onSuccess(res.tempFilePath);
}
},
fail() {
onFail && onFail();
}
});
task.onProgressUpdate((res) => {
onProgress && onProgress(res.progress);
});
};
const install = (filePath, restart = false) => {
plus.runtime.install(filePath, {
force: true
}, () => {
formatAppLog("log", "at uni_modules/guyue-updater/updater.js:23", "install success...");
if (restart) {
plus.runtime.restart();
}
}, (e) => {
formatAppLog("error", "at uni_modules/guyue-updater/updater.js:28", "install fail...", e);
});
};
const _imports_0 = "/assets/bg1.741aa005.png";
const _imports_1 = "/assets/bg2.f448d13c.png";
const _imports_2 = "/assets/close.0b53e1ac.png";
const _sfc_main$1 = {
data() {
const data = {
updateParams: {},
progress: 0,
downloading: false,
downloadSucc: false,
downloadError: false
};
return data;
},
computed: {
content() {
return (this.updateParams.content || "").replace(/[\r\n]/gim, "<br/>");
},
downloadText() {
if (this.downloadSucc) {
return this.updateParams.downSucTip;
}
if (this.downloadError) {
return this.updateParams.downErrorTip;
}
if (this.downloading) {
return this.updateParams.downMsgTip;
}
return this.updateParams.updateBtnText;
}
},
onLoad(params) {
const data = {
title: "发现新版本",
updateBtnText: "立即升级",
downMsgTip: "下载中,请稍后",
downSucTip: "下载完成,安装中",
downErrorTip: "下载失败,请重试",
quiet: false,
force: false,
...JSON.parse(decodeURIComponent(params.data))
};
this.updateParams = data;
},
onBackPress() {
return this.updateParams.force;
},
methods: {
back() {
if (!this.updateParams.force) {
uni.navigateBack();
}
},
// 开始更新
start() {
if (!this.updateParams.downUrl) {
return;
}
const isResource = [".apk", ".wgt"].some((ext) => this.updateParams.downUrl.toLocaleLowerCase().includes(ext));
if (plus.os.name !== "Android" || !isResource) {
plus.runtime.openURL(this.updateParams.downUrl);
return;
}
this.downloading = true;
const self = this;
download({
url: self.updateParams.downUrl,
onProgress(progress) {
self.progress = progress;
},
onSuccess(filePath) {
self.downloadSucc = true;
self.downloadError = false;
install(filePath, true);
},
onFail() {
self.downloading = false;
self.downloadSucc = false;
self.downloadError = true;
}
});
},
handleButton() {
if (!this.downloading) {
return this.start();
}
if (this.downloadError) {
this.progress = 0;
this.downloading = false;
this.downloadSucc = false;
this.downloadError = true;
return this.start();
}
}
}
};
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
return vue.openBlock(), vue.createElementBlock("view", { class: "container" }, [
vue.createElementVNode("view", {
class: "main",
onClick: _cache[1] || (_cache[1] = vue.withModifiers(() => {
}, ["stop"]))
}, [
vue.createElementVNode("view", { class: "header" }, [
vue.createElementVNode("image", {
src: _imports_0,
class: "bg1"
}),
vue.createElementVNode("image", {
src: _imports_1,
class: "bg2"
}),
vue.createElementVNode(
"view",
{ class: "version-title" },
vue.toDisplayString(_ctx.updateParams.title),
1
/* TEXT */
),
_ctx.updateParams.versionName ? (vue.openBlock(), vue.createElementBlock(
"view",
{
key: 0,
class: "version-name"
},
"V" + vue.toDisplayString(_ctx.updateParams.versionName),
1
/* TEXT */
)) : vue.createCommentVNode("v-if", true)
]),
vue.createElementVNode("view", { class: "title" }, "更新内容:"),
vue.createElementVNode("view", { class: "content" }, [
vue.createElementVNode("rich-text", { nodes: $options.content }, null, 8, ["nodes"])
]),
_ctx.downloading ? (vue.openBlock(), vue.createElementBlock("view", {
key: 0,
class: "progress"
}, [
vue.createElementVNode("view", { class: "slider" }, [
vue.createElementVNode(
"view",
{
class: "active-slider",
style: vue.normalizeStyle({ width: `${_ctx.progress}%` })
},
[
vue.createElementVNode("view", { class: "bar" }),
vue.createElementVNode("view", { class: "dot" }, [
vue.createElementVNode(
"view",
{ class: "text" },
vue.toDisplayString(_ctx.progress) + "%",
1
/* TEXT */
),
vue.createElementVNode("view", { class: "circle" })
])
],
4
/* STYLE */
)
])
])) : vue.createCommentVNode("v-if", true),
vue.createElementVNode(
"view",
{
class: vue.normalizeClass(["button", { "active": !_ctx.downloading || _ctx.downloadError }]),
onClick: _cache[0] || (_cache[0] = (...args) => $options.handleButton && $options.handleButton(...args))
},
vue.toDisplayString($options.downloadText),
3
/* TEXT, CLASS */
)
]),
!_ctx.updateParams.force ? (vue.openBlock(), vue.createElementBlock("view", {
key: 0,
class: "bottom",
onClick: _cache[2] || (_cache[2] = (...args) => $options.back && $options.back(...args))
}, [
vue.createElementVNode("view", { class: "line" }),
vue.createElementVNode("image", {
src: _imports_2,
class: "close"
})
])) : vue.createCommentVNode("v-if", true)
]);
}
const Uni_modulesGuyueUpdaterPagesUpdater = /* @__PURE__ */ _export_sfc(_sfc_main$1, [["render", _sfc_render], ["__file", "D:/里海数字乡村/cashier-paid/uni_modules/guyue-updater/pages/updater.vue"]]);
__definePage("pages/index/index", PagesIndexIndex);
__definePage("uni_modules/guyue-updater/pages/updater", Uni_modulesGuyueUpdaterPagesUpdater);
class Updater {
static update(options) {
if (options.quiet) {
download({
url: options.downUrl,
onSuccess(filePath) {
install(filePath, false);
}
});
} else if (options.downUrl) {
uni.navigateTo({
url: `/uni_modules/guyue-updater/pages/updater?data=${encodeURIComponent(JSON.stringify(options))}`,
animationType: "fade-in",
animationDuration: 200
});
}
}
}
function compareVersions(version1, version2) {
const arr1 = version1.split(".").map(Number);
const arr2 = version2.split(".").map(Number);
for (let i = 0; i < Math.max(arr1.length, arr2.length); i++) {
const num1 = i < arr1.length ? arr1[i] : 0;
const num2 = i < arr2.length ? arr2[i] : 0;
if (num1 > num2) {
return 1;
} else if (num1 < num2) {
return -1;
}
}
return 0;
}
const inUpdate = () => {
uni.request({
url: "http://192.168.1.22:8546/api/app_update",
method: "GET",
success: (res) => {
formatAppLog("log", "at utils/update.js:26", "更新");
formatAppLog("log", "at utils/update.js:27", "======", res);
let os = uni.getSystemInfoSync();
if (Object.keys(res.data.data).length > 0) {
if (compareVersions(res.data.data.version || "1.0.0", os.appWgtVersion) == 1) {
try {
let info = res.data.data || {};
let version = {
title: info.title || "发现新版本",
content: info.content || "修复了部分BUG",
versionName: info.version || "1.0.1",
brand: os.brand,
downUrl: info.dow_url || "",
force: info.force == 1 ? true : false,
// 是否强制更新
quiet: info.quiet == 1 ? true : false
// 是否静默更新
};
Updater.update(version);
} catch (e) {
uni.showToast({
title: "更新失败"
});
}
}
}
},
fail: (err) => {
formatAppLog("log", "at utils/update.js:57", "err", err);
},
complete: (res) => {
formatAppLog("log", "at utils/update.js:60", "结束", res);
}
});
};
const _sfc_main = {
__name: "App",
setup(__props) {
@ -382,20 +705,21 @@ if (uni.restoreGlobal) {
});
}
},
fail: (err) => formatAppLog("error", "at App.vue:23", "调用失败"),
fail: (err) => formatAppLog("error", "at App.vue:24", "调用失败"),
complete: () => {
}
});
};
onLaunch(() => {
formatAppLog("log", "at App.vue:28", "App Launch");
formatAppLog("log", "at App.vue:29", "App Launch");
inUpdate();
});
onShow(() => {
formatAppLog("log", "at App.vue:31", "App Show");
formatAppLog("log", "at App.vue:33", "App Show");
isHaveNetwork();
});
onHide(() => {
formatAppLog("log", "at App.vue:35", "App Hide");
formatAppLog("log", "at App.vue:37", "App Hide");
});
return () => {
};

64
utils/update.js Normal file
View File

@ -0,0 +1,64 @@
// #ifdef APP
import Updater from '@/uni_modules/guyue-updater/index';
// #endif
function compareVersions(version1, version2) {
const arr1 = version1.split('.').map(Number);
const arr2 = version2.split('.').map(Number);
for (let i = 0; i < Math.max(arr1.length, arr2.length); i++) {
const num1 = i < arr1.length ? arr1[i] : 0;
const num2 = i < arr2.length ? arr2[i] : 0;
if (num1 > num2) {
return 1;
} else if (num1 < num2) {
return -1;
}
}
return 0;
}
export const inUpdate = () => {
uni.request({
url: 'http://192.168.1.22:8546/api/app_update',
method: 'GET',
success: (res) => {
console.log('更新');
console.log('======', res);
// #ifdef APP-PLUS
let os = uni.getSystemInfoSync();
if (Object.keys(res.data.data).length > 0) {
// 版本更新
if (compareVersions(res.data.data.version||'1.0.0', os.appWgtVersion) == 1) {
try {
let info = res.data.data || {};
let version = {
title: info.title || '发现新版本',
content: info.content || '修复了部分BUG',
versionName: info.version || '1.0.1',
brand: os.brand,
downUrl: info.dow_url || '',
force: info.force == 1 ? true : false, // 是否强制更新
quiet: info.quiet == 1 ? true : false // 是否静默更新
}
Updater.update(version);
} catch (e) {
uni.showToast({
title: '更新失败'
})
}
// uni.hideLoading();
}
}
// #endif
},
fail: (err) => {
console.log('err', err);
},
complete: (res) => {
console.log('结束', res);
}
})
}