diff --git a/README.md b/README.md index 63c9733..87b5d6b 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ packService/ ├── backend/ # Egg.js 3(纯 API;MySQL + Redis) ├── frontend/ # Vite + Vue3 + TypeScript(用户端 SPA) ├── extension/ # Chrome MV3 扩展:注入第三方 WMS 页面,把运单号加工成溯源入口 -└── desktop/ # WPF 本机软件:本机 HTTP 服务(127.0.0.1:17300)+ yuncang:// 启动协议 +└── desktop/ # WPF 本机软件:HTTP 17300(查询/唤起/下载)+ WS 17301(拉通道/预览/云台)+ yuncang:// 启动协议 ``` ## 端口约定(⚠️ 本机项目多,不要用 Vite 默认的 5173) @@ -17,7 +17,7 @@ packService/ | 前端 dev(Vite) | **7301** | `cd frontend && npm run dev` | | 前端 preview(dist) | **7302** | `cd frontend && npm run preview` | | 后端 dev | **7300** | `cd backend && npm run dev` | -| 本机软件(WPF,只监听 loopback) | **17300** | `cd desktop && dotnet run`(详见 [`desktop/README.md`](desktop/README.md)) | +| 本机软件(WPF,只监听 loopback) | **17300**(HTTP)/ **17301**(WebSocket) | `cd desktop && dotnet run`(详见 [`desktop/README.md`](desktop/README.md)) | | 扩展自测页(可选) | **7310** | `npx --yes http-server extension/test -p 7310` | - 前端端口可用 `VITE_PORT=7303 npm run dev` 覆盖;`strictPort: true` → 端口被占用时**直接报错**,不会偷偷换端口(否则代理会对不上)。 diff --git a/backend/README.md b/backend/README.md index 5172895..59562fc 100644 --- a/backend/README.md +++ b/backend/README.md @@ -330,7 +330,12 @@ $env:MYSQL_PASSWORD = 'your-pass'; $env:REDIS_PASSWORD = 'your-pass'; npm run de - 唯一键 `(scanner_id, channel_id)`:同一中控重复上报同一个通道 = 更新通道名与 `last_report_at`,不会重复建行; - 因为 `channel_id` 只在同一中控内唯一,所以关联/去重都必须带上 `scanner_id`; -- 用软删除:曾被停用(`deleted_at` 非空)的通道再次上报时会自动「复活」。 +- 用软删除:曾被停用(`deleted_at` 非空)的通道再次上报时会自动「复活」; +- **全量对账(`replace: true`)**:桌面端的通道列表存在本地(`channels.json`),与本机设备是否在线无关 → + `replace: true` 时该中控下**不在列表里**的通道会被软删,`workstation_scan_channels` 里对应绑定物理删除, + 返回 `{ removed, unbound }`;`channels: []` + `replace: true` 表示"通道已全部删除"。不带 `replace` 的老客户端行为不变; +- **忽略 `channel_id = 'DESKTOP'`**:旧版桌面端会多报一个「本机中控」占位通道(从未有真实数据), + 迁移 `20261019230000-remove-legacy-desktop-channel` 已清掉历史行,`reportChannels()` 也会直接跳过,避免老客户端重新写回。 ### scan_records 扫码记录表 @@ -454,7 +459,7 @@ node scripts/backfill-snapshot.js --dry-run | GET | `/api/scanners?page=&pageSize=&keyword=&userId=&status=` | 设备列表(带绑定账号;管理侧) | | GET | `/api/scanners/:id` | 扫描器详情 | | DELETE | `/api/scanners/:id` | 软删除扫描器 | -| POST | `/api/scan/channels` | **需扫描器 JWT**:中控上报通道,body: `{ channels: [{ channelId, channelName }] }`(单条也可)→ `{ created, updated, invalid, errors }` | +| POST | `/api/scan/channels` | **需扫描器 JWT**:中控上报通道,body: `{ channels: [{ channelId, channelName }], replace?: boolean }`(单条也可)→ `{ created, updated, invalid, errors, removed, unbound }`。`replace: true` = 全量对账:本中控下不在列表里的通道软删并解绑工作台,允许 `channels: []` | | GET | `/api/scan/channels?page=&pageSize=&keyword=&status=` | **需扫描器 JWT**:当前中控已登记的通道 | | POST | `/api/scan/records` | **需扫描器 JWT**:中控上报扫码,body: `{ records: [{ barcode, scanTime, channelId }] }` → `{ received, inserted, updated, duplicated, suppressed, invalid, unknownChannels }`(`updated` = 24 小时内同一运单被覆盖为最新扫描时间的条数;`suppressed` = 比库里已有记录更旧、被忽略的条数) | | GET | `/api/scan/records?page=&pageSize=&channelId=&barcode=&startTime=&endTime=` | **需扫描器 JWT**:当前中控上报的扫码记录 | diff --git a/backend/app/controller/device/scan.js b/backend/app/controller/device/scan.js index 00899d8..c5a5cf1 100644 --- a/backend/app/controller/device/scan.js +++ b/backend/app/controller/device/scan.js @@ -28,16 +28,20 @@ function pickList(body, key, single) { class ScanController extends Controller { /** * POST /api/scan/channels —— 中控上报通道(需长期 JWT) - * body: { channels: [{ channelId, channelName }] } - * 同一中控 + 同一 channelId 为同一个通道,重复上报即更新通道名 + * body: { channels: [{ channelId, channelName }], replace?: boolean } + * 同一中控 + 同一 channelId 为同一个通道,重复上报即更新通道名; + * replace=true 时按全量对账(列表里没有的通道会被软删并解绑工作台),允许 channels 为空数组。 */ async reportChannels() { const { ctx } = this; const body = ctx.request.body || {}; const channels = pickList(body, 'channels', 'channelId'); - if (!channels.length) ctx.throw(422, 'channels 不能为空,body 形如 { channels: [{ channelId, channelName }] }'); + const replace = body.replace === true || body.replace === 'true' || body.replace === 1; + if (!channels.length && !replace) { + ctx.throw(422, 'channels 不能为空,body 形如 { channels: [{ channelId, channelName }] }'); + } - const data = await ctx.service.scan.reportChannels(ctx.state.scanner, channels); + const data = await ctx.service.scan.reportChannels(ctx.state.scanner, channels, { replace }); ctx.body = { ok: true, data }; } diff --git a/backend/app/controller/web/camera.js b/backend/app/controller/web/camera.js index c9b8d86..8b2108c 100644 --- a/backend/app/controller/web/camera.js +++ b/backend/app/controller/web/camera.js @@ -48,8 +48,8 @@ class WebCameraController extends Controller { const id = toId(ctx.params.id); if (!id) ctx.throw(400, 'id 必须是正整数'); - const { name, status, remark, hasPtz } = ctx.request.body || {}; - const data = await ctx.service.camera.update(id, ctx.state.subjectId, { name, status, remark, hasPtz }); + const { name, status, remark } = ctx.request.body || {}; + const data = await ctx.service.camera.update(id, ctx.state.subjectId, { name, status, remark }); ctx.body = { ok: true, data: data.toJSON() }; } diff --git a/backend/app/model/camera.js b/backend/app/model/camera.js index beb8d3b..c1a71a0 100644 --- a/backend/app/model/camera.js +++ b/backend/app/model/camera.js @@ -9,7 +9,7 @@ * `ip` / `port` 是该数字通道对应的前端设备(可能是 ONVIF 摄像机),做展示与排障用。 */ module.exports = (app) => { - const { BIGINT, STRING, INTEGER, TINYINT, BOOLEAN } = app.Sequelize; + const { BIGINT, STRING, INTEGER, TINYINT } = app.Sequelize; const Camera = app.model.define('camera', { id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, @@ -17,12 +17,11 @@ module.exports = (app) => { nvrId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属 NVR(nvrs.id)' }, channelNo: { type: INTEGER.UNSIGNED, allowNull: false, comment: '海康通道号' }, name: { type: STRING(64), allowNull: false, defaultValue: '', comment: '摄像头名称(业务别名)' }, - channelName: { type: STRING(64), comment: '设备通道名(ISAPI,拉取时刷新)' }, + channelName: { type: STRING(64), comment: '设备通道名(拉取通道时刷新,可能为空)' }, type: { type: STRING(16), allowNull: false, defaultValue: 'digital', comment: 'analog / digital' }, ip: { type: STRING(45), comment: '前端设备 IP' }, port: { type: INTEGER.UNSIGNED, comment: '前端设备管理端口' }, enabled: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '通道是否已配置' }, - hasPtz: { type: BOOLEAN, allowNull: false, defaultValue: false, comment: '是否支持云台(PTZ)' }, status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1启用 0停用' }, remark: { type: STRING(255), comment: '备注' }, }, { diff --git a/backend/app/service/camera.js b/backend/app/service/camera.js index 0149090..a372737 100644 --- a/backend/app/service/camera.js +++ b/backend/app/service/camera.js @@ -169,7 +169,7 @@ class CameraService extends Service { return { created, updated, list, nvr: await this.ctx.service.nvr.findOwned(nvr.id, subjectId) }; } - /** 更新摄像头(名称 / 状态 / 备注 / 是否带云台) */ + /** 更新摄像头(名称 / 状态 / 备注) */ async update(id, subjectId, patch = {}) { const camera = await this.findOwned(id, subjectId); @@ -177,7 +177,6 @@ class CameraService extends Service { if (patch.name !== undefined) fields.name = String(patch.name || '').trim(); if (patch.remark !== undefined) fields.remark = patch.remark; if (patch.status !== undefined) fields.status = Number(patch.status) === 0 ? 0 : 1; - if (patch.hasPtz !== undefined) fields.hasPtz = Boolean(Number(patch.hasPtz)); await camera.update(fields); return this.findOwned(id, subjectId); diff --git a/backend/app/service/scan.js b/backend/app/service/scan.js index 6e64008..983ae5e 100644 --- a/backend/app/service/scan.js +++ b/backend/app/service/scan.js @@ -105,20 +105,30 @@ class ScanService extends Service { return this.app.model.ScanRecord; } + get LinkScanChannel() { + return this.app.model.WorkstationScanChannel; + } + /** * 中控上报通道(channel_id + channel_name) * * - 同一中控 + 同一 channel_id 视为同一个通道:存在则更新通道名与最近上报时间; * - 曾被软删除的通道会被「复活」(deleted_at 置空),避免唯一键挡住重新启用; - * - 同一次上报里重复的 channel_id 只处理最后一次。 + * - 同一次上报里重复的 channel_id 只处理最后一次; + * - **`replace: true` = 全量对账**:中控的通道列表存在本地,推上来的就是全部; + * 本中控下不在列表里的旧通道会被软删除,并解绑工作台绑定(旧客户端不带该字段,行为不变); + * 此时允许 `channels: []`(表示「通道已全部删除」)。 * * @param {object} scanner 中控(扫描器实例,来自 scanner_auth) * @param {Array} channels 形如 [{ channelId, channelName }] - * @return {Promise<{received:number, created:number, updated:number, invalid:number, errors:Array, channels:Array}>} + * @param {object} [options] { replace?: boolean } + * @return {Promise<{received:number, created:number, updated:number, invalid:number, errors:Array, channels:Array, removed:number, unbound:number}>} */ - async reportChannels(scanner, channels) { + async reportChannels(scanner, channels, { replace = false } = {}) { const list = Array.isArray(channels) ? channels : []; - if (!list.length) this.ctx.throw(422, 'channels 不能为空'); + if (!list.length && !replace) { + this.ctx.throw(422, 'channels 不能为空,body 形如 { channels: [{ channelId, channelName }] }'); + } if (list.length > MAX_BATCH) this.ctx.throw(422, `单次最多上报 ${MAX_BATCH} 个通道`); const now = new Date(); @@ -141,20 +151,24 @@ class ScanService extends Service { errors.push({ index, message: `channelName 超长(>${MAX_CHANNEL_NAME})` }); return; } + // 旧版桌面端会多报一个「本机中控」占位通道(channel_id=DESKTOP), + // 新版已不再上报;这里直接忽略,避免老客户端把它重新写回来。 + if (channelId.toUpperCase() === 'DESKTOP') return; // 同一次上报里同 channelId 只保留最后一次 normalized.set(channelId, { channelId, channelName }); }); const rows = [ ...normalized.values() ]; - if (!rows.length) { - return { received: list.length, created: 0, updated: 0, invalid: errors.length, errors, channels: [] }; + const ids = rows.map(row => row.channelId); + + if (!rows.length && !replace) { + return { received: list.length, created: 0, updated: 0, invalid: errors.length, errors, channels: [], removed: 0, unbound: 0 }; } - const ids = rows.map(row => row.channelId); - const existing = await this.ScanChannel.findAll({ + const existing = ids.length ? await this.ScanChannel.findAll({ where: { scannerId: scanner.id, channelId: { [Op.in]: ids } }, paranoid: false, - }); + }) : []; const existingMap = new Map(existing.map(row => [ row.channelId, row ])); let created = 0; @@ -188,6 +202,31 @@ class ScanService extends Service { } } + let removed = 0; + let unbound = 0; + + // 全量对账:中控的通道列表在本地(channels.json),推上来的就是全部 → + // 本中控下不在列表里的通道 = 被删了,软删通道行并解绑工作台。 + if (replace) { + const keep = new Set(ids); + const current = await this.ScanChannel.findAll({ + attributes: [ 'channelId' ], + where: { scannerId: scanner.id }, + }); + const staleIds = current.map(row => row.channelId).filter(channelId => !keep.has(channelId)); + + const linkWhere = { scannerId: scanner.id }; + linkWhere.channelId = ids.length ? { [Op.notIn]: ids } : { [Op.ne]: null }; + unbound = await this.LinkScanChannel.destroy({ where: linkWhere }); + + if (staleIds.length) { + removed = await this.ScanChannel.destroy({ + where: { scannerId: scanner.id, channelId: { [Op.in]: staleIds } }, + }); + this.ctx.logger.info('[scan] 通道全量对账 %s: 删除 %d / 解绑工作台 %d', scanner.sn, removed, unbound); + } + } + this.ctx.logger.info('[scan] 通道上报 %s: 新增 %d / 更新 %d / 非法 %d', scanner.sn, created, updated, errors.length); return { received: list.length, @@ -196,6 +235,8 @@ class ScanService extends Service { invalid: errors.length, errors, channels: saved, + removed, + unbound, }; } diff --git a/backend/database/README.md b/backend/database/README.md index b26b114..e926961 100644 --- a/backend/database/README.md +++ b/backend/database/README.md @@ -50,7 +50,6 @@ npm run db:migration:generate -- create_xxx_tables # 生成迁移骨架 | `20261018200100-backfill-workstation-camera-layout` | 回填已有绑定关系的画布位置(第 1 条铺满 / 第 2 条右上 / 其余左下) | | `20261018210000-add-workstation-type` | `workstations.ws_type`(1 散单 / 2 团购) | | `20261018220000-add-workstation-record-range` | `workstations.record_before_sec/record_after_sec/record_max_sec`(录制范围与最大录制时长) | -| `20261018230000-create-subject-tables` | 新表 `subjects` / `subject_members`;`scanners`/`nvrs`/`cameras`/`workstations`/`scan_channels`/`scan_records` 加 `subject_id`,并把已有数据回填到「每人一个主体」 | - +| `20261018230000-create-subject-tables` | 新表 `subjects` / `subject_members`;`scanners`/`nvrs`/`cameras`/`workstations`/`scan_channels`/`scan_records` 加 `subject_id`,并把已有数据回填到「每人一个主体」 || `20261019233000-drop-has-ptz-from-cameras` | 删除 `cameras.has_ptz`(预览统一显示云台面板,后端不再标记是否支持云台) | > 历史遗留的 `sql/schema.sql` + `sql/migrations/*.sql`(用 `npm run db:init` 执行)是接入 sequelize-cli 之前的做法, > 只用于初始化老表;**新变更一律写 `database/migrations/*.js`**。 diff --git a/backend/database/migrations/20261018150000-add-channel-name-to-cameras.js b/backend/database/migrations/20261018150000-add-channel-name-to-cameras.js index 3d90ef8..b58b2b8 100644 --- a/backend/database/migrations/20261018150000-add-channel-name-to-cameras.js +++ b/backend/database/migrations/20261018150000-add-channel-name-to-cameras.js @@ -1,7 +1,7 @@ 'use strict'; /** - * cameras 增加 channel_name(设备上的通道名,来自 ISAPI) + * cameras 增加 channel_name(设备上的通道名,拉取通道时刷新,可能为空) * * 与 name 的区别: * name = 业务别名(用户可改,重拉通道不覆盖) @@ -13,7 +13,7 @@ module.exports = { type: Sequelize.STRING(64), allowNull: true, after: 'name', - comment: '设备通道名(ISAPI,拉取通道时刷新)', + comment: '设备通道名(拉取通道时刷新,可能为空)', }); }, diff --git a/backend/database/migrations/20261019230000-remove-legacy-desktop-channel.js b/backend/database/migrations/20261019230000-remove-legacy-desktop-channel.js new file mode 100644 index 0000000..6971f57 --- /dev/null +++ b/backend/database/migrations/20261019230000-remove-legacy-desktop-channel.js @@ -0,0 +1,45 @@ +'use strict'; + +/** + * 清理旧版桌面端上报的「本机中控」占位通道(channel_id = DESKTOP) + * + * 背景: + * - 旧版桌面端开启设备服务时,除了真实扫码通道,还会补报一个 + * channel_id='DESKTOP'、channel_name='本机中控' 的占位通道; + * - 新版本已经不再上报(见 desktop/Services/DeviceService.cs 的注释), + * 但库里那条记录还在,会一直显示在网页「设备 → 通道」列表里, + * 也会出现在工作台「可绑定扫码通道」里; + * - 它从来没有真实数据(只是在查询框里手动回车时记过 DESKTOP 扫码记录),留着只会误导。 + * + * 清理: + * - 物理删除 scan_channels 中 channel_id='DESKTOP' 的行(含已被软删除的); + * - 同步删除 workstation_scan_channels 里指向它的绑定,避免悬挂绑定; + * - scan_records 里的历史流水不动。 + * + * 不可逆:down() 不做恢复。 + */ +module.exports = { + async up(queryInterface) { + const [ channels ] = await queryInterface.sequelize.query( + "SELECT id FROM scan_channels WHERE channel_id = 'DESKTOP'", + ); + + if (!channels.length) { + console.log('[desktop-channel] 没有残留的 DESKTOP 占位通道,跳过'); + return; + } + + await queryInterface.sequelize.query( + "DELETE FROM workstation_scan_channels WHERE channel_id = 'DESKTOP'", + ); + await queryInterface.sequelize.query( + "DELETE FROM scan_channels WHERE channel_id = 'DESKTOP'", + ); + + console.log('[desktop-channel] 已删除 DESKTOP 占位通道 %d 条(含工作台绑定)', channels.length); + }, + + async down() { + // 历史占位数据,不需要恢复 + }, +}; diff --git a/backend/database/migrations/20261019233000-drop-has-ptz-from-cameras.js b/backend/database/migrations/20261019233000-drop-has-ptz-from-cameras.js new file mode 100644 index 0000000..74c2a51 --- /dev/null +++ b/backend/database/migrations/20261019233000-drop-has-ptz-from-cameras.js @@ -0,0 +1,29 @@ +'use strict'; + +/** + * cameras 删除 has_ptz(不再区分是否支持云台) + * + * 需求变更:所有摄像头预览界面都显示云台方向盘,点击无效也没关系; + * 后端不再维护/标记通道是否带云台,所以把这一列删掉。 + */ +module.exports = { + async up(queryInterface) { + const table = await queryInterface.describeTable('cameras'); + if (table.has_ptz) { + await queryInterface.removeColumn('cameras', 'has_ptz'); + } + }, + + async down(queryInterface, Sequelize) { + const table = await queryInterface.describeTable('cameras'); + if (!table.has_ptz) { + await queryInterface.addColumn('cameras', 'has_ptz', { + type: Sequelize.BOOLEAN, + allowNull: false, + defaultValue: false, + after: 'enabled', + comment: '是否支持云台(PTZ)', + }); + } + }, +}; diff --git a/backend/test/app/controller/scan.test.js b/backend/test/app/controller/scan.test.js index 92a3f2c..d6f20e9 100644 --- a/backend/test/app/controller/scan.test.js +++ b/backend/test/app/controller/scan.test.js @@ -198,6 +198,82 @@ describe('test/app/controller/scan.test.js', () => { await app.httpRequest().post('/api/scan/channels').set('Authorization', token()).send({}).expect(422); }); + it('POST /api/scan/channels replace=true:列表里没有的通道被软删并解绑工作台', async () => { + let channelDestroy = null; + let linkDestroy = null; + mock(app, 'model', { + User: {}, + Scanner: { async findByPk() { return instance(authScanner()); } }, + ScanChannel: { + async findAll(options) { + // 第一次:按 channelId 查已存在;第二次:查本中控当前全部通道 + if (options && options.attributes) { + return [ instance({ id: 1, channelId: '1' }), instance({ id: 2, channelId: '2' }) ]; + } + return [ instance({ id: 1, scannerId: 1, channelId: '1', channelName: '旧名字', deletedAt: null }) ]; + }, + async update() { + return [ 1 ]; + }, + async destroy(options) { + channelDestroy = options; + return 1; + }, + }, + WorkstationScanChannel: { + async destroy(options) { + linkDestroy = options; + return 3; + }, + }, + }); + + const res = await app.httpRequest() + .post('/api/scan/channels') + .set('Authorization', token()) + .send({ channels: [{ channelId: '1', channelName: '新名字' }], replace: true }) + .expect(200); + + assert(res.body.data.updated === 1 && res.body.data.removed === 1 && res.body.data.unbound === 3); + assert(channelDestroy.where.scannerId === 1); + assert(channelDestroy.where.channelId[Op.in].join(',') === '2', '只删不在列表里的通道'); + assert(linkDestroy.where.channelId[Op.notIn].join(',') === '1', '解绑不在列表里的工作台绑定'); + }); + + it('POST /api/scan/channels replace=true + 空列表:允许上报并清空全部通道', async () => { + let channelDestroy = null; + let linkDestroy = null; + mock(app, 'model', { + User: {}, + Scanner: { async findByPk() { return instance(authScanner()); } }, + ScanChannel: { + async findAll() { + return [ instance({ id: 1, channelId: '1' }), instance({ id: 2, channelId: '2' }) ]; + }, + async destroy(options) { + channelDestroy = options; + return 2; + }, + }, + WorkstationScanChannel: { + async destroy(options) { + linkDestroy = options; + return 4; + }, + }, + }); + + const res = await app.httpRequest() + .post('/api/scan/channels') + .set('Authorization', token()) + .send({ channels: [], replace: true }) + .expect(200); + + assert(res.body.data.received === 0 && res.body.data.removed === 2 && res.body.data.unbound === 4); + assert(channelDestroy.where.channelId[Op.in].sort().join(',') === '1,2', '两条都应被软删'); + assert(linkDestroy.where.channelId[Op.ne] === null, '空列表 = 解绑该中控全部工作台绑定'); + }); + it('POST /api/scan/records 首次上报:入库并刷新通道/心跳', async () => { let rows = null; let scannerUpdated = null; diff --git a/desktop/App.xaml.cs b/desktop/App.xaml.cs index ffdd7d2..e979ca6 100644 --- a/desktop/App.xaml.cs +++ b/desktop/App.xaml.cs @@ -26,7 +26,11 @@ public partial class App : Application private SingleInstance? _single; private AppSettings _settings = new(); private LocalHttpServer? _server; + private LocalWsServer? _wsServer; private HikDeviceService? _hik; + private HikStreamService? _stream; + private HikPreviewService? _preview; + private HikNativePreviewService? _native; private TrayIconService? _tray; private MainWindow? _main; private LoginWindow? _loginWindow; @@ -102,7 +106,7 @@ public partial class App : Application _hik = new HikDeviceService(); // 运单查询要用户令牌 + 当前主体,登录前这两个都还没有 → 用委托现取 var queryService = new OrderQueryService(() => _api, () => _settings.SubjectId, () => _session?.Token); - _server = new LocalHttpServer(queryService, _hik); + _server = new LocalHttpServer(queryService); _server.Log += AppLog.Write; // 网页靠 /api/health 里的 loggedIn 判断要不要唤起登录,靠 /api/activate-login 把登录窗叫到前台 _server.IsLoggedInProvider = () => _session is not null; @@ -110,6 +114,18 @@ public partial class App : Application _server.ServerBaseUrlProvider = () => _settings.ServerBaseUrl; _server.LoginRequested += OnLoginRequested; + // 实时预览的 WebSocket 通道(17301):网页预览/满帧率窗口**只走 WS**,HTTP 17300 不再提供预览接口。 + // 会话池(HikPreviewService)与原生窗口共用同一个 HikStreamService,避免两套码流服务。 + _stream = new HikStreamService(_hik); + _preview = new HikPreviewService(_hik, _stream, new HikFfmpegService()); + _native = new HikNativePreviewService(_stream); + _wsServer = new LocalWsServer(_hik, _preview, _native) + { + IsLoggedInProvider = () => _session is not null, + UserNameProvider = () => _session?.DisplayName, + }; + _wsServer.Log += AppLog.Write; + // 网页查件页的「下载录像」走这里:任何装了本机软件的电脑都能下,存到自己设置的目录 _server.PlaybackDownload = new PlaybackDownloadService( queryService, @@ -485,6 +501,20 @@ public partial class App : Application MessageBox.Show(ex.Message, "本机服务启动失败", MessageBoxButton.OK, MessageBoxImage.Warning); } + // WS 出问题不弹窗:网页会自动退回 HTTP 预览 + if (_wsServer is not null) + { + try + { + _wsServer.Start(); + AppLog.Write($"WS 预览服务:{_wsServer.Url}({( _wsServer.IsRunning ? "运行中" : "未启动" )})"); + } + catch (Exception ex) + { + AppLog.Write($"[ws] 启动失败(网页将退回 HTTP 预览):{ex.Message}"); + } + } + UpdateTrayStatus(); } @@ -669,6 +699,26 @@ public partial class App : Application // 退出路径忽略 } + try + { + _wsServer?.Dispose(); + } + catch + { + // 退出路径忽略 + } + + try + { + _native?.Dispose(); + _preview?.Dispose(); + _stream?.Dispose(); + } + catch + { + // 退出路径忽略 + } + try { _server?.Dispose(); @@ -694,6 +744,18 @@ public partial class App : Application { _ntpTimer?.Dispose(); _tray?.Dispose(); + _wsServer?.Dispose(); + try + { + _native?.Dispose(); + _preview?.Dispose(); + _stream?.Dispose(); + } + catch + { + // 退出路径忽略 + } + _server?.Dispose(); _hik?.Dispose(); _single?.Dispose(); diff --git a/desktop/MainWindow.xaml b/desktop/MainWindow.xaml index 383ed29..dc51148 100644 --- a/desktop/MainWindow.xaml +++ b/desktop/MainWindow.xaml @@ -68,6 +68,7 @@ + @@ -84,8 +85,15 @@ VerticalAlignment="Center" TextTrimming="CharacterEllipsis" /> - - + + + + + + + diff --git a/desktop/MainWindow.xaml.cs b/desktop/MainWindow.xaml.cs index af68294..65617e7 100644 --- a/desktop/MainWindow.xaml.cs +++ b/desktop/MainWindow.xaml.cs @@ -226,18 +226,11 @@ public partial class MainWindow : Window { if (AgentPaths.MachineMode && serviceSubject == saved) { + // 不弹窗:正常进主界面,提示统一显示在页签上方(见 UpdateDeviceMenu) AppLog.Write($"[subject] 当前账号不属于后台服务主体 {saved},只切换界面主体"); var fallback = _subjects.FirstOrDefault(item => !item.Expired) ?? _subjects[0]; ApplySubject(fallback, announce: false); - MessageBox.Show(this, - $"当前账号不属于后台扫码服务绑定的主体(id={saved})。\n\n" - + "后台服务仍在按原主体扫码、上报,不受影响。\n" - + $"本界面已切到当前账号可用的主体「{fallback.Display}」,仅用于查询/查看。\n\n" - + (fallback.IsAdmin - ? "你可以在本主体开启设备服务:需先「服务 → 关闭设备服务」停掉旧服务,再「开启设备服务」重新绑定。" - : "你不是本主体的管理员,看不到后台服务的扫码数据,也无法开启设备服务。"), - "主体", MessageBoxButton.OK, MessageBoxImage.Information); return; } @@ -378,13 +371,13 @@ public partial class MainWindow : Window RecordsTab.Visibility = scanTabs; if (scanTabs == Visibility.Collapsed && MainTabs.SelectedIndex >= 1) MainTabs.SelectedIndex = 0; - // 服务主体不一致:管理员能用,但必须明确告知处理方式 - var notice = mismatch && isAdmin - ? $"后台扫码服务运行在主体 id={ServiceSubjectId},与当前主体「{_settings.SubjectName}」不一致。" - + "本页显示的是该服务的数据;如需在当前主体下扫码,请先「服务 → 关闭设备服务」,再「开启设备服务」重新绑定。" - : null; - _scanTabView.SetNotice(notice); - _scanRecordsView.SetNotice(notice); + // 服务主体不一致:统一显示在页签上方(不弹窗,正常进界面) + SetMainNotice(mismatch + ? $"当前账号不属于后台扫码服务绑定的主体(id={ServiceSubjectId}),后台服务仍按原主体扫码、上报,不受影响。" + + (isAdmin + ? $"如需在当前主体「{_settings.SubjectName}」扫码,请先「服务 → 关闭设备服务」,再「开启设备服务」重新绑定。" + : "你不是当前主体的管理员,看不到后台服务的扫码数据,也无法开启设备服务。") + : null); // NTP 校时属于服务模式:设备服务开着才显示(开启后强制启用,不能停用) MenuNtp.Visibility = scanTabs; @@ -399,6 +392,20 @@ public partial class MainWindow : Window UpdateContextText(); } + /// 页签上方的主体/服务不一致提示(null / 空 = 隐藏) + private void SetMainNotice(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + { + SubjectNoticeText.Text = string.Empty; + SubjectNoticeBar.Visibility = Visibility.Collapsed; + return; + } + + SubjectNoticeText.Text = text; + SubjectNoticeBar.Visibility = Visibility.Visible; + } + /// 菜单里的设备令牌状态(到期时间取自 agent-token.json) private void UpdateTokenStatus() { diff --git a/desktop/README.md b/desktop/README.md index 7e0c112..49ad2a4 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -22,7 +22,8 @@ desktop/ ├── LoginWindow.xaml / .xaml.cs # 服务器地址 / 账号 / 密码 / 记住账号 / 自动恢复登录 ├── MainWindow.xaml / .xaml.cs # 服务状态、测试查询、菜单、退出登录 └── Services/ - ├── LocalHttpServer.cs # HttpListener + CORS + PNA + ├── LocalHttpServer.cs # HttpListener(17300):查询 / 唤起登录 / 下载录像 + ├── LocalWsServer.cs # WebSocket(17301):拉通道 / 预览推帧 / 云台 / 满帧率窗口 ├── OrderQueryService.cs # ★ 按运单号查数据(接真实数据源的地方) ├── ApiClient.cs # 登录 / 校验令牌(用到的全部后端接口) ├── SessionStore.cs # 登录态(%LOCALAPPDATA%\YuncangTrace\session.json) @@ -38,7 +39,7 @@ desktop/ | 场景 | 行为 | | --- | --- | -| 首次启动 | 先起本机服务(17300)与托盘,再弹登录页 → 登录成功才出主窗口 | +| 首次启动 | 先起本机服务(17300 HTTP + 17301 WS)与托盘,再弹登录页 → 登录成功才出主窗口 | | 已有令牌 | 登录窗一闪而过:`/api/web/me` 通过就直接进主窗口;失效则清掉令牌留在登录页 | | 关窗口(X) | 隐藏到托盘,本机服务继续跑(第一次会冒一个气泡提示) | | 再次双击 exe / 点网页「启动本机软件」 | 不会开第二个:把 `yuncang://open?code=…` 通过命名管道转给已运行实例 | @@ -89,7 +90,7 @@ dotnet publish -c Release -r win-x64 -p:ServerBaseUrl=https://trace.example.com - 地址等于**内置默认值**时,`settings.json` 里存空串 —— 所以换 Debug/Release 构建能自动跟随, 不会被上一次构建的默认值钉死;只有用户手改过的地址才会持久化。 - 换地址后**不会复用旧令牌**(`session.json` 里的 `ServerBaseUrl` 对不上就要求重新登录)。 -- `GET /api/health` 会回 `env` 和 `server`,排查环境是否装错时先看这两个字段。 +- `GET /api/query/{code}` 会回 `env` 和 `server`(排査环境是否装错时先看这两个字段;没登录时也带)。 ## 环境要求 @@ -137,6 +138,14 @@ dotnet publish -c Release -r win-x64 -p:ServerBaseUrl=https://trace.example.com `[ntp] 同步 NVR 完成:1/1 台(…)`;失败只记日志,不影响登录/查询。 - 回放侧仍会按录像机时钟做二次对齐(`HikPlaybackService.ClockOffset`), 即使本机时间临时不准也不会截掉面单。 +- **「同步 NVR 时间」直接写时间**:`NET_DVR_SET_TIMECFG` 写的是**设备本地时间**,我们写本机本地时间 + (NTP 校准后的值)。前提是**录像机时区必须是东八区**——现场曾把录像机时区设成伦敦(GMT+0), + 设备把本地时间当 UTC 推给摄像头,导致录像 OSD 整体跑偏 8~14 小时,而且**烧进视频后改不回来**。 + 软件走 8000 协议读不到时区,所以这一项由现场保证(时区改好后再同步)。 +- **不再依赖 ISAPI/Web 端口**:以前用 ISAPI 补通道名、探测云台、读写时区, + 但这些接口在部分摄像头/NVR 上根本不存在(实测有设备 `/ISAPI/*` 全 404),已全部移除: + 通道名留空(前端拼「NVR名-通道号」)、不再标记「是否支持云台」(预览界面统一显示方向盘)。 + `/api/hik/channels` 的 `webPort` 参数也已删除(旧前端传了会被忽略)。 ## 构建 / 运行 / 发布 @@ -313,7 +322,16 @@ cd desktop\installer > 每次测更新都要打一个**比当前安装版本高**的包(脚本会拒绝在"已是最新"时白跑)。 -## 本机接口(前端 `/local` 页用的就是这两个) +## 本机接口 + +本机软件开**两个**端口,职责分开: + +| 端口 | 协议 | 用途 | +| --- | --- | --- | +| **17300** | HTTP | 运单查询 / 唤起登录 / 按运单下载录像(低频、无状态) | +| **17301** | WebSocket | 拉通道 / 实时预览(推 JPEG 帧)/ 云台 / 满帧率窗口(预览相关全在这里) | + +### HTTP 17300(前端 `/local` 页用的就是这两个) 服务固定监听 `http://localhost:17300`(端口写在前端页面与插件里)。 代码里**同时注册了 `http://127.0.0.1:17300/`** 前缀 —— `HttpListener` 只接受「注册过的 host」, @@ -325,6 +343,32 @@ cd desktop\installer | --- | --- | --- | | GET | `/api/query/{code}` | 查信息,**同时把服务/登录状态一起返回**(见下)。没登录 → 401 `state:need-login` | | POST | `/api/activate-login` | 把本机软件的**登录窗叫到前台**(已登录时把主界面叫到前台)。网页收到 `need-login` 时自动调它 | +| POST | `/api/playback/download` | 按运单下载录像(存到本机设置目录) | + +> ⚠️ 以前的海康接口(`/api/hik/channels`、`/api/hik/preview*`、`/api/hik/ptz*`)**已全部迁移到 WS 17301**, +> HTTP 侧不再提供(访问会得到 404「接口不存在」)。前端 `api/localWs.ts` 是唯一调用入口。 + +### WebSocket 17301(预览 / 云台 / 拉通道) + +一条连接可同时推多路画面(一条工作台合成画面 4 路没问题)。文本请求 `{id, action, ...}`, +回复 `{id, ok, data | message}`;二进制帧 = `[1 字节 sid 长度][sid ASCII][JPEG]`。 + +| action | 参数 | 说明 | +| --- | --- | --- | +| `hello` | — | 服务名/版本/端口/登录状态 | +| `ping` | — | 探活 | +| `get_channels` | `host, port, user, password` | 走 8000 私有协议登录 NVR,返回通道列表(与原来 HTTP 返回同构) | +| `start_preview` | + `channel, fps?, streamType?, mode?, logicalChannel?, name?` | 建预览会话,之后持续推该 `sid` 的 JPEG 帧 | +| `stop_preview` | `sid` | 停一路、释放设备码流 | +| `open_window` | 同 `start_preview` | 在本机软件里开**满帧率原生窗口**(PlayM4 直渲染,25fps) | +| `close_window` | `wid` | 关原生窗口(网页断开时也会自动关) | +| `ptz` | + `command, stop?, speed?` | 云台连续动作(`stop=true` 停) | +| `ptz_preset` | + `presetAction`(set/goto/clear), `preset` | 预置点 | + +> `start_preview` / `get_channels` / `open_window` / `ptz*` 在服务端**并发执行**,不会把 +> 「停止预览 / 云台停转」堵在消息循环后面;云台命令之间按连接串行化,保证「开始转 → 停」不乱序。 +> +> 端口可用 `YUNCANG_LOCAL_WS_PORT` 覆盖;前端用 `VITE_LOCAL_WS` 覆盖默认 `ws://127.0.0.1:17301/`。 ### 为什么没有单独的「探活 / health」接口 @@ -489,7 +533,7 @@ reg query "HKCU\Software\Classes\yuncang\shell\open\command" | --- | --- | | 启动报「没有绑定端口的权限」/ `Access is denied (5)` | 管理员执行 `netsh http add urlacl url=http://localhost:17300/ user=%USERNAME%`,或改成以当前用户身份运行 | | 报端口被占用(错误 32) | 已经开了一个实例(单实例会把参数转过去);检查任务管理器里的残留进程 | -| 网页提示服务不可用,但软件在跑 | 先用浏览器直接打开 `http://localhost:17300/api/health`:打不开→防火墙/端口;打得开→多半是 CORS 头没回 | +| 网页提示服务不可用,但软件在跑 | 先用浏览器直接打开 `http://localhost:17300/api/query/`(会回 400 但带登录状态):打不开→防火墙/端口;打得开→多半是 CORS 头没回。预览类问题则看 `ws://127.0.0.1:17301/` 能不能打开(直接浏览器访问应该返回一小段 JSON) | | 点网页「启动本机软件」没反应 | 协议没注册(界面看「启动协议」状态);或浏览器拦了自动跳转(必须用户点击) | | 唤起时弹「You must install .NET Desktop Runtime」 | 唤起的是 `bin\Debug` 这类 framework-dependent 的 exe(拿不到 `DOTNET_ROOT`)。用自包含发布产物,并让它启动一次以校正注册表 | | 改了协议名 | 注册表重注册 + 前端 `VITE_APP_PROTOCOL` 同步 + 插件目标地址同步 | @@ -550,8 +594,8 @@ reg query "HKCU\Software\Classes\yuncang\shell\open\command" > **换账号登录(不属于后台服务主体)**:后台服务是独立进程,继续按原主体扫码/上报; > 桌面端会把**界面主体**自动切到当前账号可用的主体(查询用),并在状态行标注「服务主体 id=xxx」。 > 此时: -> - **管理员**:扫码通道 / 扫码记录页照常显示,但页顶有醒目提示「后台服务运行在主体 id=xxx,与当前主体不一致」, -> 要换到当前主体必须先「服务 → 关闭设备服务」,再「开启设备服务」重新绑定; +> - **不弹窗**,正常进主界面;页签上方常驻一条提示:「当前账号不属于后台扫码服务绑定的主体(id=xxx)…」; +> - **管理员**:扫码通道 / 扫码记录页照常显示,按提示先「服务 → 关闭设备服务」,再「开启设备服务」即可在当前主体重新绑定; > - **普通成员**:扫码通道 / 扫码记录页**直接隐藏**(本地文件是那台服务的数据,与当前账号的主体无关),只保留打包查询; > - 查询接口用的是当前账号的主体;「关闭设备服务」仍可执行:先停/卸载本地服务,再尝试通知服务器注销(不是该主体成员时服务端注销会失败,日志有记录); > - 账号下**一个主体都没有**:弹窗提醒后**直接退回登录页**(后台服务保持运行,换有主体的账号登录即可)。 @@ -585,7 +629,7 @@ reg query "HKCU\Software\Classes\yuncang\shell\open\command" | 串口指令调试 | `Views/ScannerCommandWindow`(通道页「串口指令…」) | 发任意 **HEX 字节**透传给扫码枪,预填四条常用指令(静音/恢复蜂鸣/连续扫描/间隔 0s)。换批枪后指令集不同时现场自己试,不用发版 | | 假死看门狗 | `ScanService.WatchdogLoopAsync` | 每 30s:连接看着在线但 **60s 没字节** → 回查设备侧 `SOCK.ClientIP`(CID 10001 才有)→ 本机 IP 不在里面就强制重连(设备断电重启时 TCP 不发 FIN,`ReadAsync` 会永久挂住) | | IP 变化 | `ScanService.ApplyDiscoveredIps` | 每次发现结果回来就刷新各通道 `LastIp`,变了立即用新地址重连(DHCP 续租后不会卡在旧 IP) || 通道配置 | `Services/Scan/ChannelStore.cs` | `%LOCALAPPDATA%\YuncangTrace\channels.json`(服务模式:`%ProgramData%\YuncangTrace\channels.json`),通道号取最小空号、删除后不复用;**不再有团购/散单字段**(团散在「工作台」区分) | -| 编排 | `Services/Scan/ScanService.cs` | 启动→连接所有启用通道;**通道一旦变动(增/删/停用)自动同步到服务器**:`POST /api/scan/channels` → `GET /api/scan/channels` 回查确认 → 缺了就退避重试(1s→30s)直到服务器真的有 | +| 编排 | `Services/Scan/ScanService.cs` | 启动→连接**全部**通道(没有启用/停用开关,加了就连);**通道一旦变动(增/删)自动同步到服务器**:`POST /api/scan/channels`(带 `replace: true`,全量对账)→ `GET /api/scan/channels` 回查确认 → 缺了就退避重试(1s→30s)直到服务器真的有;**删除通道会让服务器软删该通道并解绑工作台**(`removed` / `unbound`),删到 0 个也会推空列表 | | 扫码记录 | `Services/Scan/ScanRecordStore.cs` | `%LOCALAPPDATA%\YuncangTrace\scan-records.json`(服务模式:`%ProgramData%\YuncangTrace\scan-records.json`),每个通道最多 5000 条;**先落本地、服务器确认后才标「已上传」**,没确认的一直重试,断网不丢;连续扫描只刷新「最近一次扫到的时间」;**扫到后 5 分钟没再扫到同一个码才上报**,上报的就是最后一次扫描时间;同一运单 24 小时内再次扫到会**重新激活同一条本地记录**(不新增行),下一轮上报覆盖服务器记录 | | 上报队列 | `Services/DeviceService.cs` | 条码静默满 5 分钟后后台攒批(50 条/批)推 `POST /api/scan/records`,失败不标记、指数退避重发(服务端按 设备+通道+条码+秒 精确去重;**同一运单 24 小时内只保留一条,后上报的新时间会覆盖旧记录的时间与工作台快照**) | @@ -613,7 +657,7 @@ reg query "HKCU\Software\Classes\yuncang\shell\open\command" - 主窗口改成页签:**打包查询** / **扫码通道**(后者仅在「设备服务」开启后出现)。 查到条码(协议唤起或通道扫码)时**默认切回「打包查询」页签**并自动查询。 - 扫码通道页:**每个区块的状态与按钮都在各自标题行上**。 - - 「扫码通道」标题行:状态(`扫码服务运行中 · 通道 N 个(在线 M)` + 通道同步状态 + 待上传条数)+ `重连全部` / `停用` / `静音`(选中行切换,已静音时叫「恢复蜂鸣」)/ `读取设备配置` / `删除通道`; + - 「扫码通道」标题行:状态(`扫码服务运行中 · 通道 N 个(在线 M)` + 通道同步状态 + 待上传条数)+ `重连全部` / `静音`(选中行切换,已静音时叫「恢复蜂鸣」)/ `读取设备配置` / `删除通道`; 通道列表有「状态」「静音」两列; **没有「同步通道」按钮** —— 通道增删/启停都会自动上传并回查确认; - 「发现到的设备」标题行:`开始扫描`(**开关**,打开后常驻发现:每 3s 探测、socket 一直收,直到手工停止)+ `添加为通道` + 状态(`正在扫描… 未添加 N 台` / `发现 N 台未添加的设备(另有 M 台已添加)`)。 diff --git a/desktop/Services/Agent/AgentHost.cs b/desktop/Services/Agent/AgentHost.cs index 500847f..ecd3d21 100644 --- a/desktop/Services/Agent/AgentHost.cs +++ b/desktop/Services/Agent/AgentHost.cs @@ -145,7 +145,7 @@ public static class AgentHost device.EnsureUploadLoop(); await scan.StartAsync().ConfigureAwait(false); scan.StartDiscovery(); // 常驻发现:设备 DHCP 换 IP 时能自己重连 - AppLog.Write($"[agent] 扫码已启动:{scan.Channels.Count(item => item.Enabled)} 个通道" + AppLog.Write($"[agent] 扫码已启动:{scan.Channels.Count} 个通道" + $"(SN {config.DeviceSn},主体 {config.SubjectId})"); while (!ct.IsCancellationRequested) @@ -160,7 +160,7 @@ public static class AgentHost break; } - // ② 通道配置变了(桌面端增删/启停/改静音)→ 重新加载并连接 + // ② 通道配置变了(桌面端增删/改静音)→ 重新加载并连接 var newChannelsTime = AgentFiles.FileTime(AgentPaths.ChannelsFile); if (newChannelsTime != channelsTime) { @@ -169,6 +169,10 @@ public static class AgentHost scan.Stop(); await scan.StartAsync().ConfigureAwait(false); scan.StartDiscovery(); + + // 文件里就是完整通道列表:按全量对账再推一次, + // 桌面端那边推送失败(离线/未登录)时也能保证服务器跟着删/加。 + scan.RequestChannelSync(replace: true); } // ③ 桌面端的一次性命令 diff --git a/desktop/Services/Agent/ServiceInstaller.cs b/desktop/Services/Agent/ServiceInstaller.cs index cc59baa..ad55200 100644 --- a/desktop/Services/Agent/ServiceInstaller.cs +++ b/desktop/Services/Agent/ServiceInstaller.cs @@ -258,6 +258,11 @@ public static class ServiceInstaller RunSc("failure", ServiceName, "reset=", "86400", "actions=", "restart/5000/restart/10000/restart/30000"); + // ⚠️ 开发版(框架依赖)必须告诉服务 .NET 装在哪: + // 服务以 LocalSystem 跑,看不到当前用户 PATH / DOTNET_ROOT, + // apphost 会直接报「You must install .NET」→ 服务永远进不了 Running → 桌面提示“后台服务启动超时”。 + EnsureServiceDotnetEnvironment(); + var start = StartCore(); if (!start.Ok) return start; @@ -268,6 +273,51 @@ public static class ServiceInstaller }; } + /// + /// 开发版(框架依赖)装服务时,把 .NET 运行时目录写进服务的环境变量。 + /// + /// 服务以 LocalSystem 身份运行:看不到当前用户目录里的 .NET(本机 8.0 装在 + /// %LOCALAPPDATA%\Microsoft\dotnet),apphost 直接报 “You must install .NET” 并退出 → + /// SCM 状态一直进不了 Running → 桌面端只会看到「后台服务启动超时」。 + /// + /// 自包含单文件发布不需要(运行时就在 exe 里)。 + /// + private static void EnsureServiceDotnetEnvironment() + { + try + { + var sourceDir = Path.GetDirectoryName(Environment.ProcessPath ?? string.Empty) ?? string.Empty; + var frameworkDependent = File.Exists(Path.Combine(sourceDir, "YuncangTrace.LocalService.dll")); + + using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( + $@"SYSTEM\CurrentControlSet\Services\{ServiceName}", writable: true); + if (key is null) return; + + if (!frameworkDependent) + { + // 换回自包含版时把上次写的值清掉,避免指到一个不存在的目录 + if (key.GetValue("Environment") is not null) key.DeleteValue("Environment", throwOnMissingValue: false); + return; + } + + var runtimeDir = Path.GetDirectoryName(typeof(object).Assembly.Location); // ...\shared\Microsoft.NETCore.App\8.0.x + if (runtimeDir is null) return; + + var dotnetRoot = Path.GetFullPath(Path.Combine(runtimeDir, "..", "..")); + if (!File.Exists(Path.Combine(dotnetRoot, "dotnet.exe"))) return; + + key.SetValue("Environment", + new[] { $"DOTNET_ROOT={dotnetRoot}", $"PATH={dotnetRoot};%PATH%" }, + Microsoft.Win32.RegistryValueKind.MultiString); + + AppLog.Write($"[agent] 开发版服务已写入 DOTNET_ROOT={dotnetRoot}"); + } + catch (Exception ex) + { + AppLog.Write($"[agent] 写服务 DOTNET_ROOT 失败:{ex.Message}"); + } + } + private static HelperResult UninstallCore() { if (!ClockSyncService.IsElevated) return Fail("提权失败:当前进程不是管理员权限"); @@ -306,6 +356,10 @@ public static class ServiceInstaller { if (!IsInstalled) return Fail("服务未安装"); + // ⚠️ 每次启动前都补齐 .NET 环境变量:服务副本可能是开发版(框架依赖), + // 而 `.NET Runtime` 事件里只会看到 “You must install .NET”,界面上则表现为「启动超时」。 + EnsureServiceDotnetEnvironment(); + var (code, output) = RunSc("start", ServiceName); // 1056 = 已在运行;1053 = 已受理但还没进入 Running(下面轮询确认) if (code is not (0 or 1056 or 1053)) return Fail($"启动服务失败({code}):{output}"); diff --git a/desktop/Services/ApiClient.cs b/desktop/Services/ApiClient.cs index ea69397..c81442b 100644 --- a/desktop/Services/ApiClient.cs +++ b/desktop/Services/ApiClient.cs @@ -350,14 +350,17 @@ public sealed class ApiClient if (data is null) throw new ApiException(message, (int)response.StatusCode); } - /// 上报通道(设备令牌;`POST /api/scan/channels`) + /// + /// 上报通道(设备令牌;`POST /api/scan/channels`)。 + /// `replace = true` = 全量对账:服务器会软删本中控下不在列表里的旧通道,并解绑工作台。 + /// public async Task ReportChannelsAsync(string deviceToken, IEnumerable<(string ChannelId, string ChannelName)> channels, - CancellationToken ct = default) + bool replace = false, CancellationToken ct = default) { var rows = new List(); foreach (var (id, name) in channels) rows.Add(new { channelId = id, channelName = name }); - var payload = JsonSerializer.Serialize(new { channels = rows }, Json); + var payload = JsonSerializer.Serialize(new { channels = rows, replace }, Json); using var response = await SendDeviceAsync("/api/scan/channels", deviceToken, payload, "上报通道", ct) .ConfigureAwait(false); diff --git a/desktop/Services/DeviceService.cs b/desktop/Services/DeviceService.cs index 6832b41..2ede0d3 100644 --- a/desktop/Services/DeviceService.cs +++ b/desktop/Services/DeviceService.cs @@ -125,7 +125,7 @@ public sealed class DeviceService /// 上报一批通道(扫码服务的每条通道都同步给服务器,供工作台绑定) public async Task ReportChannelsAsync(IEnumerable<(string ChannelId, string ChannelName)> channels, - CancellationToken ct = default) + bool replace = false, CancellationToken ct = default) { if (!Enabled) return; @@ -133,9 +133,10 @@ public sealed class DeviceService .Where(item => !string.IsNullOrWhiteSpace(item.ChannelId)) .Select(item => (item.ChannelId, string.IsNullOrWhiteSpace(item.ChannelName) ? item.ChannelId : item.ChannelName)) .ToList(); - if (list.Count == 0) return; + // 全量对账时允许空列表(表示通道已全部删除) + if (list.Count == 0 && !replace) return; - await _api.ReportChannelsAsync(_settings.DeviceToken, list, ct).ConfigureAwait(false); + await _api.ReportChannelsAsync(_settings.DeviceToken, list, replace, ct).ConfigureAwait(false); } /// 关闭设备服务:让令牌立即作废并清掉本地状态 diff --git a/desktop/Services/Hik/HikDeviceService.cs b/desktop/Services/Hik/HikDeviceService.cs index 6be8156..8a88fe9 100644 --- a/desktop/Services/Hik/HikDeviceService.cs +++ b/desktop/Services/Hik/HikDeviceService.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; -using System.Net.Http; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; @@ -31,6 +30,17 @@ public sealed class HikDeviceService : IDisposable /// IP 通道配置缓冲区(实测设备返回 50792 字节,留余量) private const int IpParaBufferSize = 60000; + /// IP 设备项(NET_DVR_IPDEVINFO)在 IPPARACFG_V40 里的起点/大小 + private const int IpDevInfoStart = 84; + private const int IpDevInfoSize = 296; + + /// + /// 通道→IP 设备的映射表(struStreamMode):64 项、每项 496 字节。 + /// 实测 84 + 64*296 + 64*496 + 20 = 50792,正好是设备返回的字节数。 + /// + private const int StreamModeStart = IpDevInfoStart + 64 * IpDevInfoSize; + private const int StreamModeSize = 496; + private readonly ConcurrentDictionary _sessions = new(StringComparer.OrdinalIgnoreCase); private readonly Timer _sweeper; private bool _disposed; @@ -40,9 +50,9 @@ public sealed class HikDeviceService : IDisposable _sweeper = new Timer(_ => SweepIdleSessions(), null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); } - /// 读取设备通道列表(登录 → 读 IP 接入配置 → 补通道名 → 返回)。阻塞调用,调用方放在线程池里跑 - /// 设备 Web/ISAPI 端口(用于取真实通道名,默认 80;取不到就留空,不影响主流程) - public HikChannelsResult GetChannels(string host, int port, string userName, string password, int webPort = 80) + /// 读取设备通道列表(登录 → 读 IP 接入配置 → 返回)。阻塞调用,调用方放在线程池里跑 + /// 只走 8000 私有协议:部分摄像头没开 Web/ISAPI 端口,不能再依赖它。 + public HikChannelsResult GetChannels(string host, int port, string userName, string password) { Validate(host, port, userName, password); @@ -65,7 +75,7 @@ public sealed class HikDeviceService : IDisposable try { - var result = ReadChannels(session, password, webPort); + var result = ReadChannels(session); result.userId = session.UserId; result.sessionReused = reused; result.elapsedMs = stopwatch.ElapsedMilliseconds; @@ -130,7 +140,7 @@ public sealed class HikDeviceService : IDisposable /// /// 取设备的「首个数字通道号」(登录时读到的 byStartDChan) /// - /// 预览要把它换算成 ISAPI/RTSP 用的 1 起序号:logical = channel - startDigital + 1 + /// 预览要把它换算成 RTSP 用的 1 起序号:logical = channel - startDigital + 1 /// (本项目设备 32 路模拟 + 32 路数字,数字通道从 33 起 → 通道 33 对应 101 码流)。 /// 会话是池化的,重复调用只会读内存。 /// @@ -311,7 +321,7 @@ public sealed class HikDeviceService : IDisposable } /// - /// 读录像机的 NTP 配置(走 **8000 私有协议**:NET_DVR_GET_NTPCFG,不需要 Web/ISAPI 端口)。 + /// 读录像机的 NTP 配置(走 **8000 私有协议**:NET_DVR_GET_NTPCFG)。 /// public HikNtpConfig GetNtpConfig(string host, int port, string userName, string password) { @@ -421,8 +431,8 @@ public sealed class HikDeviceService : IDisposable /// 抓一帧 JPEG(预览用) /// /// 走 8000 私有协议的 NET_DVR_CaptureJPEGPicture_NEW: - /// - 不需要 ISAPI/Web 端口,也不需要解码器(PlayM4),拿到就是可直接给浏览器的 JPEG; - /// - 是**海康通道号**(数字通道从 33 起),不是 ISAPI 的 1 起序号; + /// - 不需要 Web 端口,也不需要解码器(PlayM4),拿到就是可直接给浏览器的 JPEG; + /// - 是**海康通道号**(数字通道从 33 起),不是 RTSP 的 1 起序号; /// - 同一 UserID 的抓帧被 串行化,多路预览也不会撞车(只是帧率分摊)。 /// public byte[] CaptureJpeg(string host, int port, string userName, string password, int channel) @@ -927,7 +937,7 @@ public sealed class HikDeviceService : IDisposable }; } - private static HikChannelsResult ReadChannels(Session session, string password, int webPort) + private static HikChannelsResult ReadChannels(Session session) { var device = session.Device ?? throw new HikException(3, "设备信息缺失(会话状态异常)"); @@ -974,17 +984,45 @@ public sealed class HikDeviceService : IDisposable } } + // IP 设备数组是**紧凑**的(未配置的通道被跳过),而预览/回放用的是**真实通道号**。 + // 只按数组下标推会错位(现场 IP 通道 19 是空槽,导致 51 以后全部串一位), + // 所以优先按 struStreamMode(按通道槽位给 byIPID)来映射。 + var mappingOk = CanReadStreamModes(buffer, returned, digitalCount); + for (var i = 0; i < digitalCount; i++) { - var item = ReadIpDevice(buffer, i); + var channel = startDigital + i; + + bool enabled; + IpDeviceEntry? item = null; + + if (mappingOk) + { + var offset = StreamModeStart + i * StreamModeSize; + enabled = Marshal.ReadByte(buffer, offset + 4) == 1; + var ipId = Marshal.ReadByte(buffer, offset + 5); + if (enabled && ipId >= 1 && ipId <= 64) + { + var entry = ReadIpDevice(buffer, ipId - 1); + if (entry.Enabled) item = entry; + } + } + else + { + // 老固件没有这层映射表:退回「顺序对应」 + var entry = ReadIpDevice(buffer, i); + enabled = entry.Enabled; + if (entry.Enabled) item = entry; + } + channels.Add(new HikChannelInfo { - channel = startDigital + i, + channel = channel, type = "digital", - enabled = item.Enabled, - ip = item.Enabled ? item.Ip : null, - port = item.Enabled ? item.Port : null, - user = item.Enabled ? item.UserName : null, + enabled = enabled, + ip = item?.Ip, + port = item?.Port, + user = item?.UserName, }); } } @@ -1008,8 +1046,8 @@ public sealed class HikDeviceService : IDisposable } } - // 通道名:SDK 那段配置里没有名字,走设备 Web/ISAPI 再取一次(取不到不影响其他字段) - TryFillChannelNames(session.Host, webPort, session.User, password, device.StartDigitalChannel, channels); + // 通道名:8000 协议的配置里没有(以前是走 ISAPI 补的,现已移除 —— 部分摄像头没有 Web 端口)。 + // 前端没有名字时会自己拼「NVR名-通道号」。 return new HikChannelsResult { @@ -1026,80 +1064,31 @@ public sealed class HikDeviceService : IDisposable } /// - /// 用 ISAPI 补全通道名(数字通道) - /// - /// ISAPI ContentMgmt/InputProxy/channels 返回的 id 是从 1 开始的 IP 通道序号, - /// 对应海康通道号 startDigitalChannel + (id - 1)。优先按 IP 匹配(最稳),取不到再按 id 匹配。 - /// Web 端口优先用传入的(默认 80),再试 8443(自签证书)。任何失败都静默,不拖慢主流程。 + /// 校验 struStreamMode 映射表能不能用(老固件可能不填这一层)。 + /// 判定标准:byEnable 只能 0/1;启用的槽位 byIPID 必须在 1..64。 /// - private static void TryFillChannelNames(string host, int webPort, string userName, string password, int startDigitalChannel, List channels) + private static bool CanReadStreamModes(IntPtr buffer, uint returned, int digitalCount) { - if (channels.Count == 0) return; + if (digitalCount <= 0 || digitalCount > 64) return false; + if (returned < StreamModeStart + digitalCount * StreamModeSize) return false; - var urls = new List(); - if (webPort > 0) urls.Add($"http://{host}:{webPort}/ISAPI/ContentMgmt/InputProxy/channels"); - urls.Add($"https://{host}:8443/ISAPI/ContentMgmt/InputProxy/channels"); - - foreach (var url in urls) + for (var i = 0; i < digitalCount; i++) { - try - { - using var handler = new HttpClientHandler - { - Credentials = new System.Net.NetworkCredential(userName, password), - PreAuthenticate = false, - // 设备都是自签证书,这里只用于内网取名字,不值得为它做校验 - ServerCertificateCustomValidationCallback = (_, _, _, _) => true, - }; - using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(3) }; - var xml = client.GetStringAsync(url).GetAwaiter().GetResult(); - if (string.IsNullOrWhiteSpace(xml)) continue; - - var document = XDocument.Parse(xml); - var byIp = new Dictionary(StringComparer.OrdinalIgnoreCase); - var byId = new Dictionary(); - - foreach (var node in document.Descendants().Where(e => e.Name.LocalName == "InputProxyChannel")) - { - var name = node.Elements().FirstOrDefault(e => e.Name.LocalName == "name")?.Value?.Trim() ?? string.Empty; - var idText = node.Elements().FirstOrDefault(e => e.Name.LocalName == "id")?.Value; - var ipText = node.Descendants().FirstOrDefault(e => e.Name.LocalName == "ipAddress")?.Value?.Trim(); - - if (int.TryParse(idText, out var id)) byId[id] = name; - if (!string.IsNullOrWhiteSpace(ipText)) byIp[ipText] = name; - } - - if (byIp.Count == 0 && byId.Count == 0) continue; - - foreach (var item in channels) - { - if (item.type != "digital") continue; - - if (!string.IsNullOrWhiteSpace(item.ip) && byIp.TryGetValue(item.ip!, out var nameByIp)) - { - item.name = nameByIp; - continue; - } - - // IP 对不上就按 id 推:isapi id = 1 对应第一个数字通道 - var idGuess = item.channel - startDigitalChannel + 1; - if (idGuess > 0 && byId.TryGetValue(idGuess, out var nameById)) item.name = nameById; - } - - return; // 拿到一次就够 - } - catch - { - // 换下一个地址/协议再试 - } + var offset = StreamModeStart + i * StreamModeSize; + var enabled = Marshal.ReadByte(buffer, offset + 4); + var ipId = Marshal.ReadByte(buffer, offset + 5); + if (enabled > 1) return false; + if (enabled == 1 && (ipId < 1 || ipId > 64)) return false; } + + return true; } /// NET_DVR_IPPARACFG_V40.struIPDevInfo[i](每项 296 字节,起点偏移 84) private static IpDeviceEntry ReadIpDevice(IntPtr buffer, int index) { - const int ipDeviceStart = 84; - const int ipDeviceSize = 296; + const int ipDeviceStart = IpDevInfoStart; + const int ipDeviceSize = IpDevInfoSize; var baseOffset = ipDeviceStart + index * ipDeviceSize; var enabled = Marshal.ReadByte(buffer, baseOffset); @@ -1209,7 +1198,7 @@ public sealed class HikChannelInfo public bool enabled { get; init; } - /// 设备上的通道名(来自 ISAPI,可能为空) + /// 设备上的通道名(8000 协议不返回,现已留空,由前端自行拼名字) public string? name { get; set; } /// 数字通道对应的前端 IP(未配置时为 null) diff --git a/desktop/Services/Hik/HikPlaybackService.cs b/desktop/Services/Hik/HikPlaybackService.cs index e1bf683..5be0ba6 100644 --- a/desktop/Services/Hik/HikPlaybackService.cs +++ b/desktop/Services/Hik/HikPlaybackService.cs @@ -15,7 +15,7 @@ namespace YuncangTrace.LocalService.Services.Hik; /// 一次「这个时段到底有没有录像」的探测结果 /// 拉到数据 = 有录像 /// RTSP 模式下解出的帧数(SDK 模式为 -1) -/// 换算出来的 ISAPI/RTSP 1 起通道序号(排查用) +/// 换算出来的 RTSP 1 起通道序号(排查用) /// 失败原因(无录像 / 端口不通 / 密码错) /// 实际走通的通道:SDK(8000)/ RTSP(554) public sealed record PlaybackCheck(bool HasRecord, int Frames, int LogicalChannel, string? Error, string Source = ""); @@ -33,7 +33,7 @@ public sealed record PlaybackProgress(double? Percent, string Message); /// | | SDK(`NET_DVR_GetFileByTime_V40`) | RTSP(`Streaming/tracks/...`) | /// | --- | --- | --- | /// | 端口 | 8000(现场基本都开) | 554(可能关/改端口) | -/// | 通道号 | **海康通道号**(34) | **ISAPI 序号**(2) | +/// | 通道号 | **海康通道号**(34) | **RTSP 序号**(2) | /// | 落地 | 设备原始封装 PS,需 ffmpeg 转封装 | 直接交给 ffmpeg | /// | 速度 | 2~5x 实时,带百分比进度 | 约 0.5~3x,靠 ffmpeg 进度 | /// @@ -86,7 +86,7 @@ public sealed class HikPlaybackService : IDisposable // ==================== 通道号换算 ==================== /// - /// 海康通道号 → ISAPI/RTSP 的 1 起序号 + /// 海康通道号 → RTSP 的 1 起序号 /// /// 换算依赖设备的「首个数字通道号」(本项目是 33): /// logical = channel - startDigital + 1。SDK 不可用时按 33 兜底。 @@ -168,6 +168,15 @@ public sealed class HikPlaybackService : IDisposable _clockOffsets[key] = (offset, Environment.TickCount64, ClockOffsetTtlMs); AppLog.Write($"[playback] 录像机 {host}:{port} 与本机时钟相差 {offset.TotalSeconds:+0.0;-0.0} 秒,回放时间已按录像机时钟对齐"); + + // 差到半小时以上基本不可能是「时钟没校准」,而是时区不一致: + // 这时回放时间会整体平移一个时区,画面 OSD 也会跟着对不上。 + if (Math.Abs(offset.TotalMinutes) >= 30) + { + AppLog.Write($"[playback] ⚠ 差值达 {offset.TotalHours:+0.0;-0.0} 小时,疑似录像机时区与本机不一致" + + "(请在录像机里把时区设为东八区,并检查摄像头是否跟随了错误的校时)"); + } + return offset; } catch (Exception ex) diff --git a/desktop/Services/Hik/HikPreviewService.cs b/desktop/Services/Hik/HikPreviewService.cs index bf71f76..c3ee9c3 100644 --- a/desktop/Services/Hik/HikPreviewService.cs +++ b/desktop/Services/Hik/HikPreviewService.cs @@ -6,18 +6,17 @@ using System.Threading; namespace YuncangTrace.LocalService.Services.Hik; /// -/// 预览会话管理。 +/// 预览会话管理(实时预览唯一入口,由 WS 17301 驱动)。 /// /// 为什么要有「会话」这层: -/// - 浏览器要把实时画面显示出来,必须有一个能持续拉的地址;而密码**不能**出现在 URL 里 -/// (会被历史记录、日志、代理记下来)。所以先 POST /api/hik/preview 换一个 -/// sid,之后 <img src="/api/hik/preview/mjpeg?sid=...> 只带 sid; +/// - 网页预览时凭据只发一次(走 WS 的 start_preview),之后每帧按 sid 区分, +/// 密码**不会**出现在任何 URL/帧头里(避免被历史记录、日志、代理记下来); /// - 会话里存着设备凭据与通道号,抓帧时直接复用 的连接池, -/// 不会每次请求都重新登录设备; +/// 不会每次取帧都重新登录设备; /// - 30 分钟没人刷新自动失效(滑动过期),进程内内存存储,不落盘。 /// /// 抓帧用 HCNetSDK 的 NET_DVR_CaptureJPEGPicture_NEW(8000 端口私有协议): -/// 不需要解码器、不需要转码,拿到的 JPEG 浏览器直接能显示。 +/// 不需要解码器、不需要转码,拿到的 JPEG 直接通过 WS 以二进制帧推给页面。 /// public sealed class HikPreviewService : IDisposable { @@ -51,7 +50,7 @@ public sealed class HikPreviewService : IDisposable /// capture = 设备抓帧(约 5fps)。 /// /// 0-主码流,1-子码流 - /// ISAPI/RTSP 的 1 起通道序号;不传则按设备起始数字通道推算 + /// RTSP 的 1 起通道序号;不传则按设备起始数字通道推算 public HikPreviewSession Create( string host, int port, @@ -250,7 +249,7 @@ public sealed class HikPreviewSession /// 海康通道号(数字通道从 33 起) public int Channel { get; init; } - /// ISAPI/RTSP 用的 1 起通道序号 + /// RTSP 用的 1 起通道序号 public int LogicalChannel { get; init; } /// 0-主码流(默认),1-子码流 diff --git a/desktop/Services/Hik/HikSdk.cs b/desktop/Services/Hik/HikSdk.cs index fe2a5ed..4c33c6d 100644 --- a/desktop/Services/Hik/HikSdk.cs +++ b/desktop/Services/Hik/HikSdk.cs @@ -41,6 +41,14 @@ internal static class HikSdk /// NET_DVR_GET_DEVICECFG:读取设备参数(用于探活) internal const uint NET_DVR_GET_DEVICECFG = 100; + /// + /// NET_DVR_GET_PTZPOS:读取通道的 PTZ 参数(输出 NET_DVR_PTZPOS,4 个 WORD = 8 字节)。 + /// + /// 文档写明是「获取 IP 快球 PTZ 参数」:**非云台通道通常返回失败**(err=17/23)。 + /// 拉取通道时已不再调用(预览界面统一显示云台方向盘,不再标记「是否支持云台」)。 + /// + internal const uint NET_DVR_GET_PTZPOS = 293; + /// /// NET_DVR_JPEGPARA.wPicSize 常用值 /// @@ -388,7 +396,7 @@ internal static class HikSdk bUseAsynLogin = 0, byProxyType = 0, byUseUTCTime = 0, - byLoginMode = 0, // 0 = 私有协议(走 8000);1 = ISAPI + byLoginMode = 0, // 0 = 私有协议(走 8000);1 = ISAPI 登录模式(本项目不用) byHttps = 0, // 0 = 不套 TLS iProxyID = -1, // 不使用代理时必须为 -1(填 0 新固件会报参数错误 17,实测) byVerifyMode = 0, diff --git a/desktop/Services/LocalHttpServer.cs b/desktop/Services/LocalHttpServer.cs index f4b506b..77ffd2d 100644 --- a/desktop/Services/LocalHttpServer.cs +++ b/desktop/Services/LocalHttpServer.cs @@ -5,7 +5,6 @@ using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using YuncangTrace.LocalService.Services.Hik; namespace YuncangTrace.LocalService.Services; @@ -41,11 +40,6 @@ public sealed class LocalHttpServer : IDisposable private readonly HttpListener _listener = new(); private readonly OrderQueryService _queryService; - private readonly HikDeviceService? _hik; - private readonly HikStreamService? _stream; - private readonly HikFfmpegService? _ffmpeg; - private readonly HikPreviewService? _preview; - private readonly HikNativePreviewService? _native; private CancellationTokenSource? _cts; private Task? _loop; @@ -71,18 +65,9 @@ public sealed class LocalHttpServer : IDisposable /// 当前后端地址(由 App 提供,随 `/api/query` 一起返回,排障用) public Func? ServerBaseUrlProvider { get; set; } - public LocalHttpServer(OrderQueryService queryService, HikDeviceService? hik = null) + public LocalHttpServer(OrderQueryService queryService) { _queryService = queryService; - _hik = hik; - - if (hik is not null) - { - _stream = new HikStreamService(hik); - _ffmpeg = new HikFfmpegService(); - _preview = new HikPreviewService(hik, _stream, _ffmpeg); - _native = new HikNativePreviewService(_stream); - } } /// 是否已登录(网页靠它判断要不要唤起登录) @@ -191,28 +176,7 @@ public sealed class LocalHttpServer : IDisposable return; } - // 海康设备通道:POST JSON {host,port,user,password} 或 GET ?host=&port=&user=&password= - // 走 HCNetSDK 的 8000 私有协议登录,成功后读 IP 接入配置返回通道列表 - if (path.Equals("/api/hik/channels", StringComparison.OrdinalIgnoreCase)) - { - await HandleHikChannelsAsync(request, response).ConfigureAwait(false); - return; - } - - // 海康实时预览:建会话 → MJPEG 拉流 / 单帧快照 - if (path.StartsWith("/api/hik/preview", StringComparison.OrdinalIgnoreCase)) - { - await HandleHikPreviewAsync(request, response, path).ConfigureAwait(false); - return; - } - - // 海康云台:POST /api/hik/ptz(方向/变倍/聚焦/光圈)与 /api/hik/ptz/preset(预置点) - if (path.Equals("/api/hik/ptz", StringComparison.OrdinalIgnoreCase) || - path.Equals("/api/hik/ptz/preset", StringComparison.OrdinalIgnoreCase)) - { - await HandleHikPtzAsync(request, response, path).ConfigureAwait(false); - return; - } + // ⚠️ 海康相关(拉通道 / 实时预览 / 云台 / 满帧率窗口)已全部迁到 WS 17301(LocalWsServer),这里不再提供。 // 按运单下载录像:POST /api/playback/download { code } // 网页查件页(/local?code=)用 —— 任何装了本机软件的电脑都能下,存到本机设置的目录 @@ -224,7 +188,13 @@ public sealed class LocalHttpServer : IDisposable if (!request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase)) { - await WriteJsonAsync(response, 405, new { ok = false, message = "只支持 GET" }).ConfigureAwait(false); + // 只剩 GET 接口了;旧的 POST /api/hik/* 会走到这里(预览/云台/拉通道已迁到 WS 17301) + await WriteJsonAsync(response, 404, new + { + ok = false, + state = "not-found", + message = "接口不存在(拉通道 / 预览 / 云台已迁到 WebSocket 17301)", + }).ConfigureAwait(false); return; } @@ -308,11 +278,9 @@ public sealed class LocalHttpServer : IDisposable
  • /api/query/{运单号} 查询(同时返回服务/登录状态;没登录回 401)
  • POST /api/activate-login 把登录窗叫到前台
  • -
  • POST /api/hik/channels 读取海康设备通道(body:{"host":"192.168.8.241","port":8000,"user":"admin","password":"***"})
  • -
  • POST /api/hik/preview 建预览会话(body 同 channels,加 channel)→ 返回 mjpegUrl / snapshotUrl / rtspUrl
  • -
  • POST /api/hik/ptz 云台连续动作(command=up/down/left/right/zoom-in…,stop=true 停止)
  • -
  • POST /api/hik/ptz/preset 预置点(action=set/goto/clear,preset=1~256)
  • +
  • POST /api/playback/download 按运单下载录像
+

拉通道 / 实时预览 / 云台 / 满帧率窗口走 WebSocket:ws://127.0.0.1:17301

"""; await WriteHtmlAsync(response, 200, html).ConfigureAwait(false); return; @@ -444,655 +412,6 @@ public sealed class LocalHttpServer : IDisposable } } - /// - /// 海康设备通道接口:POST /api/hik/channels(JSON)或 GET /api/hik/channels?host=&port=&user=&password=。 - /// - /// 走 HCNetSDK 的 8000 私有协议登录 → 读 NET_DVR_GET_IPPARACFG_V40 → 返回通道列表。 - /// 会话在 里池化复用,本接口**不会**每次登录。 - /// - private async Task HandleHikChannelsAsync(HttpListenerRequest request, HttpListenerResponse response) - { - if (_hik is null) - { - await WriteJsonAsync(response, 503, new { ok = false, message = "本机服务未启用海康 SDK 支持" }).ConfigureAwait(false); - return; - } - - string? host = null; - string? user = null; - string? password = null; - var port = 8000; - var webPort = 80; - - try - { - if (request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase)) - { - if (request.ContentLength64 > 8192) - { - await WriteJsonAsync(response, 413, new { ok = false, message = "请求体过大" }).ConfigureAwait(false); - return; - } - - string body; - using (var reader = new StreamReader(request.InputStream, request.ContentEncoding ?? Encoding.UTF8)) - { - body = await reader.ReadToEndAsync().ConfigureAwait(false); - } - - if (body.Trim().Length == 0) - { - await WriteJsonAsync(response, 400, new { ok = false, message = "请求体不能为空" }).ConfigureAwait(false); - return; - } - - using var document = JsonDocument.Parse(body); - var root = document.RootElement; - - host = ReadJsonString(root, "host") ?? ReadJsonString(root, "ip"); - user = ReadJsonString(root, "user") ?? ReadJsonString(root, "username") ?? ReadJsonString(root, "account"); - password = ReadJsonString(root, "password") ?? ReadJsonString(root, "pwd"); - - if (root.TryGetProperty("port", out var portElement)) - { - if (portElement.ValueKind == JsonValueKind.Number && portElement.TryGetInt32(out var number)) port = number; - else if (portElement.ValueKind == JsonValueKind.String && int.TryParse(portElement.GetString(), out var parsed)) port = parsed; - } - - if (root.TryGetProperty("webPort", out var webPortElement)) - { - if (webPortElement.ValueKind == JsonValueKind.Number && webPortElement.TryGetInt32(out var webNumber)) webPort = webNumber; - else if (webPortElement.ValueKind == JsonValueKind.String && int.TryParse(webPortElement.GetString(), out var webParsed)) webPort = webParsed; - } - } - else if (request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase)) - { - var query = request.QueryString; - host = query["host"] ?? query["ip"]; - user = query["user"] ?? query["username"]; - password = query["password"] ?? query["pwd"]; - if (int.TryParse(query["port"], out var parsed)) port = parsed; - if (int.TryParse(query["webPort"], out var parsedWeb)) webPort = parsedWeb; - } - else - { - await WriteJsonAsync(response, 405, new { ok = false, message = "只支持 POST / GET" }).ConfigureAwait(false); - return; - } - } - catch (JsonException) - { - await WriteJsonAsync(response, 400, new { ok = false, message = "请求体不是合法 JSON" }).ConfigureAwait(false); - return; - } - - try - { - var data = await Task.Run(() => _hik.GetChannels(host ?? string.Empty, port, user ?? string.Empty, password ?? string.Empty, webPort)) - .ConfigureAwait(false); - - Log?.Invoke($"海康通道读取成功:{data.endpoint},通道 {data.channels.Count} 个,耗时 {data.elapsedMs}ms(会话复用={data.sessionReused})"); - - await WriteJsonAsync(response, 200, new - { - ok = true, - state = "ok", - data, - }).ConfigureAwait(false); - } - catch (ArgumentException ex) - { - await WriteJsonAsync(response, 400, new { ok = false, state = "bad-request", message = ex.Message }).ConfigureAwait(false); - } - catch (HikException ex) - { - Log?.Invoke($"海康通道读取失败:{ex.Message}"); - await WriteJsonAsync(response, 502, new - { - ok = false, - state = "hik-error", - lastError = ex.ErrorCode, - message = ex.Message, - }).ConfigureAwait(false); - } - catch (Exception ex) - { - Log?.Invoke($"海康通道读取异常:{ex}"); - await WriteJsonAsync(response, 500, new { ok = false, message = "读取通道失败" }).ConfigureAwait(false); - } - } - - /// - /// 海康实时预览(`/api/hik/preview*`) - /// - /// 三个动作: - /// - POST /api/hik/preview:body `{host, port, user, password, channel, fps?, logicalChannel?}` → 建会话 - /// - GET /api/hik/preview/snapshot?sid=:单帧 JPEG - /// - GET /api/hik/preview/mjpeg?sid=&fps=:multipart/x-mixed-replace 连续帧,浏览器 <img> 直接能放 - /// - DELETE /api/hik/preview?sid=:释放会话 - /// - /// 为什么用 MJPEG:浏览器不认 RTSP,转 HLS/WebRTC 需要额外转码进程;而 - /// NET_DVR_CaptureJPEGPicture_NEW 拿到的就是 JPEG,推流侧零依赖。 - /// - private async Task HandleHikPreviewAsync(HttpListenerRequest request, HttpListenerResponse response, string path) - { - if (_hik is null || _preview is null) - { - await WriteJsonAsync(response, 503, new { ok = false, message = "本机服务未启用海康 SDK 支持" }).ConfigureAwait(false); - return; - } - - var isCreate = path.Equals("/api/hik/preview", StringComparison.OrdinalIgnoreCase); - var isClose = path.Equals("/api/hik/preview/close", StringComparison.OrdinalIgnoreCase); - var isSnapshot = path.Equals("/api/hik/preview/snapshot", StringComparison.OrdinalIgnoreCase); - var isMjpeg = path.Equals("/api/hik/preview/mjpeg", StringComparison.OrdinalIgnoreCase); - var isWindow = path.Equals("/api/hik/preview/window", StringComparison.OrdinalIgnoreCase); - var isWindowClose = path.Equals("/api/hik/preview/window/close", StringComparison.OrdinalIgnoreCase); - - if (!isCreate && !isClose && !isSnapshot && !isMjpeg && !isWindow && !isWindowClose) - { - await WriteJsonAsync(response, 404, new { ok = false, message = "接口不存在" }).ConfigureAwait(false); - return; - } - - // ---------- 网页关闭时用 navigator.sendBeacon 释放(只能 POST) ---------- - if (isClose) - { - var removed = _preview.Remove(request.QueryString["sid"]); - await WriteJsonAsync(response, 200, new { ok = true, removed }).ConfigureAwait(false); - return; - } - - // ---------- 满帧率原生窗口(解码器直接画到窗口,25fps) ---------- - if (isWindow || isWindowClose) - { - await HandleHikPreviewWindowAsync(request, response, isWindowClose).ConfigureAwait(false); - return; - } - - // ---------- 建会话 / 释放会话 ---------- - if (isCreate) - { - if (request.HttpMethod.Equals("DELETE", StringComparison.OrdinalIgnoreCase)) - { - var sidDelete = request.QueryString["sid"]; - var removed = _preview.Remove(sidDelete); - await WriteJsonAsync(response, 200, new { ok = true, removed }).ConfigureAwait(false); - return; - } - - if (!request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase)) - { - await WriteJsonAsync(response, 405, new { ok = false, message = "只支持 POST / DELETE" }).ConfigureAwait(false); - return; - } - - string host = string.Empty, user = string.Empty, password = string.Empty; - var port = 8000; - var channel = 0; - var fps = 25; - int? logicalChannel = null; - string? name = null; - var streamType = 0; // 0-主码流(默认) 1-子码流 - var mode = "stream"; // ffmpeg / stream / capture - - try - { - var (body, error) = await ReadJsonBodyAsync(request).ConfigureAwait(false); - if (error is not null) - { - await WriteJsonAsync(response, 400, new { ok = false, message = error }).ConfigureAwait(false); - return; - } - - using var document = JsonDocument.Parse(body!); - var root = document.RootElement; - - host = ReadJsonString(root, "host") ?? ReadJsonString(root, "ip") ?? string.Empty; - user = ReadJsonString(root, "user") ?? ReadJsonString(root, "username") ?? ReadJsonString(root, "account") ?? string.Empty; - password = ReadJsonString(root, "password") ?? ReadJsonString(root, "pwd") ?? string.Empty; - name = ReadJsonString(root, "name"); - - port = ReadJsonInt(root, "port") ?? 8000; - channel = ReadJsonInt(root, "channel") ?? ReadJsonInt(root, "channelNo") ?? 0; - fps = ReadJsonInt(root, "fps") ?? 25; - logicalChannel = ReadJsonInt(root, "logicalChannel"); - streamType = ReadJsonInt(root, "streamType") ?? 0; - - // mode:ffmpeg(主码流转码)/ stream(SDK 取流解码)/ capture(设备抓帧) - var modeText = ReadJsonString(root, "mode"); - if (!string.IsNullOrWhiteSpace(modeText)) mode = modeText.Trim().ToLowerInvariant(); - } - catch (JsonException) - { - await WriteJsonAsync(response, 400, new { ok = false, message = "请求体不是合法 JSON" }).ConfigureAwait(false); - return; - } - - try - { - var session = await Task.Run(() => _preview.Create(host, port, user, password, channel, fps, logicalChannel, name, mode, streamType)).ConfigureAwait(false); - - Log?.Invoke($"预览开始:{session.Host}:{session.Port} 通道 {session.Channel}(码流 {session.StreamId},{session.Fps}fps,{session.Mode},sid={session.Id})"); - - await WriteJsonAsync(response, 200, new - { - ok = true, - state = "ok", - data = new - { - sid = session.Id, - host = session.Host, - port = session.Port, - channel = session.Channel, - logicalChannel = session.LogicalChannel, - streamId = session.StreamId, - fps = session.Fps, - name = session.Name, - // stream/ffmpeg = 可到 25fps;capture = 设备抓帧(约 5fps) - mode = session.Mode, - streamType = session.StreamType, - maxFps = session.Mode == "capture" ? 5 : 25, - ffmpegAvailable = _ffmpeg?.IsAvailable ?? false, - warning = session.Warning, - rtspUrl = session.RtspUrl, - mjpegUrl = $"/api/hik/preview/mjpeg?sid={session.Id}", - snapshotUrl = $"/api/hik/preview/snapshot?sid={session.Id}", - expireAt = session.ExpiresAt.ToString("yyyy-MM-dd HH:mm:ss"), - }, - }).ConfigureAwait(false); - return; - } - catch (ArgumentException ex) - { - await WriteJsonAsync(response, 400, new { ok = false, state = "bad-request", message = ex.Message }).ConfigureAwait(false); - return; - } - catch (HikException ex) - { - Log?.Invoke($"预览建会话失败:{ex.Message}"); - await WriteJsonAsync(response, 502, new - { - ok = false, - state = "hik-error", - lastError = ex.ErrorCode, - message = ex.Message, - }).ConfigureAwait(false); - return; - } - catch (Exception ex) - { - Log?.Invoke($"预览建会话异常:{ex}"); - await WriteJsonAsync(response, 500, new { ok = false, message = "建立预览会话失败" }).ConfigureAwait(false); - return; - } - } - - // ---------- 以下需要 sid ---------- - if (!request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase)) - { - await WriteJsonAsync(response, 405, new { ok = false, message = "只支持 GET" }).ConfigureAwait(false); - return; - } - - var sid = request.QueryString["sid"]; - var sessionNow = _preview.Get(sid); - if (sessionNow is null) - { - await WriteJsonAsync(response, 404, new - { - ok = false, - state = "session-expired", - message = "预览会话不存在或已过期,请重新打开预览", - }).ConfigureAwait(false); - return; - } - - if (isSnapshot) - { - try - { - var jpeg = await Task.Run(() => _preview.CaptureFrame(sessionNow)).ConfigureAwait(false); - response.StatusCode = 200; - response.ContentType = "image/jpeg"; - response.Headers["Cache-Control"] = "no-store, no-cache, must-revalidate"; - response.ContentLength64 = jpeg.Length; - await response.OutputStream.WriteAsync(jpeg).ConfigureAwait(false); - } - catch (HikException ex) - { - Log?.Invoke($"预览快照失败:{ex.Message}"); - await WriteJsonAsync(response, 502, new { ok = false, state = "hik-error", lastError = ex.ErrorCode, message = ex.Message }).ConfigureAwait(false); - } - - return; - } - - await WriteMjpegAsync(request, response, sessionNow).ConfigureAwait(false); - } - - /// - /// 连续推 JPEG 帧:multipart/x-mixed-replace - /// - /// 浏览器(Chrome/Edge)对 MJPEG 的 <img> 支持一直很稳; - /// 客户端一关页面写入就会抛 IO 异常,这里直接停止抓帧,避免空转。 - /// - private async Task WriteMjpegAsync(HttpListenerRequest request, HttpListenerResponse response, HikPreviewSession session) - { - if (_preview is null) return; - - // 允许浏览器用 ?fps= 临时降/提帧(大屏 10fps 就够,看细节可到 25) - var fpsOverride = int.TryParse(request.QueryString["fps"], out var parsed) ? parsed : 0; - var fps = Math.Clamp(fpsOverride > 0 ? fpsOverride : session.Fps, 1, 25); - var frameInterval = 1000.0 / fps; // 毫秒/帧 - - response.StatusCode = 200; - response.ContentType = "multipart/x-mixed-replace; boundary=frame"; - response.Headers["Cache-Control"] = "no-store, no-cache, must-revalidate"; - response.Headers["Pragma"] = "no-cache"; - response.SendChunked = true; - - var output = response.OutputStream; - var crlf = Encoding.ASCII.GetBytes("\r\n"); - - // 按「绝对时间轴」配速(不是每帧之后再睡 40ms): - // 抓帧本身约 33ms,若写成 sleep(间隔 - 耗时) 会累积误差,实测只有 ~21fps;绝对时间轴能锁住 25fps。 - var clock = System.Diagnostics.Stopwatch.StartNew(); - var nextFrameAt = 0.0; - - try - { - while (true) - { - // 会话过期(30 分钟没人看)或被 DELETE 掉就收工 - if (_preview.Get(session.Id) is null) break; - - byte[] jpeg; - try - { - jpeg = await Task.Run(() => _preview.CaptureFrame(session)).ConfigureAwait(false); - } - catch (HikException ex) - { - Log?.Invoke($"预览中断:通道 {session.Channel} {ex.Message}"); - break; - } - - // 解码端口刚起来时可能还没出帧,跳过这轮即可(不要断流) - if (jpeg.Length == 0) - { - await Task.Delay(15).ConfigureAwait(false); - continue; - } - - var header = Encoding.ASCII.GetBytes( - $"--frame\r\nContent-Type: image/jpeg\r\nContent-Length: {jpeg.Length}\r\n\r\n"); - - await output.WriteAsync(header).ConfigureAwait(false); - await output.WriteAsync(jpeg).ConfigureAwait(false); - await output.WriteAsync(crlf).ConfigureAwait(false); - await output.FlushAsync().ConfigureAwait(false); - - nextFrameAt += frameInterval; - var delay = nextFrameAt - clock.Elapsed.TotalMilliseconds; - if (delay > 0) await Task.Delay((int)Math.Round(delay)).ConfigureAwait(false); - else nextFrameAt = clock.Elapsed.TotalMilliseconds; // 已经落后就不追,重新对齐 - } - } - catch (Exception ex) - { - // 浏览器关掉预览(img 换 src / 关弹窗)→ 写入失败,属于正常结束 - Log?.Invoke($"预览流结束:通道 {session.Channel}({ex.GetType().Name})"); - } - finally - { - try { response.Abort(); } catch { /* 忽略 */ } - } - } - - /// 读 JSON 请求体(超过 8KB 或为空都算错误) - private static async Task<(string? Body, string? Error)> ReadJsonBodyAsync(HttpListenerRequest request) - { - if (request.ContentLength64 > 8192) return (null, "请求体过大"); - - using var reader = new StreamReader(request.InputStream, request.ContentEncoding ?? Encoding.UTF8); - var body = await reader.ReadToEndAsync().ConfigureAwait(false); - if (body.Trim().Length == 0) return (null, "请求体不能为空"); - - return (body, null); - } - - private static int? ReadJsonInt(JsonElement root, string name) - { - if (!root.TryGetProperty(name, out var element)) return null; - - if (element.ValueKind == JsonValueKind.Number && element.TryGetInt32(out var number)) return number; - if (element.ValueKind == JsonValueKind.String && int.TryParse(element.GetString(), out var parsed)) return parsed; - return null; - } - - /// - /// 满帧率原生窗口:POST /api/hik/preview/window 打开,DELETE ...?wid= 关闭 - /// - /// 浏览器内嵌画面必须逐帧转 JPEG,1080p 每帧编码约 140ms(上限约 7fps); - /// 这个接口让 PlayM4 直接把画面画到一个原生窗口,能跑满设备帧率(25fps)。 - /// - private async Task HandleHikPreviewWindowAsync(HttpListenerRequest request, HttpListenerResponse response, bool isClose) - { - if (_native is null) - { - await WriteJsonAsync(response, 503, new { ok = false, message = "本机服务未启用海康 SDK 支持" }).ConfigureAwait(false); - return; - } - - // 关窗口:DELETE 或 POST(后者给 navigator.sendBeacon 用,它只能发 POST) - if (isClose || request.HttpMethod.Equals("DELETE", StringComparison.OrdinalIgnoreCase)) - { - var wid = request.QueryString["wid"]; - var closed = _native.Close(wid); - await WriteJsonAsync(response, 200, new { ok = true, closed }).ConfigureAwait(false); - return; - } - - if (!request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase)) - { - await WriteJsonAsync(response, 405, new { ok = false, message = "只支持 POST / DELETE" }).ConfigureAwait(false); - return; - } - - string host = string.Empty, user = string.Empty, password = string.Empty; - var port = 8000; - var channel = 0; - var streamType = 0; - string? name = null; - - try - { - var (body, error) = await ReadJsonBodyAsync(request).ConfigureAwait(false); - if (error is not null) - { - await WriteJsonAsync(response, 400, new { ok = false, message = error }).ConfigureAwait(false); - return; - } - - using var document = JsonDocument.Parse(body!); - var root = document.RootElement; - - host = ReadJsonString(root, "host") ?? ReadJsonString(root, "ip") ?? string.Empty; - user = ReadJsonString(root, "user") ?? ReadJsonString(root, "username") ?? string.Empty; - password = ReadJsonString(root, "password") ?? ReadJsonString(root, "pwd") ?? string.Empty; - name = ReadJsonString(root, "name"); - port = ReadJsonInt(root, "port") ?? 8000; - channel = ReadJsonInt(root, "channel") ?? ReadJsonInt(root, "channelNo") ?? 0; - streamType = ReadJsonInt(root, "streamType") ?? 1; - } - catch (JsonException) - { - await WriteJsonAsync(response, 400, new { ok = false, message = "请求体不是合法 JSON" }).ConfigureAwait(false); - return; - } - - try - { - var preview = _native.Open(host, port, user, password, channel, streamType, name); - - await WriteJsonAsync(response, 200, new - { - ok = true, - state = "ok", - data = new - { - wid = preview.Id, - host = preview.Host, - channel = preview.Channel, - streamType = preview.StreamType, - mode = "window", - fps = 25, - message = "已在本机软件里打开满帧率预览窗口", - }, - }).ConfigureAwait(false); - } - catch (ArgumentException ex) - { - await WriteJsonAsync(response, 400, new { ok = false, state = "bad-request", message = ex.Message }).ConfigureAwait(false); - } - catch (HikException ex) - { - Log?.Invoke($"满帧率预览失败:{ex.Message}"); - await WriteJsonAsync(response, 502, new - { - ok = false, - state = "hik-error", - lastError = ex.ErrorCode, - message = ex.Message, - }).ConfigureAwait(false); - } - catch (Exception ex) - { - Log?.Invoke($"满帧率预览异常:{ex}"); - await WriteJsonAsync(response, 500, new { ok = false, message = $"打开预览窗口失败:{ex.Message}" }).ConfigureAwait(false); - } - } - - /// - /// 云台控制:POST /api/hik/ptz / POST /api/hik/ptz/preset - /// - /// body:{host, port, user, password, channel, command?, stop?, speed?, action?, preset?} - /// - command:up/down/left/right/up-left/up-right/down-left/down-right/zoom-in/zoom-out/ - /// focus-near/focus-far/iris-open/iris-close/auto(自动扫描) - /// - stop:true 停止(页面松开按钮时发);方向类是“开始 + 停止”成对调用 - /// - 预置点:action=set/goto/clear,preset=1~256 - /// - /// 走 NET_DVR_PTZControlWithSpeed_Other,不需要开预览也能控。 - /// - private async Task HandleHikPtzAsync(HttpListenerRequest request, HttpListenerResponse response, string path) - { - if (_hik is null) - { - await WriteJsonAsync(response, 503, new { ok = false, message = "本机服务未启用海康 SDK 支持" }).ConfigureAwait(false); - return; - } - - if (!request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase)) - { - await WriteJsonAsync(response, 405, new { ok = false, message = "只支持 POST" }).ConfigureAwait(false); - return; - } - - string host = string.Empty, user = string.Empty, password = string.Empty; - var port = 8000; - var channel = 0; - var speed = 4; - string? command = null; - string? action = null; - var preset = 0; - var stop = false; - - try - { - var (body, error) = await ReadJsonBodyAsync(request).ConfigureAwait(false); - if (error is not null) - { - await WriteJsonAsync(response, 400, new { ok = false, message = error }).ConfigureAwait(false); - return; - } - - using var document = JsonDocument.Parse(body!); - var root = document.RootElement; - - host = ReadJsonString(root, "host") ?? ReadJsonString(root, "ip") ?? string.Empty; - user = ReadJsonString(root, "user") ?? ReadJsonString(root, "username") ?? string.Empty; - password = ReadJsonString(root, "password") ?? ReadJsonString(root, "pwd") ?? string.Empty; - command = ReadJsonString(root, "command"); - action = ReadJsonString(root, "action"); - port = ReadJsonInt(root, "port") ?? 8000; - channel = ReadJsonInt(root, "channel") ?? ReadJsonInt(root, "channelNo") ?? 0; - speed = ReadJsonInt(root, "speed") ?? 4; - preset = ReadJsonInt(root, "preset") ?? 0; - - if (root.TryGetProperty("stop", out var stopElement)) - { - stop = stopElement.ValueKind switch - { - JsonValueKind.True => true, - JsonValueKind.False => false, - JsonValueKind.Number => stopElement.TryGetInt32(out var number) && number != 0, - JsonValueKind.String => string.Equals(stopElement.GetString(), "true", StringComparison.OrdinalIgnoreCase), - _ => false, - }; - } - } - catch (JsonException) - { - await WriteJsonAsync(response, 400, new { ok = false, message = "请求体不是合法 JSON" }).ConfigureAwait(false); - return; - } - - var isPreset = path.EndsWith("/preset", StringComparison.OrdinalIgnoreCase); - - try - { - await Task.Run(() => - { - if (isPreset) - { - _hik.PtzPreset(host, port, user, password, channel, action ?? string.Empty, preset); - } - else - { - _hik.PtzControl(host, port, user, password, channel, command ?? string.Empty, stop, speed); - } - }).ConfigureAwait(false); - - await WriteJsonAsync(response, 200, new - { - ok = true, - state = "ok", - data = new { channel, command, action, preset, stop }, - }).ConfigureAwait(false); - } - catch (ArgumentException ex) - { - await WriteJsonAsync(response, 400, new { ok = false, state = "bad-request", message = ex.Message }).ConfigureAwait(false); - } - catch (HikException ex) - { - Log?.Invoke($"云台操作失败(通道 {channel}):{ex.Message}"); - await WriteJsonAsync(response, 502, new - { - ok = false, - state = "hik-error", - lastError = ex.ErrorCode, - message = ex.Message, - }).ConfigureAwait(false); - } - catch (Exception ex) - { - Log?.Invoke($"云台操作异常:{ex}"); - await WriteJsonAsync(response, 500, new { ok = false, message = "云台操作失败" }).ConfigureAwait(false); - } - } - private static string? ReadJsonString(JsonElement root, string name) => root.TryGetProperty(name, out var element) && element.ValueKind == JsonValueKind.String ? element.GetString() @@ -1105,8 +424,8 @@ public sealed class LocalHttpServer : IDisposable var origin = request.Headers["Origin"]; response.Headers["Access-Control-Allow-Origin"] = string.IsNullOrEmpty(origin) ? "*" : origin; response.Headers["Vary"] = "Origin"; - // DELETE 用于关闭预览会话;漏了它浏览器预检直接失败(实测现象:关弹窗时 console 报 CORS) - response.Headers["Access-Control-Allow-Methods"] = "GET, POST, DELETE, OPTIONS"; + // 只剩 GET / POST;漏了 POST 会导致预检直接失败(现象:网页报 CORS、实际服务在跑) + response.Headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"; response.Headers["Access-Control-Allow-Headers"] = "Content-Type, Accept"; response.Headers["Access-Control-Max-Age"] = "600"; @@ -1145,10 +464,6 @@ public sealed class LocalHttpServer : IDisposable { Stop(); _cts?.Dispose(); - _native?.Dispose(); - _preview?.Dispose(); - _ffmpeg?.Dispose(); - _stream?.Dispose(); _listener.Close(); } } diff --git a/desktop/Services/LocalWsServer.cs b/desktop/Services/LocalWsServer.cs new file mode 100644 index 0000000..0472f2a --- /dev/null +++ b/desktop/Services/LocalWsServer.cs @@ -0,0 +1,629 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.WebSockets; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using YuncangTrace.LocalService.Services.Hik; + +namespace YuncangTrace.LocalService.Services; + +/// +/// 本机 WebSocket 服务(只监听 127.0.0.1,默认端口 17301) +/// +/// 给网页的实时预览 / 云台 / 拉通道用:以前走 HTTP(先 POST 建会话、再用 <img> 拉 MJPEG), +/// 跨域/代理/多标签场景下都要多一次请求,而且浏览器对 MJPEG 的复用不总是如意;WS 下一条连接可以: +/// - hello:拿服务名/版本/登录状态; +/// - get_channels:用 8000 私有协议登录 NVR 取通道; +/// - start_preview:建预览会话,之后服务端持续推**二进制 JPEG 帧**; +/// - stop_preview:停掉某一路上行,释放设备码流; +/// - open_window / close_window:在本机软件里开/关**满帧率原生窗口**(PlayM4 直接渲染)。 +/// +/// 帧格式(服务端 → 客户端,Binary): +/// [1 字节 sid 长度][sid ASCII][JPEG 原始字节] +/// 一条连接可同时推多路(多磁贴预览),按 sid 区分。 +/// +/// 文本消息统一 { id, action, ... },回复 { id, ok, data | message }。 +/// +/// ⚠️ 页面从 https 打开时,浏览器可能把 ws://127.0.0.1 当混合内容拦掉(目前没有 HTTP 预览兼底, +/// 遇到这种情况界面会提示无法连接):调用方应先把站点上到 https,或浏览器站点设置里放行本机回环地址。 +/// +public sealed class LocalWsServer : IDisposable +{ + /// 监听端口(可用 YUNCANG_LOCAL_WS_PORT 临时覆盖) + public static int Port { get; } = ResolvePort(); + + private static int ResolvePort() + { + var raw = Environment.GetEnvironmentVariable("YUNCANG_LOCAL_WS_PORT"); + return int.TryParse(raw, out var port) && port is > 0 and < 65536 ? port : 17301; + } + + private readonly HttpListener _listener = new(); + private readonly HikDeviceService _hik; + private readonly HikPreviewService _preview; + private readonly HikNativePreviewService? _native; + private CancellationTokenSource? _cts; + private Task? _loop; + private bool _disposed; + + public LocalWsServer(HikDeviceService hik, HikPreviewService preview, HikNativePreviewService? native = null) + { + _hik = hik; + _preview = preview; + _native = native; + } + + /// 日志回调(服务线程 → UI 线程的桥) + public event Action? Log; + + /// 当前是否已登录(hello 里返回) + public Func? IsLoggedInProvider { get; set; } + + /// 当前登录用户显示名(hello 里返回) + public Func? UserNameProvider { get; set; } + + public string Url => $"ws://127.0.0.1:{Port}/"; + + public bool IsRunning => _listener.IsListening; + + /// 启动监听;端口被占/没权限会抛 (调用方只记日志,HTTP 仍可用) + public void Start() + { + if (IsRunning) return; + + _listener.Prefixes.Clear(); + _listener.Prefixes.Add($"http://localhost:{Port}/"); + _listener.Prefixes.Add($"http://127.0.0.1:{Port}/"); + _listener.Start(); + + _cts = new CancellationTokenSource(); + _loop = Task.Run(() => AcceptLoopAsync(_cts.Token)); + + Log?.Invoke($"WS 服务已启动:{Url}"); + } + + public void Stop() + { + if (!IsRunning) return; + + try { _cts?.Cancel(); } catch { /* 忽略 */ } + + try { _listener.Stop(); } catch { /* 忽略 */ } + try { _listener.Close(); } catch { /* 忽略 */ } + + _cts?.Dispose(); + _cts = null; + _loop = null; + + Log?.Invoke("WS 服务已停止"); + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + Stop(); + _listener.Close(); + } + + // ==================== 接受连接 ==================== + + private async Task AcceptLoopAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested && _listener.IsListening) + { + HttpListenerContext context; + try + { + context = await _listener.GetContextAsync().ConfigureAwait(false); + } + catch + { + break; // 监听被 Stop/Close + } + + _ = Task.Run(() => HandleContextAsync(context, ct), CancellationToken.None); + } + } + + private async Task HandleContextAsync(HttpListenerContext context, CancellationToken ct) + { + // 非 WS 请求:给网页/排障一个轻量探活 + if (!context.Request.IsWebSocketRequest) + { + await WriteProbeAsync(context).ConfigureAwait(false); + return; + } + + WebSocket socket; + try + { + var wsContext = await context.AcceptWebSocketAsync(null).ConfigureAwait(false); + socket = wsContext.WebSocket; + } + catch (Exception ex) + { + Log?.Invoke($"[ws] 建立连接失败:{ex.Message}"); + try { context.Response.StatusCode = 400; context.Response.Close(); } catch { /* 忽略 */ } + return; + } + + var conn = new Connection(socket); + Log?.Invoke($"[ws] 网页已连接({context.Request.RemoteEndPoint})"); + + try + { + await ReceiveLoopAsync(conn, ct).ConfigureAwait(false); + } + catch (Exception ex) + { + Log?.Invoke($"[ws] 连接异常:{ex.Message}"); + } + finally + { + // 页面关掉/刷新 → 它开的满帧率窗口一并关掉(否则码流会一直占着) + if (_native is not null && !conn.Windows.IsEmpty) + { + foreach (var wid in conn.Windows.Keys) + { + try { _native.Close(wid); } catch { /* 忽略 */ } + } + conn.Windows.Clear(); + } + + await conn.CloseAsync().ConfigureAwait(false); + Log?.Invoke("[ws] 网页已断开"); + } + } + + private static async Task WriteProbeAsync(HttpListenerContext context) + { + try + { + var body = Encoding.UTF8.GetBytes("{\"ok\":true,\"ws\":true,\"name\":\"YuncangTrace\"}"); + context.Response.StatusCode = 200; + context.Response.ContentType = "application/json; charset=utf-8"; + context.Response.Headers["Access-Control-Allow-Origin"] = "*"; + context.Response.ContentLength64 = body.Length; + await context.Response.OutputStream.WriteAsync(body, 0, body.Length).ConfigureAwait(false); + } + catch + { + // 探活失败不影响主流程 + } + finally + { + try { context.Response.Close(); } catch { /* 忽略 */ } + } + } + + // ==================== 消息循环 ==================== + + private async Task ReceiveLoopAsync(Connection conn, CancellationToken ct) + { + var buffer = new byte[16 * 1024]; + using var message = new MemoryStream(); + + while (!ct.IsCancellationRequested && conn.Socket.State == WebSocketState.Open) + { + var result = await conn.Socket.ReceiveAsync(new ArraySegment(buffer), ct).ConfigureAwait(false); + + if (result.MessageType == WebSocketMessageType.Close) break; + if (result.MessageType == WebSocketMessageType.Binary) continue; // 上行目前只收 JSON + + message.Write(buffer, 0, result.Count); + if (message.Length > 256 * 1024) + { + // 异常大包直接丢掉,避免被刷内存 + message.SetLength(0); + if (!result.EndOfMessage) continue; + } + + if (!result.EndOfMessage) continue; + + var text = Encoding.UTF8.GetString(message.ToArray()); + message.SetLength(0); + + // 慢命令(建会话/拉通道/开窗/云台)放后台并发执行,否则会把后面的 + // 「停止预览 / 云台停转」堵在接收循环里(建会话要 1~2 秒,拖云台会明显卡)。 + if (IsSlowAction(text)) + { + _ = Task.Run(() => HandleTextAsync(conn, text, ct), CancellationToken.None); + } + else + { + await HandleTextAsync(conn, text, ct).ConfigureAwait(false); + } + } + } + + /// 需要“不堵后面的消息”的 action + private static bool IsSlowAction(string text) + { + try + { + using var doc = JsonDocument.Parse(text); + return GetString(doc.RootElement, "action") is "start_preview" or "get_channels" or "open_window" or "ptz" or "ptz_preset"; + } + catch + { + return false; + } + } + + private async Task HandleTextAsync(Connection conn, string text, CancellationToken ct) + { + string? id = null; + try + { + using var doc = JsonDocument.Parse(text); + var root = doc.RootElement; + + if (root.TryGetProperty("id", out var idEl)) id = idEl.ToString(); + var action = GetString(root, "action"); + + switch (action) + { + case "hello": + await conn.ReplyAsync(id, true, new + { + name = "YuncangTrace", + version = typeof(LocalWsServer).Assembly.GetName().Version?.ToString() ?? "0.0.0", + port = Port, + loggedIn = IsLoggedInProvider?.Invoke() ?? false, + user = UserNameProvider?.Invoke(), + }, ct).ConfigureAwait(false); + break; + + case "ping": + await conn.ReplyAsync(id, true, new { pong = true }, ct).ConfigureAwait(false); + break; + + case "get_channels": + { + var (host, port, user, password) = ReadDevice(root); + var data = await Task.Run(() => _hik.GetChannels(host, port, user, password), ct) + .ConfigureAwait(false); + await conn.ReplyAsync(id, true, data, ct).ConfigureAwait(false); + break; + } + + case "start_preview": + { + var (host, port, user, password) = ReadDevice(root); + var channel = GetInt(root, "channel", 0); + if (channel <= 0) throw new ArgumentException("channel 必须是正整数"); + + var fps = GetInt(root, "fps", 25); + var streamType = GetInt(root, "streamType", 0); + var logical = GetInt(root, "logicalChannel", 0); + var mode = GetString(root, "mode") ?? "stream"; + var name = GetString(root, "name"); + + var session = await Task.Run(() => _preview.Create(host, port, user, password, channel, + fps, logical > 0 ? logical : null, name, mode, streamType), ct).ConfigureAwait(false); + + var job = new StreamJob(session); + if (!conn.Jobs.TryAdd(session.Id, job)) + { + _preview.Remove(session.Id); + throw new InvalidOperationException("预览会话冲突,请重试"); + } + + job.Task = Task.Run(() => StreamLoopAsync(conn, job, job.Cts.Token), CancellationToken.None); + + await conn.ReplyAsync(id, true, new + { + sid = session.Id, + channel = session.Channel, + logicalChannel = session.LogicalChannel, + streamId = session.StreamId, + mode = session.Mode, + fps = session.Fps, + streamType = session.StreamType, + warning = session.Warning, + }, ct).ConfigureAwait(false); + break; + } + + case "stop_preview": + { + var sid = GetString(root, "sid"); + if (!string.IsNullOrWhiteSpace(sid)) StopJob(conn, sid!); + await conn.ReplyAsync(id, true, new { sid }, ct).ConfigureAwait(false); + break; + } + + case "open_window": + { + if (_native is null) throw new InvalidOperationException("本机软件未启用预览窗口"); + + var (host, port, user, password) = ReadDevice(root); + var channel = GetInt(root, "channel", 0); + if (channel <= 0) throw new ArgumentException("channel 必须是正整数"); + + var streamType = GetInt(root, "streamType", 0); + var name = GetString(root, "name"); + + var window = await Task.Run( + () => _native.Open(host, port, user, password, channel, streamType, name), ct).ConfigureAwait(false); + + Log?.Invoke($"[ws] 满帧率窗口已打开:{host} 通道 {channel}(wid={window.Id})"); + conn.Windows.TryAdd(window.Id, 0); + + await conn.ReplyAsync(id, true, new + { + wid = window.Id, + host = window.Host, + channel = window.Channel, + streamType = window.StreamType, + mode = "window", + fps = 25, + message = "已在本机软件里打开满帧率预览窗口", + }, ct).ConfigureAwait(false); + break; + } + + case "close_window": + { + var wid = GetString(root, "wid"); + var closed = _native?.Close(wid) ?? false; + if (!string.IsNullOrWhiteSpace(wid)) conn.Windows.TryRemove(wid!, out _); + await conn.ReplyAsync(id, true, new { wid, closed }, ct).ConfigureAwait(false); + break; + } + + case "ptz": + case "ptz_preset": + { + var (host, port, user, password) = ReadDevice(root); + var channel = GetInt(root, "channel", 0); + if (channel <= 0) throw new ArgumentException("channel 必须是正整数"); + + var speed = GetInt(root, "speed", 4); + + // 云台命令串行化:保证「开始转 / 停转」的先后顺序(并发的 stop 可能先执行) + await conn.DeviceLock.WaitAsync(ct).ConfigureAwait(false); + try + { + if (action == "ptz_preset") + { + var presetAction = GetString(root, "presetAction") ?? "goto"; + var preset = GetInt(root, "preset", 0); + + await Task.Run(() => _hik.PtzPreset(host, port, user, password, channel, presetAction, preset), ct) + .ConfigureAwait(false); + + await conn.ReplyAsync(id, true, new { channel, presetAction, preset }, ct).ConfigureAwait(false); + } + else + { + var command = GetString(root, "command"); + if (string.IsNullOrWhiteSpace(command)) throw new ArgumentException("command 不能为空"); + + var stop = GetBool(root, "stop", false); + + await Task.Run(() => _hik.PtzControl(host, port, user, password, channel, command!, stop, speed), ct) + .ConfigureAwait(false); + + await conn.ReplyAsync(id, true, new { channel, command, stop, speed }, ct).ConfigureAwait(false); + } + } + finally + { + conn.DeviceLock.Release(); + } + + break; + } + + default: + await conn.ReplyAsync(id, false, null, ct, "未知 action").ConfigureAwait(false); + break; + } + } + catch (Exception ex) + { + await conn.ReplyAsync(id, false, null, ct, ex.Message).ConfigureAwait(false); + } + } + + private void StopJob(Connection conn, string sid) + { + if (!conn.Jobs.TryRemove(sid, out var job)) return; + + try { job.Cts.Cancel(); } catch { /* 忽略 */ } + _preview.Remove(sid); + Log?.Invoke($"[ws] 预览已停止:{sid}"); + } + + // ==================== 推帧 ==================== + + private async Task StreamLoopAsync(Connection conn, StreamJob job, CancellationToken ct) + { + var session = job.Session; + var interval = TimeSpan.FromMilliseconds(1000.0 / Math.Max(1, session.Fps)); + var next = DateTime.UtcNow; + + try + { + while (!ct.IsCancellationRequested && conn.Socket.State == WebSocketState.Open) + { + byte[] frame; + try + { + frame = await Task.Run(() => _preview.CaptureFrame(session), ct).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + Log?.Invoke($"[ws] 取帧失败({session.Id}):{ex.Message}"); + await Task.Delay(500, ct).ConfigureAwait(false); + continue; + } + + if (frame.Length > 0) + { + session.Touch(); + await conn.SendFrameAsync(session.Id, frame, ct).ConfigureAwait(false); + } + + next = next.Add(interval); + var wait = next - DateTime.UtcNow; + if (wait < TimeSpan.Zero) wait = TimeSpan.Zero; + await Task.Delay(wait, ct).ConfigureAwait(false); + } + } + catch (OperationCanceledException) + { + // 正常停止 + } + catch (Exception ex) + { + Log?.Invoke($"[ws] 推流异常({session.Id}):{ex.Message}"); + } + finally + { + conn.Jobs.TryRemove(session.Id, out _); + _preview.Remove(session.Id); + } + } + + // ==================== 参数读取 ==================== + + private static (string Host, int Port, string User, string Password) ReadDevice(JsonElement root) + { + var host = GetString(root, "host") ?? GetString(root, "ip"); + var user = GetString(root, "user") ?? GetString(root, "username") ?? GetString(root, "account"); + var password = GetString(root, "password") ?? GetString(root, "pwd"); + var port = GetInt(root, "port", 8000); + + if (string.IsNullOrWhiteSpace(host)) throw new ArgumentException("host 不能为空"); + if (string.IsNullOrWhiteSpace(user)) throw new ArgumentException("user 不能为空"); + if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("password 不能为空"); + + return (host!, port, user!, password!); + } + + private static string? GetString(JsonElement root, string name) + => root.TryGetProperty(name, out var el) && el.ValueKind == JsonValueKind.String + ? el.GetString() + : null; + + private static int GetInt(JsonElement root, string name, int fallback) + { + if (!root.TryGetProperty(name, out var el)) return fallback; + if (el.ValueKind == JsonValueKind.Number && el.TryGetInt32(out var number)) return number; + return el.ValueKind == JsonValueKind.String && int.TryParse(el.GetString(), out var parsed) ? parsed : fallback; + } + + private static bool GetBool(JsonElement root, string name, bool fallback) + { + if (!root.TryGetProperty(name, out var el)) return fallback; + if (el.ValueKind is JsonValueKind.True or JsonValueKind.False) return el.GetBoolean(); + return el.ValueKind == JsonValueKind.String && bool.TryParse(el.GetString(), out var parsed) ? parsed : fallback; + } + + // ==================== 连接 / 会话 ==================== + + private sealed class Connection + { + private readonly SemaphoreSlim _sendLock = new(1, 1); + + public Connection(WebSocket socket) => Socket = socket; + + public WebSocket Socket { get; } + + public ConcurrentDictionary Jobs { get; } = new(StringComparer.OrdinalIgnoreCase); + + /// 云台命令串行化(保证「开始转 → 停止」不会反序,否则摄像机会一直转) + public SemaphoreSlim DeviceLock { get; } = new(1, 1); + + /// 本连接打开的原生预览窗口(页面断开时一并关闭) + public ConcurrentDictionary Windows { get; } = new(StringComparer.OrdinalIgnoreCase); + + public async Task ReplyAsync(string? id, bool ok, object? data, CancellationToken ct, string? message = null) + { + var payload = new Dictionary + { + ["id"] = id, + ["ok"] = ok, + ["data"] = data, + ["message"] = message, + }; + + var json = JsonSerializer.Serialize(payload); + var bytes = Encoding.UTF8.GetBytes(json); + await SendAsync(bytes, WebSocketMessageType.Text, ct).ConfigureAwait(false); + } + + public Task SendFrameAsync(string sid, byte[] frame, CancellationToken ct) + { + var sidBytes = Encoding.ASCII.GetBytes(sid); + var buffer = new byte[1 + sidBytes.Length + frame.Length]; + buffer[0] = (byte)sidBytes.Length; + Buffer.BlockCopy(sidBytes, 0, buffer, 1, sidBytes.Length); + Buffer.BlockCopy(frame, 0, buffer, 1 + sidBytes.Length, frame.Length); + return SendAsync(buffer, WebSocketMessageType.Binary, ct); + } + + private async Task SendAsync(byte[] buffer, WebSocketMessageType type, CancellationToken ct) + { + await _sendLock.WaitAsync(ct).ConfigureAwait(false); + try + { + if (Socket.State != WebSocketState.Open) return; + await Socket.SendAsync(new ArraySegment(buffer), type, true, ct).ConfigureAwait(false); + } + finally + { + _sendLock.Release(); + } + } + + public async Task CloseAsync() + { + foreach (var job in Jobs.Values) + { + try { job.Cts.Cancel(); } catch { /* 忽略 */ } + } + Jobs.Clear(); + + try + { + if (Socket.State == WebSocketState.Open) + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2)); + await Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "bye", timeout.Token) + .ConfigureAwait(false); + } + } + catch + { + // 忽略 + } + finally + { + Socket.Dispose(); + // ⚠️ 不要 Dispose _sendLock:推流任务可能晚一步才退出,Dispose 会让它们抛 ObjectDisposedException + } + } + } + + private sealed class StreamJob + { + public StreamJob(HikPreviewSession session) => Session = session; + + public HikPreviewSession Session { get; } + public CancellationTokenSource Cts { get; } = new(); + public Task? Task { get; set; } + } +} diff --git a/desktop/Services/Scan/ChannelConnection.cs b/desktop/Services/Scan/ChannelConnection.cs index 8dcbe50..b231baa 100644 --- a/desktop/Services/Scan/ChannelConnection.cs +++ b/desktop/Services/Scan/ChannelConnection.cs @@ -113,7 +113,7 @@ public sealed class ChannelConnection : IDisposable { var attempts = 0; - while (!ct.IsCancellationRequested && _channel.Enabled && !string.IsNullOrWhiteSpace(_channel.LastIp)) + while (!ct.IsCancellationRequested && !string.IsNullOrWhiteSpace(_channel.LastIp)) { TcpClient? client = null; var reason = string.Empty; @@ -213,7 +213,7 @@ public sealed class ChannelConnection : IDisposable } } - AppLog.Write($"[scan] 通道 {_channel.Number} 重连循环结束(服务停止 / 通道被停用或删除)"); + AppLog.Write($"[scan] 通道 {_channel.Number} 重连循环结束(服务停止 / 通道被删除)"); } /// diff --git a/desktop/Services/Scan/ScanChannel.cs b/desktop/Services/Scan/ScanChannel.cs index a5dd387..8d7112c 100644 --- a/desktop/Services/Scan/ScanChannel.cs +++ b/desktop/Services/Scan/ScanChannel.cs @@ -41,9 +41,6 @@ public sealed class ScanChannel /// public string SockName { get; set; } = string.Empty; - /// 是否启用(停用就不连、不上报) - public bool Enabled { get; set; } = true; - /// 扫码枪是否静音(现场偏好,暂只记录) public bool Muted { get; set; } diff --git a/desktop/Services/Scan/ScanService.cs b/desktop/Services/Scan/ScanService.cs index 1c42d20..e1cb446 100644 --- a/desktop/Services/Scan/ScanService.cs +++ b/desktop/Services/Scan/ScanService.cs @@ -26,6 +26,9 @@ public sealed class ScanService private Task? _syncTask; private int _syncRetryMs = 1000; + /// 下一次推送是否用「全量对账」语义(添加/删除通道时置 true,成功后清掉) + private volatile bool _syncReplace; + // 看门狗:设备断电重启时 TCP 不发 FIN,read 会永久挂住 → 定期回查设备侧 ClientIP private CancellationTokenSource? _watchdogCts; private Task? _watchdogTask; @@ -158,7 +161,7 @@ public sealed class ScanService foreach (var channel in changed) { - if (Running && channel.Enabled) StartConnection(channel); + if (Running) StartConnection(channel); } } @@ -268,12 +271,11 @@ public sealed class ScanService Number = wanted, TcpPort = ScanProtocol.TcpPort, SockName = ensure.SockName, - Enabled = true, }; Channels.Add(channel); SaveChannels(); Changed?.Invoke(); - RequestChannelSync(); + RequestChannelSync(replace: true); if (Running) StartConnection(channel); @@ -288,33 +290,21 @@ public sealed class ScanService Channels.Remove(channel); SaveChannels(); Changed?.Invoke(); - RequestChannelSync(); + // 全量对账:服务器会软删这条通道并解绑工作台 + RequestChannelSync(replace: true); } - /// 启用 / 停用通道 - public void SetEnabled(ScanChannel channel, bool enabled) - { - channel.Enabled = enabled; - SaveChannels(); - - if (enabled && Running) StartConnection(channel); - else StopConnection(channel); - - Changed?.Invoke(); - RequestChannelSync(); - } - - /// 启动扫码服务:连接所有启用的通道 + (后台)同步通道列表到服务器 + /// 启动扫码服务:连接所有通道 + (后台)同步通道列表到服务器 public Task StartAsync() { Load(); Running = true; - foreach (var channel in Channels.Where(item => item.Enabled)) StartConnection(channel); + foreach (var channel in Channels) StartConnection(channel); RequestChannelSync(); EnsureWatchdog(); - AppLog.Write($"[scan] 扫码服务已启动,通道 {Channels.Count(item => item.Enabled)} 个"); + AppLog.Write($"[scan] 扫码服务已启动,通道 {Channels.Count} 个"); Changed?.Invoke(); return Task.CompletedTask; } @@ -437,11 +427,15 @@ public sealed class ScanService /// /// 把通道列表同步到服务器(`POST /api/scan/channels` 之后再用 `GET` **回查确认**)。 /// - /// 不用手动点:添加 / 删除 / 启用停用 都会调 , + /// `replace = true` = 全量对账(添加/删除通道时用):服务器会软删本中控下不在列表里的旧通道, + /// 并解绑对应工作台绑定(通道列表存在本地,与本机设备是否在线无关)。 + /// + /// 不用手动点:添加 / 删除 都会调 , /// 后台循环一直重试到服务器确实有这批通道为止(断网、服务器重启都不用手管)。 /// - public void RequestChannelSync() + public void RequestChannelSync(bool replace = false) { + if (replace) _syncReplace = true; EnsureSyncLoop(); try { @@ -491,19 +485,23 @@ public sealed class ScanService return; } - var local = Channels.Where(item => item.Enabled) + var local = Channels .Select(item => (item.ChannelId, item.DisplayName)) .ToList(); - if (local.Count == 0) + // replace = 全量对账:本地通道列表就是全部(设备离线不影响通道配置), + // 推空列表也合法 —— 表示通道已巨部删除,服务器要跟着删。 + var replace = _syncReplace; + + if (local.Count == 0 && !replace) { - SetSyncStatus("当前没有启用的通道"); + SetSyncStatus("当前没有通道"); return; } try { - await _device.ReportChannelsAsync(local, ct).ConfigureAwait(false); + await _device.ReportChannelsAsync(local, replace, ct).ConfigureAwait(false); // 服务器回查:确保它真的收到了(POST 成功≠入库成功,例如主体变更/令牌失效) var remote = await _device.ChannelsAsync(ct).ConfigureAwait(false); @@ -512,8 +510,9 @@ public sealed class ScanService if (missing.Count == 0) { _syncRetryMs = 1000; + if (replace) _syncReplace = false; SetSyncStatus($"通道已同步({local.Count} 个)"); - AppLog.Write($"[scan] 通道已同步到服务器并确认:{local.Count} 个"); + AppLog.Write($"[scan] 通道已同步到服务器并确认:{local.Count} 个" + (replace ? "(全量对账)" : "")); return; } diff --git a/desktop/Views/ScanRecordsView.xaml b/desktop/Views/ScanRecordsView.xaml index 67c4293..b98a513 100644 --- a/desktop/Views/ScanRecordsView.xaml +++ b/desktop/Views/ScanRecordsView.xaml @@ -4,21 +4,13 @@ FontFamily="Microsoft YaHei UI, Segoe UI" FontSize="13"> - - - - - - - + - @@ -49,7 +41,7 @@ - + @@ -805,8 +802,8 @@ async function doPreset(action: 'set' | 'goto' | 'clear') {

{{ ptzError }}

-

- 按暂停住方向键转动,松开即停;勾错了「支持云台」可在摄像头列表里改。 +

+ 按暂停住方向键转动,松开即停;没有云台的通道点击无效属正常现象。

{{ previewWinMsg }}

@@ -932,11 +929,6 @@ async function doPreset(action: 'set' | 'goto' | 'clear') { color: #94a3b8; } -.ptz-badge { - margin-left: 6px; - transform: scale(0.92); -} - .field-check { display: flex; align-items: center; diff --git a/frontend/src/views/NvrsView.vue b/frontend/src/views/NvrsView.vue index 821716d..57f338b 100644 --- a/frontend/src/views/NvrsView.vue +++ b/frontend/src/views/NvrsView.vue @@ -3,7 +3,7 @@ * NVR 录像机管理 * * 两段式添加摄像头: - * 1. 填地址/账号 → 「拉取通道」:**页面直接调本机软件**(localhost:17300/api/hik/channels), + * 1. 填地址/账号 → 「拉取通道」:**页面直接调本机软件**(WebSocket 17301 的 `get_channels`), * 走 8000 私有协议登录设备拿到通道列表; * 2. 勾选通道 → 提交到后端 `/api/web/nvrs/:id/channels` 落库成摄像头。 * @@ -25,7 +25,8 @@ import { updateNvr, } from '@/api/videoApi'; import type { Nvr } from '@/api/video'; -import { LocalServiceError, fetchHikChannels, type HikChannelsPayload } from '@/api/local'; +import type { HikChannelsPayload } from '@/api/local'; +import { localWs, waitForLocalWs, wakeLocalSoftware } from '@/api/localWs'; import { formatTime } from '@/utils/format'; const list = ref([]); @@ -151,6 +152,30 @@ async function openChannels(nvr: Nvr) { } } +/** 拉一次通道并把返回值写进弹窗状态(失败直接抛,由 pull() 统一处理) */ +async function pullOnce() { + if (!channelNvr.value) return; + + const data = await localWs.getChannels({ + host: channelNvr.value.host, + port: channelNvr.value.port || 8000, + user: channelNvr.value.username, + password: channelPassword.value, + }); + + payload.value = data ? { ok: true, data } : null; + + // 默认勾选「已配置、且还没导入过」的通道 + const next = new Set(); + for (const item of data?.channels || []) { + if (item.enabled && !existingChannels.value.has(item.channel)) next.add(item.channel); + } + selected.value = next; +} + +/** 连不上本机软件时,提示里的关键字(WS 报的文案见 api/localWs.ts) */ +const OFFLINE_HINT = /超时|无法连接|未连接|断开/; + async function pull() { if (!channelNvr.value) return; if (!channelPassword.value) { channelError.value = '请填写设备密码'; return; } @@ -158,36 +183,27 @@ async function pull() { pulling.value = true; channelError.value = ''; payload.value = null; + try { - const res = await fetchHikChannels({ - host: channelNvr.value.host, - port: channelNvr.value.port, - user: channelNvr.value.username, - password: channelPassword.value, - }); + try { + await pullOnce(); + } catch (err) { + const message = err instanceof Error ? err.message : '拉取失败'; - if (!res.ok) { - channelError.value = res.message || `拉取失败(错误码 ${res.lastError ?? '未知'})`; - return; - } + // 连不上本机软件 → 唤起它,等起来后再试一次(按钮就在用户手上,可以等) + if (!OFFLINE_HINT.test(message)) throw err; - payload.value = res; - // 默认勾选「已配置、且还没导入过」的通道 - const next = new Set(); - for (const item of res.data?.channels || []) { - if (item.enabled && !existingChannels.value.has(item.channel)) next.add(item.channel); - } - selected.value = next; - } catch (err) { - if (err instanceof LocalServiceError) { - if (err.status === 405) { - channelError.value = '当前本机软件版本过旧(不支持 /api/hik/channels),请升级本机软件后重试。'; - } else { - channelError.value = `本机软件不可用(${err.message})。请确认本机软件已启动。`; + wakeLocalSoftware(); + if (!(await waitForLocalWs(8000))) { + channelError.value = `连接不上本机软件(${message})。请先启动本机软件再重试。`; + return; } - } else { - channelError.value = err instanceof Error ? err.message : '拉取失败'; + + await pullOnce(); } + } catch (err) { + const message = err instanceof Error ? err.message : '拉取失败'; + channelError.value = message; } finally { pulling.value = false; } @@ -223,7 +239,7 @@ async function importSelected() { .map(item => ({ channel: item.channel, type: item.type, - // 优先用设备上的真实通道名(ISAPI 取到),没有就退成「NVR名-通道号」 + // 优先用设备上的真实通道名(如果拿到了),没有就退成「NVR名-通道号」 name: (item.name || '').trim() || `${baseName}-${item.channel}`, ip: item.ip, port: item.port,