Commit e2bcabda by liimin

feat(resolution): 实现分辨率适配系统并优化组件滚动性能

- 将分辨率适配配置从 config 移至 services/adapter 目录
- 实现完整的分辨率适配系统,支持横竖屏自动切换和响应式配置
- 为 CarBrands 和 Employee 组件添加 scroll-view 替代 view 实现滚动
- 使用 computed 响应式获取分辨率配置,提升组件渲染性能
- 重构 LayoutService 添加屏幕信息获取的安全检查机制
- 优化 WebSocket 错误处理和日志记录功能
1 parent 5763732d
<script lang="uts">
import { updateResolutionConfig } from "@/config/resolution-adapt/index.uts";
import { updateResolutionConfig } from "@/services/adapter/index.uts";
// #ifdef APP
import { layoutService } from "@/services/LayoutService.uts";
import { lockOrientation } from "@/utils/plus-screen.uts";
......@@ -11,7 +11,7 @@ let firstBackTime = 0;
export default {
onLaunch () {
// #ifdef APP
layoutService.init();
// layoutService.init();
const sys = uni.getSystemInfoSync();
console.log(`[App] 当前分辨率:${ sys.screenWidth } x ${ sys.screenHeight}`);
// pad/大屏锁定横屏,手机锁定竖屏
......
......@@ -13,11 +13,11 @@
@click="handleBackClick
<un-icon name="arrow-left" size="20"></un-icon>">
</vie -->
<view class="select-box">
<scroll-view class="select-box"
:show-scrollbar="false"
:style="{ maxHeight: windowHeight * 0.6 + 'px' }">
<!-- <view class="select-box"> -->
<!-- 品牌列表 -->
<!-- <un-transition duration="50"
mode="fade"
:show="currentView == 'brand'"> -->
<view v-show="currentView == 'brand'" class="view-content">
<template v-for="(item, index) in carBrandList"
:key="index">
......@@ -28,12 +28,8 @@
</view>
</template>
</view>
<!-- </un-transition> -->
<!-- 车系列表 -->
<!-- <un-transition duration="50"
mode="fade"
:show="currentView == 'series'"> -->
<view v-show="currentView == 'series'" class="view-content">
<template v-for="(item, index) in currentCarList"
:key="index">
......@@ -45,7 +41,7 @@
</template>
</view>
<!-- </un-transition> -->
</view>
</scroll-view>
</MessageBox>
</view>
......@@ -54,6 +50,8 @@
<script setup lang="uts">
import { ComponentPublicInstance } from "vue";
console.log('==== CarBrands 组件脚本开始执行 ====')
import { getCarBrandsListApi, getMerchantCarBrandList } from "@/api/common-api.uts";
import { recordService } from "@/services/recorder/index.uts";
import { dispatch, state } from "@/store/index.uts";
......@@ -61,11 +59,15 @@ import { storage } from "@/utils/storage.uts";
import MessageBox from "./MessageBox.uvue";
import { resolutionState } from "@/services/adapter/index.uts";
import { computed } from "vue";
import type { AppResolutionConfig } from "@/services/adapter/types/index.uts";
// 使用 computed 响应式获取最新的分辨率配置
const windowHeight = computed(() => resolutionState.windowHeight);
type UserInfo = UTSJSONObject
type UserInfo = UTSJSONObject
const props = defineProps({
carBrandKey: {
......@@ -379,11 +381,11 @@ defineExpose({ open, close, autoSelect });
<style scoped lang='scss'>
.select-box {
margin: 20px 0;
overflow-y: scroll;
max-height: 400px;
padding-bottom: 30px;
position: relative;
display: flex;
flex-direction: column;
min-height: 0;
flex: 1;
.view-content {
display: flex;
flex-wrap: wrap;
......
......@@ -6,7 +6,9 @@
:title="`请选择${title}`"
:z-index="10076"
@close="handleClose">
<view class="select-box">
<scroll-view class="select-box"
:show-scrollbar="false"
:style="{ maxHeight: windowHeight * 0.6 + 'px' }">
<template v-for="(item, index) in employeeList" :key="index">
<view class="select-item"
:class="[{ checked: (salesUuid as string) == (item as UTSJSONObject).uuid }]"
......@@ -14,7 +16,7 @@
{{ (item as UTSJSONObject).staffName }}
</view>
</template>
</view>
</scroll-view>
</MessageBox>
</template>
......@@ -26,7 +28,8 @@ import { dispatch, state } from "@/store/index.uts";
import { storage } from "@/utils/storage.uts";
import MessageBox from "./MessageBox.uvue";
import { resolutionState } from "@/services/adapter/index.uts";
import { computed } from "vue";
type Props = {
salesPropsUuid?: string
title?: string
......@@ -60,7 +63,7 @@ const salesUuid = computed(() => {
const val2 = props.salesPropsUuid;
return val1 !== null && val1 !== "" ? val1 : val2;
});
const windowHeight = computed(() => resolutionState.windowHeight);
// const employeeList = computed(() => {
// return state.user.employeeList
// })
......
......@@ -5,7 +5,7 @@
</template>
<script setup lang="uts">
import { resolutionState, useResolutionConfig } from "@/config/resolution-adapt/index.uts";
import { resolutionState, useResolutionConfig } from "@/services/adapter/index.uts";
// 在这里统一调用初始化,确保任何使用 Layout 的页面都能获得正确的配置
useResolutionConfig();
......
......@@ -380,7 +380,9 @@ async function findPayInfo(): Promise<void> {
paymentTypeList.value = paymentType;
}
onLoad((options) => {
recordService.startAudio();
if (recordService != null) {
recordService.startAudio();
}
dispatch("setCustomerInfo", {});
moduleList.value = [
{
......
......@@ -11,6 +11,7 @@ import { ref } from "vue";
import { LAYOUT_VARS } from "@/config/layout-vars.uts";
import { LAYOUT_MODES } from "@/config/layout.config.uts";
import { updateResolutionConfig } from "@/services/adapter/core.uts";
class LayoutService {
private cssVariables = ref<UTSJSONObject>({});
......@@ -38,6 +39,27 @@ class LayoutService {
}
/**
* 是否已初始化
*/
isInitialized(): boolean {
return this.initialized.value;
}
/**
* 获取屏幕宽度(响应式)
*/
getScreenWidth(): number {
return this.screenWidth.value;
}
/**
* 获取屏幕高度(响应式)
*/
getScreenHeight(): number {
return this.screenHeight.value;
}
/**
* 获取当前分辨率档位(例如 1080 / 1920)
* - 仅用于选择 I18n 适配配置,不追求特别细的区分
*/
......@@ -94,6 +116,8 @@ class LayoutService {
*/
refreshScreenInfo(): void {
this.updateScreenInfo();
// 重新计算分辨率适配配置
updateResolutionConfig();
const w = this.screenWidth.value;
const h = this.screenHeight.value;
console.log(`[LayoutService] refreshScreenInfo | w=${ w } h=${ h } | mode=${ this.currentMode.value } | ratio=${ this.scaleRatio.value.toFixed(3)}`);
......@@ -211,8 +235,22 @@ class LayoutService {
private updateScreenInfo(): void {
const systemInfo = uni.getSystemInfoSync();
// 使用 UTS 内置的 screenWidth/screenHeight,避免对 GetSystemInfoResult 进行不安全类型转换
this.screenWidth.value = systemInfo.screenWidth;
this.screenHeight.value = systemInfo.screenHeight;
const w = systemInfo.screenWidth;
const h = systemInfo.screenHeight;
// 如果获取到的值为 0,尝试使用 windowWidth/windowHeight
if (w == 0 || h == 0) {
const winInfo = uni.getWindowInfo();
if (w == 0 && winInfo.windowWidth > 0) {
this.screenWidth.value = winInfo.windowWidth;
}
if (h == 0 && winInfo.windowHeight > 0) {
this.screenHeight.value = winInfo.windowHeight;
}
} else {
this.screenWidth.value = w;
this.screenHeight.value = h;
}
this.currentMode.value = this.detectMode();
const baseWidth = this.getBaseWidth();
......
# 分辨率适配系统 (Resolution Adaptation System)
本系统旨在解决 UniApp x 在不同设备分辨率下的精确样式适配和资源加载问题。通过预定义的配置对象,根据设备实际分辨率自动加载对应的样式值和图片资源,支持横竖屏自动切换及兜底机制。
## 1. 核心机制
系统基于 **“配置对象 (Configuration Object)”** 模式:
1. **自动检测**:App 启动或窗口调整时,自动获取屏幕宽高。
2. **键值匹配**:生成如 `1024x768` 的 Key。
3. **智能加载**:
* 优先加载对应分辨率的专用配置(如 `landscape/1024x768`)。
* 未匹配则降级使用兜底配置(`landscape/common` 或 `portrait/common`)。
4. **响应式更新**:配置对象是 Vue Reactive 的,分辨率变化时页面自动更新。
## 2. 目录结构
配置文件位于 `config/resolution-adapt/`:
```text
config/resolution-adapt/
├── types/
│ └── index.uts # 【类型定义】定义所有页面配置的接口规范
├── index.uts # 【统一入口】聚合导出所有模块
├── core.uts # 【核心逻辑】updateResolutionConfig, getResponsiveImage
├── store.uts # 【状态管理】ResolutionState
├── adapter.uts # 【适配器】ResolutionAdapterImpl
├── hooks.uts # 【Hooks】useResponsiveImage
├── registry.uts # 【注册表】landscapeConfigs, portraitConfigs
├── landscape/ # 【横屏配置组】
│ ├── 1024x768/ # 特定分辨率目录
│ │ ├── demo.uts # Demo 页面专用配置
│ │ └── index.uts # 聚合导出
│ ├── 1920x1080/
│ └── common/ # 横屏兜底配置
└── portrait/ # 【竖屏配置组】
└── common/ # 竖屏兜底配置
```
## 3. 如何在页面中使用
### 3.1 页面模板 (Template)
使用全局组件 `<Layout>` 包裹页面内容,并使用全局属性 `$resState` 和 `$getResImg`。
```html
<template>
<!-- 必须使用 Layout 包裹,它会自动注入 CSS 类名 -->
<Layout>
<!-- 方式 A: 根类名切换 (CSS) -->
<!-- Layout 组件会自动在根元素加上如 layout-landscape-1920x1080 的类名 -->
<view class="content">
<text class="title">Hello World</text>
</view>
<!-- 方式 B: JS 动态样式 (Style Binding) -->
<view class="dynamic-box"
:style="{ paddingLeft: $resState.config.demo.paddingLeft }">
<!-- 动态图片:使用全局方法 $getResImg 自动选择 @2x/@3x 图片 -->
<image :src="$getResImg($resState.config.demo.heroImageSrc)"
:style="{ width: $resState.config.demo.heroImageWidth }"
mode="widthFix" />
</view>
</Layout>
</template>
<script setup lang="uts">
// 无需 import 任何分辨率适配相关的代码!
</script>
<style scoped lang="scss">
// 引入拆分后的样式文件
@import "./styles/common.scss";
@import "./styles/landscape.scss";
@import "./styles/portrait.scss";
</style>
```
### 3.2 样式文件编写 (SCSS)
在 `styles/landscape.scss` 中利用根类名进行覆盖:
```scss
/* styles/landscape.scss */
.layout {
/* 针对 1920x1080 的覆盖样式 */
&.layout-landscape-1920x1080 {
.title {
font-size: 48rpx;
color: red;
}
}
/* 兜底样式 */
&.layout-landscape-common {
.title {
font-size: 32rpx;
color: blue;
}
}
}
```
## 4. 开发指南
### 4.1 定义图片资源 (ResponsiveImage)
系统强制要求图片资源配置必须包含 `x1` 路径,可选 `x2`, `x3`。
```typescript
// types/index.uts
export type DemoPageConfig = {
heroImageSrc: ResponsiveImage // 使用 ResponsiveImage 类型
}
// landscape/common/demo.uts
heroImageSrc: {
x1: '/static/img/hero.png',
x2: '/static/img/hero@2x.png' // 编辑器会智能提示
}
```
### 4.2 添加新页面配置
假设要为 `Home` 页面添加适配:
1. **定义接口**:
在 `types/index.uts` 中添加 `HomePageConfig` 并注册到 `AppResolutionConfig`。
2. **实现配置**:
在 `landscape/common/`, `landscape/1024x768/` 等所有已注册的目录下创建 `home.uts`。
3. **导出配置**:
在各目录的 `index.uts` 中导出新页面。
### 4.3 支持新的分辨率
假设需要支持 `1280x800` 分辨率:
1. **创建目录**:新建 `config/resolution-adapt/landscape/1280x800/`。
2. **编写配置**:复制 `common` 下的文件到新目录并修改数值。
3. **注册分辨率**:
在 `config/resolution-adapt/registry.uts` 中注册新目录。
```typescript
// config/resolution-adapt/registry.uts
import { config as ls_1280 } from './landscape/1280x800/index.uts'
const landscapeConfigs = {
// ...
"1280x800": ls_1280 // 新增
} as UTSJSONObject
```
import { landscapeMap, portraitMap } from "./registry.uts";
import { AppResolutionConfig } from "./types/index.uts";
// ========================================================================
// 4. 适配器定义 (Adapter Definition)
// ========================================================================
export interface IResAdapter {
match(w: number, h: number): boolean
getConfig(key: string): AppResolutionConfig | null
getFallback(): AppResolutionConfig | null
getPrefix(): string
getCssClass(key: string): string
}
class ResolutionAdapterImpl implements IResAdapter {
private map: Map<string, AppResolutionConfig>;
private matcher: (w: number, h: number) => boolean;
private prefix: string;
constructor(prefix: string, map: Map<string, AppResolutionConfig>, matcher: (w: number, h: number) => boolean) {
this.prefix = prefix;
this.map = map;
this.matcher = matcher;
}
getConfig(key: string): AppResolutionConfig | null { return this.map.get(key); }
getCssClass(key: string): string {
// 生成 CSS 类名规则:layout-{prefix}-{width}x{height}
// 例如:layout-landscape-1920x1080
// 如果未匹配到具体分辨率,使用 layout-{prefix}-common
if (this.map.has(key)) {
return `layout-${this.prefix}-${key}`;
}
return `layout-${this.prefix}-common`;
}
getFallback(): AppResolutionConfig | null { return this.map.get("common"); }
getPrefix(): string { return this.prefix; }
match(w: number, h: number): boolean { return this.matcher(w, h); }
}
export const resolutionAdapters: IResAdapter[] = [
new ResolutionAdapterImpl("landscape", landscapeMap, (w, h) => w > h),
new ResolutionAdapterImpl("portrait", portraitMap, (w, h) => w <= h)
];
import { logger } from "@/services/logger/index.uts";
import { IResAdapter, resolutionAdapters } from "./adapter.uts";
import { initRegistry, isRegistryInitialized } from "./registry.uts";
import { resolutionState } from "./store.uts";
import { AppResolutionConfig, ResponsiveImage } from "./types/index.uts";
import { layoutService } from "@/services/LayoutService.uts";
// ========================================================================
// 5. 核心适配逻辑 (Core Logic)
// ========================================================================
export function updateResolutionConfig() {
console.log('[ResolutionAdapt] updateResolutionConfig 开始执行');
initRegistry();
// 确保 LayoutService 已初始化
if (!layoutService.isInitialized()) {
console.log('[ResolutionAdapt] LayoutService 未初始化,开始初始化');
layoutService.init();
} else {
console.log('[ResolutionAdapt] LayoutService 已初始化');
}
// 使用 LayoutService 获取屏幕信息
const w = layoutService.getScreenWidth();
const h = layoutService.getScreenHeight();
const pr = uni.getSystemInfoSync().pixelRatio;
console.log(`[ResolutionAdapt] 获取屏幕信息:w=${w}, h=${h}, pr=${pr}`);
if (w == 0 || h == 0) {
console.warn('[ResolutionAdapt] 屏幕尺寸为 0,跳过配置更新');
return;
}
const key = `${Math.round(w)}x${Math.round(h)}`;
// 使用适配器模式匹配
let adapter: IResAdapter | null = null;
for (const a of resolutionAdapters) {
if (a.match(w, h)) {
adapter = a;
break;
}
}
if (adapter === null) {
// 使用 logger 服务记录日志
logger.debug(`[ResolutionAdapt] 未找到适配器,跳过配置更新`);
return;
}
// 执行适配
let target = adapter.getConfig(key);
let usedKey = key;
if (target === null) {
target = adapter.getFallback();
usedKey = `${adapter.getPrefix()}/common`;
}
console.log('target', pr,w,h)
if (target !== null) {
resolutionState.config = target as AppResolutionConfig;
resolutionState.currentKey = usedKey;
// 更新 CSS 类名
resolutionState.cssClass = adapter.getCssClass(key);
resolutionState.pixelRatio = pr;
resolutionState.windowWidth = w;
resolutionState.windowHeight = h;
logger.info(`[ResolutionAdapt] Applied config: ${usedKey}, cssClass: ${resolutionState.cssClass}`);
}
}
// ========================================================================
// 5. 钩子函数 (Hooks)
// ========================================================================
export function useResolutionConfig() : AppResolutionConfig {
// 如果尚未初始化(比如在 App.uvue 之前调用),尝试初始化一次
if (!isRegistryInitialized) {
updateResolutionConfig();
}
return resolutionState.config;
}
/**
* 获取当前分辨率配置的 CSS 类名(响应式)
* @returns CSS 类名字符串
*/
export function useLayoutCssClass(): string {
return resolutionState.cssClass;
}
/**
* 根据当前设备的 pixelRatio 自动选择最佳图片
* @param img 响应式图片配置对象
* @returns 最佳图片路径
*/
export function getResponsiveImage(img: ResponsiveImage): string {
const pr = resolutionState.pixelRatio;
// 3x 屏优先找 x3 -> x2 -> x1
if (pr >= 3) {
if (img.x3 !== null) return img.x3;
if (img.x2 !== null) return img.x2;
}
// 2x 屏优先找 x2 -> x3 -> x1
if (pr >= 2) {
if (img.x2 !== null) return img.x2;
if (img.x3 !== null) return img.x3;
}
// 默认返回 1倍图
return img.x1;
}
import { getResponsiveImage } from "./core.uts";
import { ResponsiveImage } from "./types/index.uts";
/**
* 获取响应式图片处理函数
* 在 setup 中调用此 hook,返回一个可以直接在 template 中使用的函数
*/
export function useResponsiveImage() {
// 返回一个符合模板调用要求的 wrapper 函数
const getResImg = (img: ResponsiveImage): string => {
return getResponsiveImage(img);
};
return getResImg;
}
// 导出适配器
export { IResolutionAdapter, resolutionAdapters } from "./adapter.uts";
// 导出核心逻辑和工具函数
export { getResponsiveImage, updateResolutionConfig, useResolutionConfig } from "./core.uts";
// 导出 Hooks
export { useResponsiveImage } from "./hooks.uts";
// 导出注册表
export { initRegistry, landscapeMap, portraitMap } from "./registry.uts";
// 导出状态
export { resolutionState, ResolutionState } from "./store.uts";
// 导出类型
export * from "./types/index.uts";
import { DemoPageConfig, ResponsiveImage } from "../../types/index.uts";
export const demoConfig : DemoPageConfig = {
paddingLeft: "100rpx",
paddingRight: "100rpx",
heroImageWidth: "600px",
heroImageSrc: {
x1: "/static/images/landscape/1024/study-hero.png",
x2: "/static/images/landscape/1024/study-hero@2x.png"
} as ResponsiveImage,
titleFontSize: "80rpx"
};
import { AppResolutionConfig } from "../../types/index.uts";
import { demoConfig } from "./demo.uts";
export const config : AppResolutionConfig = {
demo: demoConfig
};
import { DemoPageConfig, ResponsiveImage } from "../../types/index.uts";
export const demoConfig : DemoPageConfig = {
paddingLeft: "150rpx",
paddingRight: "150rpx",
heroImageWidth: "800px",
heroImageSrc: {
x1: "/static/images/landscape/1920/study-hero.png",
x2: "/static/images/landscape/1920/study-hero@2x.png"
} as ResponsiveImage,
titleFontSize: "48rpx"
};
import { AppResolutionConfig } from "../../types/index.uts";
import { demoConfig } from "./demo.uts";
export const config : AppResolutionConfig = {
demo: demoConfig
};
import { DemoPageConfig, ResponsiveImage } from "../../types/index.uts";
export const demoConfig : DemoPageConfig = {
paddingLeft: "32rpx",
paddingRight: "32rpx",
heroImageWidth: "100%",
heroImageSrc: {
x1: "/static/images/common/study-hero.png",
x2: "/static/images/common/study-hero@2x.png"
} as ResponsiveImage,
titleFontSize: "32rpx"
};
import { AppResolutionConfig } from "../../types/index.uts";
import { demoConfig } from "./demo.uts";
export const config : AppResolutionConfig = {
demo: demoConfig
};
import { DemoPageConfig, ResponsiveImage } from "../../types/index.uts";
export const demoConfig : DemoPageConfig = {
paddingLeft: "24rpx",
paddingRight: "24rpx",
heroImageWidth: "100%",
heroImageSrc: {
x1: "/static/images/portrait/common/study-hero.png",
x2: "/static/images/portrait/common/study-hero@2x.png"
} as ResponsiveImage,
titleFontSize: "30rpx"
};
import { AppResolutionConfig } from "../../types/index.uts";
import { demoConfig } from "./demo.uts";
export const config : AppResolutionConfig = {
demo: demoConfig
};
// ========================================================================
// 1. 静态导入所有支持的分辨率配置 (Static Import)
// 新增分辨率时,请在此处导入并在 initRegistry 中注册
// ========================================================================
import { config as ls_1174 } from "./landscape/1174x768/index.uts";
import { config as ls_1920 } from "./landscape/1920x1080/index.uts";
// Landscape (横屏)
import { config as ls_common } from "./landscape/common/index.uts";
// Portrait (竖屏)
import { config as pt_common } from "./portrait/common/index.uts";
import { AppResolutionConfig } from "./types/index.uts";
// ========================================================================
// 2. 配置注册表 (Registry)
// ========================================================================
export const landscapeMap = new Map<string, AppResolutionConfig>();
export const portraitMap = new Map<string, AppResolutionConfig>();
// eslint-disable-next-line import/no-mutable-exports
let isRegistryInitialized = false;
// 定义配置映射表,方便统一管理和循环注册
const landscapeConfigs = {
"common": ls_common,
"1174x768": ls_1174,
"1920x1080": ls_1920
} as UTSJSONObject;
const portraitConfigs = {
"common": pt_common
// "768x1024": pt_768
} as UTSJSONObject;
export function initRegistry() {
if (isRegistryInitialized) return;
// 批量注册横屏配置
// UTS 遍历 JSONObject
for (const key in landscapeConfigs) {
const conf = landscapeConfigs[key] as AppResolutionConfig;
landscapeMap.set(key, conf);
}
// 批量注册竖屏配置
for (const key in portraitConfigs) {
const conf = portraitConfigs[key] as AppResolutionConfig;
portraitMap.set(key, conf);
}
isRegistryInitialized = true;
}
export { isRegistryInitialized };
import { reactive } from "vue";
import { config as ls_common } from "./landscape/common/index.uts";
import { AppResolutionConfig } from "./types/index.uts";
// ========================================================================
// 3. 全局状态 (Global State)
// ========================================================================
// 使用 reactive 包装,以便在 Vue 模板中自动更新
export type ResolutionState = {
config: AppResolutionConfig
cssClass: string // 新增:用于根元素的 CSS 类名
currentKey: string
pixelRatio: number
windowHeight: number
windowWidth: number
}
// 纯数据对象,不包含逻辑,避免循环依赖
export const resolutionState = reactive({
config: ls_common, // 初始默认值
currentKey: "init",
cssClass: "layout-default",
pixelRatio: 1,
windowWidth: 0,
windowHeight: 0
} as ResolutionState);
export type ResponsiveImage = {
x1: string
x2?: string // 可选
x3?: string // 可选
}
export type DemoPageConfig = {
heroImageSrc: ResponsiveImage
heroImageWidth: string
paddingLeft: string
paddingRight: string
titleFontSize: string
}
// 可以在这里添加其他页面的配置类型
// export type HomePageConfig = { ... }
export type AppResolutionConfig = {
demo: DemoPageConfig
// home: HomePageConfig
}
......@@ -136,7 +136,7 @@ export class Ws {
private async connectSocketByUrl(targetUrl: string): Promise<void> {
await new Promise<void>((resolve, reject) => {
services.logger.info(`WebSocket 连接地址: ${targetUrl}`, "Ws");
const task = uni.connectSocket({
url: targetUrl
});
......@@ -199,14 +199,16 @@ export class Ws {
private async createSocket(): Promise<void> {
await this.close(1000, "reconnect", false).catch((): void => {});
this.isManualClose = false;
const wsUrl = this.buildWsUrl(this.token, this.deviceId);
await this.connectSocketByUrl(wsUrl);
}
private async handleMessage(raw: any): Promise<void> {
services.logger.debug(`WebSocket 收到原始消息:${JSON.stringify(raw)}`, "Ws");
const payload = await this.normalizePayload(raw);
services.logger.debug(`WebSocket 解析后消息:${JSON.stringify(payload)}`, "Ws");
const errorCode = `${payload.errorCode ?? ""}`;
if (errorCode == "907") {
services.logger.warn("WebSocket token 过期,准备重连", "Ws");
......@@ -226,12 +228,16 @@ export class Ws {
this.liveLogService.stop();
}
} as WsCommandContext;
await this.router.handle(ctx, payload);
try {
await this.router.handle(ctx, payload);
} catch (error: any) {
services.logger.error(`WebSocket 路由处理失败:${JSON.stringify(error)} payload=${JSON.stringify(payload)}`, "Ws");
}
if (this.onMessage != null) {
try {
this.onMessage(payload);
} catch (error: any) {
services.logger.error(`WebSocket onMessage 回调执行异常: ${JSON.stringify(error)}`, "Ws");
services.logger.error(`WebSocket onMessage 回调执行异常:${JSON.stringify(error)}`, "Ws");
}
}
}
......@@ -242,17 +248,17 @@ export class Ws {
if (sn == "") {
throw new Error("未获取到设备 deviceId");
}
const loginUrl = this.loginAddress;
if (loginUrl == null || loginUrl == "") {
throw new Error("WebSocket 登录地址为空");
}
let lastErrorMessage: string = "";
for (let attempt = 1; attempt <= retryCount; attempt++) {
try {
services.logger.info(`WebSocket 登录第 ${attempt} 次尝试: ${sn} url=${loginUrl}`, "Ws");
const response = await new Promise<UTSJSONObject>((resolve, reject) => {
uni.request({
url: loginUrl,
......@@ -268,12 +274,12 @@ export class Ws {
}
});
});
const code = `${response.code ?? ""}`;
if (code == "200" || code == "0") {
return response;
}
const msg = `${response.message ?? response.msg ?? "未知错误"}`;
lastErrorMessage = `WebSocket 登录失败(${msg}),url=${loginUrl},response=${JSON.stringify(response)}`;
services.logger.warn(`WebSocket 登录返回失败 code=${code} msg=${msg} url=${loginUrl}`, "Ws");
......@@ -281,7 +287,7 @@ export class Ws {
lastErrorMessage = `WebSocket 登录请求异常,url=${loginUrl},error=${JSON.stringify(error)}`;
services.logger.warn(`WebSocket 登录请求异常 url=${loginUrl} error=${JSON.stringify(error)}`, "Ws");
}
if (attempt < retryCount) {
services.logger.warn(`WebSocket 登录失败,${retryDelay}ms 后重试,attempt=${attempt}`, "Ws");
await new Promise<void>((resolve) => {
......@@ -289,7 +295,7 @@ export class Ws {
});
}
}
if (lastErrorMessage != "") {
throw new Error(lastErrorMessage);
}
......@@ -300,9 +306,9 @@ export class Ws {
if (raw == null) {
return { command: "message", data: null } as UTSJSONObject;
}
let parsed: UTSJSONObject;
if (typeof raw === "string") {
try {
parsed = JSON.parse(raw) as UTSJSONObject;
......@@ -317,15 +323,15 @@ export class Ws {
return { command: "message", raw: `${raw}` } as UTSJSONObject;
}
}
// 处理服务端格式: { event: "private", data: { command: "xxx", ... } }
// 处理服务端格式:{ event: "private", data: { command: "xxx", ... } }
if (parsed.event != null && parsed.data != null) {
const data = parsed.data as UTSJSONObject;
// 直接返回 data 部分,这里包含 command
return data;
}
// 处理包装格式: { code: 200, data: { event: "private", data: { command: "xxx" } } }
// 处理包装格式:{ code: 200, data: { event: "private", data: { command: "xxx" } } }
if (parsed.code != null && parsed.data != null) {
const outerData = parsed.data as UTSJSONObject;
if (outerData.data != null) {
......@@ -334,7 +340,8 @@ export class Ws {
}
return outerData;
}
// 如果没有任何特殊字段,直接返回解析后的对象
return parsed;
}
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!