chore: 初始化仓库基线(AGENTS.md、git 规范、敏感文件排除)

This commit is contained in:
weijuesen
2026-08-10 22:30:53 +08:00
commit 84abf4454c
358 changed files with 75993 additions and 0 deletions
+49
View File
@@ -0,0 +1,49 @@
tools/apache-iotdb-2.0.8-all-bin.zip
web/node_modules
server/node_modules
tools/simulator/node_modules
tools/s3-test/node_modules
node_modules/
*.sh
# IoTDB runtime data
tools/iotdb/apache-iotdb-2.0.8-all-bin/data/
tools/iotdb/apache-iotdb-2.0.8-all-bin/logs/
# AIO shim (no longer needed on WSL2)
libaio_shim.c
aio_version.map
# Python
__pycache__/
*.pyc
# Environment
.env
#故障排查处理记录.md
#变更记录.md
.trae/
/wvp/*.sh
*.sh
*.ps1
*.py
*.sql
#故障排查处理记录(微信小程序).md
app/android/.gradle/
app/android/build/
app/node_modules/
tools/
server-go/silk-server-go-linux
server-go/server-go-linux
优化.md
app/android/app/build/
/*.txt
# 本地敏感文件与工具目录(勿提交)
silk-db-backup.dump
wvp/server.env
zlm_remote.json
zlm_config.json
.pai/
.codegraph/
app/android/local.properties
+61
View File
@@ -0,0 +1,61 @@
# AGENTS
## 沟通规则
1. 先说明结论,再说明影响和后续操作。
2. 除非项目约定另有要求,否则使用用户偏好的语言。
3. 交付说明应聚焦于修改的文件、验证结果和风险。
4. 对不清楚的需求或不可逆选择,执行前先向用户确认。
5. 创建或重写本指令文件前,询问用户该文件应使用哪种语言。
## 项目结构
本仓库是「智慧蚕房环境监测与智能调控系统」多模块 monorepo,各目录职责边界如下:
1. `server-go/` — Go 后端(Go 1.23Gin + GORM),入口为 `cmd/server/main.go`;提供 REST API(默认 :3000)、WebSocket `/ws`、视频代理 `/live/proxy`;消费 MQTT 遥测并处理阈值告警、设备控制、RBAC;依赖 PostgreSQL、IoTDB、Valkey/Redis、Ceph S3、WVP/ZLM、recorder-go。
2. `web/` — Web 后台前端(Vite + React + TypeScript + Ant Design),开发端口 5173`/api` 代理到后端 :3000。
3. `app/` — React Native 移动端(RN 0.74),后端地址通过 `.env` 配置(参考 `.env.example``API_BASE_URL`)。
4. `miniapp/` — 微信小程序(Taro 4 + React + TypeScript + Sass);`project.config.json``miniprogramRoot` 指向 `dist/`,该目录是 Taro 构建产物,不得手改。
5. `wvp/` — WVP-PRO + ZLMediaKit 视频平台(`docker-compose.yml` 包含 WVP、ZLMediaKit、MySQL、Redis),并含 `recorder-go`(Go 连续录制服务,默认 :9090)与 Dockerfile。
6. 根目录文档 — `README.md``部署指南(物理机).md``变更记录.md``故障排查处理记录.md``物联网设备接口和数据格式.md` 等为项目说明与部署运维依据。
生成文件及其来源命令:
1. `miniapp/dist/` — 由 `npm run dev:weapp` / `npm run build:weapp` 生成。
2. `web/dist/` — 由 `npm run build` 生成。
3. `app/android/app/build/outputs/apk/release/app-release.apk` — 由 `cd android && gradlew assembleRelease` 生成。
4. `server-go/server-go-linux` — 由 `go build -o server-go-linux ./cmd/server` 交叉编译生成。
## 编码规则
1. 遵循现有命名、分层、错误处理和格式化约定。
2. 将修改范围限制在用户请求的任务内。
3. 不得覆盖用户无关的已有修改。
4. 不得猜测或编造缺失的需求、事实、约定或技术决策。
5. 根据用户明确输入、仓库文件、配置、文档或命令输出验证相关结论。
6. 如果相关细节不确定、有歧义、存在冲突或无法验证,必须停止并先向用户确认,再继续操作。
7. 不得手改生成产物(如 `miniapp/dist/``web/dist/`、编译后的 APK、`server-go-linux`);需要改动时先修改源文件或源 schema,再重新生成。
## 安装与配置
1. 后端:`cd server-go && go build -o server-go-linux ./cmd/server`;开发运行用 `go run ./cmd/server`。必需环境变量以 README「Go 后端环境变量」为准:`PG``REDIS``JWT_SECRET``JWT_EXPIRES_IN``MQTT``IOTDB_URL``WVP_API_BASE``ZLM_API_BASE``RECORDER_API_BASE``S3_ENDPOINT``S3_ACCESS_KEY``S3_SECRET_KEY``S3_BUCKET``PORT``DEFAULT_ADMIN_USERNAME``DEFAULT_ADMIN_PASSWORD`
2. Web 前端:`cd web && npm install && npm run dev`;生产构建 `npm run build`
3. React Native APP`cd app && npm install`,按 `app/.env.example` 配置 `API_BASE_URL`,然后 `npm start` / `npm run android`
4. 微信小程序:`cd miniapp && npm install && npm run dev:weapp`;生产构建 `npm run build:weapp`,产物输出到 `dist/`
5. WVP 视频平台:`cd wvp && docker compose up -d`
6. 选择未明确指定的技术栈、包管理器、数据库、运行时、部署目标或外部服务前,必须先获得用户确认。
7. 初始化项目时,如果技术栈尚未明确,应先让用户选择技术栈,再创建项目文件。
8. 不得将密钥写入需要提交的文件;需要环境配置时使用占位值创建 `.env.example`
## 验证
1. 常规修改的针对性检查:Go 后端 `go build ./...`Web `npm run lint``npm run build`APP `npm run lint``npm run tsc`;小程序 `npm run build:weapp`
2. 共享行为修改或发布工作执行更广泛检查:后端 `go test ./...``go vet ./...`,前端构建产物可用性检查。
3. 如果检查无法运行(缺少依赖、网络受限等),必须清楚报告确切命令和失败原因。
## 代码审查
1. 审查修改的正确性、回归风险、安全性、可维护性和测试覆盖率。
2. 按严重程度排列审查发现,并尽可能提供文件和行号引用。
3. 具体问题优先于总结;如果没有发现问题,应明确说明。
4. 指出影响发布风险的未验证行为、缺失测试或尚未解决的不确定项。
+493
View File
@@ -0,0 +1,493 @@
# 智慧蚕房环境监测与智能调控系统
面向养蚕场景的环境实时监测、告警通知、设备联动控制与视频监控平台。系统通过 MQTT 接收蚕房传感器/网关上报的温度、湿度、光照、CO₂ 等环境参数,支持阈值配置、异常告警、设备控制、GB28181 视频监控、连续录制与历史回放、RBAC 权限管理与审计日志。
系统提供 **Web 后台**、**React Native 移动端 APP**、**微信小程序** 三端界面,后端统一由 **Go 服务**提供 API。
## 1. 核心能力
### 1.1 环境实时监测
- 通过 MQTT 订阅遥测 Topic,接收设备上报数据
- 支持温度、湿度、光照、CO₂ 等指标
- 遥测数据优先写入 Apache IoTDBIoTDB 不可用时降级写入 PostgreSQL
- 后端提供遥测列表、设备最新值、指标列表、历史聚合趋势 API
- 设备离线检测:5 分钟无数据自动标记离线,下发 info 命令作心跳唤醒
### 1.2 阈值配置与告警
- 支持按传感器配置上下限阈值、严重等级和防抖时间
- MQTT 入站遥测自动匹配设备、传感器和阈值规则
- 超限触发告警事件,恢复正常后发送恢复事件
- 支持告警列表、详情、确认、解除及告警关联视频片段查询
### 1.3 设备控制
- 支持单设备控制和批量控制,命令通过 MQTT 下行 Topic 发布
- 默认下行 Topic 格式:`silk/{deviceKey}/down/cmd`
- 支持红外设备控制(短连接、命令驱动型,需下发命令触发响应)
- 红外设备主题持久化存储,防止后端重启丢失
### 1.4 视频监控(GB28181
- 基于 WVP-PRO + ZLMediaKit 实现 GB28181 摄像头注册与信令控制
- 摄像头配置管理(GB 设备 ID、通道 ID、流地址)
- 实时点播:摄像头 → ZLMediaKit → FLV 流 → Web/APP/小程序播放
- Go 后端 `/live/proxy` 接口直接代理 ZLM FLV 流,解决移动端跨域问题
- 连续录制:`recorder-go` 拉取 ZLM FLV 流,按 5 分钟分段落 Ceph S3
- 历史回看:按日期查询录像片段,支持播放、下载
- 设备状态同步:后端每 30 秒查询 WVP 设备在线状态
### 1.5 RBAC 权限管理
- 4 个角色:`admin`(管理员)、`operator`(操作员)、`viewer`(查看者)、`farmer`(养殖员)
- 15 个权限码:涵盖看板、蚕房、设备、阈值、告警、视频、能耗、日志、用户、审计
- 后端 `RequirePermission` 中间件校验权限码,admin 自动放行
- 前端路由守卫 + 菜单动态过滤 + `<HasPermission>` 按钮级控制
- 新用户注册默认角色为 `viewer`
### 1.6 通知与实时推送
- WebSocket 网关位于 `/ws`,使用 JWT 鉴权
- 广播事件:`telemetry.all``telemetry``alarm``alarm.recovery`
- Web/APP/小程序均接入 WebSocket 实时订阅
- 登录后自动连接 WebSocket,登出自动断开
### 1.7 能耗管理
- 设备能耗数据采集与统计
- 能耗趋势图表展示
## 2. 技术架构
```text
┌──────────────┐ MQTT ┌──────────────┐
│ 传感器/模拟器 │ ───────────────▶ │ VerneMQ:1883 │
└──────────────┘ └──────┬───────┘
┌─────────────────────┼─────────────────────┐
▼ ▼ ▼
┌────────────────┐ ┌──────────────────┐ ┌──────────────┐
│ Go 后端 :3000 │ │ recorder-go :9090 │ │ WVP :18080 │
│ (Gin + GORM) │ │ (连续录制服务) │ │ ZLM :8081 │
└───┬────┬───┬───┘ └────────┬─────────┘ └──────┬───────┘
│ │ │ │ │
┌───────┘ │ └──────┐ │ │
▼ ▼ ▼ ▼ ▼
PostgreSQL IoTDB Valkey Ceph S3 GB28181 摄像头
:5432 :18081 :6379 :7480
业务数据 时序遥测 缓存/通知 录像存储
┌────────────┼────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────────┐
│ Web 后台 │ │ 安卓 APP │ │ 微信小程序 │
│ React │ │ RN 0.74 │ │ Taro │
│ :5174 │ │ │ │ │
└──────────┘ └──────────┘ └──────────────┘
```
## 3. 技术栈
| 层级 | 技术 |
|---|---|
| Go 后端 | Go 1.22+、Gin、GORM、JWT、slog、WebSocket |
| 录制服务 | Go、AWS SDK v2S3)、HTTP 拉流 |
| Web 前端 | React 18、Vite、Ant Design、Ant Design Pro、Axios、ECharts |
| 移动端 APP | React Native 0.74、React Navigation、React Native Paper、Zustand |
| 微信小程序 | Taro 4、React、TypeScript、SCSS |
| 业务数据库 | PostgreSQL 16 |
| 时序数据库 | Apache IoTDB 2.0.8REST API |
| 缓存/通知 | ValkeyRedis 兼容) |
| 设备通信 | VerneMQMQTT 3.1.1 |
| 视频流媒体 | WVP-PRO 2.7.4、ZLMediaKitGB28181 |
| 对象存储 | Ceph RGWS3 兼容) |
| 编译工具 | Go(交叉编译 Linux amd64 |
## 4. 目录结构
```text
silk/
├─ server-go/ # Go 后端服务(端口 3000)
│ ├─ cmd/server/main.go # 入口
│ ├─ internal/
│ │ ├─ config/ # 环境变量配置
│ │ ├─ database/ # GORM 数据库连接与自动迁移
│ │ ├─ handler/ # HTTP handlerauth/device/alarm/video 等)
│ │ ├─ middleware/ # JWT 鉴权、RBAC 权限、CORS、限流、安全头
│ │ ├─ model/ # GORM 数据模型 + 权限种子数据
│ │ ├─ service/ # MQTT、IoTDB、S3、Media、Transcode 服务
│ │ └─ ws/ # WebSocket 网关
│ ├─ go.mod
│ └─ start.sh # 服务器启动脚本
├─ wvp/
│ ├─ recorder-go/ # Go 录制服务(端口 9090)
│ │ ├─ main.go # 拉流录制 + S3 上传
│ │ └─ go.mod
│ ├─ docker-compose.yml # WVP + ZLMediaKit + MySQL + Redis 容器
│ └─ server.env # WVP 配置
├─ web/ # React Web 后台(端口 5174
│ ├─ src/
│ │ ├─ pages/ # 登录、仪表盘、蚕房、设备、控制、红外、
│ │ │ # 阈值、告警、视频、能耗、日志
│ │ ├─ components/ # HasPermission、StatCard、VideoPlayer
│ │ ├─ dal/ # 数据访问层
│ │ ├─ api/http.ts # Axios 实例与 JWT 注入
│ │ ├─ layout/BasicLayout.tsx # 布局 + 菜单权限过滤
│ │ └─ router.tsx # 路由守卫 + 权限控制
│ ├─ server.cjs # 生产环境静态服务 + API 代理
│ └─ vite.config.ts
├─ app/ # React Native 移动端 APP
│ ├─ src/
│ │ ├─ api/ # API 客户端(auth/device/alarm/video 等)
│ │ ├─ screens/ # 登录、仪表盘、蚕房、设备、告警、视频、设置
│ │ ├─ navigation/ # 底部 Tab 导航
│ │ ├─ store/ # Zustand 状态管理(auth + app
│ │ ├─ components/ # StatCard、MiniChart
│ │ └─ utils/ # WebSocket、格式化
│ ├─ android/ # Android 原生工程
│ ├─ .env # API_BASE_URL 配置
│ └─ package.json
├─ miniapp/ # 微信小程序(Taro)
│ ├─ src/
│ │ ├─ pages/ # 登录、仪表盘、蚕房、设备、告警、视频、设置
│ │ ├─ api/ # API 客户端
│ │ ├─ store/ # Zustand 状态管理
│ │ ├─ components/ # StatCard、MiniChart
│ │ └─ app.config.ts # 小程序配置(页面、TabBar)
│ └─ package.json
├─ tools/
│ ├─ simulator/ # MQTT 设备模拟器
│ └─ iotdb/ # 本地 Apache IoTDB 部署
├─ 变更记录.md # 项目变更记录
├─ 故障排查处理记录.md # 故障排查与处理记录
├─ 部署指南(物理机).md # 服务器部署指南
└─ 物联网设备接口和数据格式.md # 设备接口文档
```
## 5. 后端模块
| 模块 | 路径 | 功能 |
|---|---|---|
| Auth | `handler/auth.go` | 注册、登录、JWT、修改密码 |
| Users | `handler/user.go` | 用户管理(权限码 `user:manage` |
| Rooms | `handler/room.go` | 蚕房增删改查 |
| Devices | `handler/device.go` | 设备增删改查、状态同步 |
| Sensors | `handler/sensor.go` | 传感器增删改查 |
| Thresholds | `handler/threshold.go` | 阈值规则配置 |
| Telemetry | `handler/telemetry.go` | 遥测列表、指标、最新值、历史趋势 |
| Alarms | `handler/alarm.go` | 告警生成、确认、解除、查询 |
| AlarmClip | `handler/alarm_clip.go` | 告警关联视频片段 |
| Control | `handler/control.go` | MQTT 控制命令下发 |
| Notification | `handler/notification.go` | Redis 站内通知 |
| Video Camera | `handler/video_camera.go` | 摄像头管理、WVP 状态同步 |
| Video Stream | `handler/video_stream.go` | 实时点播、FLV 代理 |
| Video Record | `handler/video_record.go` | 录制启停、活跃录制查询 |
| Video Clip | `handler/video_clip.go` | 历史录像片段查询、播放、下载 |
| Storage | `handler/storage.go` | S3 存储管理 |
| Permission | `handler/permission.go` | 权限码查询、角色权限查询 |
| Audit | `handler/audit.go` | 审计日志(权限码 `audit:read` |
| Health | `handler/health.go` | PostgreSQL、Redis、IoTDB 健康检查 |
| WebSocket | `ws/gateway.go` | `/ws` 实时通道,广播遥测与告警 |
## 6. 前端页面
### 6.1 Web 后台
| 路由 | 页面 | 权限码 |
|---|---|---|
| `/login` | 登录 | - |
| `/dashboard` | 仪表盘 | `dashboard:view` |
| `/houses` | 蚕房管理 | `room:read` |
| `/devices` | 设备管理 | `device:read` |
| `/energy` | 能耗管理 | `energy:view` |
| `/control` | 设备控制 | `device:control` |
| `/ir` | 红外遥控 | `device:control` |
| `/thresholds` | 阈值配置 | `threshold:read` |
| `/alerts` | 告警中心 | `alarm:read` |
| `/videos` | 视频监控 | `video:read` |
| `/logs` | 控制日志 | `log:read` |
### 6.2 移动端 APP / 微信小程序
底部 Tab:仪表盘、蚕房、设备、告警、视频
| 页面 | 功能 |
|---|---|
| 登录 | 用户登录,JWT 持久化 |
| 仪表盘 | 环境概览、趋势图、告警概况 |
| 蚕房 | 蚕房列表与详情 |
| 设备 | 设备列表、状态、控制命令下发 |
| 告警 | 告警列表、确认、解除 |
| 视频 | 摄像头列表、实时播放、历史回看 |
| 设置 | 用户信息、服务器配置、退出登录 |
## 7. 主要 API
后端地址:`http://<服务器IP>:3000/api/v1`
鉴权:除 `GET /health``POST /auth/login``POST /auth/register` 外,所有接口需 JWT
```text
Authorization: Bearer <accessToken>
```
| API | 说明 |
|---|---|
| `GET /health` | 健康检查 |
| `POST /auth/register` | 用户注册(默认 viewer |
| `POST /auth/login` | 用户登录 |
| `GET /auth/me` | 当前用户信息与权限 |
| `GET /permissions` | 全部权限码列表 |
| `GET /permissions/roles` | 角色及权限映射 |
| `GET /users` | 用户列表(`user:manage` |
| `GET /rooms` / `POST /rooms` / `PATCH /rooms/:id` / `DELETE /rooms/:id` | 蚕房管理 |
| `GET /devices` / `POST /devices` / `PATCH /devices/:id` | 设备管理 |
| `GET /sensors` / `POST /sensors` / `PATCH /sensors/:id` | 传感器管理 |
| `GET /thresholds` / `POST /thresholds` / `PATCH /thresholds/:id` | 阈值管理 |
| `GET /telemetry` | 遥测数据列表 |
| `GET /telemetry/:deviceKey/latest` | 设备最新遥测 |
| `GET /telemetry/:deviceKey/metrics` | 设备可用指标 |
| `GET /telemetry/:deviceKey/:metric/history` | 历史聚合趋势 |
| `GET /alarms` / `GET /alarms/:id` | 告警列表/详情 |
| `POST /alarms/:id/ack` | 确认告警(`alarm:ack` |
| `POST /alarms/:id/resolve` | 解除告警(`alarm:ack` |
| `POST /control/send` | 单设备控制(`device:control` |
| `POST /control/batch` | 批量控制(`device:control` |
| `GET /video/cameras` / `POST /video/cameras` | 摄像头列表/新增 |
| `GET /video/cameras/:id/live/proxy` | 实时 FLV 流代理 |
| `GET /video/cameras/:id/playback` | 历史录像片段查询 |
| `POST /video/cameras/:id/record/start` | 启动录制(`video:record` |
| `POST /video/cameras/:id/record/stop` | 停止录制(`video:record` |
| `GET /video/recordings/active` | 活跃录制列表 |
| `GET /notifications` | 站内通知列表 |
| `GET /audit-logs` | 审计日志(`audit:read` |
## 8. 权限矩阵
| 权限码 | 说明 | admin | operator | viewer | farmer |
|---|---|:---:|:---:|:---:|:---:|
| `dashboard:view` | 看板查看 | ✓ | ✓ | ✓ | ✓ |
| `room:read` | 蚕房查看 | ✓ | ✓ | ✓ | ✓ |
| `room:write` | 蚕房管理 | ✓ | ✓ | - | - |
| `device:read` | 设备查看 | ✓ | ✓ | ✓ | ✓ |
| `device:control` | 设备控制 | ✓ | ✓ | - | ✓ |
| `threshold:read` | 阈值查看 | ✓ | ✓ | ✓ | - |
| `threshold:write` | 阈值管理 | ✓ | ✓ | - | - |
| `alarm:read` | 告警查看 | ✓ | ✓ | ✓ | ✓ |
| `alarm:ack` | 告警确认 | ✓ | ✓ | - | ✓ |
| `video:read` | 视频查看 | ✓ | ✓ | ✓ | ✓ |
| `video:record` | 视频录制 | ✓ | ✓ | - | - |
| `energy:view` | 能耗查看 | ✓ | ✓ | ✓ | ✓ |
| `log:read` | 日志查看 | ✓ | ✓ | - | - |
| `user:manage` | 用户管理 | ✓ | - | - | - |
| `audit:read` | 审计查看 | ✓ | - | - | - |
## 9. MQTT 接口
### 9.1 遥测上行
订阅 Topic`silk/+/+/+/up/telemetry`
Payload 示例:
```json
{
"msgId": "msg-1782833925818-1",
"ts": 1782833925818,
"metrics": {
"temperature": 26.8,
"humidity": 75.2,
"lux": 320,
"co2": 820
}
}
```
### 9.2 控制下行
下行 Topic`silk/{deviceKey}/down/cmd`
Payload 示例:
```json
{
"action": "on",
"value": true,
"ts": "2026-06-30T10:00:00.000Z"
}
```
## 10. 数据存储
### 10.1 PostgreSQL(业务数据)
保存用户、蚕房、设备、传感器、阈值、告警、摄像头、录像片段、审计日志、权限等业务数据。GORM 自动迁移建表,系统启动时自动初始化权限种子数据。
```env
PG=postgresql://postgres:pan@localhost:5432/silk
```
### 10.2 Apache IoTDB(时序遥测)
保存高频时序遥测数据,后端通过 REST API 写入和查询。
```env
IOTDB_URL=http://localhost:18081
```
IoTDB 路径示例:`root.silk.telemetry.`sensor-001`.temperature`
### 10.3 Valkey/Redis(缓存与通知)
用于权限缓存(5 分钟有效期)、站内通知列表。
### 10.4 Ceph S3(录像存储)
录制片段按 5 分钟分段,每段独立 S3 对象 + DB 记录。
```env
S3_ENDPOINT=http://100.83.103.1:7480
S3_ACCESS_KEY=silk-app
S3_SECRET_KEY=Silk-App-Secret-2026!
S3_BUCKET=silk-video-events
```
## 11. 服务器部署
详细部署流程参见 [部署指南(物理机).md](部署指南(物理机).md)。
### 11.1 服务架构
```text
服务器 (100.83.103.1)
├── Go 后端 :3000 API 后端 (Gin)
├── 前端静态服务 :5174 Node.js server.cjs
├── Go 录制服务 :9090 recorder-go
├── PostgreSQL 16 :5432 业务数据库
├── IoTDB 2.0.8 :18081 时序数据库
├── Valkey :6379 缓存
├── VerneMQ :1883 MQTT broker
├── Ceph RGW :7480 S3 对象存储
└── Docker
├── WVP :18080 GB28181 信令
├── ZLMediaKit :8081 流媒体
├── MySQL :3306 WVP 数据库
└── Redis :6379 WVP 缓存
```
### 11.2 Go 后端编译部署
```powershell
# 交叉编译
cd e:\silk\server-go
$env:GOOS="linux"; $env:GOARCH="amd64"
go build -o server-go-linux ./cmd/server
$env:GOOS=""; $env:GOARCH=""
# 上传 + 启动(使用 sshpass + ConnectTimeout 避免卡死)
C:\msys64\usr\bin\sshpass.exe -p "pan" C:\msys64\usr\bin\scp.exe -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -o ConnectTimeout=10 e:\silk\server-go\server-go-linux pan@100.83.103.1:/home/pan/silk/server-go/
C:\msys64\usr\bin\sshpass.exe -p "pan" C:\msys64\usr\bin\ssh.exe -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -o ConnectTimeout=10 pan@100.83.103.1 "fuser -n tcp -k 3000 2>/dev/null; sleep 1; chmod +x /home/pan/silk/server-go/server-go-linux; setsid bash /home/pan/silk/server-go/start.sh </dev/null >/home/pan/silk/server-go/server-go.log 2>&1 &"
```
### 11.3 Go 后端环境变量
| 变量 | 默认值 | 说明 |
|------|--------|------|
| `PG` | `postgresql://postgres:pan@localhost:5432/silk` | PostgreSQL 连接串 |
| `REDIS` | `redis://:pan@localhost:6379` | Valkey/Redis 连接串 |
| `JWT_SECRET` | `silk-secret-please-change-me` | JWT 签名密钥 |
| `JWT_EXPIRES_IN` | `2h` | JWT 有效期 |
| `MQTT` | `mqtt://pan:pan@localhost:1883` | MQTT 连接串 |
| `IOTDB_URL` | `http://127.0.0.1:18081` | IoTDB REST API |
| `WVP_API_BASE` | `http://localhost:18978` | WVP API 地址(生产应为 18080 |
| `ZLM_API_BASE` | `http://100.83.103.1:8081` | ZLMediaKit API |
| `RECORDER_API_BASE` | `http://localhost:9090` | 录制服务地址 |
| `S3_ENDPOINT` | `http://100.83.103.1:7480` | Ceph S3 端点 |
| `S3_ACCESS_KEY` | `silk-app` | S3 Access Key |
| `S3_SECRET_KEY` | `Silk-App-Secret-2026!` | S3 Secret Key |
| `S3_BUCKET` | `silk-video-events` | S3 Bucket |
| `PORT` | `3000` | 监听端口 |
| `DEFAULT_ADMIN_USERNAME` | `admin` | 默认管理员 |
| `DEFAULT_ADMIN_PASSWORD` | `silk@123` | 默认密码 |
## 12. 本地开发
### 12.1 Web 前端
```powershell
cd e:\silk\web
npm install
npm run dev # 开发模式,端口 5173,代理 /api 到 :3000
npm run build # 生产构建
```
### 12.2 React Native APP
```powershell
cd e:\silk\app
npm install
# 配置后端地址(.env 文件)
# API_BASE_URL=http://<服务器IP>:3000/api/v1
# 启动 Metro
npx react-native start
# 编译安装 Debug APK
npx react-native run-android
# 编译 Release APK
cd android
.\gradlew.bat assembleRelease
# 输出:android/app/build/outputs/apk/release/app-release.apk
```
### 12.3 微信小程序
```powershell
cd e:\silk\miniapp
npm install
npm run dev:weapp # 微信小程序开发模式
npm run build:weapp # 生产构建
npm run dev:h5 # H5 开发模式
npm run build:h5 # H5 生产构建
```
### 12.4 设备模拟器
```powershell
cd e:\silk\tools\simulator
npm install
npm run start
```
### 12.5 默认管理员
```text
用户名:admin
密码:silk@123
```
## 13. Git 注意事项
不要提交依赖目录和本地运行产物。`.gitignore` 应包含:
```gitignore
node_modules/
dist/
*.log
.env
server-go-linux
recorder-go-linux
*.apk
android/app/build/
ios/Pods/
```
如误将 `node_modules` 加入索引:
```powershell
git rm -r --cached server-go web app miniapp tools/simulator
```
+4
View File
@@ -0,0 +1,4 @@
# API base URL (use 10.0.2.2 for Android emulator to reach host localhost, use localhost for iOS)
API_BASE_URL=http://10.0.2.2:3000/api/v1
# WebSocket base URL
WS_BASE_URL=ws://10.0.2.2:3000/ws
+1
View File
@@ -0,0 +1 @@
{}
+12
View File
@@ -0,0 +1,12 @@
import React from 'react';
import { StatusBar } from 'react-native';
import AppNavigator from './src/navigation/AppNavigator';
export default function App() {
return (
<>
<StatusBar barStyle="dark-content" backgroundColor="#FAFAFA" />
<AppNavigator />
</>
);
}
+9
View File
@@ -0,0 +1,9 @@
source 'https://rubygems.org'
# You may use http://rbenv.org/ or https://rvm.io/ to install and use this version
ruby ">= 2.6.10"
# Cocoapods 1.15 introduced a bug which break the build. We will remove the upper
# bound in the template on Cocoapods with next React Native release.
gem 'cocoapods', '>= 1.13', '< 1.15'
gem 'activesupport', '>= 6.1.7.5', '< 7.1.0'
+127
View File
@@ -0,0 +1,127 @@
apply plugin: "com.android.application"
apply plugin: "org.jetbrains.kotlin.android"
apply plugin: "com.facebook.react"
// Force media3 to a version compatible with compileSdk 34
configurations.all {
resolutionStrategy.eachDependency { details ->
if (details.requested.group == 'androidx.media3') {
details.useVersion '1.4.1'
}
}
}
/**
* This is the configuration block to customize your React Native Android app.
* By default you don't need to apply any configuration, just uncomment the lines you need.
*/
react {
/* Folders */
// The root of your project, i.e. where "package.json" lives. Default is '..'
// root = file("../")
// The folder where the react-native NPM package is. Default is ../node_modules/react-native
// reactNativeDir = file("../node_modules/react-native")
// The folder where the react-native Codegen package is. Default is ../node_modules/@react-native/codegen
// codegenDir = file("../node_modules/@react-native/codegen")
// The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js
// cliFile = file("../node_modules/react-native/cli.js")
/* Variants */
// The list of variants to that are debuggable. For those we're going to
// skip the bundling of the JS bundle and the assets. By default is just 'debug'.
// If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
// debuggableVariants = ["liteDebug", "prodDebug"]
/* Bundling */
// A list containing the node command and its flags. Default is just 'node'.
// nodeExecutableAndArgs = ["node"]
//
// The command to run when bundling. By default is 'bundle'
// bundleCommand = "ram-bundle"
//
// The path to the CLI configuration file. Default is empty.
// bundleConfig = file(../rn-cli.config.js)
//
// The name of the generated asset file containing your JS bundle
// bundleAssetName = "MyApplication.android.bundle"
//
// The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
// entryFile = file("../js/MyApplication.android.js")
//
// A list of extra flags to pass to the 'bundle' commands.
// See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
// extraPackagerArgs = []
/* Hermes Commands */
// The hermes compiler command to run. By default it is 'hermesc'
// hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
//
// The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
// hermesFlags = ["-O", "-output-source-map"]
}
/**
* Set this to true to Run Proguard on Release builds to minify the Java bytecode.
*/
def enableProguardInReleaseBuilds = false
/**
* The preferred build flavor of JavaScriptCore (JSC)
*
* For example, to use the international variant, you can use:
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'org.webkit:android-jsc:+'
android {
ndkVersion rootProject.ext.ndkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
compileSdk rootProject.ext.compileSdkVersion
namespace "com.silkmonitor"
defaultConfig {
applicationId "com.silkmonitor"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://reactnative.dev/docs/signed-apk-android.
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
}
dependencies {
// The version of react-native is set by the React Native Gradle Plugin
implementation("com.facebook.react:react-android")
if (hermesEnabled.toBoolean()) {
implementation("com.facebook.react:hermes-android")
} else {
implementation jscFlavor
}
}
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
Binary file not shown.
+10
View File
@@ -0,0 +1,10 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:usesCleartextTraffic="true"
tools:targetApi="28"
tools:ignore="GoogleAppIndexingWarning"/>
</manifest>
@@ -0,0 +1,26 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:allowBackup="false"
android:usesCleartextTraffic="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,22 @@
package com.silkmonitor
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
class MainActivity : ReactActivity() {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
override fun getMainComponentName(): String = "SilkMonitor"
/**
* Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
* which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
*/
override fun createReactActivityDelegate(): ReactActivityDelegate =
DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
}
@@ -0,0 +1,43 @@
package com.silkmonitor
import android.app.Application
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactHost
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.facebook.react.defaults.DefaultReactNativeHost
import com.facebook.soloader.SoLoader
class MainApplication : Application(), ReactApplication {
override val reactNativeHost: ReactNativeHost =
object : DefaultReactNativeHost(this) {
override fun getPackages(): List<ReactPackage> =
PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example:
// add(MyReactNativePackage())
}
override fun getJSMainModuleName(): String = "index"
override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
}
override val reactHost: ReactHost
get() = getDefaultReactHost(applicationContext, reactNativeHost)
override fun onCreate() {
super.onCreate()
SoLoader.init(this, false)
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
// If you opted-in for the New Architecture, we load the native entry point for this app.
load()
}
}
}
@@ -0,0 +1,55 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<!-- Silkworm icon scaled from 120x120 design to fit 108dp adaptive icon safe zone -->
<group
android:scaleX="0.6"
android:scaleY="0.6"
android:translateX="18"
android:translateY="18">
<!-- Cocoon background ellipse -->
<path
android:pathData="M12,58 a48,52 0 1,0 96,0 a48,52 0 1,0 -96,0"
android:fillColor="#FDFAF5"
android:strokeColor="#E8DCC8"
android:strokeWidth="1.2" />
<!-- Main silkworm body ellipse -->
<path
android:pathData="M30,58 a30,19 0 1,0 60,0 a30,19 0 1,0 -60,0"
android:strokeColor="#7A9E7E"
android:strokeWidth="2.2"
android:fillColor="#00000000" />
<!-- Body segments -->
<path android:pathData="M39,52 L39,64" android:strokeColor="#7A9E7E" android:strokeWidth="1.2" android:strokeAlpha="0.5" />
<path android:pathData="M50,49 L50,67" android:strokeColor="#7A9E7E" android:strokeWidth="1.2" android:strokeAlpha="0.5" />
<path android:pathData="M60,48 L60,68" android:strokeColor="#7A9E7E" android:strokeWidth="1.2" android:strokeAlpha="0.5" />
<path android:pathData="M70,49 L70,67" android:strokeColor="#7A9E7E" android:strokeWidth="1.2" android:strokeAlpha="0.5" />
<path android:pathData="M81,52 L81,64" android:strokeColor="#7A9E7E" android:strokeWidth="1.2" android:strokeAlpha="0.5" />
<!-- Head dots -->
<path
android:pathData="M31.5,58 a3.5,3.5 0 1,0 7,0 a3.5,3.5 0 1,0 -7,0"
android:fillColor="#7A9E7E"
android:fillAlpha="0.8" />
<path
android:pathData="M82.2,58 a2.8,2.8 0 1,0 5.6,0 a2.8,2.8 0 1,0 -5.6,0"
android:fillColor="#7A9E7E"
android:fillAlpha="0.6" />
<!-- Bottom curve (silk thread) -->
<path
android:pathData="M22,70 C40,90 80,90 98,70"
android:strokeColor="#7A9E7E"
android:strokeWidth="1.5"
android:fillColor="#00000000"
android:strokeAlpha="0.4" />
</group>
</vector>
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="@dimen/abc_edit_text_inset_horizontal_material"
android:insetRight="@dimen/abc_edit_text_inset_horizontal_material"
android:insetTop="@dimen/abc_edit_text_inset_top_material"
android:insetBottom="@dimen/abc_edit_text_inset_bottom_material"
>
<selector>
<!--
This file is a copy of abc_edit_text_material (https://bit.ly/3k8fX7I).
The item below with state_pressed="false" and state_focused="false" causes a NullPointerException.
NullPointerException:tempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)'
<item android:state_pressed="false" android:state_focused="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
For more info, see https://bit.ly/3CdLStv (react-native/pull/29452) and https://bit.ly/3nxOMoR.
-->
<item android:state_enabled="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
<item android:drawable="@drawable/abc_textfield_activated_mtrl_alpha"/>
</selector>
</inset>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FDFAF5</color>
</resources>
@@ -0,0 +1,3 @@
<resources>
<string name="app_name">智慧蚕房</string>
</resources>
@@ -0,0 +1,9 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
<!-- Customize your theme here. -->
<item name="android:editTextBackground">@drawable/rn_edit_text_material</item>
</style>
</resources>
+23
View File
@@ -0,0 +1,23 @@
buildscript {
ext {
buildToolsVersion = "34.0.0"
minSdkVersion = 23
compileSdkVersion = 34
targetSdkVersion = 34
ndkVersion = "26.3.11579264"
kotlinVersion = "1.9.22"
}
repositories {
maven { url 'https://maven.aliyun.com/repository/google' }
maven { url 'https://maven.aliyun.com/repository/public' }
google()
mavenCentral()
}
dependencies {
classpath("com.android.tools.build:gradle")
classpath("com.facebook.react:react-native-gradle-plugin")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin")
}
}
apply plugin: "com.facebook.react.rootproject"
+44
View File
@@ -0,0 +1,44 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx512m -XX:MaxMetaspaceSize=256m
org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
# Use this property to specify which architecture you want to build.
# You can also override it from the CLI using
# ./gradlew <task> -PreactNativeArchitectures=x86_64
reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
# Use this property to enable support to the new architecture.
# This will allow you to use TurboModules and the Fabric render in
# your application. You should enable this flag either if you want
# to write custom TurboModules/Fabric components OR use libraries that
# are providing them.
newArchEnabled=false
# Use this property to enable or disable the Hermes JS engine.
# If set to false, you will be using JSC instead.
hermesEnabled=true
# Disable auto-download of JDK toolchains (use locally installed JDK)
org.gradle.java.installations.auto-download=false
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-8.6-all.zip
networkTimeout=120000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+249
View File
@@ -0,0 +1,249 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+92
View File
@@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+4
View File
@@ -0,0 +1,4 @@
rootProject.name = 'SilkMonitor'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'
includeBuild('../node_modules/@react-native/gradle-plugin')
+4
View File
@@ -0,0 +1,4 @@
{
"name": "SilkMonitor",
"displayName": "蚕房监控"
}
+18
View File
@@ -0,0 +1,18 @@
module.exports = {
presets: [
['module:@react-native/babel-preset', { enableBabelRuntime: false }],
],
plugins: [
[
'module:react-native-dotenv',
{
moduleName: '@env',
path: '.env',
blacklist: null,
whitelist: null,
safe: false,
allowUndefined: true,
},
],
],
};
+4
View File
@@ -0,0 +1,4 @@
declare module '@env' {
export const API_BASE_URL: string;
export const WS_BASE_URL: string;
}
+4
View File
@@ -0,0 +1,4 @@
import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent('SilkMonitor', () => App);
+11
View File
@@ -0,0 +1,11 @@
# This `.xcode.env` file is versioned and is used to source the environment
# used when running script phases inside Xcode.
# To customize your local environment, you can create an `.xcode.env.local`
# file that is not versioned.
# NODE_BINARY variable contains the PATH to the node executable.
#
# Customize the NODE_BINARY variable here.
# For example, to use nvm with brew, add the following line
# . "$(brew --prefix nvm)/nvm.sh" --no-use
export NODE_BINARY=$(command -v node)
+40
View File
@@ -0,0 +1,40 @@
# Resolve react_native_pods.rb with node to allow for hoisting
require Pod::Executable.execute_command('node', ['-p',
'require.resolve(
"react-native/scripts/react_native_pods.rb",
{paths: [process.argv[1]]},
)', __dir__]).strip
platform :ios, min_ios_version_supported
prepare_react_native_project!
linkage = ENV['USE_FRAMEWORKS']
if linkage != nil
Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
use_frameworks! :linkage => linkage.to_sym
end
target 'SilkAppTemp' do
config = use_native_modules!
use_react_native!(
:path => config[:reactNativePath],
# An absolute path to your application root.
:app_path => "#{Pod::Config.instance.installation_root}/.."
)
target 'SilkAppTempTests' do
inherit! :complete
# Pods for testing
end
post_install do |installer|
# https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202
react_native_post_install(
installer,
config[:reactNativePath],
:mac_catalyst_enabled => false,
# :ccache_enabled => true
)
end
end
@@ -0,0 +1,688 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 54;
objects = {
/* Begin PBXBuildFile section */
00E356F31AD99517003FC87E /* SilkAppTempTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* SilkAppTempTests.m */; };
0C80B921A6F3F58F76C31292 /* libPods-SilkAppTemp.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5DCACB8F33CDC322A6C60F78 /* libPods-SilkAppTemp.a */; };
13B07FBC1A68108700A75B9A /* AppDelegate.mm in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB01A68108700A75B9A /* AppDelegate.mm */; };
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };
13B07FC11A68108700A75B9A /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; };
7699B88040F8A987B510C191 /* libPods-SilkAppTemp-SilkAppTempTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 19F6CBCC0A4E27FBF8BF4A61 /* libPods-SilkAppTemp-SilkAppTempTests.a */; };
81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
00E356F41AD99517003FC87E /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 13B07F861A680F5B00A75B9A;
remoteInfo = SilkAppTemp;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
00E356EE1AD99517003FC87E /* SilkAppTempTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SilkAppTempTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
00E356F11AD99517003FC87E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
00E356F21AD99517003FC87E /* SilkAppTempTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SilkAppTempTests.m; sourceTree = "<group>"; };
13B07F961A680F5B00A75B9A /* SilkAppTemp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SilkAppTemp.app; sourceTree = BUILT_PRODUCTS_DIR; };
13B07FAF1A68108700A75B9A /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = SilkAppTemp/AppDelegate.h; sourceTree = "<group>"; };
13B07FB01A68108700A75B9A /* AppDelegate.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = AppDelegate.mm; path = SilkAppTemp/AppDelegate.mm; sourceTree = "<group>"; };
13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = SilkAppTemp/Images.xcassets; sourceTree = "<group>"; };
13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = SilkAppTemp/Info.plist; sourceTree = "<group>"; };
13B07FB71A68108700A75B9A /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = SilkAppTemp/main.m; sourceTree = "<group>"; };
13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = PrivacyInfo.xcprivacy; path = SilkAppTemp/PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
19F6CBCC0A4E27FBF8BF4A61 /* libPods-SilkAppTemp-SilkAppTempTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-SilkAppTemp-SilkAppTempTests.a"; sourceTree = BUILT_PRODUCTS_DIR; };
3B4392A12AC88292D35C810B /* Pods-SilkAppTemp.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SilkAppTemp.debug.xcconfig"; path = "Target Support Files/Pods-SilkAppTemp/Pods-SilkAppTemp.debug.xcconfig"; sourceTree = "<group>"; };
5709B34CF0A7D63546082F79 /* Pods-SilkAppTemp.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SilkAppTemp.release.xcconfig"; path = "Target Support Files/Pods-SilkAppTemp/Pods-SilkAppTemp.release.xcconfig"; sourceTree = "<group>"; };
5B7EB9410499542E8C5724F5 /* Pods-SilkAppTemp-SilkAppTempTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SilkAppTemp-SilkAppTempTests.debug.xcconfig"; path = "Target Support Files/Pods-SilkAppTemp-SilkAppTempTests/Pods-SilkAppTemp-SilkAppTempTests.debug.xcconfig"; sourceTree = "<group>"; };
5DCACB8F33CDC322A6C60F78 /* libPods-SilkAppTemp.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-SilkAppTemp.a"; sourceTree = BUILT_PRODUCTS_DIR; };
81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = LaunchScreen.storyboard; path = SilkAppTemp/LaunchScreen.storyboard; sourceTree = "<group>"; };
89C6BE57DB24E9ADA2F236DE /* Pods-SilkAppTemp-SilkAppTempTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SilkAppTemp-SilkAppTempTests.release.xcconfig"; path = "Target Support Files/Pods-SilkAppTemp-SilkAppTempTests/Pods-SilkAppTemp-SilkAppTempTests.release.xcconfig"; sourceTree = "<group>"; };
ED297162215061F000B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
00E356EB1AD99517003FC87E /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
7699B88040F8A987B510C191 /* libPods-SilkAppTemp-SilkAppTempTests.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
13B07F8C1A680F5B00A75B9A /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
0C80B921A6F3F58F76C31292 /* libPods-SilkAppTemp.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
00E356EF1AD99517003FC87E /* SilkAppTempTests */ = {
isa = PBXGroup;
children = (
00E356F21AD99517003FC87E /* SilkAppTempTests.m */,
00E356F01AD99517003FC87E /* Supporting Files */,
);
path = SilkAppTempTests;
sourceTree = "<group>";
};
00E356F01AD99517003FC87E /* Supporting Files */ = {
isa = PBXGroup;
children = (
00E356F11AD99517003FC87E /* Info.plist */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
13B07FAE1A68108700A75B9A /* SilkAppTemp */ = {
isa = PBXGroup;
children = (
13B07FAF1A68108700A75B9A /* AppDelegate.h */,
13B07FB01A68108700A75B9A /* AppDelegate.mm */,
13B07FB51A68108700A75B9A /* Images.xcassets */,
13B07FB61A68108700A75B9A /* Info.plist */,
81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */,
13B07FB71A68108700A75B9A /* main.m */,
13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */,
);
name = SilkAppTemp;
sourceTree = "<group>";
};
2D16E6871FA4F8E400B85C8A /* Frameworks */ = {
isa = PBXGroup;
children = (
ED297162215061F000B7C4FE /* JavaScriptCore.framework */,
5DCACB8F33CDC322A6C60F78 /* libPods-SilkAppTemp.a */,
19F6CBCC0A4E27FBF8BF4A61 /* libPods-SilkAppTemp-SilkAppTempTests.a */,
);
name = Frameworks;
sourceTree = "<group>";
};
832341AE1AAA6A7D00B99B32 /* Libraries */ = {
isa = PBXGroup;
children = (
);
name = Libraries;
sourceTree = "<group>";
};
83CBB9F61A601CBA00E9B192 = {
isa = PBXGroup;
children = (
13B07FAE1A68108700A75B9A /* SilkAppTemp */,
832341AE1AAA6A7D00B99B32 /* Libraries */,
00E356EF1AD99517003FC87E /* SilkAppTempTests */,
83CBBA001A601CBA00E9B192 /* Products */,
2D16E6871FA4F8E400B85C8A /* Frameworks */,
BBD78D7AC51CEA395F1C20DB /* Pods */,
);
indentWidth = 2;
sourceTree = "<group>";
tabWidth = 2;
usesTabs = 0;
};
83CBBA001A601CBA00E9B192 /* Products */ = {
isa = PBXGroup;
children = (
13B07F961A680F5B00A75B9A /* SilkAppTemp.app */,
00E356EE1AD99517003FC87E /* SilkAppTempTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
BBD78D7AC51CEA395F1C20DB /* Pods */ = {
isa = PBXGroup;
children = (
3B4392A12AC88292D35C810B /* Pods-SilkAppTemp.debug.xcconfig */,
5709B34CF0A7D63546082F79 /* Pods-SilkAppTemp.release.xcconfig */,
5B7EB9410499542E8C5724F5 /* Pods-SilkAppTemp-SilkAppTempTests.debug.xcconfig */,
89C6BE57DB24E9ADA2F236DE /* Pods-SilkAppTemp-SilkAppTempTests.release.xcconfig */,
);
path = Pods;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
00E356ED1AD99517003FC87E /* SilkAppTempTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "SilkAppTempTests" */;
buildPhases = (
A55EABD7B0C7F3A422A6CC61 /* [CP] Check Pods Manifest.lock */,
00E356EA1AD99517003FC87E /* Sources */,
00E356EB1AD99517003FC87E /* Frameworks */,
00E356EC1AD99517003FC87E /* Resources */,
C59DA0FBD6956966B86A3779 /* [CP] Embed Pods Frameworks */,
F6A41C54EA430FDDC6A6ED99 /* [CP] Copy Pods Resources */,
);
buildRules = (
);
dependencies = (
00E356F51AD99517003FC87E /* PBXTargetDependency */,
);
name = SilkAppTempTests;
productName = SilkAppTempTests;
productReference = 00E356EE1AD99517003FC87E /* SilkAppTempTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
13B07F861A680F5B00A75B9A /* SilkAppTemp */ = {
isa = PBXNativeTarget;
buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "SilkAppTemp" */;
buildPhases = (
C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */,
13B07F871A680F5B00A75B9A /* Sources */,
13B07F8C1A680F5B00A75B9A /* Frameworks */,
13B07F8E1A680F5B00A75B9A /* Resources */,
00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */,
00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */,
E235C05ADACE081382539298 /* [CP] Copy Pods Resources */,
);
buildRules = (
);
dependencies = (
);
name = SilkAppTemp;
productName = SilkAppTemp;
productReference = 13B07F961A680F5B00A75B9A /* SilkAppTemp.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
83CBB9F71A601CBA00E9B192 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 1210;
TargetAttributes = {
00E356ED1AD99517003FC87E = {
CreatedOnToolsVersion = 6.2;
TestTargetID = 13B07F861A680F5B00A75B9A;
};
13B07F861A680F5B00A75B9A = {
LastSwiftMigration = 1120;
};
};
};
buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "SilkAppTemp" */;
compatibilityVersion = "Xcode 12.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 83CBB9F61A601CBA00E9B192;
productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
13B07F861A680F5B00A75B9A /* SilkAppTemp */,
00E356ED1AD99517003FC87E /* SilkAppTempTests */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
00E356EC1AD99517003FC87E /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
13B07F8E1A680F5B00A75B9A /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */,
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
"$(SRCROOT)/.xcode.env.local",
"$(SRCROOT)/.xcode.env",
);
name = "Bundle React Native code and images";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "set -e\n\nWITH_ENVIRONMENT=\"$REACT_NATIVE_PATH/scripts/xcode/with-environment.sh\"\nREACT_NATIVE_XCODE=\"$REACT_NATIVE_PATH/scripts/react-native-xcode.sh\"\n\n/bin/sh -c \"$WITH_ENVIRONMENT $REACT_NATIVE_XCODE\"\n";
};
00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-SilkAppTemp/Pods-SilkAppTemp-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-SilkAppTemp/Pods-SilkAppTemp-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SilkAppTemp/Pods-SilkAppTemp-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
A55EABD7B0C7F3A422A6CC61 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-SilkAppTemp-SilkAppTempTests-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-SilkAppTemp-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
C59DA0FBD6956966B86A3779 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-SilkAppTemp-SilkAppTempTests/Pods-SilkAppTemp-SilkAppTempTests-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-SilkAppTemp-SilkAppTempTests/Pods-SilkAppTemp-SilkAppTempTests-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SilkAppTemp-SilkAppTempTests/Pods-SilkAppTemp-SilkAppTempTests-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
E235C05ADACE081382539298 /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-SilkAppTemp/Pods-SilkAppTemp-resources-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Copy Pods Resources";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-SilkAppTemp/Pods-SilkAppTemp-resources-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SilkAppTemp/Pods-SilkAppTemp-resources.sh\"\n";
showEnvVarsInLog = 0;
};
F6A41C54EA430FDDC6A6ED99 /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-SilkAppTemp-SilkAppTempTests/Pods-SilkAppTemp-SilkAppTempTests-resources-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Copy Pods Resources";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-SilkAppTemp-SilkAppTempTests/Pods-SilkAppTemp-SilkAppTempTests-resources-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SilkAppTemp-SilkAppTempTests/Pods-SilkAppTemp-SilkAppTempTests-resources.sh\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
00E356EA1AD99517003FC87E /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
00E356F31AD99517003FC87E /* SilkAppTempTests.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
13B07F871A680F5B00A75B9A /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
13B07FBC1A68108700A75B9A /* AppDelegate.mm in Sources */,
13B07FC11A68108700A75B9A /* main.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
00E356F51AD99517003FC87E /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 13B07F861A680F5B00A75B9A /* SilkAppTemp */;
targetProxy = 00E356F41AD99517003FC87E /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
00E356F61AD99517003FC87E /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 5B7EB9410499542E8C5724F5 /* Pods-SilkAppTemp-SilkAppTempTests.debug.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
INFOPLIST_FILE = SilkAppTempTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 13.4;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
OTHER_LDFLAGS = (
"-ObjC",
"-lc++",
"$(inherited)",
);
PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SilkAppTemp.app/SilkAppTemp";
};
name = Debug;
};
00E356F71AD99517003FC87E /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 89C6BE57DB24E9ADA2F236DE /* Pods-SilkAppTemp-SilkAppTempTests.release.xcconfig */;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
COPY_PHASE_STRIP = NO;
INFOPLIST_FILE = SilkAppTempTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 13.4;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
OTHER_LDFLAGS = (
"-ObjC",
"-lc++",
"$(inherited)",
);
PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SilkAppTemp.app/SilkAppTemp";
};
name = Release;
};
13B07F941A680F5B00A75B9A /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 3B4392A12AC88292D35C810B /* Pods-SilkAppTemp.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 1;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = SilkAppTemp/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
"-lc++",
);
PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = SilkAppTemp;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Debug;
};
13B07F951A680F5B00A75B9A /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 5709B34CF0A7D63546082F79 /* Pods-SilkAppTemp.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 1;
INFOPLIST_FILE = SilkAppTemp/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
"-lc++",
);
PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = SilkAppTemp;
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Release;
};
83CBBA201A601CBA00E9B192 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_CXX_LANGUAGE_STANDARD = "c++20";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = "";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.4;
LD_RUNPATH_SEARCH_PATHS = (
/usr/lib/swift,
"$(inherited)",
);
LIBRARY_SEARCH_PATHS = (
"\"$(SDKROOT)/usr/lib/swift\"",
"\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"",
"\"$(inherited)\"",
);
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
OTHER_CPLUSPLUSFLAGS = (
"$(OTHER_CFLAGS)",
"-DFOLLY_NO_CONFIG",
"-DFOLLY_MOBILE=1",
"-DFOLLY_USE_LIBCPP=1",
"-DFOLLY_CFG_NO_COROUTINES=1",
"-DFOLLY_HAVE_CLOCK_GETTIME=1",
);
SDKROOT = iphoneos;
};
name = Debug;
};
83CBBA211A601CBA00E9B192 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_CXX_LANGUAGE_STANDARD = "c++20";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = YES;
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = "";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.4;
LD_RUNPATH_SEARCH_PATHS = (
/usr/lib/swift,
"$(inherited)",
);
LIBRARY_SEARCH_PATHS = (
"\"$(SDKROOT)/usr/lib/swift\"",
"\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"",
"\"$(inherited)\"",
);
MTL_ENABLE_DEBUG_INFO = NO;
OTHER_CPLUSPLUSFLAGS = (
"$(OTHER_CFLAGS)",
"-DFOLLY_NO_CONFIG",
"-DFOLLY_MOBILE=1",
"-DFOLLY_USE_LIBCPP=1",
"-DFOLLY_CFG_NO_COROUTINES=1",
"-DFOLLY_HAVE_CLOCK_GETTIME=1",
);
SDKROOT = iphoneos;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "SilkAppTempTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
00E356F61AD99517003FC87E /* Debug */,
00E356F71AD99517003FC87E /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "SilkAppTemp" */ = {
isa = XCConfigurationList;
buildConfigurations = (
13B07F941A680F5B00A75B9A /* Debug */,
13B07F951A680F5B00A75B9A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "SilkAppTemp" */ = {
isa = XCConfigurationList;
buildConfigurations = (
83CBBA201A601CBA00E9B192 /* Debug */,
83CBBA211A601CBA00E9B192 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 83CBB9F71A601CBA00E9B192 /* Project object */;
}
@@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1210"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "SilkAppTemp.app"
BlueprintName = "SilkAppTemp"
ReferencedContainer = "container:SilkAppTemp.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "00E356ED1AD99517003FC87E"
BuildableName = "SilkAppTempTests.xctest"
BlueprintName = "SilkAppTempTests"
ReferencedContainer = "container:SilkAppTemp.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "SilkAppTemp.app"
BlueprintName = "SilkAppTemp"
ReferencedContainer = "container:SilkAppTemp.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "SilkAppTemp.app"
BlueprintName = "SilkAppTemp"
ReferencedContainer = "container:SilkAppTemp.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
+6
View File
@@ -0,0 +1,6 @@
#import <RCTAppDelegate.h>
#import <UIKit/UIKit.h>
@interface AppDelegate : RCTAppDelegate
@end
+31
View File
@@ -0,0 +1,31 @@
#import "AppDelegate.h"
#import <React/RCTBundleURLProvider.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.moduleName = @"SilkAppTemp";
// You can add your custom initial props in the dictionary below.
// They will be passed down to the ViewController used by React Native.
self.initialProps = @{};
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
return [self bundleURL];
}
- (NSURL *)bundleURL
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}
@end
@@ -0,0 +1,53 @@
{
"images" : [
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "20x20"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "20x20"
},
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "29x29"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "29x29"
},
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "40x40"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "40x40"
},
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "60x60"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "60x60"
},
{
"idiom" : "ios-marketing",
"scale" : "1x",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
+52
View File
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>SilkAppTemp</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
<!-- Do not change NSAllowsArbitraryLoads to true, or you will risk app rejection! -->
<key>NSAllowsArbitraryLoads</key>
<false/>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
<key>NSLocationWhenInUseUsageDescription</key>
<string></string>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</dict>
</plist>
@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15702" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina4_7" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15704"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="SilkAppTemp" textAlignment="center" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" minimumFontSize="18" translatesAutoresizingMaskIntoConstraints="NO" id="GJd-Yh-RWb">
<rect key="frame" x="0.0" y="202" width="375" height="43"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="36"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Powered by React Native" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" minimumFontSize="9" translatesAutoresizingMaskIntoConstraints="NO" id="MN2-I3-ftu">
<rect key="frame" x="0.0" y="626" width="375" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<constraints>
<constraint firstItem="Bcu-3y-fUS" firstAttribute="bottom" secondItem="MN2-I3-ftu" secondAttribute="bottom" constant="20" id="OZV-Vh-mqD"/>
<constraint firstItem="Bcu-3y-fUS" firstAttribute="centerX" secondItem="GJd-Yh-RWb" secondAttribute="centerX" id="Q3B-4B-g5h"/>
<constraint firstItem="MN2-I3-ftu" firstAttribute="centerX" secondItem="Bcu-3y-fUS" secondAttribute="centerX" id="akx-eg-2ui"/>
<constraint firstItem="MN2-I3-ftu" firstAttribute="leading" secondItem="Bcu-3y-fUS" secondAttribute="leading" id="i1E-0Y-4RG"/>
<constraint firstItem="GJd-Yh-RWb" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="bottom" multiplier="1/3" constant="1" id="moa-c2-u7t"/>
<constraint firstItem="GJd-Yh-RWb" firstAttribute="leading" secondItem="Bcu-3y-fUS" secondAttribute="leading" symbolic="YES" id="x7j-FC-K8j"/>
</constraints>
<viewLayoutGuide key="safeArea" id="Bcu-3y-fUS"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="52.173913043478265" y="375"/>
</scene>
</scenes>
</document>
+38
View File
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyCollectedDataTypes</key>
<array>
</array>
<key>NSPrivacyAccessedAPITypes</key>
<array>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>C617.1</string>
</array>
</dict>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategoryUserDefaults</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>CA92.1</string>
</array>
</dict>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategorySystemBootTime</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>35F9.1</string>
</array>
</dict>
</array>
<key>NSPrivacyTracking</key>
<false/>
</dict>
</plist>
+10
View File
@@ -0,0 +1,10 @@
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char *argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
+24
View File
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
@@ -0,0 +1,66 @@
#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import <React/RCTLog.h>
#import <React/RCTRootView.h>
#define TIMEOUT_SECONDS 600
#define TEXT_TO_LOOK_FOR @"Welcome to React"
@interface SilkAppTempTests : XCTestCase
@end
@implementation SilkAppTempTests
- (BOOL)findSubviewInView:(UIView *)view matching:(BOOL (^)(UIView *view))test
{
if (test(view)) {
return YES;
}
for (UIView *subview in [view subviews]) {
if ([self findSubviewInView:subview matching:test]) {
return YES;
}
}
return NO;
}
- (void)testRendersWelcomeScreen
{
UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController];
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS];
BOOL foundElement = NO;
__block NSString *redboxError = nil;
#ifdef DEBUG
RCTSetLogFunction(
^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) {
if (level >= RCTLogLevelError) {
redboxError = message;
}
});
#endif
while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) {
[[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
[[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
foundElement = [self findSubviewInView:vc.view
matching:^BOOL(UIView *view) {
if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) {
return YES;
}
return NO;
}];
}
#ifdef DEBUG
RCTSetLogFunction(RCTDefaultLogFunction);
#endif
XCTAssertNil(redboxError, @"RedBox error: %@", redboxError);
XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS);
}
@end
+16
View File
@@ -0,0 +1,16 @@
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
const config = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
};
module.exports = mergeConfig(defaultConfig, config);
+8723
View File
File diff suppressed because it is too large Load Diff
+41
View File
@@ -0,0 +1,41 @@
{
"name": "silk-monitor-app",
"version": "1.0.0",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"lint": "eslint .",
"tsc": "tsc --noEmit"
},
"dependencies": {
"@react-native-async-storage/async-storage": "^1.23.1",
"@react-native-community/netinfo": "^11.3.1",
"@react-navigation/bottom-tabs": "^6.6.0",
"@react-navigation/native": "^6.1.17",
"@react-navigation/native-stack": "^6.10.0",
"axios": "^1.7.2",
"dayjs": "^1.11.11",
"react": "18.3.1",
"react-native": "0.74.5",
"react-native-paper": "^5.12.3",
"react-native-safe-area-context": "^4.10.5",
"react-native-screens": "^3.32.0",
"react-native-vector-icons": "^10.1.0",
"react-native-video": "^6.2.0",
"victory-native": "^41.6.0",
"zustand": "^4.5.4"
},
"devDependencies": {
"@babel/core": "^7.25.2",
"@babel/preset-env": "^7.25.3",
"@babel/runtime": "^7.25.0",
"@react-native/babel-preset": "0.74.85",
"@react-native/metro-config": "^0.74.85",
"@react-native/typescript-config": "0.74.85",
"@types/react": "^18.3.3",
"react-native-dotenv": "^3.4.11",
"typescript": "^5.5.4"
}
}
+19
View File
@@ -0,0 +1,19 @@
import { get, post, toArray } from './client';
import type { Alarm, AlarmClip } from '../types';
export interface AlarmQuery {
openOnly?: boolean;
deviceKey?: string;
limit?: number;
}
export const getAlarms = async (query: AlarmQuery = {}): Promise<Alarm[]> => {
const data = await get<Alarm[] | { items?: Alarm[] }>('/alarms', query);
return toArray(data);
};
export const ackAlarm = (id: string) =>
post<{ ok?: boolean }>(`/alarms/${id}/ack`);
export const getAlarmClip = (id: string) =>
get<AlarmClip>(`/alarms/${id}/clip`);
+7
View File
@@ -0,0 +1,7 @@
import { post, get } from './client';
import type { LoginResponse, User } from '../types';
export const loginApi = (username: string, password: string) =>
post<LoginResponse>('/auth/login', { username, password });
export const getMeApi = () => get<User>('/auth/me');
+89
View File
@@ -0,0 +1,89 @@
import axios from 'axios';
import type { AxiosInstance, AxiosError } from 'axios';
import { API_BASE_URL } from '@env';
import AsyncStorage from '@react-native-async-storage/async-storage';
export const TOKEN_KEY = 'silkworm_access_token';
export const REFRESH_TOKEN_KEY = 'silkworm_refresh_token';
// Navigation ref for redirecting to login on 401
let navigationRef: { navigate: (screen: string) => void } | null = null;
export const setNavigationRef = (ref: { navigate: (screen: string) => void }) => {
navigationRef = ref;
};
// Debug: log the actual API_BASE_URL at module load time
console.log('[DEBUG] API_BASE_URL from @env:', JSON.stringify(API_BASE_URL));
export const http: AxiosInstance = axios.create({
baseURL: API_BASE_URL || 'http://localhost:3000/api/v1',
timeout: 8000,
});
// Request interceptor: attach JWT token
http.interceptors.request.use(async (config) => {
const token = await AsyncStorage.getItem(TOKEN_KEY);
if (token) {
config.headers = config.headers ?? {};
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
});
// Response interceptor: handle 401
http.interceptors.response.use(
(res) => res,
async (err: AxiosError) => {
const status = err.response?.status;
if (status === 401) {
await AsyncStorage.multiRemove([TOKEN_KEY, REFRESH_TOKEN_KEY]);
// Redirect to login screen
if (navigationRef) {
navigationRef.navigate('Login');
}
}
return Promise.reject(err);
},
);
// Helper to extract response data
export const request = <T = unknown>(config: Parameters<AxiosInstance['request']>[0]): Promise<T> =>
http.request<T>(config).then((r) => r.data);
export const get = <T = unknown>(url: string, params?: Record<string, any>) =>
request<T>({ method: 'GET', url, params });
export const post = <T = unknown>(url: string, data?: unknown) =>
request<T>({ method: 'POST', url, data });
export const patch = <T = unknown>(url: string, data?: unknown) =>
request<T>({ method: 'PATCH', url, data });
export const put = <T = unknown>(url: string, data?: unknown) =>
request<T>({ method: 'PUT', url, data });
export const del = <T = unknown>(url: string, params?: Record<string, any>) =>
request<T>({ method: 'DELETE', url, params });
// Helper: normalize array response (backend may return array or {items:[...]})
export const toArray = <T>(data: T[] | { items?: T[] } | undefined): T[] => {
if (!data) return [];
return Array.isArray(data) ? data : data.items ?? [];
};
export const extractErrorMessage = (err: any): string => {
return (
err?.response?.data?.message ||
err?.response?.data?.msg ||
err?.message ||
'请求失败'
);
};
// Resolve relative URL (e.g. /api/v1/video/clips/1/stream) to full URL
export const resolveUrl = (path: string): string => {
if (path.startsWith('http://') || path.startsWith('https://')) return path;
const base = (API_BASE_URL || 'http://localhost:3000/api/v1').replace(/\/api\/v1$/, '');
return base + path;
};
+24
View File
@@ -0,0 +1,24 @@
import { get, post, toArray } from './client';
import type { Device } from '../types';
export const getDevices = async (params?: Record<string, any>): Promise<Device[]> => {
const data = await get<Device[] | { items?: Device[] }>('/devices', params);
return toArray(data);
};
export const getDevice = (id: string) => get<Device>(`/devices/${id}`);
export interface ControlCommand {
deviceKey: string;
action: string;
value?: any;
payload?: any;
}
export const sendControl = (command: ControlCommand) =>
post<{ ok?: boolean; success?: boolean }>('/control/send', command);
export const getControlLogs = async (params?: Record<string, any>) => {
const data = await get<any[] | { items?: any[] }>('/control/logs', params);
return toArray(data);
};
+9
View File
@@ -0,0 +1,9 @@
import { get, toArray } from './client';
import type { Room } from '../types';
export const getRooms = async (): Promise<Room[]> => {
const data = await get<Room[] | { items?: Room[] }>('/rooms');
return toArray(data);
};
export const getRoom = (id: string) => get<Room>(`/rooms/${id}`);
+67
View File
@@ -0,0 +1,67 @@
import { get, toArray } from './client';
import type { TelemetryRecord, RealtimeMetric, TrendPoint } from '../types';
import { normalizeMetricKey, getMetricName, getMetricUnit, metricStatus } from '../utils/format';
export interface TelemetryQuery {
deviceKey?: string;
metric?: string;
from?: string;
to?: string;
limit?: number;
}
export const getTelemetry = async (query: TelemetryQuery = {}): Promise<TelemetryRecord[]> => {
const data = await get<TelemetryRecord[] | { items?: TelemetryRecord[] }>('/telemetry', query);
return toArray(data);
};
export const getLatestTelemetry = async (deviceKey: string): Promise<TelemetryRecord[]> => {
const data = await get<TelemetryRecord[] | { items?: TelemetryRecord[] }>(
`/telemetry/${deviceKey}/latest`,
);
return toArray(data);
};
// Normalize telemetry records into metric display format
export const normalizeRealtime = (records: TelemetryRecord[]): RealtimeMetric[] => {
const latestByMetric = new Map<string, TelemetryRecord>();
for (const record of records) {
const key = normalizeMetricKey(record.metric);
const prev = latestByMetric.get(key);
if (!prev || new Date(record.timestamp).getTime() > new Date(prev.timestamp).getTime()) {
latestByMetric.set(key, record);
}
}
return Array.from(latestByMetric.entries()).map(([key, record]) => ({
key,
name: getMetricName(key) || record.metric,
value: Number(record.value),
unit: getMetricUnit(key) || '',
status: metricStatus(key, Number(record.value)),
}));
};
// Fetch trend data for chart
export const fetchTrend = async (hours = 24): Promise<TrendPoint[]> => {
const to = new Date();
const from = new Date(to.getTime() - hours * 3600 * 1000);
const records = await getTelemetry({
from: from.toISOString(),
to: to.toISOString(),
limit: 1000,
});
return records
.slice()
.reverse()
.reduce<TrendPoint[]>((acc, record) => {
const key = normalizeMetricKey(record.metric);
if (!['temp', 'humidity', 'co2'].includes(key)) return acc;
const time = new Date(record.timestamp).toLocaleTimeString().slice(0, 5);
const point = acc.find((item) => item.time === time) ?? { time };
(point as unknown as Record<string, string | number | undefined>)[key] = Number(record.value);
if (!acc.includes(point)) acc.push(point);
return acc;
}, []);
};
+23
View File
@@ -0,0 +1,23 @@
import { get, post, patch, del, toArray } from './client';
import type { Threshold } from '../types';
export const getThresholds = async (params?: Record<string, any>): Promise<Threshold[]> => {
const data = await get<Threshold[] | { items?: Threshold[] }>('/thresholds', params);
return toArray(data);
};
export const createThreshold = (data: Partial<Threshold>) =>
post<Threshold>('/thresholds', {
...data,
minValue: data.minValue ?? data.min,
maxValue: data.maxValue ?? data.max,
});
export const updateThreshold = (id: string, data: Partial<Threshold>) =>
patch<Threshold>(`/thresholds/${id}`, {
...data,
minValue: data.minValue ?? data.min,
maxValue: data.maxValue ?? data.max,
});
export const deleteThreshold = (id: string) => del<{ ok?: boolean }>(`/thresholds/${id}`);
+23
View File
@@ -0,0 +1,23 @@
import { get, post, toArray } from './client';
import type { Camera, PlayInfo, VideoClip, ClipListResponse } from '../types';
export const getCameras = async (): Promise<Camera[]> => {
const data = await get<Camera[] | { items?: Camera[] }>('/video/cameras');
return toArray(data);
};
export const playCamera = (id: number | string, format: 'hls' | 'flv' | 'webrtc' = 'hls') =>
post<PlayInfo>(`/video/cameras/${id}/play`, { format });
export interface ClipQuery {
cameraId?: string;
from?: string;
to?: string;
limit?: number;
}
export const getClips = async (query: ClipQuery = {}): Promise<VideoClip[]> => {
const data = await get<ClipListResponse | VideoClip[]>('/video/clips', query);
if (Array.isArray(data)) return data;
return data.items ?? [];
};
+34
View File
@@ -0,0 +1,34 @@
import React from 'react';
import { View, StyleSheet, Text, Dimensions } from 'react-native';
interface MiniChartProps {
data: { time: string; temp?: number; humidity?: number; co2?: number }[];
height?: number;
color?: string;
metric?: 'temp' | 'humidity' | 'co2';
}
export const MiniChart: React.FC<MiniChartProps> = ({ data, height = 120, color = '#7A9E7E', metric = 'temp' }) => {
const values = data.map(d => d[metric]).filter((v): v is number => v !== undefined);
if (values.length === 0) return <Text style={{ textAlign: 'center', color: '#B8B3AA', padding: 20 }}></Text>;
const min = Math.min(...values);
const max = Math.max(...values);
const range = max - min || 1;
return (
<View style={[styles.container, { height }]}>
{values.map((v, i) => {
const barHeight = ((v - min) / range) * (height - 20);
return (
<View key={i} style={[styles.bar, { height: barHeight + 2, backgroundColor: color }]} />
);
})}
</View>
);
};
const styles = StyleSheet.create({
container: { flexDirection: 'row', alignItems: 'flex-end', paddingHorizontal: 10, gap: 2 },
bar: { flex: 1, borderRadius: 3, minHeight: 2 },
});
+88
View File
@@ -0,0 +1,88 @@
import React from 'react';
import { StyleSheet, View } from 'react-native';
import { Card, Text, useTheme } from 'react-native-paper';
import type { MD3Theme } from 'react-native-paper';
interface StatCardProps {
title: string;
value: number | string;
suffix?: string;
color?: string;
icon?: string;
}
export const StatCard: React.FC<StatCardProps> = ({ title, value, suffix, color, icon }) => {
const theme = useTheme<MD3Theme>();
return (
<Card style={styles.card} mode="elevated">
<Card.Content style={styles.content}>
<View style={styles.headerRow}>
{icon ? (
<Text style={[styles.icon, { color: color || theme.colors.primary }]}>{icon}</Text>
) : null}
<Text variant="labelMedium" style={styles.title}>
{title}
</Text>
</View>
<Text variant="headlineMedium" style={[styles.value, { color: color || '#2D2A26' }]}>
{value}
{suffix ? <Text variant="titleMedium" style={styles.suffix}> {suffix}</Text> : null}
</Text>
</Card.Content>
</Card>
);
};
const styles = StyleSheet.create({
card: {
flex: 1,
minWidth: 140,
},
content: {
paddingVertical: 12,
paddingHorizontal: 16,
},
headerRow: {
flexDirection: 'row',
alignItems: 'center',
marginBottom: 4,
},
icon: {
fontSize: 18,
marginRight: 6,
},
title: {
opacity: 0.7,
},
value: {
fontWeight: 'bold',
},
suffix: {
fontWeight: 'normal',
opacity: 0.6,
},
});
interface StatCardRowProps {
items: StatCardProps[];
}
export const StatCardRow: React.FC<StatCardRowProps> = ({ items }) => {
return (
<View style={statRowStyles.container}>
{items.map((item, index) => (
<StatCard key={`${item.title}-${index}`} {...item} />
))}
</View>
);
};
const statRowStyles = StyleSheet.create({
container: {
flexDirection: 'row',
flexWrap: 'wrap',
gap: 12,
marginVertical: 6,
},
});
+232
View File
@@ -0,0 +1,232 @@
import React, { useEffect } from 'react';
import { NavigationContainer, useNavigation } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { Provider as PaperProvider, useTheme, MD3LightTheme } from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { setNavigationRef } from '../api/client';
import { useAuthStore } from '../store/authStore';
import { useAppStore } from '../store/appStore';
import { wsManager } from '../utils/ws';
import type { RootStackParamList, MainTabParamList } from '../types';
import LoginScreen from '../screens/LoginScreen';
import DashboardScreen from '../screens/DashboardScreen';
import RoomsScreen from '../screens/RoomsScreen';
import RoomDetailScreen from '../screens/RoomDetailScreen';
import DevicesScreen from '../screens/DevicesScreen';
import DeviceControlScreen from '../screens/DeviceControlScreen';
import AlertsScreen from '../screens/AlertsScreen';
import ThresholdsScreen from '../screens/ThresholdsScreen';
import VideoScreen from '../screens/VideoScreen';
import VideoPlayerScreen from '../screens/VideoPlayerScreen';
import SettingsScreen from '../screens/SettingsScreen';
const Stack = createNativeStackNavigator<RootStackParamList>();
const Tab = createBottomTabNavigator<MainTabParamList>();
const TabIcon: React.FC<{ name: string; activeName: string; color: string; size: number; focused: boolean }> = ({ name, activeName, color, size, focused }) => (
<Icon name={focused ? activeName : name} size={focused ? 26 : 22} color={color} />
);
function MainTabs() {
const navigation = useNavigation<any>();
return (
<Tab.Navigator
screenOptions={{
headerShown: true,
tabBarActiveTintColor: '#5C7D60',
tabBarInactiveTintColor: '#C4BFB6',
tabBarStyle: {
backgroundColor: '#FFFFFF',
borderTopColor: '#F0EDE8',
borderTopWidth: 1,
paddingBottom: 6,
paddingTop: 6,
height: 60,
},
tabBarLabelStyle: {
fontSize: 15,
fontWeight: '700',
marginTop: 2,
},
tabBarIconStyle: {
marginBottom: 2,
},
headerStyle: {
backgroundColor: '#FAF8F5',
},
headerTitleStyle: {
color: '#2D2A26',
fontSize: 18,
fontWeight: '500',
},
headerTintColor: '#5C7D60',
headerRight: () => (
<Icon
name="cog-outline"
size={24}
color="#8C8780"
style={{ marginRight: 12 }}
onPress={() => navigation.navigate('Settings')}
/>
),
}}
>
<Tab.Screen
name="Dashboard"
component={DashboardScreen}
options={{
title: '仪表盘',
tabBarIcon: ({ color, size, focused }) => <TabIcon name="view-dashboard-outline" activeName="view-dashboard" color={color} size={size} focused={focused} />,
}}
/>
<Tab.Screen
name="Rooms"
component={RoomsScreen}
options={{
title: '蚕房',
tabBarIcon: ({ color, size, focused }) => <TabIcon name="home-outline" activeName="home-variant" color={color} size={size} focused={focused} />,
}}
/>
<Tab.Screen
name="Devices"
component={DevicesScreen}
options={{
title: '设备',
tabBarIcon: ({ color, size, focused }) => <TabIcon name="router-wireless" activeName="router-wireless" color={color} size={size} focused={focused} />,
}}
/>
<Tab.Screen
name="Alerts"
component={AlertsScreen}
options={{
title: '告警',
tabBarIcon: ({ color, size, focused }) => <TabIcon name="bell-alert-outline" activeName="bell-alert" color={color} size={size} focused={focused} />,
}}
/>
<Tab.Screen
name="Video"
component={VideoScreen}
options={{
title: '视频',
tabBarIcon: ({ color, size, focused }) => <TabIcon name="video-outline" activeName="video" color={color} size={size} focused={focused} />,
}}
/>
</Tab.Navigator>
);
}
function AppContent() {
const token = useAuthStore((s) => s.token);
const restoreSession = useAuthStore((s) => s.restoreSession);
const setRealtimeData = useAppStore((s) => s.setRealtimeData);
const [isReady, setIsReady] = React.useState(false);
useEffect(() => {
(async () => {
await restoreSession();
setIsReady(true);
})();
}, [restoreSession]);
// Subscribe to WebSocket telemetry
useEffect(() => {
const unsub = wsManager.subscribe((data) => {
if (data?.type === 'telemetry' || data?.metric) {
const telemetry = useAppStore.getState().realtimeData;
setRealtimeData([...telemetry, data].slice(-100));
}
});
return unsub;
}, [setRealtimeData]);
if (!isReady) {
return null;
}
return (
<NavigationContainer
ref={(ref) => {
if (ref) {
setNavigationRef({
navigate: (screen: string) => {
(ref as any).navigate(screen);
},
});
}
}}
>
<Stack.Navigator screenOptions={{ headerShown: false }} initialRouteName={token ? 'Main' : 'Login'}>
<Stack.Screen name="Login" component={LoginScreen} />
<Stack.Screen name="Main" component={MainTabs} />
<Stack.Screen
name="RoomDetail"
component={RoomDetailScreen}
options={{ headerShown: true, title: '蚕房详情', headerBackTitle: '返回' }}
/>
<Stack.Screen
name="DeviceControl"
component={DeviceControlScreen}
options={{ headerShown: true, title: '设备控制', headerBackTitle: '返回' }}
/>
<Stack.Screen
name="VideoPlayer"
component={VideoPlayerScreen}
options={{ headerShown: false }}
/>
<Stack.Screen
name="Thresholds"
component={ThresholdsScreen}
options={{ headerShown: true, title: '阈值管理', headerBackTitle: '返回' }}
/>
<Stack.Screen
name="Settings"
component={SettingsScreen}
options={{ headerShown: true, title: '设置', headerBackTitle: '返回' }}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
export default function AppNavigator() {
const silkTheme = {
...MD3LightTheme,
colors: {
...MD3LightTheme.colors,
primary: '#7A9E7E',
primaryContainer: '#E8F0E9',
onPrimary: '#FFFFFF',
onPrimaryContainer: '#5C7D60',
secondary: '#6B8F71',
secondaryContainer: '#F0EDE8',
onSecondary: '#FFFFFF',
onSecondaryContainer: '#5C7D60',
error: '#D4847A',
errorContainer: '#F9E8E5',
onError: '#FFFFFF',
background: '#FAF8F5',
onBackground: '#2D2A26',
surface: '#FFFFFF',
onSurface: '#2D2A26',
surfaceVariant: '#F5F0E8',
onSurfaceVariant: '#8C8780',
outline: '#E8E4DE',
outlineVariant: '#F0EDE8',
elevation: {
...MD3LightTheme.colors.elevation,
level0: 'transparent',
level1: '#FFFFFF',
level2: '#FFFFFF',
},
},
};
return (
<PaperProvider theme={silkTheme}>
<AppContent />
</PaperProvider>
);
}
+312
View File
@@ -0,0 +1,312 @@
import React, { useEffect, useState, useCallback } from 'react';
import { StyleSheet, View, FlatList, RefreshControl, Alert } from 'react-native';
import { Text, Card, useTheme, ActivityIndicator, Surface, SegmentedButtons, Button, Snackbar } from 'react-native-paper';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { getAlarms, ackAlarm, getAlarmClip } from '../api/alarms';
import { extractErrorMessage } from '../api/client';
import { formatRelativeTime, getSeverityLabel } from '../utils/format';
import type { Alarm } from '../types';
export default function AlertsScreen() {
const theme = useTheme();
const navigation = useNavigation<any>();
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [alarms, setAlarms] = useState<Alarm[]>([]);
const [filter, setFilter] = useState('open');
const [error, setError] = useState<string | null>(null);
const [snackMsg, setSnackMsg] = useState('');
const [snackVisible, setSnackVisible] = useState(false);
const [ackingId, setAkingId] = useState<string | null>(null);
const getSevColor = (severity?: string) => {
switch (severity?.toLowerCase()) {
case 'danger':
case 'critical':
case 'high':
return '#D4847A';
case 'warn':
case 'warning':
case 'medium':
return '#D4B87A';
case 'info':
case 'low':
return '#6B8F71';
default:
return '#B8B3AA';
}
};
const loadData = useCallback(async (isRefresh = false) => {
if (isRefresh) setRefreshing(true);
try {
const data = await getAlarms({ openOnly: filter === 'open' });
setAlarms(data);
setError(null);
} catch (err: any) {
setError(err?.message || '加载失败');
} finally {
setLoading(false);
setRefreshing(false);
}
}, [filter]);
useEffect(() => {
setLoading(true);
loadData();
}, [loadData]);
const handleAck = async (id: string) => {
setAkingId(id);
try {
await ackAlarm(id);
setAlarms((prev) =>
prev.map((a) => (a.id === id ? { ...a, acknowledged: true, open: false } : a)),
);
setSnackMsg('告警已确认');
setSnackVisible(true);
} catch (err: any) {
Alert.alert('操作失败', extractErrorMessage(err));
} finally {
setAkingId(null);
}
};
const handleViewClip = async (alarm: Alarm) => {
try {
const clip = await getAlarmClip(alarm.id);
if (clip.playbackUrl) {
Alert.alert(
'告警片段',
`开始时间: ${formatRelativeTime(clip.startAt)}\n结束时间: ${formatRelativeTime(clip.endAt)}`,
);
} else {
Alert.alert('提示', '暂无关联的视频片段');
}
} catch (err: any) {
Alert.alert('获取片段失败', extractErrorMessage(err));
}
};
const renderItem = ({ item }: { item: Alarm }) => {
const sevColor = getSevColor(item.severity || item.level);
return (
<Card style={[styles.card, { borderLeftColor: sevColor, borderLeftWidth: 4 }]}>
<Card.Content style={styles.cardContent}>
<View style={styles.alarmHeader}>
<View style={styles.alarmTitleRow}>
<Surface style={[styles.sevBadge, { backgroundColor: sevColor }]}>
<Text style={styles.sevBadgeText}>{getSeverityLabel(item.severity || item.level)}</Text>
</Surface>
<Text variant="bodyMedium" style={styles.alarmTitle}>
{item.title || item.message || item.content || item.code || '告警'}
</Text>
</View>
{item.open ? (
<Surface style={styles.openBadge}>
<Text style={styles.openBadgeText}></Text>
</Surface>
) : (
<Surface style={[styles.openBadge, { backgroundColor: '#F0EDE8' }]}>
<Text style={[styles.openBadgeText, { color: '#8C8780' }]}></Text>
</Surface>
)}
</View>
{item.message && item.title ? (
<Text variant="bodySmall" style={styles.alarmMessage}>{item.message}</Text>
) : null}
<View style={styles.alarmMeta}>
{item.deviceKey ? <Text style={styles.metaText}>: {item.deviceKey}</Text> : null}
{item.metric ? <Text style={styles.metaText}>: {item.metric}</Text> : null}
{item.value !== undefined ? <Text style={styles.metaText}>: {item.value}</Text> : null}
</View>
<View style={styles.alarmFooter}>
<Text style={styles.timeText}>
{formatRelativeTime(item.triggeredAt || item.createdAt)}
</Text>
<View style={styles.footerActions}>
{item.open && !item.acknowledged ? (
<Button
mode="text"
onPress={() => handleAck(item.id)}
loading={ackingId === item.id}
disabled={ackingId === item.id}
textColor="#5C7D60"
>
</Button>
) : null}
<Button
mode="text"
onPress={() => handleViewClip(item)}
textColor="#6B8F71"
icon="video"
>
</Button>
</View>
</View>
</Card.Content>
</Card>
);
};
if (loading) {
return (
<SafeAreaView style={styles.center}>
<ActivityIndicator size="large" />
</SafeAreaView>
);
}
return (
<SafeAreaView style={styles.container} edges={['bottom']}>
<View style={styles.filterContainer}>
<SegmentedButtons
value={filter}
onValueChange={setFilter}
buttons={[
{ value: 'open', label: '未处理' },
{ value: 'all', label: '全部' },
]}
/>
</View>
<FlatList
data={alarms}
keyExtractor={(item) => item.id}
renderItem={renderItem}
contentContainerStyle={styles.list}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={() => loadData(true)} />
}
ListEmptyComponent={
error ? (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}>{error}</Text>
</View>
) : (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}></Text>
</View>
)
}
/>
<Snackbar
visible={snackVisible}
onDismiss={() => setSnackVisible(false)}
duration={2000}
>
{snackMsg}
</Snackbar>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FAF8F5',
},
center: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
filterContainer: {
padding: 16,
paddingBottom: 8,
},
list: {
padding: 16,
paddingTop: 8,
paddingBottom: 32,
},
card: {
marginBottom: 12,
borderRadius: 14,
backgroundColor: '#FFFFFF',
},
cardContent: {
paddingVertical: 12,
},
alarmHeader: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'flex-start',
marginBottom: 4,
},
alarmTitleRow: {
flexDirection: 'row',
alignItems: 'center',
gap: 8,
flex: 1,
},
sevBadge: {
paddingHorizontal: 8,
paddingVertical: 3,
borderRadius: 10,
elevation: 0,
},
sevBadgeText: {
color: 'white',
fontSize: 11,
fontWeight: '500',
},
alarmTitle: {
color: '#2D2A26',
fontWeight: '500',
flex: 1,
},
openBadge: {
backgroundColor: '#F9E8E5',
paddingHorizontal: 8,
paddingVertical: 3,
borderRadius: 10,
elevation: 0,
},
openBadgeText: {
color: '#D4847A',
fontSize: 11,
fontWeight: '500',
},
alarmMessage: {
color: '#8C8780',
marginTop: 4,
},
alarmMeta: {
flexDirection: 'row',
flexWrap: 'wrap',
gap: 12,
marginTop: 8,
},
metaText: {
fontSize: 12,
color: '#B8B3AA',
},
alarmFooter: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginTop: 8,
},
timeText: {
fontSize: 12,
color: '#B8B3AA',
},
footerActions: {
flexDirection: 'row',
gap: 4,
},
emptyContainer: {
alignItems: 'center',
paddingTop: 64,
},
emptyText: {
color: '#B8B3AA',
fontSize: 16,
},
});
+369
View File
@@ -0,0 +1,369 @@
import React, { useEffect, useState, useCallback, useRef } from 'react';
import { StyleSheet, View, ScrollView, RefreshControl } from 'react-native';
import { Text, Card, ActivityIndicator, Surface } from 'react-native-paper';
import { SafeAreaView } from 'react-native-safe-area-context';
import { MiniChart } from '../components/MiniChart';
import { StatCard } from '../components/StatCard';
import { getRooms } from '../api/rooms';
import { getDevices } from '../api/devices';
import { getAlarms } from '../api/alarms';
import { getTelemetry, normalizeRealtime, fetchTrend } from '../api/telemetry';
import type { Room, Device, Alarm, RealtimeMetric, TrendPoint } from '../types';
export default function DashboardScreen() {
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [rooms, setRooms] = useState<Room[]>([]);
const [devices, setDevices] = useState<Device[]>([]);
const [alarms, setAlarms] = useState<Alarm[]>([]);
const [metrics, setMetrics] = useState<RealtimeMetric[]>([]);
const [trend, setTrend] = useState<TrendPoint[]>([]);
const [trendLoading, setTrendLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const loadTrend = useCallback(async () => {
setTrendLoading(true);
try {
const trendData = await fetchTrend(24).catch(() => [] as TrendPoint[]);
setTrend(trendData);
} finally {
setTrendLoading(false);
}
}, []);
const loadData = useCallback(async (isRefresh = false) => {
if (isRefresh) setRefreshing(true);
try {
const [roomsData, devicesData, alarmsData, telemetryData] = await Promise.all([
getRooms().catch(() => [] as Room[]),
getDevices().catch(() => [] as Device[]),
getAlarms({ openOnly: true }).catch(() => [] as Alarm[]),
getTelemetry({ limit: 100 }).catch(() => [] as any[]),
]);
setRooms(roomsData);
setDevices(devicesData);
setAlarms(alarmsData);
setMetrics(normalizeRealtime(telemetryData));
setError(null);
} catch (err: any) {
setError(err?.message || '数据加载失败');
} finally {
setLoading(false);
setRefreshing(false);
}
// Load trend data in the background (non-blocking)
loadTrend();
}, [loadTrend]);
useEffect(() => {
loadData();
intervalRef.current = setInterval(() => loadData(), 30000);
return () => {
if (intervalRef.current) clearInterval(intervalRef.current);
};
}, [loadData]);
const onlineDevices = devices.filter((d) => d.onlineStatus === 'online' || d.status === 'online').length;
const offlineDevices = devices.length - onlineDevices;
const activeAlarms = alarms.filter((a) => a.open).length;
if (loading) {
return (
<SafeAreaView style={styles.center}>
<ActivityIndicator size="large" />
<Text style={styles.loadingText}>...</Text>
</SafeAreaView>
);
}
const statusColor = (status: RealtimeMetric['status']) => {
switch (status) {
case 'danger': return '#D4847A';
case 'warn': return '#D4B87A';
default: return '#7A9E7E';
}
};
return (
<SafeAreaView style={styles.container} edges={['bottom']}>
<ScrollView
style={styles.scrollView}
contentContainerStyle={styles.content}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={() => loadData(true)} />
}
>
{error ? (
<Card style={styles.errorCard}>
<Card.Content>
<Text style={{ color: '#D4847A' }}>{error}</Text>
</Card.Content>
</Card>
) : null}
<View style={styles.statsRow}>
<StatCard title="蚕房总数" value={rooms.length} icon="🏠" color="#7A9E7E" />
<StatCard title="在线设备" value={onlineDevices} icon="📡" color="#7A9E7E" />
</View>
<View style={styles.statsRow}>
<StatCard title="离线设备" value={offlineDevices} icon="📡" color="#B8B3AA" />
<StatCard title="活跃告警" value={activeAlarms} icon="🔔" color={activeAlarms > 0 ? '#D4847A' : '#7A9E7E'} />
</View>
<View style={styles.sectionTitleRow}>
<View style={styles.sectionDot} />
<Text variant="titleLarge" style={styles.sectionTitle}></Text>
</View>
{metrics.length === 0 ? (
<Card style={styles.emptyCard}>
<Card.Content>
<Text style={styles.emptyText}></Text>
</Card.Content>
</Card>
) : (
<View style={styles.metricsGrid}>
{metrics.map((m) => (
<Card key={m.key} style={[styles.metricCard, { borderLeftColor: statusColor(m.status), borderLeftWidth: 4 }]}>
<Card.Content style={styles.metricContent}>
<Text variant="labelMedium" style={styles.metricName}>{m.name}</Text>
<Text style={[styles.metricValue, { color: statusColor(m.status) }]}>
{m.value.toFixed(1)}
<Text style={styles.metricUnit}> {m.unit}</Text>
</Text>
</Card.Content>
</Card>
))}
</View>
)}
<View style={styles.sectionTitleRow}>
<View style={styles.sectionDot} />
<Text variant="titleLarge" style={styles.sectionTitle}>24</Text>
</View>
{trendLoading && trend.length === 0 ? (
<Card style={styles.emptyCard}>
<Card.Content>
<View style={styles.trendLoadingRow}>
<ActivityIndicator size="small" color="#7A9E7E" />
<Text style={styles.emptyText}>...</Text>
</View>
</Card.Content>
</Card>
) : trend.length > 0 ? (
<Card style={styles.chartCard} mode="elevated">
<Card.Content>
<Text style={styles.chartMetricLabel}> (°C)</Text>
<MiniChart data={trend} metric="temp" color="#D4847A" height={100} />
<Text style={styles.chartMetricLabel}>湿 (%)</Text>
<MiniChart data={trend} metric="humidity" color="#6B8F71" height={100} />
<View style={styles.legendRow}>
<View style={styles.legendItem}>
<View style={[styles.legendDot, { backgroundColor: '#D4847A' }]} />
<Text style={styles.legendText}></Text>
</View>
<View style={styles.legendItem}>
<View style={[styles.legendDot, { backgroundColor: '#6B8F71' }]} />
<Text style={styles.legendText}>湿</Text>
</View>
</View>
</Card.Content>
</Card>
) : (
<Card style={styles.emptyCard}>
<Card.Content>
<Text style={styles.emptyText}></Text>
</Card.Content>
</Card>
)}
<View style={styles.sectionTitleRow}>
<View style={styles.sectionDot} />
<Text variant="titleLarge" style={styles.sectionTitle}></Text>
</View>
{alarms.length === 0 ? (
<Card style={styles.emptyCard}>
<Card.Content>
<Text style={styles.emptyText}></Text>
</Card.Content>
</Card>
) : (
alarms.slice(0, 5).map((alarm) => (
<Card key={alarm.id} style={styles.alarmCard}>
<Card.Content style={styles.alarmContent}>
<View style={styles.alarmLeft}>
<Text variant="bodyMedium" style={styles.alarmTitle}>
{alarm.title || alarm.message || alarm.code || '告警'}
</Text>
<Text variant="bodySmall" style={styles.alarmTime}>
{alarm.triggeredAt || alarm.createdAt || '-'}
</Text>
</View>
<Surface style={[styles.alarmBadge, { backgroundColor: alarm.severity === 'danger' ? '#D4847A' : alarm.severity === 'warn' ? '#D4B87A' : '#7A9E7E' }]}>
<Text style={styles.alarmBadgeText}>
{alarm.severity === 'danger' ? '严重' : alarm.severity === 'warn' ? '警告' : '提示'}
</Text>
</Surface>
</Card.Content>
</Card>
))
)}
</ScrollView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FAF8F5',
},
center: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
loadingText: {
marginTop: 12,
color: '#8C8780',
},
scrollView: {
flex: 1,
},
content: {
padding: 16,
paddingBottom: 32,
},
errorCard: {
marginBottom: 12,
backgroundColor: '#F9E8E5',
},
statsRow: {
flexDirection: 'row',
gap: 12,
marginBottom: 12,
},
sectionTitle: {
fontWeight: 'bold',
color: '#2D2A26',
},
sectionTitleRow: {
flexDirection: 'row',
alignItems: 'center',
marginTop: 20,
marginBottom: 12,
gap: 8,
},
sectionDot: {
width: 8,
height: 8,
borderRadius: 4,
backgroundColor: '#7A9E7E',
},
metricsGrid: {
flexDirection: 'row',
flexWrap: 'wrap',
gap: 12,
},
metricCard: {
flexBasis: '47%',
flexGrow: 1,
backgroundColor: '#FDFAF5',
borderColor: '#E8E4DE',
borderWidth: 1,
borderRadius: 14,
},
metricContent: {
paddingVertical: 8,
},
metricName: {
opacity: 0.7,
marginBottom: 4,
},
metricValue: {
fontSize: 28,
fontWeight: 'bold',
},
metricUnit: {
fontSize: 14,
fontWeight: 'normal',
opacity: 0.6,
},
chartCard: {
borderRadius: 14,
},
chartMetricLabel: {
fontSize: 12,
color: '#8C8780',
marginTop: 8,
marginBottom: 4,
},
legendRow: {
flexDirection: 'row',
justifyContent: 'center',
gap: 24,
marginTop: 8,
},
legendItem: {
flexDirection: 'row',
alignItems: 'center',
gap: 6,
},
legendDot: {
width: 12,
height: 12,
borderRadius: 6,
},
legendText: {
fontSize: 12,
color: '#8C8780',
},
emptyCard: {
marginBottom: 12,
backgroundColor: '#F5F0E8',
},
trendLoadingRow: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
gap: 8,
paddingVertical: 4,
},
emptyText: {
textAlign: 'center',
color: '#B8B3AA',
paddingVertical: 8,
},
alarmCard: {
marginBottom: 8,
borderRadius: 14,
},
alarmContent: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingVertical: 8,
},
alarmLeft: {
flex: 1,
},
alarmTitle: {
fontWeight: '500',
},
alarmTime: {
color: '#B8B3AA',
marginTop: 2,
},
alarmBadge: {
paddingHorizontal: 10,
paddingVertical: 4,
borderRadius: 12,
elevation: 0,
},
alarmBadgeText: {
color: 'white',
fontSize: 12,
fontWeight: '500',
},
});
+367
View File
@@ -0,0 +1,367 @@
import React, { useEffect, useState, useCallback } from 'react';
import { StyleSheet, View, ScrollView, Alert } from 'react-native';
import { Text, Card, Button, Switch, useTheme, ActivityIndicator, TextInput, SegmentedButtons, Divider, Snackbar } from 'react-native-paper';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRoute } from '@react-navigation/native';
import { sendControl } from '../api/devices';
import { getTelemetry, normalizeRealtime } from '../api/telemetry';
import { extractErrorMessage } from '../api/client';
import { formatNumber } from '../utils/format';
import type { RealtimeMetric } from '../types';
export default function DeviceControlScreen() {
const theme = useTheme();
const route = useRoute<any>();
const { deviceKey, deviceName } = route.params;
const [loading, setLoading] = useState(true);
const [metrics, setMetrics] = useState<RealtimeMetric[]>([]);
const [isOn, setIsOn] = useState(false);
const [sending, setSending] = useState(false);
const [snackMsg, setSnackMsg] = useState('');
const [snackVisible, setSnackVisible] = useState(false);
const [speed, setSpeed] = useState('1');
const [mode, setMode] = useState('cool');
const [tempValue, setTempValue] = useState('26');
const loadData = useCallback(async () => {
try {
const [telemetryData] = await Promise.all([
getTelemetry({ deviceKey, limit: 50 }).catch(() => [] as any[]),
]);
setMetrics(normalizeRealtime(telemetryData));
} catch {
// ignore
} finally {
setLoading(false);
}
}, [deviceKey]);
useEffect(() => {
loadData();
const interval = setInterval(loadData, 30000);
return () => clearInterval(interval);
}, [loadData]);
const handleSend = async (action: string, value?: any) => {
setSending(true);
try {
await sendControl({ deviceKey, action, value });
setSnackMsg(`命令已发送: ${action}`);
setSnackVisible(true);
if (action === 'power') {
setIsOn(!!value);
}
} catch (err: any) {
const msg = extractErrorMessage(err);
setSnackMsg(`发送失败: ${msg}`);
setSnackVisible(true);
} finally {
setSending(false);
}
};
const handleToggle = (newVal: boolean) => {
handleSend('power', newVal ? 'on' : 'off');
};
if (loading) {
return (
<SafeAreaView style={styles.center}>
<ActivityIndicator size="large" />
</SafeAreaView>
);
}
return (
<SafeAreaView style={styles.container} edges={['bottom']}>
<ScrollView contentContainerStyle={styles.content}>
<Card style={[styles.card, styles.headerCard]} mode="elevated">
<Card.Content>
<View style={styles.headerRow}>
<View>
<Text variant="headlineSmall" style={styles.deviceName}>{deviceName}</Text>
<Text variant="bodySmall" style={styles.deviceKey}>Key: {deviceKey}</Text>
</View>
<View style={styles.powerRow}>
<Text style={styles.powerLabel}>{isOn ? '开启' : '关闭'}</Text>
<Switch
value={isOn}
onValueChange={handleToggle}
disabled={sending}
color={'#7A9E7E'}
/>
</View>
</View>
</Card.Content>
</Card>
<Card style={styles.card}>
<Card.Content>
<Text variant="titleMedium" style={styles.sectionTitle}></Text>
<Text style={styles.controlLabel}></Text>
<SegmentedButtons
value={mode}
onValueChange={setMode}
buttons={[
{ value: 'cool', label: '制冷' },
{ value: 'heat', label: '制热' },
{ value: 'fan', label: '通风' },
{ value: 'auto', label: '自动' },
]}
style={styles.segmented}
theme={{ colors: { primary: '#7A9E7E' } }}
/>
<Divider style={styles.divider} />
<Text style={styles.controlLabel}></Text>
<SegmentedButtons
value={speed}
onValueChange={setSpeed}
buttons={[
{ value: '0', label: '自动' },
{ value: '1', label: '低' },
{ value: '2', label: '中' },
{ value: '3', label: '高' },
]}
style={styles.segmented}
theme={{ colors: { primary: '#7A9E7E' } }}
/>
<Divider style={styles.divider} />
<Text style={styles.controlLabel}></Text>
<View style={styles.tempRow}>
<TextInput
mode="outlined"
keyboardType="numeric"
value={tempValue}
onChangeText={setTempValue}
style={styles.tempInput}
right={<TextInput.Affix text="℃" />}
/>
<Button
mode="contained"
onPress={() => handleSend('set_temp', parseInt(tempValue, 10) || 26)}
disabled={sending}
style={styles.sendBtn}
buttonColor="#7A9E7E"
>
</Button>
</View>
<Divider style={styles.divider} />
<View style={styles.actionButtons}>
<Button
mode="outlined"
onPress={() => handleSend('fan_on')}
disabled={sending}
style={styles.actionBtn}
icon="fan"
textColor="#5C7D60"
theme={{ colors: { outline: '#7A9E7E' } }}
>
</Button>
<Button
mode="outlined"
onPress={() => handleSend('fan_off')}
disabled={sending}
style={styles.actionBtn}
icon="fan-off"
textColor="#5C7D60"
theme={{ colors: { outline: '#7A9E7E' } }}
>
</Button>
</View>
<View style={styles.actionButtons}>
<Button
mode="outlined"
onPress={() => handleSend('dehumidifier_on')}
disabled={sending}
style={styles.actionBtn}
icon="water-percent"
textColor="#5C7D60"
theme={{ colors: { outline: '#7A9E7E' } }}
>
湿
</Button>
<Button
mode="outlined"
onPress={() => handleSend('dehumidifier_off')}
disabled={sending}
style={styles.actionBtn}
icon="water-off"
textColor="#5C7D60"
theme={{ colors: { outline: '#7A9E7E' } }}
>
湿
</Button>
</View>
</Card.Content>
</Card>
<Text variant="titleLarge" style={styles.sectionTitle}></Text>
{metrics.length === 0 ? (
<Card style={styles.emptyCard}>
<Card.Content>
<Text style={styles.emptyText}></Text>
</Card.Content>
</Card>
) : (
<View style={styles.metricsGrid}>
{metrics.map((m) => {
const color = m.status === 'danger' ? '#D4847A' : m.status === 'warn' ? '#D4B87A' : '#7A9E7E';
return (
<Card key={m.key} style={[styles.metricCard, { borderLeftColor: color, borderLeftWidth: 4 }]}>
<Card.Content style={styles.metricContent}>
<Text variant="labelMedium" style={styles.metricName}>{m.name}</Text>
<Text style={[styles.metricValue, { color }]}>
{formatNumber(m.value, 1)}
<Text style={styles.metricUnit}> {m.unit}</Text>
</Text>
</Card.Content>
</Card>
);
})}
</View>
)}
</ScrollView>
<Snackbar
visible={snackVisible}
onDismiss={() => setSnackVisible(false)}
duration={3000}
>
{snackMsg}
</Snackbar>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FAF8F5',
},
center: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
content: {
padding: 16,
paddingBottom: 32,
},
card: {
marginBottom: 16,
borderRadius: 14,
},
headerCard: {
borderRadius: 20,
backgroundColor: '#FDFAF5',
borderWidth: 1,
borderColor: '#E8E4DE',
},
headerRow: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
deviceName: {
color: '#2D2A26',
fontWeight: '600',
},
deviceKey: {
color: '#B8B3AA',
marginTop: 4,
},
powerRow: {
flexDirection: 'row',
alignItems: 'center',
gap: 8,
},
powerLabel: {
fontSize: 14,
color: '#8C8780',
},
sectionTitle: {
color: '#2D2A26',
fontWeight: '600',
marginBottom: 12,
},
controlLabel: {
fontSize: 14,
color: '#8C8780',
marginBottom: 8,
marginTop: 8,
},
segmented: {
marginBottom: 8,
},
divider: {
marginVertical: 12,
},
tempRow: {
flexDirection: 'row',
alignItems: 'center',
gap: 12,
},
tempInput: {
flex: 1,
},
sendBtn: {
borderRadius: 999,
},
actionButtons: {
flexDirection: 'row',
gap: 12,
marginBottom: 8,
},
actionBtn: {
flex: 1,
borderRadius: 999,
},
metricsGrid: {
flexDirection: 'row',
flexWrap: 'wrap',
gap: 12,
},
metricCard: {
flexBasis: '47%',
flexGrow: 1,
backgroundColor: '#FDFAF5',
borderRadius: 14,
borderWidth: 1,
borderColor: '#E8E4DE',
},
metricContent: {
paddingVertical: 8,
},
metricName: {
opacity: 0.7,
marginBottom: 4,
},
metricValue: {
fontSize: 28,
fontWeight: 'bold',
},
metricUnit: {
fontSize: 14,
fontWeight: 'normal',
opacity: 0.6,
},
emptyCard: {
marginBottom: 12,
backgroundColor: '#F5F0E8',
},
emptyText: {
textAlign: 'center',
color: '#B8B3AA',
paddingVertical: 8,
},
});
+245
View File
@@ -0,0 +1,245 @@
import React, { useEffect, useState, useCallback } from 'react';
import { StyleSheet, View, FlatList, RefreshControl } from 'react-native';
import { Text, Card, useTheme, ActivityIndicator, Surface, Searchbar, IconButton } from 'react-native-paper';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { getDevices } from '../api/devices';
import { formatRelativeTime } from '../utils/format';
import type { Device } from '../types';
export default function DevicesScreen() {
const theme = useTheme();
const navigation = useNavigation<any>();
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [devices, setDevices] = useState<Device[]>([]);
const [filteredDevices, setFilteredDevices] = useState<Device[]>([]);
const [search, setSearch] = useState('');
const [error, setError] = useState<string | null>(null);
const loadData = useCallback(async (isRefresh = false) => {
if (isRefresh) setRefreshing(true);
try {
const data = await getDevices();
setDevices(data);
setFilteredDevices(data);
setError(null);
} catch (err: any) {
setError(err?.message || '加载失败');
} finally {
setLoading(false);
setRefreshing(false);
}
}, []);
useEffect(() => {
loadData();
}, [loadData]);
useEffect(() => {
if (!search.trim()) {
setFilteredDevices(devices);
} else {
const lower = search.toLowerCase();
setFilteredDevices(
devices.filter(
(d) =>
d.name.toLowerCase().includes(lower) ||
d.deviceKey.toLowerCase().includes(lower) ||
(d.kind || '').toLowerCase().includes(lower),
),
);
}
}, [search, devices]);
const isControllable = (device: Device) => {
const kind = (device.kind || device.type || '').toLowerCase();
return kind === 'actuator' || kind === 'controller' || kind === 'fan' || kind === 'ac' || kind === 'dehumidifier';
};
const getDeviceIcon = (device: Device) => {
const kind = (device.kind || device.type || '').toLowerCase();
const name = device.name.toLowerCase();
if (name.includes('fan') || kind.includes('fan')) return 'fan';
if (name.includes('ac') || name.includes('空调') || kind.includes('ac')) return 'air-conditioner';
if (name.includes('humid') || name.includes('除湿') || kind.includes('humid')) return 'water-percent';
if (name.includes('light') || name.includes('灯') || kind.includes('light')) return 'lightbulb';
if (name.includes('sensor') || kind.includes('sensor')) return 'thermometer';
if (name.includes('camera') || kind.includes('camera')) return 'video';
return 'router-wireless';
};
const renderItem = ({ item }: { item: Device }) => {
const isOnline = item.onlineStatus === 'online' || item.status === 'online';
const controllable = isControllable(item);
return (
<Card
style={styles.card}
onPress={controllable ? () => navigation.navigate('DeviceControl', { deviceKey: item.deviceKey, deviceName: item.name }) : undefined}
>
<Card.Content style={styles.cardContent}>
<View style={styles.deviceLeft}>
<View style={[styles.iconBox, { backgroundColor: isOnline ? '#E8F0E9' : '#F5F0E8' }]}>
<IconButton icon={getDeviceIcon(item)} size={24} iconColor={isOnline ? '#7A9E7E' : '#B8B3AA'} />
</View>
<View style={styles.deviceInfo}>
<Text variant="bodyMedium" style={styles.deviceName}>{item.name}</Text>
<Text variant="bodySmall" style={styles.deviceKey}>{item.deviceKey}</Text>
<View style={styles.tagRow}>
<Text variant="bodySmall" style={styles.deviceKind}>{item.kind || item.type || '设备'}</Text>
{item.model ? <Text variant="bodySmall" style={styles.deviceModel}> · {item.model}</Text> : null}
</View>
{item.lastSeen ? (
<Text variant="bodySmall" style={styles.deviceTime}>线: {formatRelativeTime(item.lastSeen)}</Text>
) : null}
</View>
</View>
<View style={styles.deviceRight}>
<Surface style={[styles.statusBadge, { backgroundColor: isOnline ? '#7A9E7E' : '#B8B3AA' }]}>
<Text style={styles.statusText}>{isOnline ? '在线' : '离线'}</Text>
</Surface>
{controllable ? (
<IconButton icon="chevron-right" size={24} iconColor="#B8B3AA" />
) : null}
</View>
</Card.Content>
</Card>
);
};
if (loading) {
return (
<SafeAreaView style={styles.center}>
<ActivityIndicator size="large" />
</SafeAreaView>
);
}
return (
<SafeAreaView style={styles.container} edges={['bottom']}>
<View style={styles.searchContainer}>
<Searchbar
placeholder="搜索设备..."
value={search}
onChangeText={setSearch}
style={styles.searchbar}
/>
</View>
<FlatList
data={filteredDevices}
keyExtractor={(item) => item.id}
renderItem={renderItem}
contentContainerStyle={styles.list}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={() => loadData(true)} />
}
ListEmptyComponent={
error ? (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}>{error}</Text>
</View>
) : (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}></Text>
</View>
)
}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FAF8F5',
},
center: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
searchContainer: {
padding: 16,
paddingBottom: 8,
},
searchbar: {
borderRadius: 14,
backgroundColor: '#FFFFFF',
},
list: {
padding: 16,
paddingTop: 8,
paddingBottom: 32,
},
card: {
marginBottom: 12,
borderRadius: 14,
backgroundColor: '#FFFFFF',
},
cardContent: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingVertical: 4,
},
deviceLeft: {
flexDirection: 'row',
alignItems: 'center',
flex: 1,
},
iconBox: {
borderRadius: 12,
marginRight: 8,
},
deviceInfo: {
flex: 1,
},
deviceName: {
color: '#2D2A26',
fontWeight: '500',
},
deviceKey: {
color: '#B8B3AA',
fontSize: 12,
marginTop: 2,
},
tagRow: {
flexDirection: 'row',
alignItems: 'center',
marginTop: 2,
},
deviceKind: {
color: '#8C8780',
},
deviceModel: {
color: '#B8B3AA',
},
deviceTime: {
color: '#B8B3AA',
marginTop: 2,
},
deviceRight: {
flexDirection: 'row',
alignItems: 'center',
},
statusBadge: {
paddingHorizontal: 10,
paddingVertical: 4,
borderRadius: 14,
elevation: 0,
},
statusText: {
color: 'white',
fontSize: 12,
fontWeight: '500',
},
emptyContainer: {
alignItems: 'center',
paddingTop: 64,
},
emptyText: {
color: '#B8B3AA',
fontSize: 16,
},
});
+137
View File
@@ -0,0 +1,137 @@
import React, { useState } from 'react';
import { StyleSheet, View, KeyboardAvoidingView, Platform, ScrollView, Alert } from 'react-native';
import { Text, TextInput, Button, Card, ActivityIndicator } from 'react-native-paper';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { useAuthStore } from '../store/authStore';
export default function LoginScreen() {
const navigation = useNavigation<any>();
const { login, isLoading, error } = useAuthStore();
const [username, setUsername] = useState('admin');
const [password, setPassword] = useState('silk@123');
const [showPassword, setShowPassword] = useState(false);
const handleLogin = async () => {
if (!username.trim() || !password.trim()) {
Alert.alert('提示', '请输入用户名和密码');
return;
}
const success = await login(username.trim(), password);
if (success) {
navigation.reset({
index: 0,
routes: [{ name: 'Main' }],
});
}
};
return (
<SafeAreaView style={styles.container}>
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
style={styles.flex}
>
<ScrollView contentContainerStyle={styles.scrollContent} keyboardShouldPersistTaps="handled">
<View style={styles.header}>
<Text style={[styles.title, { color: '#5C7D60' }]}></Text>
<Text style={styles.subtitle}></Text>
</View>
<Card style={styles.card} mode="elevated">
<Card.Content style={styles.cardContent}>
<TextInput
label="用户名"
value={username}
onChangeText={setUsername}
mode="outlined"
left={<TextInput.Icon icon="account" />}
style={styles.input}
activeOutlineColor="#7A9E7E"
autoCapitalize="none"
autoCorrect={false}
/>
<TextInput
label="密码"
value={password}
onChangeText={setPassword}
mode="outlined"
left={<TextInput.Icon icon="lock" />}
right={
<TextInput.Icon
icon={showPassword ? 'eye-off' : 'eye'}
onPress={() => setShowPassword(!showPassword)}
/>
}
secureTextEntry={!showPassword}
style={styles.input}
autoCapitalize="none"
autoCorrect={false}
/>
{error ? <Text style={styles.errorText}>{error}</Text> : null}
<Button
mode="contained"
onPress={handleLogin}
style={styles.button}
buttonColor="#7A9E7E"
disabled={isLoading}
>
{isLoading ? <ActivityIndicator color="white" size="small" /> : '登录'}
</Button>
</Card.Content>
</Card>
</ScrollView>
</KeyboardAvoidingView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FAF8F5',
},
flex: {
flex: 1,
},
scrollContent: {
flexGrow: 1,
justifyContent: 'center',
padding: 24,
},
header: {
alignItems: 'center',
marginBottom: 32,
},
title: {
fontSize: 32,
fontWeight: 'bold',
},
subtitle: {
fontSize: 16,
color: '#8C8780',
marginTop: 8,
},
card: {
borderRadius: 20,
backgroundColor: '#F5F0E8',
},
cardContent: {
padding: 8,
},
input: {
marginBottom: 16,
},
errorText: {
color: '#D4847A',
fontSize: 14,
marginBottom: 12,
},
button: {
marginTop: 8,
paddingVertical: 6,
borderRadius: 999,
},
});
+321
View File
@@ -0,0 +1,321 @@
import React, { useEffect, useState, useCallback, useRef } from 'react';
import { StyleSheet, View, ScrollView, RefreshControl } from 'react-native';
import { Text, Card, useTheme, ActivityIndicator, Surface } from 'react-native-paper';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRoute } from '@react-navigation/native';
import { getRoom } from '../api/rooms';
import { getTelemetry, normalizeRealtime, fetchTrend } from '../api/telemetry';
import { getDevices } from '../api/devices';
import { MiniChart } from '../components/MiniChart';
import { formatRelativeTime } from '../utils/format';
import type { Room, RealtimeMetric, Device, TrendPoint } from '../types';
export default function RoomDetailScreen() {
const theme = useTheme();
const route = useRoute<any>();
const { roomId, roomName } = route.params;
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [room, setRoom] = useState<Room | null>(null);
const [metrics, setMetrics] = useState<RealtimeMetric[]>([]);
const [devices, setDevices] = useState<Device[]>([]);
const [trend, setTrend] = useState<TrendPoint[]>([]);
const [error, setError] = useState<string | null>(null);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const loadData = useCallback(async (isRefresh = false) => {
if (isRefresh) setRefreshing(true);
try {
const [roomData, devicesData, telemetryData] = await Promise.all([
getRoom(roomId).catch(() => null),
getDevices({ roomId }).catch(() => [] as Device[]),
getTelemetry({ limit: 100 }).catch(() => [] as any[]),
]);
setRoom(roomData);
setDevices(devicesData);
setMetrics(normalizeRealtime(telemetryData));
// Build trend from telemetry
const trendData = await fetchTrend(24).catch(() => [] as TrendPoint[]);
setTrend(trendData);
setError(null);
} catch (err: any) {
setError(err?.message || '加载失败');
} finally {
setLoading(false);
setRefreshing(false);
}
}, [roomId]);
useEffect(() => {
loadData();
intervalRef.current = setInterval(() => loadData(), 30000);
return () => {
if (intervalRef.current) clearInterval(intervalRef.current);
};
}, [loadData]);
if (loading) {
return (
<SafeAreaView style={styles.center}>
<ActivityIndicator size="large" />
</SafeAreaView>
);
}
const statusColor = (status: RealtimeMetric['status']) => {
switch (status) {
case 'danger': return '#D4847A';
case 'warn': return '#D4B87A';
default: return '#7A9E7E';
}
};
return (
<SafeAreaView style={styles.container} edges={['bottom']}>
<ScrollView
contentContainerStyle={styles.content}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={() => loadData(true)} />
}
>
{error ? (
<Card style={styles.errorCard}>
<Card.Content>
<Text style={{ color: '#D4847A' }}>{error}</Text>
</Card.Content>
</Card>
) : null}
<Card style={styles.infoCard} mode="elevated">
<Card.Content>
<Text variant="headlineSmall" style={styles.roomName}>{room?.name || roomName}</Text>
{room?.code ? <Text style={styles.infoText}>: {room.code}</Text> : null}
{room?.location ? <Text style={styles.infoText}>: {room.location}</Text> : null}
{room?.description ? <Text style={styles.infoText}>: {room.description}</Text> : null}
{room?.status ? <Text style={styles.infoText}>: {room.status}</Text> : null}
</Card.Content>
</Card>
<Text variant="titleLarge" style={styles.sectionTitle}></Text>
{metrics.length === 0 ? (
<Card style={styles.emptyCard}>
<Card.Content>
<Text style={styles.emptyText}></Text>
</Card.Content>
</Card>
) : (
<View style={styles.metricsGrid}>
{metrics.map((m) => (
<Card key={m.key} style={[styles.metricCard, { borderLeftColor: statusColor(m.status), borderLeftWidth: 4 }]}>
<Card.Content style={styles.metricContent}>
<Text variant="labelMedium" style={styles.metricName}>{m.name}</Text>
<Text style={[styles.metricValue, { color: statusColor(m.status) }]}>
{m.value.toFixed(1)}
<Text style={styles.metricUnit}> {m.unit}</Text>
</Text>
</Card.Content>
</Card>
))}
</View>
)}
<Text variant="titleLarge" style={styles.sectionTitle}>24</Text>
{trend.length > 0 ? (
<Card style={styles.chartCard} mode="elevated">
<Card.Content>
<Text style={styles.chartMetricLabel}> (°C)</Text>
<MiniChart data={trend} metric="temp" color="#D4847A" height={100} />
<Text style={styles.chartMetricLabel}>湿 (%)</Text>
<MiniChart data={trend} metric="humidity" color="#6B8F71" height={100} />
<View style={styles.legendRow}>
<View style={styles.legendItem}>
<View style={[styles.legendDot, { backgroundColor: '#D4847A' }]} />
<Text style={styles.legendText}></Text>
</View>
<View style={styles.legendItem}>
<View style={[styles.legendDot, { backgroundColor: '#6B8F71' }]} />
<Text style={styles.legendText}>湿</Text>
</View>
</View>
</Card.Content>
</Card>
) : (
<Card style={styles.emptyCard}>
<Card.Content>
<Text style={styles.emptyText}></Text>
</Card.Content>
</Card>
)}
<Text variant="titleLarge" style={styles.sectionTitle}></Text>
{devices.length === 0 ? (
<Card style={styles.emptyCard}>
<Card.Content>
<Text style={styles.emptyText}></Text>
</Card.Content>
</Card>
) : (
devices.map((device) => (
<Card key={device.id} style={styles.deviceCard}>
<Card.Content style={styles.deviceContent}>
<View style={styles.deviceInfo}>
<Text variant="bodyMedium" style={styles.deviceName}>{device.name}</Text>
<Text variant="bodySmall" style={styles.deviceKey}>Key: {device.deviceKey}</Text>
{device.lastSeen ? (
<Text variant="bodySmall" style={styles.deviceTime}>
线: {formatRelativeTime(device.lastSeen)}
</Text>
) : null}
</View>
<Surface style={[styles.deviceBadge, { backgroundColor: device.onlineStatus === 'online' || device.status === 'online' ? '#7A9E7E' : '#B8B3AA' }]}>
<Text style={styles.deviceBadgeText}>
{device.onlineStatus === 'online' || device.status === 'online' ? '在线' : '离线'}
</Text>
</Surface>
</Card.Content>
</Card>
))
)}
</ScrollView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FAF8F5',
},
center: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
content: {
padding: 16,
paddingBottom: 32,
},
errorCard: {
marginBottom: 12,
backgroundColor: '#F9E8E5',
},
infoCard: {
borderRadius: 12,
marginBottom: 8,
},
roomName: {
color: '#2D2A26',
fontWeight: '600',
marginBottom: 8,
},
infoText: {
color: '#8C8780',
marginTop: 4,
},
sectionTitle: {
marginTop: 20,
marginBottom: 12,
color: '#2D2A26',
fontWeight: '600',
},
metricsGrid: {
flexDirection: 'row',
flexWrap: 'wrap',
gap: 12,
},
metricCard: {
flexBasis: '47%',
flexGrow: 1,
},
metricContent: {
paddingVertical: 8,
},
metricName: {
opacity: 0.7,
marginBottom: 4,
},
metricValue: {
fontSize: 28,
fontWeight: 'bold',
},
metricUnit: {
fontSize: 14,
fontWeight: 'normal',
opacity: 0.6,
},
chartCard: {
borderRadius: 12,
},
chartMetricLabel: {
fontSize: 12,
color: '#8C8780',
marginTop: 8,
marginBottom: 4,
},
legendRow: {
flexDirection: 'row',
justifyContent: 'center',
gap: 24,
marginTop: 8,
},
legendItem: {
flexDirection: 'row',
alignItems: 'center',
gap: 6,
},
legendDot: {
width: 12,
height: 12,
borderRadius: 6,
},
legendText: {
fontSize: 12,
color: '#8C8780',
},
emptyCard: {
marginBottom: 12,
backgroundColor: '#F5F0E8',
},
emptyText: {
textAlign: 'center',
color: '#B8B3AA',
paddingVertical: 8,
},
deviceCard: {
marginBottom: 8,
borderRadius: 8,
},
deviceContent: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingVertical: 8,
},
deviceInfo: {
flex: 1,
},
deviceName: {
fontWeight: '500',
},
deviceKey: {
color: '#B8B3AA',
marginTop: 2,
},
deviceTime: {
color: '#B8B3AA',
marginTop: 2,
},
deviceBadge: {
paddingHorizontal: 10,
paddingVertical: 4,
borderRadius: 12,
elevation: 0,
},
deviceBadgeText: {
color: 'white',
fontSize: 12,
fontWeight: '500',
},
});
+184
View File
@@ -0,0 +1,184 @@
import React, { useEffect, useState, useCallback } from 'react';
import { StyleSheet, View, FlatList, RefreshControl } from 'react-native';
import { Text, Card, useTheme, ActivityIndicator, IconButton } from 'react-native-paper';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { getRooms } from '../api/rooms';
import { formatRelativeTime } from '../utils/format';
import type { Room } from '../types';
export default function RoomsScreen() {
const theme = useTheme();
const navigation = useNavigation<any>();
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [rooms, setRooms] = useState<Room[]>([]);
const [error, setError] = useState<string | null>(null);
const loadData = useCallback(async (isRefresh = false) => {
if (isRefresh) setRefreshing(true);
try {
const data = await getRooms();
setRooms(data);
setError(null);
} catch (err: any) {
setError(err?.message || '加载失败');
} finally {
setLoading(false);
setRefreshing(false);
}
}, []);
useEffect(() => {
loadData();
}, [loadData]);
const getStatusColor = (status?: string) => {
switch (status) {
case 'active':
case 'running':
return '#7A9E7E';
case 'alarm':
return '#D4847A';
case 'idle':
case 'inactive':
return '#B8B3AA';
default:
return '#6B8F71';
}
};
const getStatusLabel = (status?: string) => {
switch (status) {
case 'active': return '运行中';
case 'running': return '运行中';
case 'idle': return '空闲';
case 'inactive': return '停用';
case 'alarm': return '告警';
default: return status || '未知';
}
};
const renderItem = ({ item }: { item: Room }) => (
<Card
style={styles.card}
onPress={() => navigation.navigate('RoomDetail', { roomId: item.id, roomName: item.name })}
>
<Card.Content style={styles.cardContent}>
<View style={styles.roomInfo}>
<View style={styles.roomHeader}>
<Text variant="titleMedium" style={styles.roomName}>{item.name}</Text>
<View style={[styles.statusBadge, { backgroundColor: getStatusColor(item.status) }]}>
<Text style={styles.statusText}>{getStatusLabel(item.status)}</Text>
</View>
</View>
{item.code ? <Text variant="bodySmall" style={styles.roomCode}>: {item.code}</Text> : null}
{item.location ? <Text variant="bodySmall" style={styles.roomLocation}>📍 {item.location}</Text> : null}
{item.description ? <Text variant="bodySmall" style={styles.roomDesc} numberOfLines={2}>{item.description}</Text> : null}
</View>
<IconButton icon="chevron-right" size={28} iconColor="#B8B3AA" />
</Card.Content>
</Card>
);
if (loading) {
return (
<SafeAreaView style={styles.center}>
<ActivityIndicator size="large" />
</SafeAreaView>
);
}
return (
<SafeAreaView style={styles.container} edges={['bottom']}>
<FlatList
data={rooms}
keyExtractor={(item) => item.id}
renderItem={renderItem}
contentContainerStyle={styles.list}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={() => loadData(true)} />
}
ListEmptyComponent={
error ? (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}>{error}</Text>
</View>
) : (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}></Text>
</View>
)
}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FAF8F5',
},
center: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
list: {
padding: 16,
paddingBottom: 32,
},
card: {
marginBottom: 12,
borderRadius: 14,
backgroundColor: '#FFFFFF',
},
cardContent: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
roomInfo: {
flex: 1,
},
roomHeader: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
marginBottom: 4,
},
roomName: {
color: '#2D2A26',
fontWeight: '600',
},
statusBadge: {
paddingHorizontal: 10,
paddingVertical: 3,
borderRadius: 12,
},
statusText: {
color: 'white',
fontSize: 11,
fontWeight: '500',
},
roomCode: {
color: '#B8B3AA',
marginBottom: 2,
},
roomLocation: {
color: '#8C8780',
marginBottom: 2,
},
roomDesc: {
color: '#8C8780',
},
emptyContainer: {
alignItems: 'center',
paddingTop: 64,
},
emptyText: {
color: '#B8B3AA',
fontSize: 16,
},
});
+179
View File
@@ -0,0 +1,179 @@
import React, { useState } from 'react';
import { StyleSheet, View, Alert, ScrollView } from 'react-native';
import { Text, Card, Button, useTheme, Divider, TextInput, List, Avatar } from 'react-native-paper';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { useAuthStore } from '../store/authStore';
import { API_BASE_URL } from '@env';
export default function SettingsScreen() {
const theme = useTheme();
const navigation = useNavigation<any>();
const { user, logout } = useAuthStore();
const [apiUrl, setApiUrl] = useState(API_BASE_URL || 'http://localhost:3000/api/v1');
const handleLogout = () => {
Alert.alert('确认退出', '确定要退出登录吗?', [
{ text: '取消', style: 'cancel' },
{
text: '退出',
style: 'destructive',
onPress: async () => {
await logout();
},
},
]);
};
const getRoleLabel = (role?: string) => {
switch (role) {
case 'admin': return '管理员';
case 'operator': return '操作员';
case 'viewer': return '查看者';
default: return role || '未知';
}
};
return (
<SafeAreaView style={styles.container} edges={['bottom']}>
<ScrollView style={styles.scrollView} contentContainerStyle={styles.content}>
<View style={styles.profileSection}>
<Avatar.Text
size={72}
label={user?.username?.charAt(0).toUpperCase() || 'U'}
style={{ backgroundColor: theme.colors.primary }}
color="white"
/>
<Text variant="headlineSmall" style={styles.userName}>
{user?.fullName || user?.username || '用户'}
</Text>
<Text style={styles.userRole}>{getRoleLabel(user?.role)}</Text>
</View>
<Card style={styles.card} mode="elevated">
<Card.Content>
<Text variant="titleMedium" style={styles.sectionTitle}></Text>
<List.Item
title="用户名"
description={user?.username || '-'}
left={(props) => <List.Icon {...props} icon="account" />}
/>
<Divider />
<List.Item
title="邮箱"
description={user?.email || '-'}
left={(props) => <List.Icon {...props} icon="email" />}
/>
<Divider />
<List.Item
title="姓名"
description={user?.fullName || '-'}
left={(props) => <List.Icon {...props} icon="card-account-details" />}
/>
<Divider />
<List.Item
title="角色"
description={getRoleLabel(user?.role)}
left={(props) => <List.Icon {...props} icon="shield-account" />}
/>
</Card.Content>
</Card>
<Card style={styles.card}>
<Card.Content>
<Text variant="titleMedium" style={styles.sectionTitle}></Text>
<TextInput
label="API 地址"
value={apiUrl}
onChangeText={setApiUrl}
mode="outlined"
style={styles.input}
autoCapitalize="none"
autoCorrect={false}
/>
<Text style={styles.hintText}>
Android 使 10.0.2.2 localhost
</Text>
</Card.Content>
</Card>
<Card style={styles.card}>
<Card.Content>
<Text variant="titleMedium" style={styles.sectionTitle}></Text>
<List.Item
title="应用名称"
description="智慧蚕房"
left={(props) => <List.Icon {...props} icon="information" />}
/>
<Divider />
<List.Item
title="版本"
description="1.0.0"
left={(props) => <List.Icon {...props} icon="tag" />}
/>
</Card.Content>
</Card>
<Button
mode="contained"
onPress={handleLogout}
style={styles.logoutBtn}
buttonColor="#D4847A"
icon="logout"
>
退
</Button>
</ScrollView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FAF8F5',
},
scrollView: {
flex: 1,
},
content: {
padding: 16,
paddingBottom: 32,
},
profileSection: {
alignItems: 'center',
paddingVertical: 24,
},
userName: {
color: '#2D2A26',
fontWeight: '600',
marginTop: 12,
},
userRole: {
color: '#8C8780',
marginTop: 4,
},
card: {
marginBottom: 16,
borderRadius: 14,
backgroundColor: '#FFFFFF',
},
sectionTitle: {
color: '#2D2A26',
fontWeight: '600',
marginBottom: 8,
},
input: {
marginTop: 8,
},
hintText: {
fontSize: 12,
color: '#B8B3AA',
marginTop: 8,
},
logoutBtn: {
marginTop: 16,
borderRadius: 999,
paddingVertical: 6,
},
});
+433
View File
@@ -0,0 +1,433 @@
import React, { useEffect, useState, useCallback } from 'react';
import { StyleSheet, View, FlatList, RefreshControl, Alert, Modal } from 'react-native';
import { Text, Card, Button, Switch, useTheme, ActivityIndicator, TextInput, FAB, IconButton, Surface } from 'react-native-paper';
import { SafeAreaView } from 'react-native-safe-area-context';
import { getThresholds, createThreshold, updateThreshold, deleteThreshold } from '../api/thresholds';
import { extractErrorMessage } from '../api/client';
import { getMetricName, getMetricUnit } from '../utils/format';
import type { Threshold } from '../types';
export default function ThresholdsScreen() {
const theme = useTheme();
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [thresholds, setThresholds] = useState<Threshold[]>([]);
const [error, setError] = useState<string | null>(null);
const [modalVisible, setModalVisible] = useState(false);
const [editing, setEditing] = useState<Threshold | null>(null);
const [saving, setSaving] = useState(false);
// Form state
const [name, setName] = useState('');
const [metric, setMetric] = useState('temperature');
const [minValue, setMinValue] = useState('20');
const [maxValue, setMaxValue] = useState('30');
const [debounce, setDebounce] = useState('30');
const [severity, setSeverity] = useState('1');
const [enabled, setEnabled] = useState(true);
const loadData = useCallback(async (isRefresh = false) => {
if (isRefresh) setRefreshing(true);
try {
const data = await getThresholds();
setThresholds(data);
setError(null);
} catch (err: any) {
setError(err?.message || '加载失败');
} finally {
setLoading(false);
setRefreshing(false);
}
}, []);
useEffect(() => {
loadData();
}, [loadData]);
const openCreate = () => {
setEditing(null);
setName('');
setMetric('temperature');
setMinValue('20');
setMaxValue('30');
setDebounce('30');
setSeverity('1');
setEnabled(true);
setModalVisible(true);
};
const openEdit = (item: Threshold) => {
setEditing(item);
setName(item.name || '');
setMetric(item.metric || 'temperature');
setMinValue(String(item.minValue ?? item.min ?? ''));
setMaxValue(String(item.maxValue ?? item.max ?? ''));
setDebounce(String(item.debounceSeconds ?? '30'));
setSeverity(String(item.severity ?? '1'));
setEnabled(item.enabled);
setModalVisible(true);
};
const handleSave = async () => {
if (!metric.trim()) {
Alert.alert('提示', '请输入监控指标');
return;
}
const payload = {
name: name.trim() || undefined,
metric: metric.trim(),
minValue: parseFloat(minValue) || 0,
maxValue: parseFloat(maxValue) || 0,
debounceSeconds: parseInt(debounce, 10) || 0,
severity: parseInt(severity, 10) || 1,
enabled,
};
setSaving(true);
try {
if (editing) {
await updateThreshold(editing.id, payload);
setThresholds((prev) =>
prev.map((t) => (t.id === editing.id ? { ...t, ...payload } : t)),
);
} else {
const created = await createThreshold(payload);
setThresholds((prev) => [...prev, created]);
}
setModalVisible(false);
} catch (err: any) {
Alert.alert('保存失败', extractErrorMessage(err));
} finally {
setSaving(false);
}
};
const handleDelete = (item: Threshold) => {
Alert.alert('确认删除', `确定要删除阈值"${item.name || item.metric}"吗?`, [
{ text: '取消', style: 'cancel' },
{
text: '删除',
style: 'destructive',
onPress: async () => {
try {
await deleteThreshold(item.id);
setThresholds((prev) => prev.filter((t) => t.id !== item.id));
} catch (err: any) {
Alert.alert('删除失败', extractErrorMessage(err));
}
},
},
]);
};
const getSevColor = (sev: number) => {
if (sev >= 3) return '#D4847A';
if (sev >= 2) return '#D4B87A';
return '#6B8F71';
};
const renderItem = ({ item }: { item: Threshold }) => (
<Card style={styles.card}>
<Card.Content style={styles.cardContent}>
<View style={styles.headerRow}>
<View style={styles.titleRow}>
<Surface style={[styles.sevDot, { backgroundColor: getSevColor(item.severity) }]}>{null}</Surface>
<Text variant="titleMedium" style={styles.thresholdName}>
{item.name || getMetricName(item.metric || '')}
</Text>
</View>
<Switch
value={item.enabled}
onValueChange={async (val) => {
try {
await updateThreshold(item.id, { enabled: val });
setThresholds((prev) =>
prev.map((t) => (t.id === item.id ? { ...t, enabled: val } : t)),
);
} catch (err: any) {
Alert.alert('更新失败', extractErrorMessage(err));
}
}}
color={theme.colors.primary}
/>
</View>
<View style={styles.rangeRow}>
<View style={styles.rangeItem}>
<Text style={styles.rangeLabel}></Text>
<Text style={styles.rangeValue}>
{item.minValue ?? item.min} {getMetricUnit(item.metric || '')}
</Text>
</View>
<View style={styles.rangeItem}>
<Text style={styles.rangeLabel}></Text>
<Text style={styles.rangeValue}>
{item.maxValue ?? item.max} {getMetricUnit(item.metric || '')}
</Text>
</View>
<View style={styles.rangeItem}>
<Text style={styles.rangeLabel}></Text>
<Text style={styles.rangeValue}>{item.debounceSeconds}s</Text>
</View>
</View>
<View style={styles.actionsRow}>
<Button mode="text" onPress={() => openEdit(item)} textColor="#5C7D60">
</Button>
<Button mode="text" onPress={() => handleDelete(item)} textColor="#D4847A">
</Button>
</View>
</Card.Content>
</Card>
);
if (loading) {
return (
<SafeAreaView style={styles.center}>
<ActivityIndicator size="large" />
</SafeAreaView>
);
}
return (
<SafeAreaView style={styles.container} edges={['bottom']}>
<FlatList
data={thresholds}
keyExtractor={(item) => item.id}
renderItem={renderItem}
contentContainerStyle={styles.list}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={() => loadData(true)} />
}
ListEmptyComponent={
error ? (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}>{error}</Text>
</View>
) : (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}></Text>
<Text style={styles.emptySubtext}></Text>
</View>
)
}
/>
<FAB icon="plus" style={styles.fab} onPress={openCreate} color="white" />
<Modal visible={modalVisible} animationType="slide" transparent>
<View style={styles.modalOverlay}>
<Card style={styles.modalCard}>
<Card.Content>
<View style={styles.modalHeader}>
<Text variant="titleLarge">{editing ? '编辑阈值' : '新建阈值'}</Text>
<IconButton icon="close" onPress={() => setModalVisible(false)} />
</View>
<TextInput
label="名称 (可选)"
value={name}
onChangeText={setName}
mode="outlined"
style={styles.input}
/>
<TextInput
label="监控指标"
value={metric}
onChangeText={setMetric}
mode="outlined"
style={styles.input}
placeholder="temperature, humidity, co2..."
/>
<View style={styles.twoColRow}>
<TextInput
label="下限"
value={minValue}
onChangeText={setMinValue}
mode="outlined"
keyboardType="numeric"
style={styles.halfInput}
/>
<TextInput
label="上限"
value={maxValue}
onChangeText={setMaxValue}
mode="outlined"
keyboardType="numeric"
style={styles.halfInput}
/>
</View>
<View style={styles.twoColRow}>
<TextInput
label="延迟(秒)"
value={debounce}
onChangeText={setDebounce}
mode="outlined"
keyboardType="numeric"
style={styles.halfInput}
/>
<TextInput
label="严重级别(1-3)"
value={severity}
onChangeText={setSeverity}
mode="outlined"
keyboardType="numeric"
style={styles.halfInput}
/>
</View>
<View style={styles.switchRow}>
<Text></Text>
<Switch value={enabled} onValueChange={setEnabled} color={theme.colors.primary} />
</View>
<View style={styles.modalActions}>
<Button mode="outlined" onPress={() => setModalVisible(false)} style={styles.modalBtn}>
</Button>
<Button
mode="contained"
onPress={handleSave}
loading={saving}
disabled={saving}
style={styles.modalBtn}
>
</Button>
</View>
</Card.Content>
</Card>
</View>
</Modal>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FAF8F5',
},
center: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
list: {
padding: 16,
paddingBottom: 80,
},
card: {
marginBottom: 12,
borderRadius: 14,
backgroundColor: '#FFFFFF',
},
cardContent: {
paddingVertical: 8,
},
headerRow: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 8,
},
titleRow: {
flexDirection: 'row',
alignItems: 'center',
gap: 8,
},
sevDot: {
width: 10,
height: 10,
borderRadius: 5,
elevation: 0,
},
thresholdName: {
color: '#2D2A26',
fontWeight: '500',
},
rangeRow: {
flexDirection: 'row',
gap: 16,
marginBottom: 8,
},
rangeItem: {
flex: 1,
},
rangeLabel: {
fontSize: 12,
color: '#B8B3AA',
},
rangeValue: {
fontSize: 16,
color: '#2D2A26',
fontWeight: '500',
marginTop: 2,
},
actionsRow: {
flexDirection: 'row',
justifyContent: 'flex-end',
},
emptyContainer: {
alignItems: 'center',
paddingTop: 64,
},
emptyText: {
color: '#B8B3AA',
fontSize: 16,
},
emptySubtext: {
color: '#C4BFB6',
fontSize: 14,
marginTop: 8,
},
fab: {
position: 'absolute',
margin: 16,
right: 0,
bottom: 0,
backgroundColor: '#7A9E7E',
},
modalOverlay: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0.5)',
justifyContent: 'center',
padding: 24,
},
modalCard: {
borderRadius: 20,
maxHeight: '85%',
},
modalHeader: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 16,
},
input: {
marginBottom: 12,
},
twoColRow: {
flexDirection: 'row',
gap: 12,
},
halfInput: {
flex: 1,
marginBottom: 12,
},
switchRow: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 16,
},
modalActions: {
flexDirection: 'row',
gap: 12,
},
modalBtn: {
flex: 1,
borderRadius: 999,
},
});
+188
View File
@@ -0,0 +1,188 @@
import React, { useState, useRef, useEffect } from 'react';
import { StyleSheet, View, StatusBar, Alert, ActivityIndicator } from 'react-native';
import { Text, IconButton, Surface } from 'react-native-paper';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRoute, useNavigation } from '@react-navigation/native';
import Video, { type VideoRef } from 'react-native-video';
export default function VideoPlayerScreen() {
const route = useRoute<any>();
const navigation = useNavigation<any>();
const { cameraName, streamUrl } = route.params;
const videoRef = useRef<VideoRef>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [paused, setPaused] = useState(false);
const [muted, setMuted] = useState(true);
useEffect(() => {
if (!streamUrl) {
setError('无视频流地址');
setLoading(false);
}
}, [streamUrl]);
const handleLoad = () => {
setLoading(false);
setError(null);
};
const handleError = (e: any) => {
setLoading(false);
const msg = e?.error?.errorString || e?.error?.localizedDescription || '视频加载失败';
setError(msg);
};
return (
<View style={styles.container}>
<StatusBar barStyle="light-content" />
<SafeAreaView style={styles.header} edges={['top']}>
<IconButton
icon="arrow-left"
iconColor="white"
size={24}
onPress={() => navigation.goBack()}
/>
<Text style={styles.headerTitle}>{cameraName}</Text>
<View style={{ width: 48 }} />
</SafeAreaView>
<View style={styles.videoContainer}>
{error ? (
<View style={styles.errorContainer}>
<IconButton icon="alert-circle-outline" size={48} iconColor="#B8B3AA" />
<Text style={styles.errorText}>{error}</Text>
</View>
) : (
<>
{streamUrl ? (
<Video
ref={videoRef}
source={{ uri: streamUrl }}
style={styles.video}
resizeMode="contain"
paused={paused}
muted={muted}
onLoad={handleLoad}
onError={handleError}
playInBackground={false}
controls={false}
bufferConfig={{
minBufferMs: 1000,
maxBufferMs: 3000,
bufferForPlaybackMs: 500,
bufferForPlaybackAfterRebufferMs: 1000,
}}
/>
) : null}
{loading ? (
<View style={styles.loadingOverlay}>
<ActivityIndicator size="large" color="white" />
<Text style={styles.loadingText}>...</Text>
</View>
) : null}
{!loading && !error ? (
<View style={styles.controlsOverlay}>
<Surface style={styles.controlBar}>
<IconButton
icon={paused ? 'play' : 'pause'}
iconColor="white"
size={28}
onPress={() => setPaused(!paused)}
/>
<IconButton
icon={muted ? 'volume-off' : 'volume-high'}
iconColor="white"
size={24}
onPress={() => setMuted(!muted)}
/>
</Surface>
</View>
) : null}
</>
)}
</View>
<View style={styles.footer}>
<Text style={styles.streamUrl}>: {streamUrl || 'N/A'}</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#000',
},
header: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
backgroundColor: '#1A1815',
paddingHorizontal: 4,
},
headerTitle: {
color: 'white',
fontSize: 18,
fontWeight: '500',
flex: 1,
textAlign: 'center',
},
videoContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#000',
},
video: {
width: '100%',
height: '100%',
},
loadingOverlay: {
...StyleSheet.absoluteFillObject,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(26,24,21,0.5)',
},
loadingText: {
color: 'white',
marginTop: 12,
},
controlsOverlay: {
position: 'absolute',
bottom: 24,
left: 0,
right: 0,
alignItems: 'center',
},
controlBar: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: 'rgba(26,24,21,0.6)',
borderRadius: 28,
paddingHorizontal: 8,
elevation: 0,
},
errorContainer: {
alignItems: 'center',
justifyContent: 'center',
},
errorText: {
color: '#B8B3AA',
fontSize: 16,
marginTop: 8,
textAlign: 'center',
paddingHorizontal: 32,
},
footer: {
padding: 12,
backgroundColor: '#1A1815',
},
streamUrl: {
color: '#8C8780',
fontSize: 11,
},
});
+274
View File
@@ -0,0 +1,274 @@
import React, { useEffect, useState, useCallback } from 'react';
import { StyleSheet, View, FlatList, RefreshControl, Alert } from 'react-native';
import { Text, Card, Button, useTheme, ActivityIndicator, Surface, IconButton, SegmentedButtons } from 'react-native-paper';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { getCameras, getClips, playCamera } from '../api/video';
import { extractErrorMessage, resolveUrl } from '../api/client';
import { formatDateTime, formatDuration, formatFileSize } from '../utils/format';
import type { Camera, VideoClip } from '../types';
export default function VideoScreen() {
const theme = useTheme();
const navigation = useNavigation<any>();
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [cameras, setCameras] = useState<Camera[]>([]);
const [clips, setClips] = useState<VideoClip[]>([]);
const [error, setError] = useState<string | null>(null);
const [tab, setTab] = useState('cameras');
const loadData = useCallback(async (isRefresh = false) => {
if (isRefresh) setRefreshing(true);
try {
const [camerasData, clipsData] = await Promise.all([
getCameras().catch(() => [] as Camera[]),
getClips({ limit: 20 }).catch(() => [] as VideoClip[]),
]);
setCameras(camerasData);
setClips(clipsData);
setError(null);
} catch (err: any) {
setError(err?.message || '加载失败');
} finally {
setLoading(false);
setRefreshing(false);
}
}, []);
useEffect(() => {
loadData();
}, [loadData]);
const handlePlay = async (camera: Camera) => {
const streamUrl = resolveUrl(`/api/v1/video/cameras/${camera.id}/live/stream`);
navigation.navigate('VideoPlayer', {
cameraId: camera.id,
cameraName: camera.name,
streamUrl,
});
};
const handlePlayClip = async (clip: VideoClip) => {
if (clip.playbackUrl) {
navigation.navigate('VideoPlayer', {
cameraId: clip.cameraId,
cameraName: `录像片段 ${clip.startAt ? formatDateTime(clip.startAt) : ''}`,
streamUrl: resolveUrl(clip.playbackUrl),
});
} else {
Alert.alert('提示', '该录像暂无播放地址');
}
};
const renderCamera = ({ item }: { item: Camera }) => {
const isOnline = item.isOnline ?? item.online;
return (
<Card style={styles.card}>
<Card.Content style={styles.cardContent}>
<View style={styles.cameraInfo}>
<View style={[styles.iconBox, { backgroundColor: isOnline ? '#E8F0E9' : '#F5F0E8' }]}>
<IconButton icon="video" size={24} iconColor={isOnline ? '#7A9E7E' : '#B8B3AA'} />
</View>
<View style={styles.cameraDetail}>
<Text variant="bodyMedium" style={styles.cameraName}>{item.name}</Text>
<Text variant="bodySmall" style={styles.cameraCode}>: {item.code}</Text>
{item.position ? <Text variant="bodySmall" style={styles.cameraMeta}>📍 {item.position}</Text> : null}
{item.resolution ? <Text variant="bodySmall" style={styles.cameraMeta}>: {item.resolution}</Text> : null}
</View>
</View>
<View style={styles.cameraRight}>
<Surface style={[styles.statusBadge, { backgroundColor: isOnline ? '#7A9E7E' : '#B8B3AA' }]}>
<Text style={styles.statusText}>{isOnline ? '在线' : '离线'}</Text>
</Surface>
<Button
mode="contained"
onPress={() => handlePlay(item)}
disabled={!isOnline}
style={styles.playBtn}
buttonColor="#7A9E7E"
icon="play"
>
</Button>
</View>
</Card.Content>
</Card>
);
};
const renderClip = ({ item }: { item: VideoClip }) => (
<Card style={styles.card} onPress={() => handlePlayClip(item)}>
<Card.Content style={styles.cardContent}>
<View style={styles.clipInfo}>
<IconButton icon="filmstrip" size={28} iconColor={theme.colors.primary} />
<View style={styles.clipDetail}>
<Text variant="bodyMedium" style={styles.clipTitle}>
{item.trigger === 'alarm' ? '告警录像' : item.trigger === 'manual' ? '手动录像' : item.trigger === 'schedule' ? '定时录像' : '录像片段'}
</Text>
<Text variant="bodySmall" style={styles.clipMeta}>
: {formatDateTime(item.startAt)}
</Text>
<Text variant="bodySmall" style={styles.clipMeta}>
: {formatDuration(item.durationSec)}
{item.resolution ? ` · ${item.resolution}` : ''}
</Text>
{item.sizeBytes ? (
<Text variant="bodySmall" style={styles.clipMeta}>
: {formatFileSize(item.sizeBytes)}
</Text>
) : null}
</View>
</View>
<IconButton icon="play-circle-outline" size={32} iconColor={theme.colors.primary} />
</Card.Content>
</Card>
);
if (loading) {
return (
<SafeAreaView style={styles.center}>
<ActivityIndicator size="large" />
</SafeAreaView>
);
}
return (
<SafeAreaView style={styles.container} edges={['bottom']}>
<View style={styles.filterContainer}>
<SegmentedButtons
value={tab}
onValueChange={setTab}
buttons={[
{ value: 'cameras', label: '摄像头' },
{ value: 'clips', label: '录像片段' },
]}
/>
</View>
<FlatList
data={(tab === 'cameras' ? cameras : clips) as any[]}
keyExtractor={(item) => String(item.id)}
renderItem={(tab === 'cameras' ? renderCamera : renderClip) as any}
contentContainerStyle={styles.list}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={() => loadData(true)} />
}
ListEmptyComponent={
error ? (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}>{error}</Text>
</View>
) : (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}>
{tab === 'cameras' ? '暂无摄像头' : '暂无录像片段'}
</Text>
</View>
)
}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FAF8F5',
},
center: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
filterContainer: {
padding: 16,
paddingBottom: 8,
},
list: {
padding: 16,
paddingTop: 8,
paddingBottom: 32,
},
card: {
marginBottom: 12,
borderRadius: 14,
backgroundColor: '#FFFFFF',
},
cardContent: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingVertical: 8,
},
cameraInfo: {
flexDirection: 'row',
alignItems: 'center',
flex: 1,
},
iconBox: {
borderRadius: 12,
},
cameraDetail: {
flex: 1,
marginLeft: 4,
},
cameraName: {
color: '#2D2A26',
fontWeight: '500',
},
cameraCode: {
color: '#B8B3AA',
fontSize: 12,
marginTop: 2,
},
cameraMeta: {
color: '#B8B3AA',
fontSize: 12,
marginTop: 2,
},
cameraRight: {
alignItems: 'flex-end',
gap: 6,
},
statusBadge: {
paddingHorizontal: 10,
paddingVertical: 3,
borderRadius: 12,
elevation: 0,
},
statusText: {
color: 'white',
fontSize: 11,
fontWeight: '500',
},
playBtn: {
borderRadius: 999,
},
clipInfo: {
flexDirection: 'row',
alignItems: 'center',
flex: 1,
},
clipDetail: {
flex: 1,
marginLeft: 4,
},
clipTitle: {
color: '#2D2A26',
fontWeight: '500',
},
clipMeta: {
color: '#B8B3AA',
fontSize: 12,
marginTop: 2,
},
emptyContainer: {
alignItems: 'center',
paddingTop: 64,
},
emptyText: {
color: '#B8B3AA',
fontSize: 16,
},
});
+24
View File
@@ -0,0 +1,24 @@
import { create } from 'zustand';
import type { Room, TelemetryRecord } from '../types';
interface AppState {
currentRoom: Room | null;
setCurrentRoom: (room: Room | null) => void;
refreshTrigger: number;
triggerRefresh: () => void;
realtimeData: TelemetryRecord[];
setRealtimeData: (data: TelemetryRecord[]) => void;
wsConnected: boolean;
setWsConnected: (connected: boolean) => void;
}
export const useAppStore = create<AppState>()((set) => ({
currentRoom: null,
setCurrentRoom: (room) => set({ currentRoom: room }),
refreshTrigger: 0,
triggerRefresh: () => set((state) => ({ refreshTrigger: state.refreshTrigger + 1 })),
realtimeData: [],
setRealtimeData: (data) => set({ realtimeData: data }),
wsConnected: false,
setWsConnected: (connected) => set({ wsConnected: connected }),
}));
+97
View File
@@ -0,0 +1,97 @@
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { loginApi, getMeApi } from '../api/auth';
import { TOKEN_KEY, REFRESH_TOKEN_KEY } from '../api/client';
import { wsManager } from '../utils/ws';
import type { User } from '../types';
interface AuthState {
token: string | null;
refreshToken: string | null;
user: User | null;
isLoading: boolean;
error: string | null;
login: (username: string, password: string) => Promise<boolean>;
logout: () => Promise<void>;
fetchUser: () => Promise<void>;
restoreSession: () => Promise<void>;
}
export const useAuthStore = create<AuthState>()(
persist(
(set, get) => ({
token: null,
refreshToken: null,
user: null,
isLoading: false,
error: null,
login: async (username: string, password: string) => {
set({ isLoading: true, error: null });
try {
const res = await loginApi(username, password);
const token = res.accessToken;
const refreshToken = res.refreshToken || null;
await AsyncStorage.setItem(TOKEN_KEY, token);
if (refreshToken) {
await AsyncStorage.setItem(REFRESH_TOKEN_KEY, refreshToken);
}
set({
token,
refreshToken,
user: res.user,
isLoading: false,
error: null,
});
wsManager.connect(token);
return true;
} catch (err: any) {
const msg =
err?.response?.data?.message ||
err?.response?.data?.msg ||
err?.message ||
'登录失败';
set({ isLoading: false, error: msg });
return false;
}
},
logout: async () => {
wsManager.disconnect();
await AsyncStorage.multiRemove([TOKEN_KEY, REFRESH_TOKEN_KEY]);
set({ token: null, refreshToken: null, user: null, error: null });
},
fetchUser: async () => {
const user = await getMeApi();
set({ user });
},
restoreSession: async () => {
const token = await AsyncStorage.getItem(TOKEN_KEY);
if (token) {
set({ token });
try {
await get().fetchUser();
wsManager.connect(token);
} catch {
await get().logout();
}
}
},
}),
{
name: 'auth-storage',
storage: createJSONStorage(() => AsyncStorage),
partialize: (state) => ({
token: state.token,
refreshToken: state.refreshToken,
user: state.user,
}),
},
),
);
+179
View File
@@ -0,0 +1,179 @@
export interface User {
id: string;
username: string;
email?: string;
fullName?: string;
role?: string;
}
export interface LoginResponse {
accessToken: string;
refreshToken?: string;
user: User;
}
export interface Room {
id: string;
name: string;
code?: string;
location?: string;
status?: string;
description?: string;
capacity?: number;
stage?: string;
createdAt?: string;
}
export interface Device {
id: string;
deviceKey: string;
name: string;
kind: string;
type?: string;
model?: string;
onlineStatus: string;
status?: string;
lastSeen?: string;
roomId?: string;
houseId?: string;
meta?: Record<string, any>;
}
export interface TelemetryRecord {
deviceKey: string;
metric: string;
value: number;
timestamp: string;
unit?: string;
}
export interface Alarm {
id: string;
code?: string;
title?: string;
message?: string;
content?: string;
severity?: string;
level?: string;
open: boolean;
acknowledged: boolean;
triggeredAt: string;
resolvedAt?: string;
deviceKey?: string;
metric?: string;
value?: number;
thresholdMin?: number;
thresholdMax?: number;
createdAt?: string;
}
export interface AlarmClip {
id: string;
playbackUrl?: string;
cameraId?: string;
startAt?: string;
endAt?: string;
mock?: boolean;
}
export interface Threshold {
id: string;
name?: string;
metric?: string;
minValue: number;
maxValue: number;
min?: number;
max?: number;
debounceSeconds: number;
severity: number;
enabled: boolean;
sensorId?: string;
roomId?: string;
houseId?: string;
unit?: string;
}
export interface Camera {
id: number;
roomId?: string;
code: string;
name: string;
rtspUrl?: string;
streamUrl?: string;
hlsUrl?: string;
flvUrl?: string;
webrtcUrl?: string;
isOnline: boolean;
online?: boolean;
gbDeviceId?: string;
gbChannelId?: string;
position?: string;
resolution?: string;
}
export interface PlayInfo {
cameraId: string;
format: 'hls' | 'flv' | 'webrtc';
url: string;
expiresAt?: string;
mock?: boolean;
}
export interface VideoClip {
id: string;
cameraId: string;
trigger: string;
format: string;
startAt: string;
endAt?: string;
durationSec: number;
resolution?: string;
sizeBytes?: string | number;
playbackUrl?: string;
mock?: boolean;
}
export interface ClipListResponse {
items: VideoClip[];
total: number;
}
export interface RealtimeMetric {
key: string;
name: string;
value: number;
unit: string;
status: 'normal' | 'warn' | 'danger';
}
export interface TrendPoint {
time: string;
temp?: number;
humidity?: number;
co2?: number;
}
export interface DeviceSummary {
total: number;
online: number;
offline: number;
alarm: number;
}
export type RootStackParamList = {
Login: undefined;
Main: undefined;
RoomDetail: { roomId: string; roomName: string };
DeviceControl: { deviceKey: string; deviceName: string };
VideoPlayer: { cameraId: number; cameraName: string; streamUrl?: string };
Thresholds: { roomId?: string } | undefined;
Settings: undefined;
};
export type MainTabParamList = {
Dashboard: undefined;
Rooms: undefined;
Devices: undefined;
Alerts: undefined;
Video: undefined;
};
+8
View File
@@ -0,0 +1,8 @@
declare module 'react-native-vector-icons/MaterialCommunityIcons' {
import * as React from 'react';
export default class MaterialCommunityIcons extends React.Component<any, any> {}
}
declare module 'react-native-vector-icons' {
import * as React from 'react';
export default class VectorIcon extends React.Component<any, any> {}
}
+127
View File
@@ -0,0 +1,127 @@
import dayjs from 'dayjs';
export const formatDateTime = (date: string | Date | undefined): string => {
if (!date) return '-';
return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};
export const formatDate = (date: string | Date | undefined): string => {
if (!date) return '-';
return dayjs(date).format('YYYY-MM-DD');
};
export const formatTime = (date: string | Date | undefined): string => {
if (!date) return '-';
return dayjs(date).format('HH:mm:ss');
};
export const formatRelativeTime = (date: string | Date | undefined): string => {
if (!date) return '-';
const now = dayjs();
const target = dayjs(date);
const diffSec = now.diff(target, 'second');
const diffMin = now.diff(target, 'minute');
const diffHour = now.diff(target, 'hour');
const diffDay = now.diff(target, 'day');
if (diffSec < 60) return `${diffSec}秒前`;
if (diffMin < 60) return `${diffMin}分钟前`;
if (diffHour < 24) return `${diffHour}小时前`;
if (diffDay < 30) return `${diffDay}天前`;
return formatDate(date);
};
export const formatNumber = (value: number | undefined, digits = 1): string => {
if (value === undefined || value === null || isNaN(value)) return '-';
return value.toFixed(digits);
};
export const formatDuration = (seconds: number): string => {
if (seconds < 60) return `${seconds}`;
const min = Math.floor(seconds / 60);
const sec = seconds % 60;
return `${min}${sec}`;
};
export const formatFileSize = (bytes: number | string | undefined): string => {
if (bytes === undefined || bytes === null) return '-';
const size = typeof bytes === 'string' ? parseInt(bytes, 10) : bytes;
if (isNaN(size)) return '-';
if (size < 1024) return `${size} B`;
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(1)} MB`;
return `${(size / (1024 * 1024 * 1024)).toFixed(1)} GB`;
};
export const METRIC_NAME: Record<string, string> = {
temperature: '温度',
temp: '温度',
humidity: '湿度',
co2: 'CO₂',
light: '光照',
ph: 'PH',
};
export const METRIC_UNIT: Record<string, string> = {
temperature: '℃',
temp: '℃',
humidity: '%',
co2: 'ppm',
light: 'lux',
ph: '',
};
export const getMetricName = (metric: string): string => {
return METRIC_NAME[metric] || metric;
};
export const getMetricUnit = (metric: string): string => {
return METRIC_UNIT[metric] || '';
};
export const normalizeMetricKey = (metric: string): string => {
return metric === 'temperature' ? 'temp' : metric;
};
export const metricStatus = (key: string, value: number): 'normal' | 'warn' | 'danger' => {
if (key === 'temp') return value < 20 || value > 30 ? 'danger' : value < 22 || value > 28 ? 'warn' : 'normal';
if (key === 'humidity') return value < 55 || value > 85 ? 'danger' : value < 60 || value > 80 ? 'warn' : 'normal';
if (key === 'co2') return value > 1500 ? 'danger' : value > 1000 ? 'warn' : 'normal';
return 'normal';
};
export const getSeverityColor = (severity?: string): string => {
switch (severity?.toLowerCase()) {
case 'danger':
case 'critical':
case 'high':
return '#D4847A';
case 'warn':
case 'warning':
case 'medium':
return '#D4B87A';
case 'info':
case 'low':
return '#6B8F71';
default:
return '#B8B3AA';
}
};
export const getSeverityLabel = (severity?: string): string => {
switch (severity?.toLowerCase()) {
case 'danger':
case 'critical':
case 'high':
return '严重';
case 'warn':
case 'warning':
case 'medium':
return '警告';
case 'info':
case 'low':
return '提示';
default:
return severity || '未知';
}
};
+123
View File
@@ -0,0 +1,123 @@
import { WS_BASE_URL } from '@env';
export type WSMessageHandler = (data: any) => void;
class WebSocketManager {
private ws: WebSocket | null = null;
private token: string | null = null;
private handlers: Set<WSMessageHandler> = new Set();
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectAttempts = 0;
private maxReconnectAttempts = 10;
private isManualClose = false;
connect(token: string): void {
// Close any existing connection before creating a new one
if (this.ws) {
this.isManualClose = true;
this.ws.onclose = null;
this.ws.onerror = null;
this.ws.close();
this.ws = null;
}
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
this.reconnectAttempts = 0;
this.token = token;
this.isManualClose = false;
this.doConnect();
}
private doConnect(): void {
if (!this.token) return;
const wsUrl = (WS_BASE_URL || 'ws://localhost:3000/ws').replace(/\?.*$/, '');
const url = `${wsUrl}?token=${encodeURIComponent(this.token)}`;
try {
this.ws = new WebSocket(url);
} catch (e) {
console.warn('[WS] Failed to create WebSocket:', e);
this.scheduleReconnect();
return;
}
this.ws.onopen = () => {
console.log('[WS] Connected');
this.reconnectAttempts = 0;
};
this.ws.onmessage = (event: WebSocketMessageEvent) => {
try {
const data = JSON.parse(event.data);
this.handlers.forEach((handler) => handler(data));
} catch (e) {
console.warn('[WS] Failed to parse message:', e);
}
};
this.ws.onerror = (error: WebSocketErrorEvent) => {
console.warn('[WS] Error:', error);
};
this.ws.onclose = () => {
console.log('[WS] Disconnected');
this.ws = null;
if (!this.isManualClose) {
this.scheduleReconnect();
}
};
}
private scheduleReconnect(): void {
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
console.warn('[WS] Max reconnection attempts reached');
return;
}
this.reconnectAttempts++;
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
console.log(`[WS] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);
this.reconnectTimer = setTimeout(() => {
if (!this.isManualClose && this.token) {
this.doConnect();
}
}, delay);
}
disconnect(): void {
this.isManualClose = true;
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
if (this.ws) {
this.ws.close();
this.ws = null;
}
this.reconnectAttempts = 0;
}
subscribe(handler: WSMessageHandler): () => void {
this.handlers.add(handler);
return () => {
this.handlers.delete(handler);
};
}
send(data: any): void {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(data));
}
}
get isConnected(): boolean {
return this.ws?.readyState === WebSocket.OPEN;
}
}
export const wsManager = new WebSocketManager();
+12
View File
@@ -0,0 +1,12 @@
{
"extends": "@react-native/typescript-config/tsconfig.json",
"compilerOptions": {
"jsx": "react-jsx",
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
},
"types": []
},
"include": ["src/**/*.ts", "src/**/*.tsx", "App.tsx", "env.d.ts"]
}
+1
View File
@@ -0,0 +1 @@
{"name":"测试摄像头","code":"CAM-TEST","online":true,"enabled":true}
+42
View File
@@ -0,0 +1,42 @@
# Git 使用规范(本仓库)
## 1、分支模型
- `master`:稳定主分支,只接受经评审后的合并,不直接提交开发代码。
- `develop`:开发集成分支,日常开发默认从它拉分支、合回。
- 功能分支:`feature/<简短描述>`,从 `develop` 拉出,完成后合回 `develop`
- 修复分支:`bugfix/<简短描述>`,从 `develop` 拉出。
- 紧急修复:`hotfix/<简短描述>`,从 `master` 拉出,修复后合回 `master``develop`
- 发布分支:`release/<版本号>`,从 `develop` 拉出,测试通过后合回 `master` 并打标签 `v<版本号>`
## 2、首次克隆与开分支
```bash
git clone <仓库地址>
git checkout -b feature/my-feature develop # 从 develop 拉功能分支
```
## 3、日常提交
```bash
git add <文件> # 只添加本次改动相关文件,不要 git add -A 一把梭
git commit -m "feat: 新增xxx" # 提交信息格式:type: 描述
git pull --rebase origin develop # 合入前先同步远端
git push -u origin feature/my-feature
```
提交信息前缀:`feat`(功能)、`fix`(修复)、`docs`(文档)、`refactor`(重构)、`test`(测试)、`chore`(杂项)。
## 4、合并与评审
- 通过合并请求(MR/PR)把功能分支合入 `develop`,由他人评审后合并。
- 不要把自己的个人分支长期保留在共享远端;合并后删除。
- 合入前确保已通过对应模块的验证命令(见 AGENTS.md「验证」)。
## 5、与远端同步
```bash
git fetch origin
git pull --rebase origin develop
```
+15
View File
@@ -0,0 +1,15 @@
// babel-preset-taro 更多选项和默认值:
// https://github.com/NervJS/taro/blob/next/packages/babel-preset-taro/README.md
module.exports = {
presets: [
[
'taro',
{
framework: 'react',
ts: 'true',
compiler: 'webpack5',
},
],
],
plugins: [],
};
+22
View File
@@ -0,0 +1,22 @@
import type { UserConfigExport } from '@tarojs/cli';
export default {
logger: {
quiet: false,
stats: true,
},
mini: {},
h5: {
devServer: {
open: false, //禁止自动打开浏览器
proxy: [
{
context: ['/api', '/ws'],
target: 'http://localhost:3000',
changeOrigin: true,
secure: false,
ws: true,
},
],
},
},
} satisfies UserConfigExport<'webpack5'>;
+108
View File
@@ -0,0 +1,108 @@
import { defineConfig, type UserConfigExport } from '@tarojs/cli';
import TsconfigPathsPlugin from 'tsconfig-paths-webpack-plugin';
import devConfig from './dev';
import prodConfig from './prod';
import vitePluginImp from 'vite-plugin-imp';
// https://taro-docs.jd.com/docs/next/config#defineconfig-辅助函数
export default defineConfig<'webpack5'>(async (merge, { command, mode }) => {
const baseConfig: UserConfigExport<'webpack5'> = {
projectName: 'taro_template',
date: '2025-12-10',
designWidth: 375,
deviceRatio: {
640: 2.34 / 2,
750: 1,
375: 2,
828: 1.81 / 2,
},
sourceRoot: 'src',
outputRoot: process.env.TARO_OUTPUT_DIR || 'dist',
plugins: ['@tarojs/plugin-html'],
defineConstants: {},
copy: {
patterns: [],
options: {},
},
framework: 'react',
compiler: {
type: 'webpack5',
prebundle: {
enable: false,
},
},
cache: {
enable: false, // Webpack 持久化缓存配置,建议开启。默认配置请参考:https://docs.taro.zone/docs/config-detail#cache
},
mini: {
postcss: {
pxtransform: {
enable: true,
config: {
selectorBlackList: ['nut-'],
},
},
cssModules: {
enable: true, // 开启 CSS Modules
config: {
namingPattern: 'module', // 仅 *.module.scss 生效
generateScopedName: '[name]__[local]___[hash:base64:5]',
},
},
},
webpackChain(chain) {
chain.resolve.plugin('tsconfig-paths').use(TsconfigPathsPlugin);
},
},
h5: {
publicPath: '/',
staticDirectory: 'static',
output: {
filename: 'js/[name].[hash:8].js',
chunkFilename: 'js/[name].[chunkhash:8].js',
},
miniCssExtractPluginOption: {
ignoreOrder: true,
filename: 'css/[name].[hash].css',
chunkFilename: 'css/[name].[chunkhash].css',
},
postcss: {
autoprefixer: {
enable: true,
config: {},
},
cssModules: {
enable: true, // 开启 CSS Modules
config: {
namingPattern: 'module', // 仅 *.module.scss 生效
generateScopedName: '[name]__[local]___[hash:base64:5]',
},
},
pxtransform: {
enable: true,
config: {
selectorBlackList: ['body'],
baseFontSize: 37.5,
unitPrecision: 5,
},
},
},
webpackChain(chain) {
chain.resolve.plugin('tsconfig-paths').use(TsconfigPathsPlugin);
},
},
rn: {
appName: 'taroDemo',
postcss: {
cssModules: {
enable: true,
},
},
},
};
if (process.env.NODE_ENV === 'development') {
// 本地开发构建配置(不混淆压缩)
return merge({}, baseConfig, devConfig);
}
// 生产构建配置(默认开启压缩混淆等)
return merge({}, baseConfig, prodConfig);
});
+25
View File
@@ -0,0 +1,25 @@
import type { UserConfigExport } from '@tarojs/cli';
export default {
mini: {
optimizeMainPackage: {
enable: true,
},
minify: {
enable: true,
config: {
keep_classnames: false,
keep_fnames: false,
mangle: {
toplevel: true,
},
},
},
treeShaking: {
enable: true,
},
uglify: {
enable: true,
},
},
h5: {},
} satisfies UserConfigExport<'webpack5'>;
+1
View File
@@ -0,0 +1 @@
.h5-button,.h5-form,.h5-input,.h5-label,.h5-textarea,image,navigator,page,scroll-view,swiper,swiper-item,text,view{-webkit-box-sizing:border-box;box-sizing:border-box}page{background-color:#f5f6f7;color:#1d2129;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,PingFang SC,Hiragino Sans GB,sans-serif;font-size:28rpx;line-height:1.5}
+2
View File
File diff suppressed because one or more lines are too long
+29
View File
@@ -0,0 +1,29 @@
/**
* @license React
* react-reconciler-constants.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* react-reconciler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
+1
View File
@@ -0,0 +1 @@
{"pages":["pages/login/index","pages/dashboard/index","pages/rooms/index","pages/rooms/detail/index","pages/devices/index","pages/devices/control/index","pages/alerts/index","pages/thresholds/index","pages/video/index","pages/video/player/index","pages/settings/index"],"window":{"backgroundTextStyle":"dark","navigationBarBackgroundColor":"#10b981","navigationBarTitleText":"蚕房监控","navigationBarTextStyle":"white","backgroundColor":"#f5f6f7"},"tabBar":{"color":"#86909c","selectedColor":"#10b981","backgroundColor":"#ffffff","borderStyle":"white","list":[{"pagePath":"pages/dashboard/index","text":"仪表盘","iconPath":"assets/tabbar/dashboard.png","selectedIconPath":"assets/tabbar/dashboard-selected.png"},{"pagePath":"pages/rooms/index","text":"蚕房","iconPath":"assets/tabbar/rooms.png","selectedIconPath":"assets/tabbar/rooms-selected.png"},{"pagePath":"pages/devices/index","text":"设备","iconPath":"assets/tabbar/devices.png","selectedIconPath":"assets/tabbar/devices-selected.png"},{"pagePath":"pages/alerts/index","text":"告警","iconPath":"assets/tabbar/alerts.png","selectedIconPath":"assets/tabbar/alerts-selected.png"},{"pagePath":"pages/video/index","text":"视频","iconPath":"assets/tabbar/video.png","selectedIconPath":"assets/tabbar/video-selected.png"}]}}

Some files were not shown because too many files have changed in this diff Show More