Add 'src/starCloud/' from commit '758363cd101aa5e0a544a224b5871dab4d2f2f41'
git-subtree-dir: src/starCloud git-subtree-mainline: 6dd9eb00675514a6a086dd740db15bfff0f8ab82 git-subtree-split: 758363cd101aa5e0a544a224b5871dab4d2f2f41
This commit is contained in:
commit
9e5feda04a
1
src/starCloud/.gitignore
vendored
Normal file
1
src/starCloud/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
.idea
|
||||
168
src/starCloud/README.md
Normal file
168
src/starCloud/README.md
Normal file
@ -0,0 +1,168 @@
|
||||
## 星云SDK
|
||||
|
||||
### 1. 安装
|
||||
|
||||
在需要引用的项目中执行命令
|
||||
|
||||
```git
|
||||
git subtree add --prefix=starCloud git@code.star-lock.cn:StarlockTeam/starcloud-sdk-uniapp.git master
|
||||
```
|
||||
|
||||
更新
|
||||
|
||||
```git
|
||||
git subtree pull --prefix=starCloud git@code.star-lock.cn:StarlockTeam/starcloud-sdk-uniapp.git master
|
||||
```
|
||||
|
||||
推送
|
||||
|
||||
```git
|
||||
git subtree push --prefix=starCloud git@code.star-lock.cn:StarlockTeam/starcloud-sdk-uniapp.git master
|
||||
```
|
||||
|
||||
### 2. 需安装的npm包
|
||||
|
||||
`npm install buffer crc js-md5 pinia sm-crypto`
|
||||
|
||||
pinia是全局状态管理工具,需在main.js中引入
|
||||
|
||||
```javascript
|
||||
import * as Pinia from 'pinia'
|
||||
|
||||
const store = Pinia.createPinia()
|
||||
app.use(store)
|
||||
```
|
||||
|
||||
### 3. 使用
|
||||
|
||||
```javascript
|
||||
import { useStarCloudStore } from '@/starCloud/starCloud'
|
||||
|
||||
const $starCloud = useStarCloudStore()
|
||||
|
||||
/**
|
||||
* 初始化星云
|
||||
* @param params
|
||||
* @param {String} params.clientId 客户端Id
|
||||
* @param {String} params.clientSecret 客户端密码
|
||||
* @param {String} params.env 环境
|
||||
* @param {Boolean} params.isReportLog 是否上报日志
|
||||
*/
|
||||
$starCloud.initStarCloud(params)
|
||||
|
||||
// 注册,后续所有方法调用返回值均为code, data, message
|
||||
// code对应报错码有三部分组合构成,锁端报错码+星云服务端报错码+自定义报错码
|
||||
// Result类定义了所有自定义报错码,具体报错码请查看Result类
|
||||
const { code, data, message } = await $starCloud.register()
|
||||
if (code === Result.Success.code) {
|
||||
// 逻辑代码
|
||||
} else {
|
||||
// 错误处理
|
||||
}
|
||||
|
||||
/**
|
||||
* 退出登录
|
||||
* @param params
|
||||
* @param {Number} params.uid 用户ID
|
||||
*/
|
||||
const { code, data, message } = await $starCloud.logout(params)
|
||||
|
||||
/**
|
||||
* 选择锁
|
||||
* @param params
|
||||
* @param {AccountInfo} params.accountInfo 账号信息
|
||||
* @param {Number} params.lockId 锁ID
|
||||
* @returns {Promise<Result>}
|
||||
*/
|
||||
const { code, data, message } = await $starCloud.selectLock(params)
|
||||
|
||||
/**
|
||||
* 开门
|
||||
* @param params
|
||||
* @param {AccountInfo} params.accountInfo 账号信息
|
||||
* @param {String} params.type 开门方式 close: 关门 open: 开门
|
||||
* @param {Boolean} params.disconnect 操作后是否断开连接
|
||||
* @returns {Promise<Result>}
|
||||
*/
|
||||
const { code, data, message } = await $starCloud.openDoor(params)
|
||||
|
||||
/**
|
||||
* 获取离线密码
|
||||
* @param {AccountInfo} accountInfo 账号信息
|
||||
* @param {OfflinePassword} password 密码信息
|
||||
* @returns {Promise<Result>}
|
||||
*/
|
||||
const data = await $starCloud.getOfflinePassword(accountInfo, password)
|
||||
|
||||
/**
|
||||
* 自定义密码
|
||||
* @param params
|
||||
* @param {AccountInfo} params.accountInfo 账号信息
|
||||
* @param {CustomPassword} params.password 密码信息
|
||||
* @param {Boolean} params.disconnect 操作后是否断开连接
|
||||
* @returns {Promise<Result>}
|
||||
*/
|
||||
const data = await $starCloud.customPassword(params)
|
||||
|
||||
/**
|
||||
* 搜索蓝牙设备
|
||||
*/
|
||||
await $starCloud.searchDevice(searchDevice)
|
||||
const searchDevice = async result => {
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止搜索
|
||||
*/
|
||||
await $starCloud.stopSearchDevice()
|
||||
|
||||
/**
|
||||
* 绑定设备
|
||||
* @param params
|
||||
* @param {AccountInfo} params.accountInfo 账号信息
|
||||
* @param {String} params.name 设备名称
|
||||
* @returns {Promise<Result>}
|
||||
*/
|
||||
const data = await $starCloud.bindDevice(params)
|
||||
|
||||
/**
|
||||
* 移除坏锁
|
||||
* @param params
|
||||
* @param {AccountInfo} params.accountInfo 账号信息
|
||||
* @param {List[int]} params.lockIds 锁Id列表
|
||||
* @returns {Promise<Result>}
|
||||
*/
|
||||
const data = await $starCloud.removeBadLock(params)
|
||||
|
||||
/**
|
||||
* 删除锁
|
||||
* @param params
|
||||
* @param {AccountInfo} params.accountInfo 账号信息
|
||||
*/
|
||||
const data = await $starCloud.deleteLock(params)
|
||||
|
||||
/**
|
||||
* 修改管理员密码
|
||||
* @param params
|
||||
* @param {AccountInfo} params.accountInfo 账号信息
|
||||
* @param {String} params.adminPwd 管理员密码
|
||||
* @param {Boolean} params.disconnect 操作后是否断开连接
|
||||
* @returns {Promise<Result>}
|
||||
*/
|
||||
const data = await $starCloud.updateAdminPassword(params)
|
||||
|
||||
/**
|
||||
* 同步全部开门记录
|
||||
* @param params
|
||||
* @param {AccountInfo} params.accountInfo 账号信息
|
||||
* @param {Boolean} params.disconnect 操作后是否断开连接
|
||||
* @returns {Promise<Result>}
|
||||
*/
|
||||
const data = await $starCloud.syncAllOpenRecord(params)
|
||||
|
||||
/**
|
||||
* 获取服务器时间
|
||||
* @returns {Promise<Result>}
|
||||
*/
|
||||
const data = await $starCloud.getServerTimestamp()
|
||||
```
|
||||
163
src/starCloud/api.js
Normal file
163
src/starCloud/api.js
Normal file
@ -0,0 +1,163 @@
|
||||
import request from '@/starCloud/request'
|
||||
|
||||
// 创建账号
|
||||
export function starCloudCreateUser(data) {
|
||||
return request({
|
||||
url: '/createUser',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 获取访问令牌
|
||||
export function getStarCloudToken(data) {
|
||||
return request({
|
||||
url: '/oauth2/token',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 更新锁用户
|
||||
export function updateLockUserNoRequest(data) {
|
||||
return request({
|
||||
url: '/v1/key/updateLockUserNo',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 获取所有锁用户
|
||||
export function getUserNoListRequest(data) {
|
||||
return request({
|
||||
url: '/v1/key/getUserNoList',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 获取手机联网token
|
||||
export function getLockNetTokenRequest(data) {
|
||||
return request({
|
||||
url: '/v1/lock/getLockNetToken',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 获取服务器时间
|
||||
export function getServerDatetimeRequest(data) {
|
||||
return request({
|
||||
url: '/v1/lock/queryDate',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 获取锁详情
|
||||
export function getLockDetailRequest(data) {
|
||||
return request({
|
||||
url: '/v1/lock/detail',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 获取离线密码
|
||||
export function getOfflinePasswordRequest(data) {
|
||||
return request({
|
||||
url: '/v1/keyboardPwd/get',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 添加自定义密码
|
||||
export function addCustomPasswordRequest(data) {
|
||||
return request({
|
||||
url: '/v1/keyboardPwd/add',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 更新密码
|
||||
export function updatePasswordRequest(data) {
|
||||
return request({
|
||||
url: '/v1/keyboardPwd/update',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 删除密码
|
||||
export function deletePasswordRequest(data) {
|
||||
return request({
|
||||
url: '/v1/keyboardPwd/delete',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 绑定智能锁
|
||||
export function bindLockRequest(data) {
|
||||
return request({
|
||||
url: '/v1/lock/initialize',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 移除坏锁
|
||||
export function removeBadLockRequest(data) {
|
||||
return request({
|
||||
url: '/v1/lock/removeBadLock',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 删除锁
|
||||
export function deleteLockRequest(data) {
|
||||
return request({
|
||||
url: '/v1/lock/delete',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 删除锁
|
||||
export function updateElectricQuantityRequest(data) {
|
||||
return request({
|
||||
url: '/v1/lock/updateElectricQuantity',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 修改管理员密码
|
||||
export function changeAdminKeyboardPwdRequest(data) {
|
||||
return request({
|
||||
url: '/v1/lock/changeAdminKeyboardPwd',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 获取操作记录的最后上传时间
|
||||
export function getLastRecordTimeRequest(data) {
|
||||
return request({
|
||||
url: '/v1/lockRecord/getLastRecordTime',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 上传操作记录
|
||||
export function uploadRecordRequest(data) {
|
||||
return request({
|
||||
url: '/v1/lockRecord/upload',
|
||||
method: 'POST',
|
||||
data
|
||||
})
|
||||
}
|
||||
493
src/starCloud/basic.js
Normal file
493
src/starCloud/basic.js
Normal file
@ -0,0 +1,493 @@
|
||||
export class Result {
|
||||
static codes = {
|
||||
Success: 0,
|
||||
Fail: -1,
|
||||
|
||||
NotMoreData: -10,
|
||||
|
||||
NotAvailableBluetooth: -20,
|
||||
NotAvailableBluetoothPermission: -21,
|
||||
NotAvailableWeChatNearbyDevicesPermission: -22,
|
||||
NotAvailableWeChatLocationPermission: -23,
|
||||
NotAvailableWeChatNearbyDevicesEmpty: -24,
|
||||
NotAvailableWeChatBluetoothPermission: -25,
|
||||
DeviceHasBeenReset: -30,
|
||||
|
||||
NotRegisteredLock: 4,
|
||||
NotTokenLock: 6,
|
||||
NotMoreKeyLock: 12,
|
||||
ReadyHasKeyLock: 15,
|
||||
ReadyHasPassword: 251
|
||||
}
|
||||
|
||||
static resultsMap = new Map([
|
||||
[Result.codes.Success, { message: '成功', data: {} }],
|
||||
[Result.codes.Fail, { message: '失败', data: {} }],
|
||||
|
||||
[Result.codes.NotMoreData, { message: '没有更多数据', data: {} }],
|
||||
|
||||
[Result.codes.NotAvailableBluetooth, { message: '蓝牙尚未打开,请先打开蓝牙', data: {} }],
|
||||
[
|
||||
Result.codes.NotAvailableBluetoothPermission,
|
||||
{ message: '小程序蓝牙功能被禁用,请打开小程序蓝牙权限', data: {} }
|
||||
],
|
||||
[
|
||||
Result.codes.NotAvailableWeChatNearbyDevicesPermission,
|
||||
{ message: '蓝牙功能需要附近设备权限,请前往设置开启微信的附近设备权限后再试', data: {} }
|
||||
],
|
||||
[
|
||||
Result.codes.NotAvailableWeChatLocationPermission,
|
||||
{ message: '蓝牙功能需要定位权限,请前往设置开启微信的定位权限后再试', data: {} }
|
||||
],
|
||||
[
|
||||
Result.codes.NotAvailableWeChatNearbyDevicesEmpty,
|
||||
{
|
||||
message: '蓝牙功能需要定位服务,请前往设置开启定位服务后再试',
|
||||
data: {}
|
||||
}
|
||||
],
|
||||
[
|
||||
Result.codes.NotAvailableWeChatBluetoothPermission,
|
||||
{
|
||||
message: '微信的蓝牙权限被禁用,请前往设置开启微信的蓝牙权限后再试',
|
||||
data: {}
|
||||
}
|
||||
],
|
||||
[Result.codes.DeviceHasBeenReset, { message: '设备已被重置', data: {} }],
|
||||
|
||||
[Result.codes.NotRegisteredLock, { message: '用户在锁端未注册', data: {} }],
|
||||
[Result.codes.NotTokenLock, { message: '用户在锁端token失效', data: {} }],
|
||||
[Result.codes.NotMoreKeyLock, { message: '锁端钥匙数量已达上限', data: {} }],
|
||||
[Result.codes.ReadyHasKeyLock, { message: '用户已是锁端用户', data: {} }],
|
||||
[Result.codes.ReadyHasPassword, { message: '该密码已存在', data: {} }]
|
||||
])
|
||||
|
||||
constructor(code, data, message) {
|
||||
const result = Result.resultsMap.get(code)
|
||||
if (result) {
|
||||
this.code = code
|
||||
this.message = message || result.message
|
||||
this.data = data || result.data
|
||||
} else {
|
||||
this.code = code
|
||||
this.message = message || ''
|
||||
this.data = data || {}
|
||||
}
|
||||
}
|
||||
|
||||
// 成功
|
||||
static get Success() {
|
||||
return new Result(Result.codes.Success)
|
||||
}
|
||||
|
||||
// 失败(默认错误)
|
||||
static get Fail() {
|
||||
return new Result(Result.codes.Fail)
|
||||
}
|
||||
|
||||
// 没有更多数据
|
||||
static get NotMoreData() {
|
||||
return new Result(Result.codes.NotMoreData)
|
||||
}
|
||||
|
||||
// 蓝牙未开启
|
||||
static get NotAvailableBluetooth() {
|
||||
return new Result(Result.codes.NotAvailableBluetooth)
|
||||
}
|
||||
|
||||
// 小程序蓝牙权限被禁用
|
||||
static get NotAvailableBluetoothPermission() {
|
||||
return new Result(Result.codes.NotAvailableBluetoothPermission)
|
||||
}
|
||||
|
||||
// 微信附近的设备权限被禁用
|
||||
static get NotAvailableWeChatNearbyDevicesPermission() {
|
||||
return new Result(Result.codes.NotAvailableWeChatNearbyDevicesPermission)
|
||||
}
|
||||
|
||||
// 微信定位权限被禁用
|
||||
static get NotAvailableWeChatLocationPermission() {
|
||||
return new Result(Result.codes.NotAvailableWeChatLocationPermission)
|
||||
}
|
||||
|
||||
// 手机定位服务被关闭
|
||||
static get NotAvailableWeChatNearbyDevicesEmpty() {
|
||||
return new Result(Result.codes.NotAvailableWeChatNearbyDevicesEmpty)
|
||||
}
|
||||
|
||||
// 微信的蓝牙权限被禁用
|
||||
static get NotAvailableWeChatBluetoothPermission() {
|
||||
return new Result(Result.codes.NotAvailableWeChatBluetoothPermission)
|
||||
}
|
||||
|
||||
// 设备已被重置
|
||||
static get DeviceHasBeenReset() {
|
||||
return new Result(Result.codes.DeviceHasBeenReset)
|
||||
}
|
||||
|
||||
// 用户在锁端未注册
|
||||
static get NotRegisteredLock() {
|
||||
return new Result(Result.codes.NotRegisteredLock)
|
||||
}
|
||||
|
||||
// 用户在锁端token失效
|
||||
static get NotTokenLock() {
|
||||
return new Result(Result.codes.NotTokenLock)
|
||||
}
|
||||
|
||||
// 锁端钥匙数量已达上限
|
||||
static get NotMoreKeyLock() {
|
||||
return new Result(Result.codes.NotMoreKeyLock)
|
||||
}
|
||||
|
||||
// 锁端钥匙数量已达上限
|
||||
static get ReadyHasKeyLock() {
|
||||
return new Result(Result.codes.ReadyHasKeyLock)
|
||||
}
|
||||
|
||||
// 密码已存在
|
||||
static get ReadyHasPassword() {
|
||||
return new Result(Result.codes.ReadyHasPassword)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef {Object} err
|
||||
* @property {number} errno - 错误代码
|
||||
* @property {number} errCode - 错误代码
|
||||
* @property {String} errMsg - 错误信息
|
||||
*/
|
||||
|
||||
// 查找设备并连接
|
||||
export function searchAndConnectDevice(name, reset = true) {
|
||||
// 循环查找设备
|
||||
let timer
|
||||
// 超时计时器
|
||||
let timeoutTimer
|
||||
|
||||
return new Promise(async resolve => {
|
||||
const result = await startBluetoothDevicesDiscovery()
|
||||
if (result.code === Result.Success.code) {
|
||||
let searchFlag = false
|
||||
timeoutTimer = setTimeout(async () => {
|
||||
await stopBluetoothDevicesDiscovery()
|
||||
clearInterval(timer)
|
||||
if (!searchFlag) {
|
||||
resolve(Result.NotAvailableWeChatNearbyDevicesEmpty)
|
||||
} else {
|
||||
resolve(Result.Fail)
|
||||
}
|
||||
}, 10500)
|
||||
timer = setInterval(async () => {
|
||||
const queryResult = await getBluetoothDevices()
|
||||
if (queryResult.code === Result.Success.code) {
|
||||
const deviceList = queryResult.data
|
||||
if (searchFlag === false && deviceList.length > 0) {
|
||||
searchFlag = true
|
||||
}
|
||||
for (let i = 0; i < deviceList.length; i++) {
|
||||
if (deviceList[i]?.name === name) {
|
||||
const uuid = deviceList[i]?.advertisServiceUUIDs[0]
|
||||
if (uuid && uuid.slice(2, 8) === '758824') {
|
||||
await stopBluetoothDevicesDiscovery()
|
||||
clearTimeout(timeoutTimer)
|
||||
clearInterval(timer)
|
||||
if (uuid.slice(30, 32) === '00' && reset) {
|
||||
resolve(Result.DeviceHasBeenReset)
|
||||
} else {
|
||||
const connectResult = await createBLEConnection(deviceList[i].deviceId)
|
||||
resolve(connectResult)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
resolve(queryResult)
|
||||
}
|
||||
}, 1000)
|
||||
} else {
|
||||
resolve(result)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 蓝牙操作报错处理
|
||||
async function handleError(err, event) {
|
||||
if (err.errCode === 10000) {
|
||||
const result = await openBluetoothAdapter()
|
||||
if (result.code === Result.Success.code) {
|
||||
return await event()
|
||||
}
|
||||
return result
|
||||
}
|
||||
if (err.errCode === 10001) {
|
||||
if (err.state === 3) {
|
||||
return Result.NotAvailableWeChatBluetoothPermission
|
||||
}
|
||||
return Result.NotAvailableBluetooth
|
||||
}
|
||||
if (err.errno === 3) {
|
||||
return Result.NotAvailableWeChatNearbyDevicesPermission
|
||||
}
|
||||
if (err.errno === 103) {
|
||||
return Result.NotAvailableBluetoothPermission
|
||||
}
|
||||
if (err.errno === 1509008) {
|
||||
return Result.NotAvailableWeChatLocationPermission
|
||||
}
|
||||
if (err.errMsg === 'openBluetoothAdapter:fail already opened') {
|
||||
return Result.Success
|
||||
}
|
||||
return Result.Fail
|
||||
}
|
||||
|
||||
// 初始化蓝牙模块
|
||||
function openBluetoothAdapter() {
|
||||
return new Promise(resolve => {
|
||||
uni.openBluetoothAdapter({
|
||||
success() {
|
||||
resolve(Result.Success)
|
||||
},
|
||||
async fail(err) {
|
||||
resolve(await handleError(err))
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 关闭蓝牙模块
|
||||
export function closeBluetoothAdapter() {
|
||||
uni.closeBluetoothAdapter()
|
||||
}
|
||||
|
||||
// 移除蓝牙适配器的全部监听
|
||||
export function offBluetoothAdapterStateChange() {
|
||||
uni.offBluetoothAdapterStateChange()
|
||||
}
|
||||
|
||||
// 监听蓝牙特征值改变
|
||||
export function onBLECharacteristicValueChange(callback) {
|
||||
uni.onBLECharacteristicValueChange(res => {
|
||||
callback(res)
|
||||
})
|
||||
}
|
||||
|
||||
// 开始搜索附近的蓝牙设备
|
||||
export function startBluetoothDevicesDiscovery() {
|
||||
return new Promise(resolve => {
|
||||
uni.startBluetoothDevicesDiscovery({
|
||||
success() {
|
||||
resolve(Result.Success)
|
||||
},
|
||||
async fail(err) {
|
||||
resolve(await handleError(err, startBluetoothDevicesDiscovery))
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 获取所有已发现的蓝牙设备
|
||||
export function getBluetoothDevices() {
|
||||
return new Promise(resolve => {
|
||||
uni.getBluetoothDevices({
|
||||
success(res) {
|
||||
resolve(new Result(Result.Success.code, res.devices))
|
||||
},
|
||||
async fail(err) {
|
||||
resolve(await handleError(err, getBluetoothDevices))
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 停止搜索附近的蓝牙设备
|
||||
export function stopBluetoothDevicesDiscovery() {
|
||||
return new Promise(resolve => {
|
||||
uni.stopBluetoothDevicesDiscovery({
|
||||
success() {
|
||||
resolve(Result.Success)
|
||||
},
|
||||
async fail(err) {
|
||||
resolve(await handleError(err))
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 连接低功耗蓝牙设备
|
||||
export function createBLEConnection(deviceId, reconnectNumber = 0) {
|
||||
return new Promise(resolve => {
|
||||
uni.createBLEConnection({
|
||||
deviceId,
|
||||
timeout: 10000,
|
||||
async success() {
|
||||
const res = await getBLEDeviceServicesAndCharacteristics(deviceId)
|
||||
await notifyBLECharacteristicValueChange(
|
||||
deviceId,
|
||||
res.data.serviceId,
|
||||
res.data.notifyCharacteristicId
|
||||
)
|
||||
resolve(res)
|
||||
},
|
||||
async fail(err) {
|
||||
if (err.errno === 1509007) {
|
||||
const res = await getBLEDeviceServicesAndCharacteristics(deviceId)
|
||||
await notifyBLECharacteristicValueChange(
|
||||
deviceId,
|
||||
res.data.serviceId,
|
||||
res.data.notifyCharacteristicId
|
||||
)
|
||||
resolve(res)
|
||||
} else if (err.errno === 1509001 && reconnectNumber < 1) {
|
||||
resolve(Result.Fail)
|
||||
} else if (reconnectNumber < 1) {
|
||||
resolve(await createBLEConnection(deviceId, reconnectNumber + 1))
|
||||
} else {
|
||||
resolve(Result.Fail)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 获取服务及对应特征值
|
||||
async function getBLEDeviceServicesAndCharacteristics(deviceId) {
|
||||
const { code, data } = await getBLEDeviceServices(deviceId)
|
||||
if (code === Result.Success.code) {
|
||||
const { serviceId } = data
|
||||
const {
|
||||
code,
|
||||
data: { notifyCharacteristicId, writeCharacteristicId }
|
||||
} = await getBLEDeviceCharacteristics(deviceId, serviceId)
|
||||
if (code === Result.Success.code) {
|
||||
return new Result(Result.Success.code, {
|
||||
deviceId,
|
||||
serviceId,
|
||||
notifyCharacteristicId,
|
||||
writeCharacteristicId
|
||||
})
|
||||
}
|
||||
return Result.Fail
|
||||
}
|
||||
return Result.Fail
|
||||
}
|
||||
|
||||
// 获取设备的服务
|
||||
function getBLEDeviceServices(deviceId) {
|
||||
return new Promise(resolve => {
|
||||
uni.getBLEDeviceServices({
|
||||
deviceId,
|
||||
success(res) {
|
||||
let serviceId
|
||||
for (let i = 0; i < res.services.length; i++) {
|
||||
if (res.services[i].uuid.indexOf('FFF0') !== -1) {
|
||||
serviceId = res.services[i].uuid
|
||||
}
|
||||
}
|
||||
if (!serviceId) {
|
||||
resolve(Result.Fail)
|
||||
return
|
||||
}
|
||||
resolve(new Result(Result.Success.code, { serviceId }))
|
||||
},
|
||||
fail() {
|
||||
resolve(Result.Fail)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 获取服务的特征值
|
||||
function getBLEDeviceCharacteristics(deviceId, serviceId) {
|
||||
return new Promise(resolve => {
|
||||
uni.getBLEDeviceCharacteristics({
|
||||
deviceId,
|
||||
serviceId,
|
||||
success(res) {
|
||||
let notifyCharacteristicId
|
||||
let writeCharacteristicId
|
||||
for (let i = 0; i < res.characteristics.length; i++) {
|
||||
const characteristic = res.characteristics[i]
|
||||
if (characteristic.properties.notify) {
|
||||
notifyCharacteristicId = characteristic.uuid
|
||||
}
|
||||
if (characteristic.properties.write) {
|
||||
writeCharacteristicId = characteristic.uuid
|
||||
}
|
||||
}
|
||||
if (notifyCharacteristicId && writeCharacteristicId) {
|
||||
resolve(
|
||||
new Result(Result.Success.code, { notifyCharacteristicId, writeCharacteristicId })
|
||||
)
|
||||
} else {
|
||||
resolve(Result.Fail)
|
||||
}
|
||||
},
|
||||
fail() {
|
||||
resolve(Result.Fail)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 订阅特征值
|
||||
function notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId) {
|
||||
return new Promise(resolve => {
|
||||
uni.notifyBLECharacteristicValueChange({
|
||||
deviceId,
|
||||
serviceId,
|
||||
characteristicId,
|
||||
state: true,
|
||||
success() {
|
||||
resolve(Result.Success)
|
||||
},
|
||||
fail() {
|
||||
resolve(Result.Fail)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 断开与低功耗蓝牙设备的连接
|
||||
export function closeBLEConnection(deviceId) {
|
||||
return new Promise(resolve => {
|
||||
uni.closeBLEConnection({
|
||||
deviceId,
|
||||
success() {
|
||||
console.log('断开连接成功')
|
||||
resolve(Result.Success)
|
||||
},
|
||||
fail() {
|
||||
console.log('断开连接失败')
|
||||
resolve(Result.Fail)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 写入特征值
|
||||
export function writeBLECharacteristicValue(deviceId, serviceId, characteristicId, binaryData) {
|
||||
return new Promise(resolve => {
|
||||
const count = Math.ceil(binaryData.length / 20)
|
||||
let successCount = 0
|
||||
for (let i = 0; i < count; i++) {
|
||||
const writeData = binaryData.slice(i * 20, i === count - 1 ? binaryData.length : (i + 1) * 20)
|
||||
uni.writeBLECharacteristicValue({
|
||||
deviceId,
|
||||
serviceId,
|
||||
characteristicId,
|
||||
value: writeData.buffer,
|
||||
success() {
|
||||
successCount++
|
||||
if (successCount === count) {
|
||||
resolve(Result.Success)
|
||||
}
|
||||
},
|
||||
fail() {
|
||||
resolve(Result.Fail)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
28
src/starCloud/env.js
Normal file
28
src/starCloud/env.js
Normal file
@ -0,0 +1,28 @@
|
||||
// 版本号
|
||||
export const version = '1.0.0'
|
||||
// 构建号
|
||||
export const buildNumber = 1
|
||||
|
||||
// 环境配置
|
||||
export const configs = {
|
||||
DEV: {
|
||||
name: 'DEV',
|
||||
baseUrl: 'https://dev.cloud.star-lock.cn/sdk'
|
||||
},
|
||||
PRE: {
|
||||
name: 'PRE',
|
||||
baseUrl: 'https://pre.cloud.star-lock.cn/sdk'
|
||||
},
|
||||
PRE_SKY: {
|
||||
name: 'PRE_SKY',
|
||||
baseUrl: 'https://pre.cloud.star-lock.cn/sdk'
|
||||
},
|
||||
XHJ: {
|
||||
name: 'XHJ',
|
||||
baseUrl: 'https://cloud.xhjcn.ltd/sdk'
|
||||
},
|
||||
SKY: {
|
||||
name: 'SKY',
|
||||
baseUrl: 'https://cloud.skychip.top/sdk'
|
||||
}
|
||||
}
|
||||
79
src/starCloud/format.js
Normal file
79
src/starCloud/format.js
Normal file
@ -0,0 +1,79 @@
|
||||
import { md5 } from 'js-md5'
|
||||
import crc from 'crc'
|
||||
|
||||
// 周数组转换
|
||||
export function convertWeekdaysToNumber(weekDay) {
|
||||
let weekStr = '00000000'
|
||||
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
for (const day of weekDay) {
|
||||
const index = day % 7
|
||||
weekStr = weekStr.substring(0, index) + '1' + weekStr.substring(index + 1)
|
||||
}
|
||||
|
||||
// 倒序 weekStr
|
||||
weekStr = weekStr.split('').reverse().join('')
|
||||
|
||||
return parseInt(weekStr, 2)
|
||||
}
|
||||
|
||||
// 时间戳转二进制
|
||||
export function timestampToArray(timestamp) {
|
||||
const array = new Uint8Array(4)
|
||||
array[0] = (timestamp & 0xff000000) >> 24
|
||||
array[1] = (timestamp & 0xff0000) >> 16
|
||||
array[2] = (timestamp & 0xff00) >> 8
|
||||
array[3] = timestamp & 0xff
|
||||
return array
|
||||
}
|
||||
|
||||
// md5加密
|
||||
export function md5Encrypt(text, token, key) {
|
||||
const length = text.length + 4 + 16
|
||||
const md5Array = new Uint8Array(length)
|
||||
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
md5Array[i] = text.charCodeAt(i)
|
||||
}
|
||||
|
||||
md5Array.set(token, text.length)
|
||||
md5Array.set(key, text.length + 4)
|
||||
|
||||
const md5Text = md5(md5Array)
|
||||
return new Uint8Array(md5Text.match(/.{1,2}/g).map(byte => parseInt(byte, 16)))
|
||||
}
|
||||
|
||||
// 生成包尾 头部数据+内容数据
|
||||
export function createPackageEnd(headArray, contentArray) {
|
||||
// 拼接头部和内容
|
||||
let mergerArray = new Uint8Array(headArray.length + contentArray.length)
|
||||
mergerArray.set(headArray)
|
||||
mergerArray.set(contentArray, headArray.length)
|
||||
|
||||
// crc加密
|
||||
const crcResult = crc.crc16kermit(mergerArray)
|
||||
|
||||
// 拼接crc
|
||||
let newArray = new Uint8Array(mergerArray.length + 2)
|
||||
newArray.set(mergerArray)
|
||||
newArray.set([crcResult / 256, crcResult % 256], mergerArray.length)
|
||||
|
||||
return newArray
|
||||
}
|
||||
|
||||
// 二进制转时间戳
|
||||
export function arrayToTimestamp(array) {
|
||||
const timestamp = (array[0] << 24) | (array[1] << 16) | (array[2] << 8) | array[3]
|
||||
return timestamp >>> 0
|
||||
}
|
||||
|
||||
// 二进制转字符串
|
||||
export function uint8ArrayToString(uint8Array) {
|
||||
let str = ''
|
||||
for (let i = 0; i < uint8Array.length; i++) {
|
||||
if (uint8Array[i] !== 0) {
|
||||
str += String.fromCharCode(uint8Array[i])
|
||||
}
|
||||
}
|
||||
return str
|
||||
}
|
||||
50
src/starCloud/log.js
Normal file
50
src/starCloud/log.js
Normal file
@ -0,0 +1,50 @@
|
||||
import { useStarCloudStore } from '@/starCloud/starCloud'
|
||||
|
||||
const log = wx.getRealtimeLogManager ? wx.getRealtimeLogManager() : null
|
||||
|
||||
export default {
|
||||
debug() {
|
||||
if (!log) return
|
||||
const $starCloud = useStarCloudStore()
|
||||
if (!$starCloud.isReportLog) return
|
||||
// eslint-disable-next-line prefer-spread,prefer-rest-params
|
||||
log.debug.apply(log, arguments)
|
||||
},
|
||||
info() {
|
||||
if (!log) return
|
||||
const $starCloud = useStarCloudStore()
|
||||
if (!$starCloud.isReportLog) return
|
||||
// eslint-disable-next-line prefer-spread,prefer-rest-params
|
||||
log.info.apply(log, arguments)
|
||||
},
|
||||
warn() {
|
||||
if (!log) return
|
||||
const $starCloud = useStarCloudStore()
|
||||
if (!$starCloud.isReportLog) return
|
||||
// eslint-disable-next-line prefer-spread,prefer-rest-params
|
||||
log.warn.apply(log, arguments)
|
||||
},
|
||||
error() {
|
||||
if (!log) return
|
||||
const $starCloud = useStarCloudStore()
|
||||
if (!$starCloud.isReportLog) return
|
||||
// eslint-disable-next-line prefer-spread,prefer-rest-params
|
||||
log.error.apply(log, arguments)
|
||||
},
|
||||
setFilterMsg(msg) {
|
||||
// 从基础库2.7.3开始支持
|
||||
if (!log || !log.setFilterMsg) return
|
||||
if (typeof msg !== 'string') return
|
||||
const $starCloud = useStarCloudStore()
|
||||
if (!$starCloud.isReportLog) return
|
||||
log.setFilterMsg(msg)
|
||||
},
|
||||
addFilterMsg(msg) {
|
||||
// 从基础库2.8.1开始支持
|
||||
if (!log || !log.addFilterMsg) return
|
||||
if (typeof msg !== 'string') return
|
||||
const $starCloud = useStarCloudStore()
|
||||
if (!$starCloud.isReportLog) return
|
||||
log.addFilterMsg(msg)
|
||||
}
|
||||
}
|
||||
105
src/starCloud/request.js
Normal file
105
src/starCloud/request.js
Normal file
@ -0,0 +1,105 @@
|
||||
import { getStorage, removeStorage } from '@/starCloud/storage'
|
||||
import { useStarCloudStore } from '@/starCloud/starCloud'
|
||||
import { Result } from '@/starCloud/basic'
|
||||
|
||||
/*
|
||||
* config
|
||||
* baseUrl: 请求域名
|
||||
* url: 请求路径
|
||||
* method: 请求方法
|
||||
* header: 请求头
|
||||
* token: 请求token
|
||||
* data: 请求参数
|
||||
* */
|
||||
|
||||
const request = config => {
|
||||
const starCloud = useStarCloudStore()
|
||||
let timer
|
||||
return new Promise(async resolve => {
|
||||
const baseConfig = starCloud.getConfig()
|
||||
|
||||
const token = config?.token ? config.token : getStorage('starCloudToken')
|
||||
// 请求地址
|
||||
const URL = config.baseUrl ? config.baseUrl + config.url : baseConfig.baseUrl + config.url
|
||||
|
||||
// 默认请求头
|
||||
const headerDefault = {
|
||||
version: baseConfig.version + '+' + baseConfig.buildNumber
|
||||
}
|
||||
const header = {
|
||||
...headerDefault,
|
||||
...config.header
|
||||
}
|
||||
const method = config.method || 'POST'
|
||||
const data = {
|
||||
...config.data,
|
||||
accessToken: token,
|
||||
clientId: starCloud.clientId
|
||||
}
|
||||
const timestamp = new Date().getTime()
|
||||
|
||||
// 超时处理
|
||||
timer = setTimeout(() => {
|
||||
resolve(new Result(Result.Fail.code, {}, '网络访问失败,请检查网络是否正常'))
|
||||
}, 3200)
|
||||
|
||||
uni.request({
|
||||
url: URL,
|
||||
method,
|
||||
header,
|
||||
data,
|
||||
timeout: 3000,
|
||||
async success(res) {
|
||||
const { statusCode, data } = res
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
if (statusCode === 200) {
|
||||
const code = data.errcode
|
||||
const message = data.errmsg
|
||||
if (code === 10003) {
|
||||
removeStorage('starCloudToken')
|
||||
removeStorage('starCloudUser')
|
||||
const { code } = await starCloud.login({
|
||||
username: starCloud.starCloudAccountInfo.username,
|
||||
password: starCloud.starCloudAccountInfo.password,
|
||||
uid: starCloud.starCloudAccountInfo.uid
|
||||
})
|
||||
if (code === Result.Success.code) {
|
||||
resolve(await request(config))
|
||||
}
|
||||
} else {
|
||||
resolve({
|
||||
code,
|
||||
data: data.data,
|
||||
message
|
||||
})
|
||||
}
|
||||
} else {
|
||||
resolve(new Result(Result.Fail.code, {}, '网络访问失败,请检查网络是否正常'))
|
||||
}
|
||||
},
|
||||
async fail(res) {
|
||||
console.log('网络访问失败', res)
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
resolve(new Result(Result.Fail.code, {}, '网络访问失败,请检查网络是否正常'))
|
||||
},
|
||||
async complete(res) {
|
||||
console.log(URL.substring(baseConfig.baseUrl.length + 1), {
|
||||
env: baseConfig.name,
|
||||
url: URL.substring(baseConfig.baseUrl.length + 1),
|
||||
req: config?.data || {},
|
||||
code: res?.data?.errcode,
|
||||
res: res?.data?.data,
|
||||
token: header?.authorization || '',
|
||||
message: res?.data?.errmsg,
|
||||
duration: new Date().getTime() - timestamp
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export default request
|
||||
2050
src/starCloud/starCloud.js
Normal file
2050
src/starCloud/starCloud.js
Normal file
File diff suppressed because it is too large
Load Diff
18
src/starCloud/storage.js
Normal file
18
src/starCloud/storage.js
Normal file
@ -0,0 +1,18 @@
|
||||
import { useStarCloudStore } from '@/starCloud/starCloud'
|
||||
|
||||
export function setStorage(key, value) {
|
||||
return uni.setStorageSync(getPrefix() + key, value)
|
||||
}
|
||||
|
||||
export function getStorage(key) {
|
||||
return uni.getStorageSync(getPrefix() + key)
|
||||
}
|
||||
|
||||
export function removeStorage(key) {
|
||||
return uni.removeStorageSync(getPrefix() + key)
|
||||
}
|
||||
|
||||
function getPrefix() {
|
||||
const starCloud = useStarCloudStore()
|
||||
return `${starCloud.envVersion}:`
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user