From 8f327bcb0eb8a48667b65a5bab81c37f21761019 Mon Sep 17 00:00:00 2001 From: linfso Date: Sun, 29 Jun 2025 09:25:58 +0800 Subject: [PATCH] md --- common/lbs/XdLbsUniSdk.js | 460 ++++++++++++++++++ static/images/mine/daihuikuan.png | Bin 0 -> 3713 bytes uni_modules/uni-getbatteryinfo/changelog.md | 16 + uni_modules/uni-getbatteryinfo/package.json | 94 ++++ uni_modules/uni-getbatteryinfo/readme.md | 38 ++ .../utssdk/app-android/config.json | 3 + .../utssdk/app-android/index.uts | 84 ++++ .../utssdk/app-harmony/index.uts | 27 + .../utssdk/app-ios/config.json | 3 + .../utssdk/app-ios/index.uts | 34 ++ .../uni-getbatteryinfo/utssdk/index.d.ts | 43 ++ .../uni-getbatteryinfo/utssdk/interface.uts | 147 ++++++ .../utssdk/mp-alipay/index.js | 6 + .../utssdk/mp-baidu/index.js | 6 + .../uni-getbatteryinfo/utssdk/mp-qq/index.js | 6 + .../utssdk/mp-weixin/index.js | 6 + .../uni-getbatteryinfo/utssdk/unierror.uts | 35 ++ .../uni-getbatteryinfo/utssdk/web/index.js | 23 + 18 files changed, 1031 insertions(+) create mode 100644 common/lbs/XdLbsUniSdk.js create mode 100644 static/images/mine/daihuikuan.png create mode 100644 uni_modules/uni-getbatteryinfo/changelog.md create mode 100644 uni_modules/uni-getbatteryinfo/package.json create mode 100644 uni_modules/uni-getbatteryinfo/readme.md create mode 100644 uni_modules/uni-getbatteryinfo/utssdk/app-android/config.json create mode 100644 uni_modules/uni-getbatteryinfo/utssdk/app-android/index.uts create mode 100644 uni_modules/uni-getbatteryinfo/utssdk/app-harmony/index.uts create mode 100644 uni_modules/uni-getbatteryinfo/utssdk/app-ios/config.json create mode 100644 uni_modules/uni-getbatteryinfo/utssdk/app-ios/index.uts create mode 100644 uni_modules/uni-getbatteryinfo/utssdk/index.d.ts create mode 100644 uni_modules/uni-getbatteryinfo/utssdk/interface.uts create mode 100644 uni_modules/uni-getbatteryinfo/utssdk/mp-alipay/index.js create mode 100644 uni_modules/uni-getbatteryinfo/utssdk/mp-baidu/index.js create mode 100644 uni_modules/uni-getbatteryinfo/utssdk/mp-qq/index.js create mode 100644 uni_modules/uni-getbatteryinfo/utssdk/mp-weixin/index.js create mode 100644 uni_modules/uni-getbatteryinfo/utssdk/unierror.uts create mode 100644 uni_modules/uni-getbatteryinfo/utssdk/web/index.js diff --git a/common/lbs/XdLbsUniSdk.js b/common/lbs/XdLbsUniSdk.js new file mode 100644 index 0000000..22d75ee --- /dev/null +++ b/common/lbs/XdLbsUniSdk.js @@ -0,0 +1,460 @@ +/* + XdLbsUniSdk + */ +class XdLbsUniSdk { + + VERSION="1.0.0" + MAX_SENT_RETRY_COUNT = 9; + LBS_UP_FREQ = 60 ; + WS_URL = 'wss://pushlbs.xdadan.com/ws'; + custNo = null; + deviceNo =null; + + msisdn = null; + + deviceInfo = null; + batteryInfo = null; + maximumAge = 60000; + + token = null; + + AUTH_TOKEN=null; + + WS_INIT = 0; + WS_OPEN = 1; + WS_CLOSING = 2; + WS_CLOSE = 3; + + // 和服务端连接的socket对象 + ws = null; + // WS 回调函数 + onOpenCallback =[]; + onCloseCallback=[]; + onErrorCallback =[]; + onMessageCallback=[]; + + lbsWatcherId = null; + + registerCheckTimer = null; + heartbeatChenkTimer = null; + + // 自定义 回调函数 + callbacks ={} + + // 标识:是否连接成功 , 记录重试的次数,重新连接尝试的次数 + connected = false; + printerIsRead = false; + sendRetryCount = 0; + connectRetryCount = 0; + + static instance = null; + constructor(custNo) { + this.instance = null + this.custNo=custNo + } + static getInstance(custNo) { + if (!this.instance) { + this.instance = new XdLbsUniSdk(custNo) + } + return this.instance + } + // 外部方法---------------------------------------------------------------- + init(deviceNo){ + // 初始化参数建立连接 + // this.token=getToken(); + + if(this.deviceNo==null){ + this.deviceNo=deviceNo; + this.connect(); + this.start(); + this.initBatteryInfo(); + this.initDeviceInfo(); + + // init lbs + this.maximumAge = Number(this.LBS_UP_FREQ) * Number(1000); + this.startLbs(this.maximumAge); + } + } + + setOnOpen(callback){ + this.onOpenCallback.push(callback); + + if(this.connected){ + if(callback!=null){ + callback(); + } + } + } + + setOnClose(callback){ + this.onCloseCallback.push(callback); + + if(!this.connected){ + if(callback!=null){ + callback(); + } + } + } + + setOnError(callback){ + this.onErrorCallback.push(callback); + } + + setOnMessage(callback){ + this.onMessageCallback.push(callback); + if(this.connected){ + if(callback!=null){ + callback(); + } + } + + } + + getRequestId() { + let requestId = 'req' + new Date().getTime().toString(36) + Math.random().toString(36).substring(2, 9); + return requestId; + } + + //--内部方法-------------------------------------------------------------- + + // 连接服务器的方法 + connect() { + const that=this; + if (!this.ws || this.getWSReadyState() === this.WS_CLOSING || this.getWSReadyState() === this.WS_CLOSE) { + try { + this.ws = uni.connectSocket({ + url: this.WS_URL, + header: { + 'content-type': 'application/json' + }, + protocols: ['protocol1'], + success(res){ + // console.error("connectSocket success===="); + console.log('WebSocket 连接启动成功'); + that.connectRetryCount = 0; // 重置重连计数 + }, + fail(err) { + console.error("connectSocket fail====", err) + setTimeout(reConnectSock, 3000) + } + }) + + this.ws.onError((err)=> { + console.log('ws.onError: ', JSON.stringify(err)); + // console.log("ws onerror!"); + if(this.onErrorCallback.length>0){ + this.onErrorCallback.forEach(callback=>{ + if(callback!=null){ + callback(err); + } + }) + } + }) + + this.ws.onOpen((res)=>{ + console.log("===>ws onopen!"); + this.connected = true + this.connectRetryCount = 0 + + // 注册客户端 + this.register() + + if(this.onOpenCallback.length>0){ + this.onOpenCallback.forEach(callback=>{ + if(callback!=null){ + callback(); + } + }) + } + }) + + this.ws.onClose((res = {})=> { + console.log('ws.onClose: ', JSON.stringify(res)); + this.connected = false; + this.connectRetryCount++; + if(this.connectRetryCount>120){ + this.connectRetryCount=0; + } + if(this.onCloseCallback.length>0){ + this.onCloseCallback.forEach(callback=>{ + if(callback!=null){ + callback(); + } + }) + } + // * this.connectRetryCount + setTimeout(() => { + this.connect() + }, 1000 ) + }) + + this.ws.onMessage(function (res) { + console.log('==>ws onmessage:' + res.data) + let resData = JSON.parse(res.data) + + if(resData.code == 200){ + let resCmd=resData.data; + if(resCmd.cmdType=='LbsRegister'){ + that.msisdn = resCmd.msisdn + } + } + + // if(this.onMessageCallback.length>0){ + // this.onMessageCallback.forEach(callback=>{ + // if(callback!=null){ + // callback(e.data); + // } + // }) + // } + }) + + } catch (ex) { + setTimeout(() => { + this.connect() + }, 60000 ) + } + } + + return this.ws; + } + + jsonToObj(json){ + return JSON.parse(json) + } + + objToJson(obj){ + return JSON.stringify(obj) + } + + /** + * readyState->0:尚未建立连接;1:已经建立连接;2:正在关闭;3:已经关闭或不可用 + * 0:连接正在建立 + 1:连接已建立,可以通信 + 2:连接正在关闭 + 3:连接已关闭或无法打开 + * @param thisWs + * @returns {*} + */ + getWSReadyState() { + if (this.ws.readyState !== undefined) { + return this.ws.readyState; + } + return this.WS_INIT; + }; + + // 发送数据的方法 + send(data) { + // console.log("send:"+data) + if (this.getWSReadyState() === this.WS_OPEN ) { + this.sendRetryCount = 0 + this.ws.send({data:data}) + return 1; + } else { + console.log("Ws is abnormal,send faild!!") + return -1 + } + } + + // 关闭socket连接 + close() { + if (this.ws) { + this.ws.close(); + this.connected = false; // 更新连接状态 + clearInterval(this.heartbeatChenkTimer); // 清除心跳检测定时器 + clearInterval(this.registerCheckTimer); + } + } + // 开启检测 + start() { + const that=this; + this.heartbeatChenkTimer = setInterval(() => { + that.connect() + }, 600000); + + this.registerCheckTimer = setInterval(() => { + this.register(); + }, 60000); + } + + // 注册客户端 + register(){ + if(this.deviceNo != null && this.msisdn == null){ + let postData = { + cmdType:"LbsRegister", + custNo:this.custNo, + deviceNo:this.deviceNo, + reqId:this.getRequestId(), + // deviceInfo:this.deviceInfo + } + const jsonString = JSON.stringify(postData) + let base64Str=btoa(jsonString) + this.send(base64Str); + } + } + + initDeviceInfo() { + const that=this + if(that.deviceInfo==null){ + that.deviceInfo = uni.getSystemInfoSync() + } + } + + //检测是否开启系统定位权限 + hasLocationPermission() { + let system = uni.getSystemInfoSync(); + if (system.platform === 'android') { //安卓 + let context = plus.android.importClass("android.content.Context"); + let locationManager = plus.android.importClass("android.location.LocationManager"); + let main = plus.android.runtimeMainActivity(); + let service = main.getSystemService(context.LOCATION_SERVICE); + //已开启系统定位服务功能 + if (service.isProviderEnabled(locationManager.GPS_PROVIDER)) return true; + else { //未开启引导开启 + uni.showModal({ + title: '友情提示', + content: '请开启位置服务功能', + success: e => { + if (e.confirm) { + //打开手机系统gps定位设置页面 + let Intent = plus.android.importClass('android.content.Intent'); + let Settings = plus.android.importClass('android.provider.Settings'); + let intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); + main.startActivity(intent); + } + } + }) + + } + } else if (system.platform === 'ios') { //ios + let cllocationManger = plus.ios.import("CLLocationManager"); + let enable = cllocationManger.locationServicesEnabled(); + let status = cllocationManger.authorizationStatus(); + plus.ios.deleteObject(cllocationManger); + if (enable && status != 2) return true; //已开启定位功能 + else { + uni.showModal({ + title: '友情提示', + content: '请前往设置-定位服务打开定位服务功能', + success: e => { + if (e.confirm) { + let UIApplication = plus.ios.import("UIApplication"); + let application = UIApplication.sharedApplication(); + let NSURL = plus.ios.import("NSURL"); + let setting = NSURL.URLWithString("app-settings:"); + application.openURL(setting); + plus.ios.deleteObject(setting); + plus.ios.deleteObject(NSURL); + plus.ios.deleteObject(application); + } + } + }); + } + } + return false; + } + startLbs(maximumAge = 60*1000) { + const that=this; + console.log("==>maximumAge:",maximumAge) + // 先关闭再启动 + this.closeLbs(); + + if (this.hasLocationPermission()) { //有定位权限 + that.lbsWatcherId = plus.geolocation.watchPosition((position) => { + let coords=position.coords + if(that.deviceNo != null && that.msisdn != null){ + let postData = { + cmdType:"LbsPush", + custNo:that.custNo, + deviceNo:that.deviceNo, + reqId:that.getRequestId(), + msisdn:that.msisdn, + longitude:coords.longitude, + latitude:coords.latitude, + altitude:coords.altitude, + heading:coords.heading, + speed:coords.speed, + altitudeAccuracy:coords.altitudeAccuracy, + battaryRate:-1, + } + const jsonString = JSON.stringify(postData) + let base64Str=btoa(jsonString) + that.send(base64Str); + } + + }, function(e) { + console.log(e, '定位失败'); + }, { + maximumAge, //获取位置间隔时间,在不同定位模块下支持范围值可能不同,如百度定位模块的间隔范围为大于等于1秒,如果设置的值小于最小值则使用最小值。iOS平台根据设备位置变化自动计算回调更新的间隔时间。 + // provider: 'amap', //优先使用定位模块,“system”:表示系统定位模块,支持wgs84坐标系; “baidu”:表示百度定位模块,支持gcj02/bd09/bd09ll坐标系; “amap”:表示高德定位模板,支持gcj02坐标系,默认值按以下优先顺序获取(amap>baidu>system) + // timeout: 10000, //定位超时 + enableHighAccuracy: true,//高精确度获取位置信息 + coordsType:"wgs84",//坐标系类型, “wgs84”:表示WGS-84坐标系; “gcj02”:表示国测局经纬度坐标系,"bd09":百度地图使用的坐标系 + //geocode:false//是否解析地址 + }); + } + } + + // 应用启动时初始化 + // initBatteryInfo() { + // const env = uni.getEnv(); + // console.log('==>initBatteryInfo==env=>:', env) + // if (env === uni.ENV_TYPE.APP) { + // // App 端使用 uni API + // return uni.getBatteryInfo({ + // success: (res) => console.log('App 电量:', res), + // fail: (err) => console.error('App 获取失败:', err) + // }); + // } else if (env === uni.ENV_TYPE.WECHAT) { + // // 微信小程序使用 wx API(兼容处理) + // return wx.getBatteryInfo({ + // success: (res) => console.log('微信电量:', res), + // fail: (err) => console.error('微信获取失败:', err) + // }); + // } else if (env === uni.ENV_TYPE.H5) { + // // H5 端使用浏览器 API + // if (navigator.getBattery) { + // return navigator.getBattery().then(battery => { + // console.log('H5 电量:', { + // level: Math.round(battery.level * 100), + // isCharging: battery.charging + // }); + // }).catch(err => console.error('H5 获取失败:', err)); + // } else { + // console.warn('当前浏览器不支持电池 API'); + // } + // } else { + // console.warn('当前平台不支持获取电池信息'); + // } + // } + + async initBatteryInfo() { + const that=this; + try { + this.batteryInfo = await uni.getBatteryInfo(); + console.log('电量信息已缓存:', this.batteryInfo); + // 监听电量变化,实时更新缓存 + uni.onBatteryInfoChange(info => { + that.batteryInfo = info; + console.log('电量变化:', this.batteryInfo); + }); + } catch (err) { + console.error('初始化电量失败:', err); + } + } + + // 同步获取缓存的电量 + getBatteryLevel() { + return cachedBatteryInfo?.level ?? -1; + } + + //关闭定位功能 + closeLbs() { + if(this.lbsWatcherId!=null){ + plus.geolocation.clearWatch(this.lbsWatcherId) + this.lbsWatcherId=null; + } + } + +} + +export default XdLbsUniSdk; diff --git a/static/images/mine/daihuikuan.png b/static/images/mine/daihuikuan.png new file mode 100644 index 0000000000000000000000000000000000000000..10a5f9dc9f17649185dd970ef33706695e77f80e GIT binary patch literal 3713 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 literal 0 HcmV?d00001 diff --git a/uni_modules/uni-getbatteryinfo/changelog.md b/uni_modules/uni-getbatteryinfo/changelog.md new file mode 100644 index 0000000..51341e4 --- /dev/null +++ b/uni_modules/uni-getbatteryinfo/changelog.md @@ -0,0 +1,16 @@ +## 1.3.2(2024-10-14) +- 新增 支持 HarmonyOS Next 调用 +## 1.3.1(2023-09-15) +app端适配使用UniError + +## 1.3.0(2023-05-30) +新增 同步获取电量api + +## 1.2.0(2022-10-17) +实现百度小程序/支付宝小程序/QQ小程序获取电量 + +## 1.1.0(2022-10-17) +实现ios平台获取电量 + +## 1.0.0(2022-09-01) +实现android/web/微信小程序平台获取电量 diff --git a/uni_modules/uni-getbatteryinfo/package.json b/uni_modules/uni-getbatteryinfo/package.json new file mode 100644 index 0000000..4057e16 --- /dev/null +++ b/uni_modules/uni-getbatteryinfo/package.json @@ -0,0 +1,94 @@ +{ + "id": "uni-getbatteryinfo", + "displayName": "uni-getbatteryinfo", + "version": "1.3.2", + "description": "使用uts开发,实现在多个平台获取电池电量功能", + "keywords": [ + "battery" +], + "repository": "", + "engines": { + "HBuilderX": "^3.9.0" + }, + "dcloudext": { + "type": "uts", + "sale": { + "regular": { + "price": "0.00" + }, + "sourcecode": { + "price": "0.00" + } + }, + "contact": { + "qq": "" + }, + "declaration": { + "ads": "无", + "data": "插件不采集任何数据", + "permissions": "无" + }, + "npmurl": "" + }, + "uni_modules": { + "uni-ext-api": { + "uni": { + "getBatteryInfo": "getBatteryInfo", + "getBatteryInfoSync": { + "web": false + } + } + }, + "dependencies": [], + "encrypt": [], + "platforms": { + "cloud": { + "tcb": "y", + "aliyun": "y", + "alipay": "n" + }, + "client": { + "Vue": { + "vue2": "n", + "vue3": "y" + }, + "App": { + "app-android": { + "minVersion": "21" + }, + "app-ios": { + "minVersion": "9" + } + }, + "H5-mobile": { + "Safari": "y", + "Android Browser": "y", + "微信浏览器(Android)": "y", + "QQ浏览器(Android)": "y" + }, + "H5-pc": { + "Chrome": "y", + "IE": "y", + "Edge": "y", + "Firefox": "y", + "Safari": "y" + }, + "小程序": { + "微信": "y", + "阿里": "y", + "百度": "y", + "字节跳动": "u", + "QQ": "y", + "钉钉": "u", + "快手": "u", + "飞书": "u", + "京东": "u" + }, + "快应用": { + "华为": "u", + "联盟": "u" + } + } + } + } +} diff --git a/uni_modules/uni-getbatteryinfo/readme.md b/uni_modules/uni-getbatteryinfo/readme.md new file mode 100644 index 0000000..0609fee --- /dev/null +++ b/uni_modules/uni-getbatteryinfo/readme.md @@ -0,0 +1,38 @@ +# uni-getbatteryinfo + +## 使用文档 + +```ts + // 获取电量信息 +uni.getBatteryInfo({ + success(res) { + console.log(res); + uni.showToast({ + title: "当前电量:" + res.level + '%', + icon: 'none' + }); + } +}) +``` + + + +### 参数 + +Object object + +|属性|类型|必填|说明| +|----|---|----|----| +|success|function|否|接口调用成功的回调函数| +|fail|function|否|接口调用失败的回调函数| +|complete|function|否|接口调用结束的回调函数(调用成功、失败都会执行)| + + + +object.success 回调函数 + + +|属性|类型|说明| +|----|---|----| +|level|number|设备电量,范围 1 - 100| +|isCharging|boolean|是否正在充电中| diff --git a/uni_modules/uni-getbatteryinfo/utssdk/app-android/config.json b/uni_modules/uni-getbatteryinfo/utssdk/app-android/config.json new file mode 100644 index 0000000..bf95925 --- /dev/null +++ b/uni_modules/uni-getbatteryinfo/utssdk/app-android/config.json @@ -0,0 +1,3 @@ +{ + "minSdkVersion": "21" +} \ No newline at end of file diff --git a/uni_modules/uni-getbatteryinfo/utssdk/app-android/index.uts b/uni_modules/uni-getbatteryinfo/utssdk/app-android/index.uts new file mode 100644 index 0000000..23f0b75 --- /dev/null +++ b/uni_modules/uni-getbatteryinfo/utssdk/app-android/index.uts @@ -0,0 +1,84 @@ +import Context from "android.content.Context"; +import BatteryManager from "android.os.BatteryManager"; + +import { GetBatteryInfo, GetBatteryInfoOptions, GetBatteryInfoSuccess, GetBatteryInfoResult,GetBatteryInfoSync } from '../interface.uts' +import IntentFilter from 'android.content.IntentFilter'; +import Intent from 'android.content.Intent'; + +import { GetBatteryInfoFailImpl } from '../unierror'; + +/** + * 异步获取电量 + */ +export const getBatteryInfo : GetBatteryInfo = function (options : GetBatteryInfoOptions) { + + + const context = UTSAndroid.getAppContext(); + if (context != null) { + const manager = context.getSystemService( + Context.BATTERY_SERVICE + ) as BatteryManager; + const level = manager.getIntProperty( + BatteryManager.BATTERY_PROPERTY_CAPACITY + ); + + let ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); + let batteryStatus = context.registerReceiver(null, ifilter); + let status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1); + let isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; + + const res : GetBatteryInfoSuccess = { + errMsg: 'getBatteryInfo:ok', + level, + isCharging: isCharging + } + options.success?.(res) + options.complete?.(res) + } else { + let res = new GetBatteryInfoFailImpl(1001); + options.fail?.(res) + options.complete?.(res) + } +} + +/** + * 同步获取电量示例 + */ +export const getBatteryInfoSync : GetBatteryInfoSync = function (): GetBatteryInfoResult { + + const context = UTSAndroid.getAppContext(); + if (context != null) { + + + const manager = context.getSystemService( + Context.BATTERY_SERVICE + ) as BatteryManager; + const level = manager.getIntProperty( + BatteryManager.BATTERY_PROPERTY_CAPACITY + ); + + let ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); + let batteryStatus = context.registerReceiver(null, ifilter); + let status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1); + let isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; + + const res : GetBatteryInfoResult = { + level: level, + isCharging: isCharging + }; + + return res; + } + else { + /** + * 无有效上下文 + */ + const res : GetBatteryInfoResult = { + level: -1, + isCharging: false + }; + return res; + } + + +} diff --git a/uni_modules/uni-getbatteryinfo/utssdk/app-harmony/index.uts b/uni_modules/uni-getbatteryinfo/utssdk/app-harmony/index.uts new file mode 100644 index 0000000..efe6fde --- /dev/null +++ b/uni_modules/uni-getbatteryinfo/utssdk/app-harmony/index.uts @@ -0,0 +1,27 @@ +import batteryInfo from '@ohos.batteryInfo'; +import { GetBatteryInfo, GetBatteryInfoOptions, GetBatteryInfoSuccess, GetBatteryInfoResult, GetBatteryInfoSync } from '../interface.uts'; + +export const getBatteryInfoSync : GetBatteryInfoSync = function () : GetBatteryInfoResult { + return { + level: batteryInfo.batterySOC, + isCharging: batteryInfo.chargingStatus === batteryInfo.BatteryChargeState.ENABLE || batteryInfo.chargingStatus === batteryInfo.BatteryChargeState.FULL, + }; +} + +export const getBatteryInfo : GetBatteryInfo = function (options : GetBatteryInfoOptions) { + const batteryInfoResult : GetBatteryInfoSuccess = { + errMsg: "getBatteryInfo:ok", + level: batteryInfo.batterySOC, + isCharging: batteryInfo.chargingStatus === batteryInfo.BatteryChargeState.ENABLE || batteryInfo.chargingStatus === batteryInfo.BatteryChargeState.FULL, + } + try { + options.success && options.success(batteryInfoResult) + } catch (e) { + console.error(e) + } + try { + options.complete && options.complete(batteryInfoResult) + } catch (e) { + console.error(e) + } +} \ No newline at end of file diff --git a/uni_modules/uni-getbatteryinfo/utssdk/app-ios/config.json b/uni_modules/uni-getbatteryinfo/utssdk/app-ios/config.json new file mode 100644 index 0000000..721b81e --- /dev/null +++ b/uni_modules/uni-getbatteryinfo/utssdk/app-ios/config.json @@ -0,0 +1,3 @@ +{ + "deploymentTarget": "9" +} \ No newline at end of file diff --git a/uni_modules/uni-getbatteryinfo/utssdk/app-ios/index.uts b/uni_modules/uni-getbatteryinfo/utssdk/app-ios/index.uts new file mode 100644 index 0000000..a86ec8d --- /dev/null +++ b/uni_modules/uni-getbatteryinfo/utssdk/app-ios/index.uts @@ -0,0 +1,34 @@ +// 引用 iOS 原生平台 api +import { UIDevice } from "UIKit"; + +import { GetBatteryInfo, GetBatteryInfoSuccess, GetBatteryInfoResult, GetBatteryInfoSync } from '../interface.uts'; +/** + * 导出 获取电量方法 + */ +export const getBatteryInfo : GetBatteryInfo = function (options) { + + // 开启电量检测 + UIDevice.current.isBatteryMonitoringEnabled = true + + // 返回数据 + const res : GetBatteryInfoSuccess = { + errMsg: "getBatteryInfo:ok", + level: Number(UIDevice.current.batteryLevel * 100), + isCharging: UIDevice.current.batteryState == UIDevice.BatteryState.charging, + }; + options.success?.(res); + options.complete?.(res); +} + +export const getBatteryInfoSync : GetBatteryInfoSync = function (): GetBatteryInfoResult { + + // 开启电量检测 + UIDevice.current.isBatteryMonitoringEnabled = true + + // 返回数据 + const res : GetBatteryInfoResult = { + level: Number(UIDevice.current.batteryLevel * 100), + isCharging: UIDevice.current.batteryState == UIDevice.BatteryState.charging, + }; + return res; +} \ No newline at end of file diff --git a/uni_modules/uni-getbatteryinfo/utssdk/index.d.ts b/uni_modules/uni-getbatteryinfo/utssdk/index.d.ts new file mode 100644 index 0000000..367327b --- /dev/null +++ b/uni_modules/uni-getbatteryinfo/utssdk/index.d.ts @@ -0,0 +1,43 @@ +declare namespace UniNamespace { + interface GetBatteryInfoSuccessCallbackResult { + /** + * 是否正在充电中 + */ + isCharging: boolean; + /** + * 设备电量,范围 1 - 100 + */ + level: number; + errMsg: string; + } + + interface GetBatteryInfoOption { + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: Function + /** + * 接口调用失败的回调函数 + */ + fail?: Function + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetBatteryInfoSuccessCallbackResult) => void + } +} + +declare interface Uni { + /** + * 获取设备电量 + * + * @tutorial https://uniapp.dcloud.net.cn/api/system/batteryInfo.html + */ + getBatteryInfo(option?: UniNamespace.GetBatteryInfoOption): void; + + /** + * 同步获取电池电量信息 + * @tutorial https://uniapp.dcloud.net.cn/api/system/batteryInfo.html + */ + getBatteryInfoSync(): UniNamespace.GetBatteryInfoSuccessCallbackResult; +} diff --git a/uni_modules/uni-getbatteryinfo/utssdk/interface.uts b/uni_modules/uni-getbatteryinfo/utssdk/interface.uts new file mode 100644 index 0000000..0caaa20 --- /dev/null +++ b/uni_modules/uni-getbatteryinfo/utssdk/interface.uts @@ -0,0 +1,147 @@ +export type GetBatteryInfoSuccess = { + errMsg: string, + /** + * 设备电量,范围1 - 100 + */ + level: number, + /** + * 是否正在充电中 + */ + isCharging: boolean +} + +export type GetBatteryInfoOptions = { + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + success?: (res: GetBatteryInfoSuccess) => void + /** + * 接口调用失败的回调函数 + */ + fail?: (res: UniError) => void + /** + * 接口调用成功的回调 + */ + complete?: (res: any) => void +} + +export type GetBatteryInfoResult = { + /** + * 设备电量,范围1 - 100 + */ + level: number, + /** + * 是否正在充电中 + */ + isCharging: boolean +} + +/** + * 错误码 + * - 1001 getAppContext is null + */ +export type GetBatteryInfoErrorCode = 1001 | 1002; +/** + * GetBatteryInfo 的错误回调参数 + */ +export interface GetBatteryInfoFail extends IUniError { + errCode: GetBatteryInfoErrorCode +}; + +/** +* 获取电量信息 +* @param {GetBatteryInfoOptions} options +* +* +* @tutorial https://uniapp.dcloud.net.cn/api/system/batteryInfo.html +* @platforms APP-IOS = ^9.0,APP-ANDROID = ^22 +* @since 3.6.11 +* +* @assert () => success({errCode: 0, errSubject: "uni-getBatteryInfo", errMsg: "getBatteryInfo:ok", level: 60, isCharging: false }) +* @assert () => fail({errCode: 1001, errSubject: "uni-getBatteryInfo", errMsg: "getBatteryInfo:fail getAppContext is null" }) +*/ +export type GetBatteryInfo = (options: GetBatteryInfoOptions) => void + + +export type GetBatteryInfoSync = () => GetBatteryInfoResult + +interface Uni { + + /** + * 获取电池电量信息 + * + * @example + * ```typescript + * uni.getBatteryInfo({ + * success(res) { + * console.log(res); + * } + * }) + * ``` + * @remark + * - 该接口需要同步调用 + * @uniPlatform { + * "app": { + * "android": { + * "osVer": "4.4.4", + * "uniVer": "3.6.11", + * "unixVer": "3.9.0" + * }, + * "ios": { + * "osVer": "12.0", + * "uniVer": "3.6.11", + * "unixVer": "4.11" + * }, + * "harmony": { + * "osVer": "3.0", + * "uniVer": "4.23", + * "unixVer": "x" + * } + * }, + * "web": { + * "uniVer": "3.6.11", + * "unixVer": "4.0" + * } + * } + * @uniVueVersion 2,3 //支持的vue版本 + * + */ + getBatteryInfo(options: GetBatteryInfoOptions): void, + /** + * 同步获取电池电量信息 + * + * @example + * ```typescript + * uni.getBatteryInfo() + * ``` + * @remark + * - 该接口需要同步调用 + * @uniPlatform { + * "app": { + * "android": { + * "osVer": "4.4.4", + * "uniVer": "3.6.11", + * "unixVer": "3.9.0" + * }, + * "ios": { + * "osVer": "12.0", + * "uniVer": "3.6.11", + * "unixVer": "4.11" + * }, + * "harmony": { + * "osVer": "3.0", + * "uniVer": "4.23", + * "unixVer": "x" + * } + * }, + * "web": { + * "uniVer": "3.6.11", + * "unixVer": "4.0" + * } + * } + * @uniVueVersion 2,3 //支持的vue版本 + * + */ + getBatteryInfoSync(): GetBatteryInfoResult + +} diff --git a/uni_modules/uni-getbatteryinfo/utssdk/mp-alipay/index.js b/uni_modules/uni-getbatteryinfo/utssdk/mp-alipay/index.js new file mode 100644 index 0000000..473f1a0 --- /dev/null +++ b/uni_modules/uni-getbatteryinfo/utssdk/mp-alipay/index.js @@ -0,0 +1,6 @@ +export function getBatteryInfo(options) { + return my.getBatteryInfo(options) +} +export function getBatteryInfoSync(options) { + return my.getBatteryInfoSync(options) +} diff --git a/uni_modules/uni-getbatteryinfo/utssdk/mp-baidu/index.js b/uni_modules/uni-getbatteryinfo/utssdk/mp-baidu/index.js new file mode 100644 index 0000000..1ee373a --- /dev/null +++ b/uni_modules/uni-getbatteryinfo/utssdk/mp-baidu/index.js @@ -0,0 +1,6 @@ +export function getBatteryInfo(options) { + return swan.getBatteryInfo(options) +} +export function getBatteryInfoSync(options) { + return swan.getBatteryInfoSync(options) +} diff --git a/uni_modules/uni-getbatteryinfo/utssdk/mp-qq/index.js b/uni_modules/uni-getbatteryinfo/utssdk/mp-qq/index.js new file mode 100644 index 0000000..6eabfcf --- /dev/null +++ b/uni_modules/uni-getbatteryinfo/utssdk/mp-qq/index.js @@ -0,0 +1,6 @@ +export function getBatteryInfo(options) { + return qq.getBatteryInfo(options) +} +export function getBatteryInfoSync(options) { + return qq.getBatteryInfoSync(options) +} diff --git a/uni_modules/uni-getbatteryinfo/utssdk/mp-weixin/index.js b/uni_modules/uni-getbatteryinfo/utssdk/mp-weixin/index.js new file mode 100644 index 0000000..3bdfa91 --- /dev/null +++ b/uni_modules/uni-getbatteryinfo/utssdk/mp-weixin/index.js @@ -0,0 +1,6 @@ +export function getBatteryInfo(options) { + return wx.getBatteryInfo(options) +} +export function getBatteryInfoSync(options) { + return wx.getBatteryInfoSync(options) +} diff --git a/uni_modules/uni-getbatteryinfo/utssdk/unierror.uts b/uni_modules/uni-getbatteryinfo/utssdk/unierror.uts new file mode 100644 index 0000000..1ed635c --- /dev/null +++ b/uni_modules/uni-getbatteryinfo/utssdk/unierror.uts @@ -0,0 +1,35 @@ +import { GetBatteryInfoErrorCode, GetBatteryInfoFail } from "./interface.uts" +/** + * 错误主题 + */ +export const UniErrorSubject = 'uni-getBatteryInfo'; + + +/** + * 错误信息 + * @UniError + */ +export const UniErrors : Map = new Map([ + /** + * 错误码及对应的错误信息 + */ + [1001, 'getBatteryInfo:fail getAppContext is null'], + [1002, 'getBatteryInfo:fail not support'], +]); + + +/** + * 错误对象实现 + */ +export class GetBatteryInfoFailImpl extends UniError implements GetBatteryInfoFail { + override errCode : GetBatteryInfoErrorCode; + /** + * 错误对象构造函数 + */ + constructor(errCode : GetBatteryInfoErrorCode) { + super(); + this.errSubject = UniErrorSubject; + this.errCode = errCode; + this.errMsg = UniErrors[errCode] ?? ""; + } +} diff --git a/uni_modules/uni-getbatteryinfo/utssdk/web/index.js b/uni_modules/uni-getbatteryinfo/utssdk/web/index.js new file mode 100644 index 0000000..4049f50 --- /dev/null +++ b/uni_modules/uni-getbatteryinfo/utssdk/web/index.js @@ -0,0 +1,23 @@ +export function getBatteryInfo(options) { + if (navigator.getBattery) { + navigator.getBattery().then(battery => { + const res = { + errCode: 0, + errSubject: "uni-getBatteryInfo", + errMsg: 'getBatteryInfo:ok', + level: battery.level * 100, + isCharging: battery.charging + } + options.success && options.success(res) + options.complete && options.complete(res) + }) + } else { + const res = { + errCode: 1002, + errSubject: "uni-getBatteryInfo", + errMsg: 'getBatteryInfo:fail navigator.getBattery is unsupported' + } + options.fail && options.fail(res) + options.complete && options.complete(res) + } +}