Compare commits
10 Commits
53da30f733
...
fe8c0d62a1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe8c0d62a1 | ||
|
|
2042f5207d | ||
|
|
2a81047f81 | ||
|
|
18f258014f | ||
|
|
7a82bf13c7 | ||
|
|
aecb85d55b | ||
|
|
b45c8a29f4 | ||
|
|
434b5d38a8 | ||
|
|
c07d5c640b | ||
|
|
21ffb6a54f |
2
.gitignore
vendored
2
.gitignore
vendored
@ -45,6 +45,8 @@ logs-*/
|
||||
run/
|
||||
tmp/
|
||||
backend/temp/
|
||||
# 仓库根的 temp/:现场排查记录、临时脚本等,整个目录都不跟踪
|
||||
temp/
|
||||
*.log
|
||||
*.pid
|
||||
|
||||
|
||||
@ -73,6 +73,9 @@ dispatchKeyEvent → StringBuilder → commitScan → StationService.pushBarcode
|
||||
- **禁止**在主线程写 socket。所有推送都在 `ScanServer` 的 `station-scan-write` 线程完成。
|
||||
- **禁止去重**:重复条码也必须上报;连续扫描的重复帧由桌面端判断。
|
||||
- 扫码枪没有回车/Tab 后缀时,50ms 无输入自动提交;不要再调大。
|
||||
- **结束键要按设备判定**:有的枪(Newtologic DW-8200)发 `KEYCODE_DPAD_CENTER` 而不是回车;
|
||||
结束键集合包含 DPAD_CENTER,但必须 `event.getDeviceId()` 等于「刚发过条码字符的设备」,
|
||||
否则遥控器 OK 会被误判,枪的 DPAD_CENTER 还会激活焦点按钮(进设置页/清空记录)。
|
||||
- 条码清理用首尾字符扫描,不要用正则。
|
||||
|
||||
## 语音播报
|
||||
|
||||
@ -48,6 +48,11 @@
|
||||
现场据此确认「摄像头认的是不是这张面单」(只显示、只播报,不回推桌面端)。
|
||||
- USB 扫码枪是键盘设备:在 Activity 层统一收键,连续可打印字符攒成一条条码,
|
||||
回车/Tab 立即提交;没有后缀时停手 **50ms** 自动提交。
|
||||
- ⚠️ **结束键不一定是回车**:实测 Newtologic DW-8200(T95MAX / Android 12)发的是
|
||||
`KEYCODE_DPAD_CENTER`(code 23)。所以「结束键」判定要包含 DPAD_CENTER,并且**只认
|
||||
发过条码字符的那台设备**(比较 `event.getDeviceId()`)——否则遥控器的 OK 键会被误当成
|
||||
结束键,而枪的 DPAD_CENTER 又会落到当前焦点按钮上(现场表现:一扫就进「服务设置」,
|
||||
焦点在「清空记录」时还会把记录清掉)。
|
||||
- 底部「服务设置」「清空记录」两个按钮可用遥控器操作。
|
||||
- `FLAG_KEEP_SCREEN_ON` 保证长期不接显示器时 Activity 仍保持前台、服务不被挂起。
|
||||
|
||||
@ -89,6 +94,15 @@
|
||||
在 `station-speech` 独立线程完成,不阻塞扫码上报。
|
||||
- 同一串条码 2.5 秒内不重复播报(连续扫描的重复帧);换了条码立即打断上一句播最新的。
|
||||
**上报不受影响**:重复条码仍然逐条发送。
|
||||
- ⚠️ **个别 Allwinner 机型(实测 T95MAX / Android 12)的输出路由改不了**:它有三种输出
|
||||
`AUDIO_CODEC / AUDIO_SPDIF / AUDIO_HDMI`,只有 CODEC(AV / 3.5mm)那一路接的喇叭有声音,
|
||||
插着 HDMI 开机后会被固件重置成 `AUDIO_HDMI`。该 HAL **只在初始化时**读
|
||||
`vendor.audio.output.active`:运行期 `AudioManager.setParameters`
|
||||
(`raw_data_output` / `mediasw.sft.rawdata` / `audio_output_channel` / `devices_out_active` /
|
||||
`routing`)和 `MediaPlayer/AudioTrack.setPreferredDevice` **全部被忽略**;只有
|
||||
「设属性 + 重启 `vendor.audio-hal`」才切到 `open card=0`,而那需要 root(普通应用没有 su)。
|
||||
这类机器只能现场解决:系统设置里选一次 CODEC(重启会丢)、HDMI 音频分离器、
|
||||
音箱接电视的音频输出,或换机型。
|
||||
- 语音内容:条码末尾 4 个字母/数字(标点跳过)+ 「开始打包」。
|
||||
- 启动时 `BarcodeSpeaker.maximizeVolume` 把媒体音量设为最大(实测 `11 -> 15`)。
|
||||
需要 `MODIFY_AUDIO_SETTINGS` 普通权限。
|
||||
|
||||
@ -73,6 +73,7 @@ public class MainActivity extends AppCompatActivity {
|
||||
private TextView recentView;
|
||||
|
||||
private long lastCommitMs;
|
||||
private int scanInputDeviceId = Integer.MIN_VALUE;
|
||||
private boolean listening;
|
||||
private int tick;
|
||||
|
||||
@ -142,6 +143,7 @@ public class MainActivity extends AppCompatActivity {
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
BarcodeSpeaker.instance().start(this);
|
||||
service.start(this);
|
||||
renderClock();
|
||||
@ -278,9 +280,15 @@ public class MainActivity extends AppCompatActivity {
|
||||
*/
|
||||
@Override
|
||||
public boolean dispatchKeyEvent(KeyEvent event) {
|
||||
if (event.getAction() == KeyEvent.ACTION_DOWN) {
|
||||
int keyCode = event.getKeyCode();
|
||||
int keyCode = event.getKeyCode();
|
||||
if (isScannerEndKey(keyCode) && event.getDeviceId() == scanInputDeviceId) {
|
||||
if (event.getAction() == KeyEvent.ACTION_DOWN && scanBuffer.length() > 0) {
|
||||
commitScan();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (event.getAction() == KeyEvent.ACTION_DOWN) {
|
||||
if (keyCode == KeyEvent.KEYCODE_ENTER
|
||||
|| keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER
|
||||
|| keyCode == KeyEvent.KEYCODE_TAB) {
|
||||
@ -309,13 +317,13 @@ public class MainActivity extends AppCompatActivity {
|
||||
return super.dispatchKeyEvent(event);
|
||||
}
|
||||
|
||||
int unicode = event.getUnicodeChar(event.getMetaState());
|
||||
if (unicode >= 0x20 && unicode != 0x7F
|
||||
&& !event.isCtrlPressed() && !event.isAltPressed() && !event.isMetaPressed()) {
|
||||
char scanCharacter = barcodeCharacter(event);
|
||||
if (scanCharacter != 0) {
|
||||
if (scanBuffer.length() >= MAX_INPUT) {
|
||||
scanBuffer.setLength(0);
|
||||
}
|
||||
scanBuffer.append((char) unicode);
|
||||
scanBuffer.append(scanCharacter);
|
||||
scanInputDeviceId = event.getDeviceId();
|
||||
handler.removeCallbacks(flushTask);
|
||||
handler.postDelayed(flushTask, FLUSH_DELAY_MS);
|
||||
return true;
|
||||
@ -324,6 +332,57 @@ public class MainActivity extends AppCompatActivity {
|
||||
return super.dispatchKeyEvent(event);
|
||||
}
|
||||
|
||||
private static boolean isScanTerminator(int keyCode) {
|
||||
return keyCode == KeyEvent.KEYCODE_ENTER
|
||||
|| keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER
|
||||
|| keyCode == KeyEvent.KEYCODE_TAB;
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫码枪的「结束键」:除了常规回车,还要接受 {@link KeyEvent#KEYCODE_DPAD_CENTER}。
|
||||
*
|
||||
* <p>实测 Newtologic DW-8200(T95MAX,Android 12)发的是 `DPAD_CENTER`(code 23)而不是
|
||||
* 回车,结果它既不被当成结束键(扫码只能等 50ms 超时提交),又会落到当前焦点按钮上
|
||||
* → 「一扫就进服务设置/清空记录」。
|
||||
*
|
||||
* <p>只对**发过条码字符的那台设备**生效(见调用处的 deviceId 比较),遥控器的
|
||||
* 方向键/OK 键照旧正常使用。
|
||||
*/
|
||||
private static boolean isScannerEndKey(int keyCode) {
|
||||
return isScanTerminator(keyCode) || keyCode == KeyEvent.KEYCODE_DPAD_CENTER;
|
||||
}
|
||||
|
||||
private static char barcodeCharacter(KeyEvent event) {
|
||||
if (event.isCtrlPressed() || event.isAltPressed() || event.isMetaPressed()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int unicode = event.getUnicodeChar(event.getMetaState());
|
||||
if (unicode >= 0x20 && unicode != 0x7F) {
|
||||
return (char) unicode;
|
||||
}
|
||||
|
||||
int keyCode = event.getKeyCode();
|
||||
if (keyCode >= KeyEvent.KEYCODE_A && keyCode <= KeyEvent.KEYCODE_Z) {
|
||||
char letter = (char) ('a' + keyCode - KeyEvent.KEYCODE_A);
|
||||
return event.isShiftPressed() || event.isCapsLockOn()
|
||||
? Character.toUpperCase(letter) : letter;
|
||||
}
|
||||
if (keyCode == KeyEvent.KEYCODE_0) {
|
||||
return '0';
|
||||
}
|
||||
if (keyCode >= KeyEvent.KEYCODE_1 && keyCode <= KeyEvent.KEYCODE_9) {
|
||||
return (char) ('1' + keyCode - KeyEvent.KEYCODE_1);
|
||||
}
|
||||
if (keyCode == KeyEvent.KEYCODE_NUMPAD_0) {
|
||||
return '0';
|
||||
}
|
||||
if (keyCode >= KeyEvent.KEYCODE_NUMPAD_1 && keyCode <= KeyEvent.KEYCODE_NUMPAD_9) {
|
||||
return (char) ('1' + keyCode - KeyEvent.KEYCODE_NUMPAD_1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private void commitScan() {
|
||||
handler.removeCallbacks(flushTask);
|
||||
String raw = scanBuffer.toString();
|
||||
|
||||
@ -46,6 +46,7 @@ public class SettingsActivity extends AppCompatActivity {
|
||||
private EditText discoveryPortField;
|
||||
private SwitchCompat serviceSwitch;
|
||||
private SwitchCompat discoverySwitch;
|
||||
private SwitchCompat speakerSwitch;
|
||||
private TextView statusView;
|
||||
private TextView homeStatusView;
|
||||
private Button setHomeButton;
|
||||
@ -61,6 +62,7 @@ public class SettingsActivity extends AppCompatActivity {
|
||||
discoveryPortField = findViewById(R.id.et_discovery_port);
|
||||
serviceSwitch = findViewById(R.id.sw_service_enabled);
|
||||
discoverySwitch = findViewById(R.id.sw_discovery_enabled);
|
||||
speakerSwitch = findViewById(R.id.sw_speaker_output);
|
||||
statusView = findViewById(R.id.tv_settings_status);
|
||||
homeStatusView = findViewById(R.id.tv_home_status);
|
||||
setHomeButton = findViewById(R.id.btn_set_home);
|
||||
@ -71,6 +73,7 @@ public class SettingsActivity extends AppCompatActivity {
|
||||
discoveryPortField.setText(String.valueOf(StationSettings.discoveryPort(this)));
|
||||
serviceSwitch.setChecked(StationSettings.serviceEnabled(this));
|
||||
discoverySwitch.setChecked(StationSettings.discoveryEnabled(this));
|
||||
speakerSwitch.setChecked(StationSettings.speakerOutput(this));
|
||||
|
||||
Button save = findViewById(R.id.btn_save);
|
||||
save.setOnClickListener(new View.OnClickListener() {
|
||||
@ -330,7 +333,7 @@ public class SettingsActivity extends AppCompatActivity {
|
||||
}
|
||||
|
||||
StationSettings.save(this, name, servicePort, discoveryPort,
|
||||
serviceSwitch.isChecked(), discoverySwitch.isChecked());
|
||||
serviceSwitch.isChecked(), discoverySwitch.isChecked(), speakerSwitch.isChecked());
|
||||
StationService.instance().restart();
|
||||
renderStatus();
|
||||
|
||||
|
||||
@ -19,6 +19,7 @@ public final class StationSettings {
|
||||
private static final String KEY_DISCOVERY_PORT = "discovery_port";
|
||||
private static final String KEY_SERVICE_ENABLED = "service_enabled";
|
||||
private static final String KEY_DISCOVERY_ENABLED = "discovery_enabled";
|
||||
private static final String KEY_SPEAKER_OUTPUT = "speaker_output";
|
||||
|
||||
/** 与桌面端 {@code ScanProtocol.TcpPort} 保持一致 */
|
||||
public static final int DEFAULT_SERVICE_PORT = 8087;
|
||||
@ -82,14 +83,26 @@ public final class StationSettings {
|
||||
return prefs(context).getBoolean(KEY_DISCOVERY_ENABLED, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 播报是否强制走**本机扬声器**(模拟输出 / AV / 3.5mm)。
|
||||
*
|
||||
* <p>**默认关闭**,保持系统默认路由:多数机型(如 rk3288)本机扬声器就是默认输出,
|
||||
* 强制指定反而可能把本该走 HDMI 的声音压回小喇叭。只有在"接电视/显示器时声音被
|
||||
* HDMI 抢走、现场用 AV 音箱"的机型上才需要打开。
|
||||
*/
|
||||
public static boolean speakerOutput(Context context) {
|
||||
return prefs(context).getBoolean(KEY_SPEAKER_OUTPUT, false);
|
||||
}
|
||||
|
||||
public static void save(Context context, String name, int servicePort, int discoveryPort,
|
||||
boolean serviceEnabled, boolean discoveryEnabled) {
|
||||
boolean serviceEnabled, boolean discoveryEnabled, boolean speakerOutput) {
|
||||
prefs(context).edit()
|
||||
.putString(KEY_DEVICE_NAME, name == null ? "" : name.trim())
|
||||
.putInt(KEY_SERVICE_PORT, servicePort)
|
||||
.putInt(KEY_DISCOVERY_PORT, discoveryPort)
|
||||
.putBoolean(KEY_SERVICE_ENABLED, serviceEnabled)
|
||||
.putBoolean(KEY_DISCOVERY_ENABLED, discoveryEnabled)
|
||||
.putBoolean(KEY_SPEAKER_OUTPUT, speakerOutput)
|
||||
.commit();
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,13 +2,16 @@ package com.gztbyc.scancenter.core.speech;
|
||||
|
||||
import android.content.Context;
|
||||
import android.media.AudioAttributes;
|
||||
import android.media.AudioDeviceInfo;
|
||||
import android.media.AudioManager;
|
||||
import android.media.MediaPlayer;
|
||||
import android.os.Build;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
|
||||
import com.gztbyc.scancenter.R;
|
||||
import com.gztbyc.scancenter.core.StationSettings;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
@ -335,6 +338,8 @@ public final class BarcodeSpeaker {
|
||||
.build());
|
||||
created.setDataSource(file.getAbsolutePath());
|
||||
created.prepare();
|
||||
// 必须在 prepare() 之后:这时 MediaPlayer 才建好 AudioTrack,指定输出设备才会生效
|
||||
routeToBuiltInSpeaker(created);
|
||||
// 明确拉满音量:有些 ROM 会在新音频流起播时做淡入/被别的流压一点音量,
|
||||
// 显式设置后至少不会被我们自己的上一个播放残留影响
|
||||
created.setVolume(1f, 1f);
|
||||
@ -404,6 +409,42 @@ public final class BarcodeSpeaker {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把播报**显式**送到本机扬声器(模拟输出 / AV / 3.5mm)。
|
||||
*
|
||||
* <p>实测 T95MAX(Android 12):只要插着 HDMI,HAL 就把媒体声音整体送给 HDMI
|
||||
* (`vendor.audio.output.active=AUDIO_HDMI`),现场接在 AV 口的音箱完全没声音,
|
||||
* 而 App 侧日志显示「已播报、未静音」。指定输出设备后声音回到模拟输出。
|
||||
*
|
||||
* <p>开关在「服务设置 → 播报走本机扬声器」;关掉就恢复系统默认路由(HDMI 优先)。
|
||||
*/
|
||||
private void routeToBuiltInSpeaker(MediaPlayer target) {
|
||||
Context ctx = context;
|
||||
if (ctx == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
|
||||
return;
|
||||
}
|
||||
if (!StationSettings.speakerOutput(ctx)) {
|
||||
return;
|
||||
}
|
||||
|
||||
AudioManager audio = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
|
||||
if (audio == null) {
|
||||
return;
|
||||
}
|
||||
for (AudioDeviceInfo device : audio.getDevices(AudioManager.GET_DEVICES_OUTPUTS)) {
|
||||
if (device.getType() == AudioDeviceInfo.TYPE_BUILTIN_SPEAKER) {
|
||||
if (target.setPreferredDevice(device)) {
|
||||
i("播报输出设备", "扬声器", device.getProductName());
|
||||
}
|
||||
else {
|
||||
w("指定扬声器输出失败,走系统默认路由");
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
w("找不到内建扬声器输出,走系统默认路由");
|
||||
}
|
||||
|
||||
private void releaseIfCurrent(int expectedGeneration) {
|
||||
MediaPlayer target;
|
||||
File file;
|
||||
|
||||
@ -142,6 +142,15 @@
|
||||
android:textColor="@color/text_primary"
|
||||
android:textSize="16sp" />
|
||||
|
||||
<androidx.appcompat.widget.SwitchCompat
|
||||
android:id="@+id/sw_speaker_output"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/settings_speaker_output"
|
||||
android:textColor="@color/text_primary"
|
||||
android:textSize="16sp" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
|
||||
@ -47,6 +47,7 @@
|
||||
<string name="settings_discovery_port_label">设备发现端口(UDP)</string>
|
||||
<string name="settings_service_enabled">启用扫码服务</string>
|
||||
<string name="settings_discovery_enabled">允许被桌面端发现</string>
|
||||
<string name="settings_speaker_output">播报走本机扬声器(AV / 3.5mm)</string>
|
||||
<string name="settings_note">桌面端会在局域网内自动发现本机,并连接上面的扫码服务端口读取 USB 扫码枪结果。\n默认:TCP 8087 / UDP 48899。修改后请与桌面端约定保持一致。</string>
|
||||
<string name="settings_section_status">当前状态</string>
|
||||
<string name="settings_section_home">开机 / 桌面</string>
|
||||
|
||||
@ -7,7 +7,7 @@ packService/
|
||||
├── backend/ # Egg.js 3(纯 API;MySQL + Redis)
|
||||
├── frontend/ # Vite + Vue3 + TypeScript(用户端 SPA)
|
||||
├── extension/ # Chrome MV3 扩展:注入第三方 WMS 页面,把运单号加工成溯源入口
|
||||
├── desktop/ # WPF 本机软件:HTTP 17300(查询/唤起/下载)+ WS 17301(拉通道/预览/云台)+ yuncang:// 启动协议
|
||||
├── desktop/ # WPF 本机软件:HTTP 16000(查询/唤起/下载)+ WS 16001(拉通道/预览/云台)+ yuncang:// 启动协议
|
||||
└── AndroidStation/ # Android 设备端:UDP 48899 被桌面端发现 + TCP 8087 推送 USB 扫码结果
|
||||
```
|
||||
|
||||
@ -18,7 +18,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**(HTTP)/ **17301**(WebSocket) | `cd desktop && dotnet run`(详见 [`desktop/README.md`](desktop/README.md)) |
|
||||
| 本机软件(WPF,只监听 loopback) | **16000**(HTTP)/ **16001**(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` → 端口被占用时**直接报错**,不会偷偷换端口(否则代理会对不上)。
|
||||
|
||||
@ -640,6 +640,14 @@ node scripts/backfill-snapshot.js --dry-run
|
||||
> 本表**不用软删除**(paranoid 关闭):软删除会让记录占用唯一键,导致同一条扫码数据再也无法入库;
|
||||
> 需要清理请按时间物理删除:`DELETE FROM scan_records WHERE scan_time < ?`。
|
||||
|
||||
索引(和 `/api/web/records` 列表页强相关,2026-11-16 补的):
|
||||
|
||||
- `(subject_id, barcode)`:按运单号精确定位(回放查询用);
|
||||
- `(subject_id, scanner_id, scan_time)`:列表页 `findAndCountAll` 那条 **`count(*)` 的覆盖索引**。
|
||||
少了它 MySQL 只能走 `(subject_id, barcode)` 再逐行回表判断 `scanner_id`——线上 16.5 万条时
|
||||
`Rows_examined` ≈ 33 万,冷缓存 9.9 s / 热缓存 0.45 s;补完是纯索引扫描,0.09 s(迁移 `20261116200000`);
|
||||
- `(scanner_id, channel_id, scan_time)`:散单要取同通道「上一条 / 下一条」的扫码时间。
|
||||
|
||||
## 页面(在前端项目里)
|
||||
|
||||
⚠️ **后端不再渲染页面**:`app/view/`、nunjucks、session、CSRF 都已移除,`app/controller/page/` 也删掉了。
|
||||
|
||||
@ -133,11 +133,21 @@ Write-Host "JAVA_HOME=$javaHome"
|
||||
# ---------------- 4. 构建 APK ----------------
|
||||
Push-Location $projectDir
|
||||
try {
|
||||
# 2>&1 | Write-Host:gradle 会把 javac 的提示写到 stderr(例如「使用了已过时的 API」),
|
||||
# 直接调用时 PowerShell 会把它当错误记录,配合 $ErrorActionPreference='Stop' 会误判构建失败。
|
||||
& $gradlew --no-daemon assembleRelease "-PversionName=$Version" "-PversionCode=$VersionCode" 2>&1 |
|
||||
ForEach-Object { Write-Host $_ }
|
||||
if ($LASTEXITCODE -ne 0) { throw "gradlew assembleRelease 失败($LASTEXITCODE)" }
|
||||
# gradle 会把 javac 的提示写到 stderr(例如「使用了已过时的 API」)。在
|
||||
# $ErrorActionPreference='Stop' 下,这些 stderr 行会被当成**终止错误**,
|
||||
# 即使构建成功也会中断脚本(实测 release 构建必失败)。所以这里临时放宽,
|
||||
# 只以 $LASTEXITCODE 判定成败。
|
||||
$previousEap = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
& $gradlew --no-daemon assembleRelease "-PversionName=$Version" "-PversionCode=$VersionCode" 2>&1 |
|
||||
ForEach-Object { Write-Host $_ }
|
||||
$exitCode = $LASTEXITCODE
|
||||
}
|
||||
finally {
|
||||
$ErrorActionPreference = $previousEap
|
||||
}
|
||||
if ($exitCode -ne 0) { throw "gradlew assembleRelease 失败($exitCode)" }
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
|
||||
@ -12,7 +12,7 @@ function toId(value) {
|
||||
* web 用户端:**我的 NVR**(`/api/web/nvrs`)
|
||||
*
|
||||
* 拉取通道是由**前端**发起的两步:
|
||||
* 1. 页面直接调本机软件 `POST http://localhost:17300/api/hik/channels`(带 host/port/user/password)
|
||||
* 1. 页面直接调本机软件 `POST http://localhost:16000/api/hik/channels`(带 host/port/user/password)
|
||||
* 2. 用户勾选通道后,把结果 POST 到 `/api/web/nvrs/:id/channels` 落库
|
||||
* 后端服务器**不接触设备**(设备在用户内网)。
|
||||
*/
|
||||
|
||||
@ -174,7 +174,7 @@ module.exports = (app) => {
|
||||
router.get('/api/web/nvrs/:id/credential', apiAuth, subjectAuth, controller.web.nvr.credential);
|
||||
|
||||
// ---------- 视频接入:NVR / 摄像头 / 工作台(只碰本主体的数据;仅主体管理员)----------
|
||||
// 拉取通道 = 前端调本机软件(localhost:17300/api/hik/channels)→ 勾选 → POST /nvrs/:id/channels 落库
|
||||
// 拉取通道 = 前端调本机软件(localhost:16000/api/hik/channels)→ 勾选 → POST /nvrs/:id/channels 落库
|
||||
router.get('/api/web/nvrs', apiAuth, subjectAuth, subjectAdmin, controller.web.nvr.index);
|
||||
router.post('/api/web/nvrs', apiAuth, subjectAuth, subjectAdmin, controller.web.nvr.create);
|
||||
router.get('/api/web/nvrs/:id', apiAuth, subjectAuth, subjectAdmin, controller.web.nvr.show);
|
||||
|
||||
@ -306,9 +306,6 @@ ${this.styles()}
|
||||
${this.renderBody(active, current)}
|
||||
</main>
|
||||
</div>
|
||||
<footer class="footer">
|
||||
<span>${SITE_NAME} · 文档由「平台管理 → 文档管理」维护</span>
|
||||
</footer>
|
||||
${this.tocScript()}
|
||||
</body>
|
||||
</html>
|
||||
@ -455,9 +452,7 @@ a:hover { text-decoration: underline; }
|
||||
grid-template-columns: 248px minmax(0, 1fr);
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
flex: 1 1 auto;
|
||||
max-width: 1440px;
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
@ -581,15 +576,6 @@ a:hover { text-decoration: underline; }
|
||||
.empty h1 { font-size: 26px; }
|
||||
.empty p { color: var(--text-muted); }
|
||||
|
||||
.footer {
|
||||
flex: 0 0 auto;
|
||||
border-top: 1px solid var(--border);
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
font-size: 12.5px;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.layout {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
|
||||
@ -136,10 +136,10 @@ class NvrService extends Service {
|
||||
/**
|
||||
* 新增 NVR
|
||||
*
|
||||
* 同一 `host + port + username` 全局唯一(唯一索引):重复添加时
|
||||
* - 已被其他主体占用 → 409
|
||||
* - 自己之前删过 → 复活并更新
|
||||
* - 当前主体已存在 → 更新(覆盖密码等信息)
|
||||
* 唯一范围是**主体内**的 `host + port + username`(唯一索引 `uk_subject_host_port_username`):
|
||||
* - 当前主体已存在(含自己之前删过的)→ 复活并更新(覆盖密码等信息)
|
||||
* - **其他主体加过同样的地址不算冲突** —— 不同仓库的内网地址经常一模一样,
|
||||
* 以前用全局唯一会让第二个仓库永远加不进来
|
||||
*
|
||||
* @param {object} params { subjectId 当前主体, userId 创建人, name, host, port, username, password, serialNumber?, deviceModel?, remark? }
|
||||
*/
|
||||
@ -152,17 +152,20 @@ class NvrService extends Service {
|
||||
const finalUser = String(username || '').trim() || 'admin';
|
||||
if (!password) this.ctx.throw(422, 'password 不能为空');
|
||||
|
||||
// 只在本主体内找:别的仓库用同一个内网地址不算重复
|
||||
// 带已删除的一起查:软删的行仍占着唯一键
|
||||
const existing = await this.Nvr.findOne({
|
||||
where: { host: finalHost, port: finalPort, username: finalUser },
|
||||
where: {
|
||||
subjectId: Number(subjectId),
|
||||
host: finalHost,
|
||||
port: finalPort,
|
||||
username: finalUser,
|
||||
},
|
||||
attributes: { include: [ 'passwordEnc' ] },
|
||||
paranoid: false,
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
if (existing.subjectId && Number(existing.subjectId) !== Number(subjectId)) {
|
||||
this.ctx.throw(409, `NVR ${finalHost}:${finalPort} 已被其他主体添加`);
|
||||
}
|
||||
if (existing.deletedAt) await existing.restore();
|
||||
|
||||
await existing.update({
|
||||
@ -179,19 +182,28 @@ class NvrService extends Service {
|
||||
return this.findOwned(existing.id, subjectId);
|
||||
}
|
||||
|
||||
const created = await this.Nvr.create({
|
||||
subjectId: Number(subjectId),
|
||||
userId: Number(userId),
|
||||
name: String(name || '').trim(),
|
||||
host: finalHost,
|
||||
port: finalPort,
|
||||
username: finalUser,
|
||||
passwordEnc: this.encrypt(password),
|
||||
serialNumber: serialNumber || null,
|
||||
deviceModel: deviceModel || null,
|
||||
remark: remark || null,
|
||||
status: 1,
|
||||
});
|
||||
let created;
|
||||
try {
|
||||
created = await this.Nvr.create({
|
||||
subjectId: Number(subjectId),
|
||||
userId: Number(userId),
|
||||
name: String(name || '').trim(),
|
||||
host: finalHost,
|
||||
port: finalPort,
|
||||
username: finalUser,
|
||||
passwordEnc: this.encrypt(password),
|
||||
serialNumber: serialNumber || null,
|
||||
deviceModel: deviceModel || null,
|
||||
remark: remark || null,
|
||||
status: 1,
|
||||
});
|
||||
} catch (err) {
|
||||
// 并发下两个请求同时通过了上面的查重;唯一键现在只约束本主体
|
||||
if (err && err.name === 'SequelizeUniqueConstraintError') {
|
||||
this.ctx.throw(409, `本主体已添加过 NVR ${finalHost}:${finalPort}`);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
this.ctx.logger.info('[nvr] 主体 %s 新增 NVR %s(%s:%s)', subjectId, created.name, finalHost, finalPort);
|
||||
return this.findOwned(created.id, subjectId);
|
||||
@ -222,7 +234,7 @@ class NvrService extends Service {
|
||||
await nvr.update(fields);
|
||||
} catch (err) {
|
||||
if (err && err.name === 'SequelizeUniqueConstraintError') {
|
||||
this.ctx.throw(409, '该地址 + 账号的 NVR 已存在');
|
||||
this.ctx.throw(409, '本主体已添加过该地址 + 账号的 NVR');
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
@ -61,5 +61,6 @@ npm run db:migration:generate -- create_xxx_tables # 生成迁移骨架
|
||||
| `20261029120000-create-admin-members` | 新表 `admin_members`(平台管理员:`user_id` 唯一、`name`、`role`、`status`、`remark`)+ 把内置管理员(`username='admin'`,没有就 `id=1`)先入表 |
|
||||
| `20261107120000-create-doc-tables` | 新表 `doc_categories` / `doc_sections` / `doc_articles`(文档站三级结构)+ 一页「欢迎使用」示例(⚠️ 表结构已被 `20261109230000` 收紧成两级) |
|
||||
| `20261109230000-doc-two-level-structure` | 文档站改成**两级**:`doc_categories` 改名 `doc_sections`(即「栏目」,保留 `code` / 名称 / 说明 / 排序 / 显隐),删掉原二级栏目表,`doc_articles.section_id` 改指栏目并删 `category_id` |
|
||||
| `20261116010000-scope-nvr-unique-to-subject` | NVR 唯一键从全局 `(host, port, username)` 改成 `(subject_id, host, port, username)`:不同仓库的内网地址经常相同,之前会导致「已被其他主体添加」 |
|
||||
> 历史遗留的 `sql/schema.sql` + `sql/migrations/*.sql`(用 `npm run db:init` 执行)是接入 sequelize-cli 之前的做法,
|
||||
> 只用于初始化老表;**新变更一律写 `database/migrations/*.js`**。
|
||||
|
||||
@ -0,0 +1,49 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* NVR 唯一键从「全局」改成「按主体」
|
||||
*
|
||||
* 之前是 `(host, port, username)` 全局唯一 —— 结果是**别的仓库**加过同一个内网地址
|
||||
* (192.168.8.242:8000 这种各仓库都一样的默认地址)后,本主体就再也加不进去,
|
||||
* 报「已被其他主体添加」。不同主体本来就是不同的仓库,地址撞车是正常现象。
|
||||
*
|
||||
* 改成 `(subject_id, host, port, username)`:同一主体内仍然不允许重复添加同一台 NVR,
|
||||
* 不同主体之间互不影响。
|
||||
*/
|
||||
|
||||
const INDEX_NAME = 'uk_host_port_username';
|
||||
const SCOPED_INDEX_NAME = 'uk_subject_host_port_username';
|
||||
|
||||
/** 判断索引是否存在(重跑/已经手工改过的库不报错) */
|
||||
async function hasIndex(queryInterface, table, name) {
|
||||
const indexes = await queryInterface.showIndex(table);
|
||||
return indexes.some(item => item.name === name);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
if (await hasIndex(queryInterface, 'nvrs', INDEX_NAME)) {
|
||||
await queryInterface.removeIndex('nvrs', INDEX_NAME);
|
||||
}
|
||||
|
||||
if (!(await hasIndex(queryInterface, 'nvrs', SCOPED_INDEX_NAME))) {
|
||||
await queryInterface.addIndex('nvrs', [ 'subject_id', 'host', 'port', 'username' ], {
|
||||
name: SCOPED_INDEX_NAME,
|
||||
unique: true,
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
if (await hasIndex(queryInterface, 'nvrs', SCOPED_INDEX_NAME)) {
|
||||
await queryInterface.removeIndex('nvrs', SCOPED_INDEX_NAME);
|
||||
}
|
||||
|
||||
if (!(await hasIndex(queryInterface, 'nvrs', INDEX_NAME))) {
|
||||
await queryInterface.addIndex('nvrs', [ 'host', 'port', 'username' ], {
|
||||
name: INDEX_NAME,
|
||||
unique: true,
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 扫码记录列表(`/api/web/records`):补一个能被「覆盖」的索引
|
||||
*
|
||||
* 该接口是 `findAndCountAll`,一次请求会跑两条 SQL:
|
||||
* 1. 列表:`WHERE subject_id = ? AND scanner_id IN (...) ORDER BY scan_time DESC, id DESC LIMIT 20`
|
||||
* 2. 总数:`WHERE` 同上,但**没有 LIMIT**(`count(id)` 要数完整个集合)
|
||||
*
|
||||
* 2026-11-16 线上实测(主体 1,约 16.5 万条):
|
||||
* - 列表:走 `idx_scan_time` 反向扫 + 过滤,约 28 ms,本来不慢;
|
||||
* - 总数:走 `idx_scan_subject_barcode`(`subject_id, barcode`)——索引里没有 `scanner_id`,
|
||||
* 只能**逐行回表**判断,`Rows_examined` ≈ 33 万;冷缓存 9.9 s、热缓存 0.45 s。
|
||||
* 「第一次打开扫码记录很慢」就是它。
|
||||
*
|
||||
* 加 `(subject_id, scanner_id, scan_time)` 后,总数变成纯索引扫描(不回表),
|
||||
* 顺带让「按设备过滤 + 按时间倒序」的列表也能直接吃索引顺序。
|
||||
*
|
||||
* 注意:`sql/schema.sql` 基线已同步这个索引,空库执行时幂等。
|
||||
*/
|
||||
|
||||
const INDEX_NAME = 'idx_scan_subject_scanner_time';
|
||||
|
||||
/** 判断索引是否存在(重跑/已经手工加过的库不报错) */
|
||||
async function hasIndex(queryInterface, table, name) {
|
||||
try {
|
||||
const indexes = await queryInterface.showIndex(table);
|
||||
return indexes.some(item => item.name === name);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
if (await hasIndex(queryInterface, 'scan_records', INDEX_NAME)) return;
|
||||
await queryInterface.addIndex('scan_records', [ 'subject_id', 'scanner_id', 'scan_time' ], {
|
||||
name: INDEX_NAME,
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
if (!(await hasIndex(queryInterface, 'scan_records', INDEX_NAME))) return;
|
||||
await queryInterface.removeIndex('scan_records', INDEX_NAME);
|
||||
},
|
||||
};
|
||||
@ -153,7 +153,9 @@ CREATE TABLE IF NOT EXISTS `scan_records` (
|
||||
KEY `idx_barcode` (`barcode`),
|
||||
KEY `idx_channel_scan_time` (`channel_id`, `scan_time`),
|
||||
KEY `idx_scan_subject_barcode` (`subject_id`, `barcode`),
|
||||
KEY `idx_scan_channel_seq` (`scanner_id`, `channel_id`, `scan_time`)
|
||||
KEY `idx_scan_channel_seq` (`scanner_id`, `channel_id`, `scan_time`),
|
||||
-- ↓ 2026-11-16 新增(迁移 20261116200000):列表页 count(*) 走覆盖索引,不再逐行回表
|
||||
KEY `idx_scan_subject_scanner_time` (`subject_id`, `scanner_id`, `scan_time`)
|
||||
) ENGINE = InnoDB
|
||||
DEFAULT CHARSET = utf8mb4
|
||||
COMMENT = '扫码记录表(同 中控+通道+条码+扫描时间 去重;带当时的工作台快照)';
|
||||
|
||||
87
backend/test/app/service/nvr-subject-scope.test.js
Normal file
87
backend/test/app/service/nvr-subject-scope.test.js
Normal file
@ -0,0 +1,87 @@
|
||||
'use strict';
|
||||
|
||||
const { app, assert } = require('egg-mock/bootstrap');
|
||||
|
||||
/**
|
||||
* NVR 唯一性只约束「本主体」
|
||||
*
|
||||
* 现场问题:A 仓库添加过 `192.168.8.242:8000`,B 仓库再加同一个内网地址时被拒绝
|
||||
* (`NVR 192.168.8.242:8000 已被其他主体添加`)。内网地址在不同仓库之间撞车是正常的,
|
||||
* 唯一键必须是 `(subject_id, host, port, username)`,查重也只能查本主体。
|
||||
*/
|
||||
describe('test/app/service/nvr-subject-scope.test.js', () => {
|
||||
const SUBJECT_A = 11;
|
||||
const SUBJECT_B = 22;
|
||||
const ADDRESS = { host: '192.168.8.242', port: 8000, username: 'admin' };
|
||||
|
||||
function instance(data) {
|
||||
const row = { ...data };
|
||||
row.toJSON = () => ({ ...row });
|
||||
row.update = async patch => Object.assign(row, patch);
|
||||
row.restore = async () => { row.deletedAt = null; };
|
||||
return row;
|
||||
}
|
||||
|
||||
/** 极简 NVR 表:findOne 按 where 里的 subject_id + host/port/username 过滤,模拟真实唯一键的范围 */
|
||||
function fakeNvrModel(rows) {
|
||||
const calls = [];
|
||||
return {
|
||||
calls,
|
||||
async findOne({ where }) {
|
||||
calls.push(where);
|
||||
return rows.find(row => Number(row.subjectId) === Number(where.subjectId)
|
||||
&& row.host === where.host
|
||||
&& Number(row.port) === Number(where.port)
|
||||
&& row.username === where.username) || null;
|
||||
},
|
||||
async findByPk(id) {
|
||||
return rows.find(row => String(row.id) === String(id)) || null;
|
||||
},
|
||||
async create(values) {
|
||||
const row = instance({ id: rows.length + 101, deletedAt: null, ...values });
|
||||
rows.push(row);
|
||||
return row;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function serviceWith(rows) {
|
||||
const service = app.createAnonymousContext().service.nvr;
|
||||
Object.defineProperty(service, 'Nvr', { value: fakeNvrModel(rows), configurable: true });
|
||||
return service;
|
||||
}
|
||||
|
||||
it('别的仓库已经用同一个内网地址,本仓库仍然能添加', async () => {
|
||||
const rows = [ instance({ id: 7, subjectId: SUBJECT_A, deletedAt: null, name: 'A仓录像机', ...ADDRESS }) ];
|
||||
const service = serviceWith(rows);
|
||||
|
||||
const created = await service.create({ subjectId: SUBJECT_B, userId: 9, password: 'p@ss', ...ADDRESS });
|
||||
|
||||
assert(created.subjectId === SUBJECT_B, JSON.stringify(created));
|
||||
assert(rows.length === 2, '不同主体各存一条,不能被判成冲突');
|
||||
assert(rows[1].host === ADDRESS.host);
|
||||
});
|
||||
|
||||
it('查重只看本主体:where 里必须带 subjectId', async () => {
|
||||
const rows = [];
|
||||
const service = serviceWith(rows);
|
||||
|
||||
await service.create({ subjectId: SUBJECT_B, userId: 9, password: 'p@ss', ...ADDRESS });
|
||||
|
||||
const where = service.Nvr.calls[0];
|
||||
assert(Number(where.subjectId) === SUBJECT_B, `查重条件必须限定主体:${JSON.stringify(where)}`);
|
||||
});
|
||||
|
||||
it('同一个主体重复添加同一台 NVR:更新原记录(含之前软删的)', async () => {
|
||||
const rows = [ instance({ id: 8, subjectId: SUBJECT_B, deletedAt: new Date(), name: '旧名字', ...ADDRESS }) ];
|
||||
const service = serviceWith(rows);
|
||||
|
||||
const updated = await service.create({
|
||||
subjectId: SUBJECT_B, userId: 9, name: '新名字', password: 'p@ss', ...ADDRESS,
|
||||
});
|
||||
|
||||
assert(rows.length === 1, '同一主体内不应新增第二条');
|
||||
assert(rows[0].deletedAt === null, '软删的记录要复活');
|
||||
assert(updated.name === '新名字', JSON.stringify(updated));
|
||||
});
|
||||
});
|
||||
@ -16,7 +16,7 @@ namespace YuncangTrace.LocalService;
|
||||
/// 应用入口,负责五件事:
|
||||
///
|
||||
/// 1. **防多开**:全局互斥体;第二个实例把参数(可能是 `yuncang://open?code=xxx`)送给第一个实例后自己退出;
|
||||
/// 2. **本机 HTTP 服务**(127.0.0.1:17300):登录前就起来,关窗口也不停(托盘里继续跑);
|
||||
/// 2. **本机 HTTP 服务**(127.0.0.1:16000):登录前就起来,关窗口也不停(托盘里继续跑);
|
||||
/// 3. **托盘图标**:关窗口 = 缩到托盘;只有从托盘菜单「退出」才真正退出;
|
||||
/// 4. **登录**:有本地令牌先验证(`/api/web/me`),失效就弹登录窗;登录成功再开主窗口。
|
||||
/// </summary>
|
||||
@ -127,7 +127,7 @@ public partial class App : Application
|
||||
_server.ServerBaseUrlProvider = () => _settings.ServerBaseUrl;
|
||||
_server.LoginRequested += OnLoginRequested;
|
||||
|
||||
// 实时预览的 WebSocket 通道(17301):网页预览/满帧率窗口**只走 WS**,HTTP 17300 不再提供预览接口。
|
||||
// 实时预览的 WebSocket 通道(16001):网页预览/满帧率窗口**只走 WS**,HTTP 16000 不再提供预览接口。
|
||||
// 会话池(HikPreviewService)与原生窗口共用同一个 HikStreamService,避免两套码流服务。
|
||||
_stream = new HikStreamService(_hik);
|
||||
_preview = new HikPreviewService(_hik, _stream, new HikFfmpegService());
|
||||
@ -518,7 +518,7 @@ public partial class App : Application
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 托盘菜单「重启软件」:先让本进程退出(释放单实例互斥体与 17300 端口),2 秒后再拉起自己。
|
||||
/// 托盘菜单「重启软件」:先让本进程退出(释放单实例互斥体与 16000 端口),2 秒后再拉起自己。
|
||||
/// 直接用 Process.Start 会撞上单实例检测(新进程把参数转发给正在退出的旧进程后就没了)。
|
||||
/// 用 explorer 拉起:即使当前是管理员进程,新实例也会是**普通权限**(否则协议唤起会失效)。
|
||||
/// </summary>
|
||||
|
||||
@ -4,14 +4,14 @@ Windows 桌面端,用**前端 `/local` 公共页**和 **Chrome 插件**做对
|
||||
|
||||
- **登录页**:账号密码登录后端(`POST /api/web/auth/login`)拿 user JWT,令牌存本机;
|
||||
下次启动先用 `/api/web/me` 验证,还有效就直接进主界面;
|
||||
- 在 `127.0.0.1:17300` 起一个本机 HTTP 服务,浏览器里的页面直接查询本机数据;
|
||||
- 在 `127.0.0.1:16000` 起一个本机 HTTP 服务,浏览器里的页面直接查询本机数据;
|
||||
- 注册 `yuncang://` 启动协议,网页可以「叫醒」本软件(前提是已安装);
|
||||
- **托盘图标**:关窗口只是缩到托盘(本机服务不能因关窗断掉),双击托盘恢复窗口,
|
||||
右键菜单有「打开主界面 / 重启软件 / 退出」;
|
||||
- **界面不展示服务地址**:登录页和主界面都不显示后端地址 / 本机端口,它们属于内部实现细节;
|
||||
后端地址由构建注入(`package.config.json` 的 `serverBaseUrl`),需要临时指向别处时用启动参数
|
||||
`--server=http://x.x.x.x:7300`(只对本次运行生效,不写进界面)。
|
||||
- **防多开**:全局互斥体 + 命名管道 —— 第二个实例不会抢 17300 端口,而是把
|
||||
- **防多开**:全局互斥体 + 命名管道 —— 第二个实例不会抢 16000 端口,而是把
|
||||
`yuncang://open?code=xxx` 转给已运行的实例(在托盘里也会被叫出来并直接查询),然后自己退出。
|
||||
|
||||
```
|
||||
@ -23,9 +23,9 @@ desktop/
|
||||
├── LoginWindow.xaml / .xaml.cs # 账号 / 密码 / 记住账号 / 自动恢复登录(不展示服务地址)
|
||||
├── MainWindow.xaml / .xaml.cs # 服务状态、测试查询、菜单、退出登录
|
||||
└── Services/
|
||||
├── LocalHttpServer.cs # 本机 HTTP(17300):查询 / 唤起登录 / 下载录像
|
||||
├── LocalHttpServer.cs # 本机 HTTP(16000):查询 / 唤起登录 / 下载录像
|
||||
├── LoopbackHttpServer.cs # 回环 HTTP/1.1 服务端(TcpListener 自实现,不依赖 HTTP.sys)
|
||||
├── LocalWsServer.cs # WebSocket(17301):拉通道 / 预览推帧 / 云台 / 满帧率窗口
|
||||
├── LocalWsServer.cs # WebSocket(16001):拉通道 / 预览推帧 / 云台 / 满帧率窗口
|
||||
├── OrderQueryService.cs # ★ 按运单号查数据(接真实数据源的地方)
|
||||
├── ApiClient.cs # 登录 / 校验令牌(用到的全部后端接口)
|
||||
├── SessionStore.cs # 登录态(%LOCALAPPDATA%\YuncangTrace\session.json)
|
||||
@ -41,13 +41,13 @@ desktop/
|
||||
|
||||
| 场景 | 行为 |
|
||||
| --- | --- |
|
||||
| 首次启动 | 先起本机服务(17300 HTTP + 17301 WS)与托盘,再弹登录页 → 登录成功才出主窗口 |
|
||||
| 首次启动 | 先起本机服务(16000 HTTP + 16001 WS)与托盘,再弹登录页 → 登录成功才出主窗口 |
|
||||
| 启动时检查更新 | 进登录页的同时就开始查 `GET /download/version.json`(老版本用户卡在登录页也能收到提示)。**查到的版本不会塞进登录窗的模态循环**:登录窗还开着就先记下,等主窗口显示完再弹(`_pendingUpdate`)。以前直接盖在登录页上,会撞上「登录窗要关闭、但它挂着模态子窗」→ 父子窗一起被隐藏、两个模态循环互等,**主界面永远出不来**(日志停在 `已恢复登录` 之后,进程还在但没有任何窗口) |
|
||||
| 已有令牌 | 登录窗一闪而过:`/api/web/me` 通过就直接进主窗口;失效则清掉令牌留在登录页 |
|
||||
| 关窗口(X) | 隐藏到托盘,本机服务继续跑(第一次会冒一个气泡提示) |
|
||||
| 再次双击 exe / 点网页「启动本机软件」 | 不会开第二个:把 `yuncang://open?code=…` 通过命名管道转给已运行实例;**没带参数(双击快捷方式)也会转发一条 `--show`**,让已运行实例把主界面叫到前面 —— 以前这种情况什么都不发、第二个实例直接退出,表现就是「点图标没反应」 |
|
||||
| 托盘双击 / 右键「打开主界面」 | 恢复窗口 |
|
||||
| 托盘右键「重启软件」 | 等 2 秒后拉起新进程(先退出才能释放单实例互斥体与 17300) |
|
||||
| 托盘右键「重启软件」 | 等 2 秒后拉起新进程(先退出才能释放单实例互斥体与 16000) |
|
||||
| 「退出登录」 | 清令牌 → 关闭主窗口 → 回到登录页(取消登录则退出程序) |
|
||||
| 网页请求唤起登录(`POST /api/activate-login`) | 未登录:登录窗弹到最前;已登录:主界面弹到最前(不影响本机服务) |
|
||||
| 托盘右键「退出」 | 真正退出(dispose 托盘与本机服务) |
|
||||
@ -379,7 +379,7 @@ cd desktop\installer
|
||||
2. 关掉正在运行的软件(单文件自解压出来的真实进程);
|
||||
3. 带 `YUNCANG_AUTO_UPDATE=1` 启动**旧版本**(更新窗口出现后自动下载,不用手点);
|
||||
4. 轮询 `%LOCALAPPDATA%\Programs\YuncangTrace\*.exe` 的 `ProductVersion`,直到变成目标版本;
|
||||
5. 检查本机服务 17300 是否有响应、进程是否已恢复。
|
||||
5. 检查本机服务 16000 是否有响应、进程是否已恢复。
|
||||
|
||||
输出形如:
|
||||
|
||||
@ -391,7 +391,7 @@ cd desktop\installer
|
||||
[6.1s] 安装版本 =
|
||||
[10.4s] 安装版本 = 1.0.7+d32656a…
|
||||
✔ 自动更新完成:1.0.6 → 1.0.7(耗时 10.4s)
|
||||
✔ 本机服务 17300 有响应(HTTP 401)
|
||||
✔ 本机服务 16000 有响应(HTTP 401)
|
||||
✔ 软件进程已恢复(PID 12024)
|
||||
```
|
||||
|
||||
@ -403,12 +403,12 @@ cd desktop\installer
|
||||
|
||||
| 端口 | 协议 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| **17300** | HTTP | 运单查询 / 唤起登录 / 按运单下载录像(低频、无状态) |
|
||||
| **17301** | WebSocket | 拉通道 / 实时预览(推 JPEG 帧)/ 云台 / 满帧率窗口(预览相关全在这里) |
|
||||
| **16000** | HTTP | 运单查询 / 唤起登录 / 按运单下载录像(低频、无状态) |
|
||||
| **16001** | WebSocket | 拉通道 / 实时预览(推 JPEG 帧)/ 云台 / 满帧率窗口(预览相关全在这里) |
|
||||
|
||||
### HTTP 17300(前端 `/local` 页用的就是这两个)
|
||||
### HTTP 16000(前端 `/local` 页用的就是这两个)
|
||||
|
||||
服务固定监听 `http://localhost:17300`(端口写在前端页面与插件里)。
|
||||
服务固定监听 `http://localhost:16000`(端口写在前端页面与插件里)。
|
||||
`LoopbackHttpServer` 直接监听 **127.0.0.1 和 ::1**,所以 `localhost` / `127.0.0.1` 两种写法都能连
|
||||
(前端改 `VITE_LOCAL_SERVICE` 时不会碰到「回 400」)。请求的 `Host` 不是回环地址会被直接断开。
|
||||
|
||||
@ -416,7 +416,7 @@ cd desktop\installer
|
||||
> 或者卡在 STOP_PENDING 时,`HttpListener.Start()` 会抛 `句柄无效(6)`,HTTP 与 WS 会**同时**起不来
|
||||
> (2026-10-23 升级 1.0.113 后的现场故障就是它)。自建 TcpListener 不需要 HTTP.sys / urlacl / 管理员权限。
|
||||
|
||||
浏览器直接打开 <http://localhost:17300/> 会看到一个说明页(列了接口,方便排查)。
|
||||
浏览器直接打开 <http://localhost:16000/> 会看到一个说明页(列了接口,方便排查)。
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
| --- | --- | --- |
|
||||
@ -424,10 +424,10 @@ cd desktop\installer
|
||||
| POST | `/api/activate-login` | 把本机软件的**登录窗叫到前台**(已登录时把主界面叫到前台)。网页收到 `need-login` 时自动调它 |
|
||||
| POST | `/api/playback/download` | 按运单下载录像(存到本机设置目录) |
|
||||
|
||||
> ⚠️ 以前的海康接口(`/api/hik/channels`、`/api/hik/preview*`、`/api/hik/ptz*`)**已全部迁移到 WS 17301**,
|
||||
> ⚠️ 以前的海康接口(`/api/hik/channels`、`/api/hik/preview*`、`/api/hik/ptz*`)**已全部迁移到 WS 16001**,
|
||||
> HTTP 侧不再提供(访问会得到 404「接口不存在」)。前端 `api/localWs.ts` 是唯一调用入口。
|
||||
|
||||
### WebSocket 17301(预览 / 云台 / 拉通道)
|
||||
### WebSocket 16001(预览 / 云台 / 拉通道)
|
||||
|
||||
一条连接可同时推多路画面(一条工作台合成画面 4 路没问题)。文本请求 `{id, action, ...}`,
|
||||
回复 `{id, ok, data | message}`;二进制帧 = `[1 字节 sid 长度][sid ASCII][JPEG]`。
|
||||
@ -447,7 +447,7 @@ cd desktop\installer
|
||||
> `start_preview` / `get_channels` / `open_window` / `ptz*` 在服务端**并发执行**,不会把
|
||||
> 「停止预览 / 云台停转」堵在消息循环后面;云台命令之间按连接串行化,保证「开始转 → 停」不乱序。
|
||||
>
|
||||
> 端口可用 `YUNCANG_LOCAL_WS_PORT` 覆盖;前端用 `VITE_LOCAL_WS` 覆盖默认 `ws://127.0.0.1:17301/`。
|
||||
> 端口可用 `YUNCANG_LOCAL_WS_PORT` 覆盖;前端用 `VITE_LOCAL_WS` 覆盖默认 `ws://127.0.0.1:16001/`。
|
||||
|
||||
#### 预览延迟(子码流 / 主码流是两条完全不同的链路)
|
||||
|
||||
@ -503,9 +503,9 @@ cd desktop\installer
|
||||
示例:
|
||||
|
||||
```powershell
|
||||
curl http://localhost:17300/api/query/321408064481776
|
||||
curl http://localhost:17300/api/query/ # 400 bad-request,但带着登录状态
|
||||
curl -X POST http://localhost:17300/api/activate-login
|
||||
curl http://localhost:16000/api/query/321408064481776
|
||||
curl http://localhost:16000/api/query/ # 400 bad-request,但带着登录状态
|
||||
curl -X POST http://localhost:16000/api/activate-login
|
||||
```
|
||||
|
||||
为什么唤起登录用 **POST**:GET 会被浏览器/聊天工具的链接预取误触发,POST 不会。
|
||||
@ -569,7 +569,7 @@ reg query "HKCU\Software\Classes\yuncang\shell\open\command"
|
||||
|
||||
1. 点击 → 隐藏 iframe 触发 `yuncang://open?code=xxx`(不能导航当前页,否则协议没注册会变成错误页);
|
||||
2. **判断到底成没成,不看页面焦点,看本机服务在不在**:协议触发后每 0.7s 探测一次
|
||||
`http://localhost:17300/api/query/`(任何 HTTP 响应都算成功,扩展带 host 权限,不受页面 CSP 影响);
|
||||
`http://localhost:16000/api/query/`(任何 HTTP 响应都算成功,扩展带 host 权限,不受页面 CSP 影响);
|
||||
- 探测到 → 什么也不做(软件本来就在跑时也能正确判定,不会误报);
|
||||
- 8 秒都探测不到 → 认为没起来,右下角弹出兜底卡片:
|
||||
- **在网页中查看** → 打开插件设置里的「唤不起时的兜底页」(默认 `http://localhost:7301/local?code={code}`,
|
||||
@ -658,6 +658,69 @@ reg query "HKCU\Software\Classes\yuncang\shell\open\command"
|
||||
查询日志只记结论(`[pack-query] 运单号 → found=… records=… streams=…`),不再写完整 JSON;
|
||||
要排查原始数据看后端日志或页面。
|
||||
|
||||
### 合成滤镜图:一次 `xstack`,不要链式 `overlay`
|
||||
|
||||
各路画面按快照里的矩形摆放时,**用一条 `xstack` 一次合成**(`ComposeAsync`),
|
||||
不要像以前那样「黑画布 + 逐个 `overlay`」:
|
||||
|
||||
```
|
||||
[v0][v1][v2][v3]xstack=inputs=4:layout=0_0|960_0|0_540|960_540:fill=black,pad=1920:1080:0:0:black[out]
|
||||
```
|
||||
|
||||
链式 overlay 在 1080p 画布上要走 N−1 遍**整帧**混合(4 路就是 3 遍),每遍都要读两帧写一帧;
|
||||
xstack 只做一遍。实测(本机 i5-12400 + UHD 730,机器同时在跑别的程序,所以按中位数看):
|
||||
|
||||
| 场景 | 链式 overlay | 一次 xstack |
|
||||
| --- | --- | --- |
|
||||
| 60 s × 4 路,libx264(5 次中位数) | 24.7 s / CPU 88 s | **16.1 s / CPU 74 s** |
|
||||
| 60 s × 4 路,h264_qsv(5 次中位数) | 26.5 s / CPU 47 s | **16.5 s / CPU 34 s** |
|
||||
| 120 s × 4 路,`ComposeAsync` 实路径 + libx264 | 37.1 / 35.4 s | **25.3 / 25.1 s** |
|
||||
| 300 s × 4 路,libx264(2 次,负载高、波动大) | 141.6 / 102.3 s | **67.9 / 62.7 s** |
|
||||
|
||||
- 画布比矩形并集大 → `pad` 补黑;比画布大(有越界摆位)→ `crop` 裁掉,与原来叠在黑画布上等价;
|
||||
- 矩形重叠时 z-order 与 overlay 链一致(后一路在上),已用纯色片源验证;
|
||||
- 输出与旧实现**逐像素一致**:标准 2×2、混合尺寸 + 留空 + 越界裁剪两种布局,PSNR 都是 `inf`。
|
||||
|
||||
> 全 GPU 合成(`vpp_qsv` + `xstack_qsv` + `h264_qsv`,输入 `-hwaccel qsv -hwaccel_output_format qsv`
|
||||
> + `-init_hw_device qsv=hw -filter_hw_device hw`,注意要加 `-noautoscale`)在本机**能跑通**:
|
||||
> CPU 再降一半(60 s × 4 路 CPU 34 s → 16 s),但**墙钟反而慢一点**(中位数 11.1 s → 13.2 s)。
|
||||
> 合并的首要痛点是时长,所以没做成默认;等哪天要求「合并时机器必须近乎空闲」再切过去。
|
||||
|
||||
### 合并用的编码器(CPU / 核显)
|
||||
|
||||
合并没办法 `-c:v copy`(多路 overlay 要重画每个像素),所以这一步是纯转码,客户机 CPU 一忙整机就卡。
|
||||
现在会**优先用硬件编码**([FfmpegVideoEncoder](Services/Hik/FfmpegVideoEncoder.cs)):
|
||||
|
||||
| 编码器 | 什么时候用 | 300 秒 × 4 路 | 300 秒 × 2 路 |
|
||||
| --- | --- | --- | --- |
|
||||
| `h264_qsv` | Intel 核显(优先) | **58.5 s** / CPU 212 s / 148.3 MB | **42.3 s** / CPU 126 s / 74.8 MB |
|
||||
| `h264_nvenc` | NVIDIA 独显 | 未实测(同档参数 `-qp 26`) | — |
|
||||
| `h264_amf` | AMD 独显 / APU | 未实测(同档参数 `-qp_i/-qp_p 26`) | — |
|
||||
| `libx264` | 都没有 / 硬件跑不起来(兜底) | 73.7 s / CPU 420 s / 138.6 MB | 47.6 s / CPU 273 s / 69.1 MB |
|
||||
|
||||
(i5-12400 + UHD 730,720p 片源合到 1920×1080@25,只编码不改滤镜链;体积含 `+faststart`)
|
||||
|
||||
> ⚠️ **收益随片长变化**:5 分钟这种长片段编码占比高,硬件编码快 **11%~21%**;
|
||||
> 8 秒这种短片段被进程启动 / 首帧抖动盖住,墙钟几乎一样(3.03 s vs 3.04 s),只省 CPU(11.5 s → 6.6 s)。
|
||||
> 质量上 `gq 26` 与 `crf 23` 基本持平(PSNR 41.9 dB vs 42.1 dB),体积大 7%;
|
||||
> 想省体积可按 `YUNCANG_COMPOSE_ENCODER` 之外的参数改成 `gq 28`(40.7 dB,比 crf 23 小 19%,画面会软一点)。
|
||||
|
||||
- **探测**:进程内第一次合并时,拿 0.2 秒黑场**真编一帧**(`-f lavfi -i color=… -f null -`),
|
||||
成功才用 —— 光看 `ffmpeg -encoders` 列表不够(装了 nvenc 但没有 N 卡也照样在列表里)。
|
||||
结果缓存在进程里(**每次进程启动只付一次**),日志:
|
||||
`[playback] 合并编码器:h264_qsv(硬件编码,探测用时 1024ms)`。
|
||||
- **探测开销**:有核显的机器约 **1.0 秒**(QSV 初始化 Media SDK 设备,与探测内容无关);
|
||||
驱动缺失的候选是 dlopen 立刻失败,**0.04~0.06 秒**(≈ 一次 ffmpeg 启动);全都没有时三个候选合计约 0.1 秒。
|
||||
单个候选最多等 **4 秒**(驱动卡死时),超时就跳过。
|
||||
- **兜底**:硬件编码跑到一半失败(驱动被独占 / 参数组合不支持 / 退出码 0 但没写出文件)→ 删掉半成品,
|
||||
**用 libx264 重来一次**,不让用户白等(日志 `[playback] 合并用 h264_qsv 失败(退出码 …),改用 libx264 重试`)。
|
||||
软件编码再失败才抛异常,此时调用方保留各路段(另见「合并失败不丢数据」)。
|
||||
- **质量档位**和原来 `crf 23` 对齐:QSV 用 `-global_quality 26`(`23` 会输出到 5.85 MB,比原来大 57%,
|
||||
而成片还要上传云端,所以退一档),NVENC 用 `-qp 26`,AMF 用 `-qp_i/-qp_p 26`。
|
||||
- **排障**:环境变量 `YUNCANG_COMPOSE_ENCODER=libx264`(或 `h264_qsv` 等)可跳过探测强制指定;写错名字按 libx264 处理。
|
||||
- ⚠️ 只把**编码**交给硬件:解码 / `scale` / `xstack` 仍是 CPU。
|
||||
全 GPU 那条链(`vpp_qsv` + `xstack_qsv`)实测 CPU 再减半、墙钟略慢,见上一节,暂未启用。
|
||||
|
||||
要换成别的数据源,只改 `OrderQueryService.QueryAsync` 一个方法就行(返回 `QueryResult`,
|
||||
`Data` 是扁平字典即可,前端 `/local` 页也吃这份数据)。
|
||||
|
||||
@ -678,7 +741,7 @@ reg query "HKCU\Software\Classes\yuncang\shell\open\command"
|
||||
| 报端口被占用(`AddressAlreadyInUse`) | 已经开了一个实例(单实例会把参数转过去);检查任务管理器里的残留进程 |
|
||||
| 双击图标没反应 / 主界面打不开,托盘图标还在 | 1.0.134 起:再次启动会把已运行实例的主界面叫到前面(托盘双击也行)。更老的版本点了没反应是正常的(第二个实例直接退出),从托盘打开即可 |
|
||||
| 升级后主界面仍然出不来 | 看日志最后几行:停在 `准备显示更新窗口…` 之后就是老版本的「更新窗盖在登录窗上」死锁,装新版本即可;有 `[app] 主窗口没建:server=… session=… api=…` 说明登录态没建立 |
|
||||
| 网页提示服务不可用,但软件在跑 | 先用浏览器直接打开 `http://localhost:17300/api/query/`(会回 400 但带登录状态):打不开→防火墙/端口;打得开→多半是 CORS 头没回。预览类问题则看 `ws://127.0.0.1:17301/` 能不能打开(直接浏览器访问应该返回一小段 JSON) |
|
||||
| 网页提示服务不可用,但软件在跑 | 先用浏览器直接打开 `http://localhost:16000/api/query/`(会回 400 但带登录状态):打不开→防火墙/端口;打得开→多半是 CORS 头没回。预览类问题则看 `ws://127.0.0.1:16001/` 能不能打开(直接浏览器访问应该返回一小段 JSON) |
|
||||
| 点网页「启动本机软件」没反应 | 协议没注册(界面看「启动协议」状态);或浏览器拦了自动跳转(必须用户点击) |
|
||||
| 唤起时弹「You must install .NET Desktop Runtime」 | 唤起的是 `bin\Debug` 这类 framework-dependent 的 exe(拿不到 `DOTNET_ROOT`)。用自包含发布产物,并让它启动一次以校正注册表 |
|
||||
| 改了协议名 | 注册表重注册 + 前端 `VITE_APP_PROTOCOL` 同步 + 插件目标地址同步 |
|
||||
@ -784,7 +847,8 @@ reg query "HKCU\Software\Classes\yuncang\shell\open\command"
|
||||
|
||||
### 添加通道(设备名 + 通道号)
|
||||
|
||||
`扫描设备 → 选中 → 添加为通道` 会弹窗让用户定**通道号**与**设备名**(与 AndroidScanCenter 一致):
|
||||
在「发现到的设备」列表里点该行**「操作」列的「添加」**,会弹窗让用户定**通道号**与**设备名**(与 AndroidScanCenter 一致)。
|
||||
入口放在行内、不依赖选中项 —— 发现列表每 3 秒刷新一次,靠「先选中再点标题行按钮」会因为选中项被刷新清掉而点不到:
|
||||
|
||||
- **通道号**:`1..50` 的下拉框,已占用的号照样列出来并标注「已被 xx 占用」,选中就提示、不关框;
|
||||
默认勾在最小空号上。没有「通道号」设备字段 —— 它是**本地概念**(现场认工位),上报时就是 `channelId`。
|
||||
@ -993,16 +1057,18 @@ ffmpeg(RTSP, tcp) → 灰度 rawvideo 帧 → 读帧线程只留最新一帧(
|
||||
### 界面
|
||||
- 主窗口改成页签:**打包查询** / **扫码通道**(后者仅在「设备服务」开启后出现)。
|
||||
查到条码(协议唤起或通道扫码)时**默认切回「打包查询」页签**并自动查询。
|
||||
- 扫码通道页:**每个区块的状态与按钮都在各自标题行上**。
|
||||
- 扫码通道页:状态在各自标题行上;**通道操作**在标题行(作用于选中行),**发现设备的「添加」**在列表行内。
|
||||
- 「扫码通道」标题行:状态(`扫码服务运行中 · 通道 N 个(在线 M)` + 通道同步状态 + 待上传条数)+ `重连全部` / `静音`(选中行切换,已静音时叫「恢复蜂鸣」)/ `读取设备配置` / `重命名` / `删除通道`(后三个都要先选中一行);
|
||||
通道列表有「类型」「状态」「静音」三列(类型 = `安卓扫描通道` / `扫码枪`,来自 UDP 发现应答的设备型号,
|
||||
`AndroidStation` 才标成安卓扫描通道。**只有安卓扫描通道需要「扫码成功」通知**:摄像头识别到条码时
|
||||
通知它播报语音;扫码枪通道没有语音能力,不发。**记录一直在写,与通道类型/在线状态无关**);
|
||||
**没有「同步通道」按钮** —— 通道增删/启停都会自动上传并回查确认;
|
||||
- 「发现到的设备」标题行:`开始扫描`(**开关**,打开后常驻发现:每 3s 探测、socket 一直收,直到手工停止)+ `添加为通道` + 状态(`正在扫描… 未添加 N 台` / `发现 N 台未添加的设备(另有 M 台已添加)`);
|
||||
- 「发现到的设备」标题行:`开始扫描`(**开关**,打开后常驻发现:每 3s 探测、socket 一直收,直到手工停止)+ 状态(`正在扫描… 未添加 N 台` / `发现 N 台未添加的设备(另有 M 台已添加)`);
|
||||
列表最后一列是**「操作」**,每行一个「添加」按钮(**标题行不再有「添加为通道」**:列表刷新会清掉选中项,靠选中再点按钮经常点不到);
|
||||
发现列表和「添加通道」弹窗都会标注 **安卓扫描通道**(型号 `AndroidStation`),添加时把型号一起落进 `channels.json`。
|
||||
- **已经添加为通道的设备不会再出现在发现列表里**:显示集合与「发现到的全集」分开存(`_allDevices` / `_devices`),
|
||||
按通道 MAC 过滤;删掉通道后那台设备会自己回到列表里,不用重新扫。每轮结果按 MAC 合并,不整表覆盖(UDP 丢包时设备不会闪没)。
|
||||
按通道 MAC 过滤;删掉通道后那台设备会自己回到列表里,不用重新扫。每轮结果**按 MAC 就地合并**(能复用的对象不重建),
|
||||
不整表 `Clear` 重填 —— 否则每 3 秒一次刷新会把 ListView 的选中项和滚动位置一起清掉(现场表现:「列表一直在刷,设备选不中」)。
|
||||
- 扫码记录页(对应 AndroidScanCenter 的「通道回放」,`Views/ScanRecordsView`):
|
||||
通道筛选 / `立即上传` / `清空`,列表显示 时间 / 通道 / 号 / 条码 / **已上传或待上传** / 确认时间,
|
||||
状态行是 `全部通道:显示 N 条 · 本地共 M 条 · 待上传 K 条`。
|
||||
|
||||
@ -162,7 +162,7 @@ public static class AgentHost
|
||||
await scan.StartAsync().ConfigureAwait(false);
|
||||
scan.StartDiscovery(); // 常驻发现:设备 DHCP 换 IP 时能自己重连
|
||||
|
||||
// 自检要尽早:worker 一就绪,局域网询问才有应答(UDP 17310)。
|
||||
// 自检要尽早:worker 一就绪,局域网询问才有应答(UDP 16100)。
|
||||
// 以前延后 20 秒,导致「刚启动/刚更新完」这段时间本机查询探测不到设备管理服务,
|
||||
// 白白退化成云端中转 —— 而云任务反过来才把 worker 拉起来,形成恶性循环。
|
||||
_ = Task.Run(async () =>
|
||||
|
||||
@ -113,7 +113,8 @@ public static class HikWorkerOps
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 局域网发现用的端口(与 17300/17301 同族,但独立进程独立端口)。
|
||||
/// 局域网发现用的端口(与桌面端本机端口 16000/16001 同段,但独立进程独立端口)。
|
||||
/// 取 161xx 而不是 160xx:16010 常被向日葵等远控软件占用。
|
||||
///
|
||||
/// - <see cref="UdpQuery"/>:收桌面端的广播询问(**询问-应答**,不是主动公告);
|
||||
/// - <see cref="Http"/>:取流健康端点,桌面端用一次 TCP 连接就能判定"是否同 LAN"。
|
||||
@ -121,10 +122,10 @@ public static class HikWorkerOps
|
||||
public static class HikWorkerPorts
|
||||
{
|
||||
/// <summary>可用 <c>YUNCANG_EDGE_UDP_PORT</c> 临时覆盖(同机并行跑两个实例测试时用)</summary>
|
||||
public static int UdpQuery { get; } = Resolve("YUNCANG_EDGE_UDP_PORT", 17310);
|
||||
public static int UdpQuery { get; } = Resolve("YUNCANG_EDGE_UDP_PORT", 16100);
|
||||
|
||||
/// <summary>可用 <c>YUNCANG_EDGE_HTTP_PORT</c> 临时覆盖</summary>
|
||||
public static int Http { get; } = Resolve("YUNCANG_EDGE_HTTP_PORT", 17311);
|
||||
public static int Http { get; } = Resolve("YUNCANG_EDGE_HTTP_PORT", 16101);
|
||||
|
||||
/// <summary>
|
||||
/// 监听地址。默认 <c>0.0.0.0</c>(局域网可发现可直连);
|
||||
|
||||
@ -2,6 +2,7 @@ using System;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
@ -359,6 +360,13 @@ public static class ServiceInstaller
|
||||
return new HelperResult { Ok = true, Message = "后台服务已卸载" };
|
||||
}
|
||||
|
||||
/// <summary>旧版本用 17xxx 端口时的防火墙规则名(升级时清掉,别继续占着别人项目的端口)</summary>
|
||||
private static readonly string[] LegacyFirewallRuleNames =
|
||||
{
|
||||
"YuncangTrace Edge (TCP 17311)",
|
||||
"YuncangTrace Edge (UDP 17310)",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 放行局域网发现端口(TCP 取流健康端点 + UDP 询问应答)。
|
||||
///
|
||||
@ -370,8 +378,14 @@ public static class ServiceInstaller
|
||||
/// </summary>
|
||||
private static void EnsureFirewallRules()
|
||||
{
|
||||
AddFirewallRule("YuncangTrace Edge (TCP 17311)", "TCP", "17311");
|
||||
AddFirewallRule("YuncangTrace Edge (UDP 17310)", "UDP", "17310");
|
||||
AddFirewallRule("YuncangTrace Edge (TCP 16101)", "TCP", "16101");
|
||||
AddFirewallRule("YuncangTrace Edge (UDP 16100)", "UDP", "16100");
|
||||
|
||||
// 老版本(17xxx)装过的规则名带端口号,升级后不会自动消失,这里顺手清掉
|
||||
foreach (var name in LegacyFirewallRuleNames)
|
||||
{
|
||||
RunTool("netsh.exe", "advfirewall", "firewall", "delete", "rule", $"name={name}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void AddFirewallRule(string name, string protocol, string port)
|
||||
@ -393,7 +407,8 @@ public static class ServiceInstaller
|
||||
|
||||
private static void RemoveFirewallRules()
|
||||
{
|
||||
foreach (var name in new[] { "YuncangTrace Edge (TCP 17311)", "YuncangTrace Edge (UDP 17310)" })
|
||||
foreach (var name in new[] { "YuncangTrace Edge (TCP 16101)", "YuncangTrace Edge (UDP 16100)" }
|
||||
.Concat(LegacyFirewallRuleNames))
|
||||
{
|
||||
RunTool("netsh.exe", "advfirewall", "firewall", "delete", "rule", $"name={name}");
|
||||
}
|
||||
|
||||
182
desktop/Services/Hik/FfmpegVideoEncoder.cs
Normal file
182
desktop/Services/Hik/FfmpegVideoEncoder.cs
Normal file
@ -0,0 +1,182 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
|
||||
namespace YuncangTrace.LocalService.Services.Hik;
|
||||
|
||||
/// <summary>
|
||||
/// 合并视频(多路 overlay → 一路)用的 H.264 编码器:**有硬件编码就用,没有/跑不起来回落 libx264**
|
||||
///
|
||||
/// 合并没办法 `-c:v copy`(每个像素都要重画),所以这一步是纯转码,客户机 CPU 一忙整机就卡。
|
||||
/// 实测(i5-12400 + UHD 730,4 路 / 2 路 720p 合到 1920×1080@25,testsrc2 片源):
|
||||
/// <code>
|
||||
/// 300s × 4 路 libx264: 73.7s 墙钟 / 420s CPU / 138.6MB
|
||||
/// h264_qsv(gq26): 58.5s 墙钟 / 212s CPU / 148.3MB ← 快 21%、CPU 减半
|
||||
/// 300s × 2 路 libx264: 47.6s 墙钟 / 273s CPU / 69.1MB
|
||||
/// h264_qsv(gq26): 42.3s 墙钟 / 126s CPU / 74.8MB ← 快 11%
|
||||
/// 8s × 4 路 两者墙钟几乎一样(3.03s vs 3.04s,CPU 11.5s → 6.6s)
|
||||
/// </code>
|
||||
///
|
||||
/// ⚠️ **片越短,硬件编码的墙钟收益越小**:8 秒这种短片段被进程启动 / 首帧抖动盖住,
|
||||
/// 省到的只有 CPU;5 分钟这种长片段编码占比上来,才有 10~20% 的时长收益。
|
||||
/// 质量:`gq 26` 的 PSNR 与 `crf 23` 基本持平(41.9dB vs 42.1dB),体积大 7%;
|
||||
/// 想省体积可以按 `gq 28`(40.7dB,比 crf 23 小 19%),但画面会明显软一点。
|
||||
///
|
||||
/// ⚠️ **只把编码交给硬件**:解码 / scale / overlay 仍走 CPU。
|
||||
/// 实测把解码也丢给核显(`-hwaccel qsv -hwaccel_output_format nv12`)没有收益,
|
||||
/// 而 overlay_qsv 那条全 GPU 链路在实测机器上 `hwupload` 直接失败(frame pool 建不起来),
|
||||
/// 不能当默认 —— 客户机型号杂,赌不起。
|
||||
///
|
||||
/// 探测开销(每次进程启动只付一次,结果缓存在 <see cref="_picked"/>):QSV 需要初始化
|
||||
/// Media SDK 设备,实测 **约 1.0 秒**且与探测内容无关(1 帧 64×64 也要 0.98s);
|
||||
/// 驱动缺失的候选则是 dlopen 立刻失败,**0.04~0.06 秒**(≈ 一次 ffmpeg 启动的开销)。
|
||||
///
|
||||
/// 排障:环境变量 `YUNCANG_COMPOSE_ENCODER=libx264|h264_qsv|h264_nvenc|h264_amf` 可跳过探测强制指定。
|
||||
/// </summary>
|
||||
internal static class FfmpegVideoEncoder
|
||||
{
|
||||
/// <summary>软件编码(兜底,永远可用)</summary>
|
||||
public const string Software = "libx264";
|
||||
|
||||
private const string OverrideVariable = "YUNCANG_COMPOSE_ENCODER";
|
||||
|
||||
/// <summary>
|
||||
/// 按优先级排的候选:Intel 核显 → NVIDIA → AMD → 软件。
|
||||
///
|
||||
/// 质量档位刻意和 `libx264 -crf 23` 对齐(QSV 的 `-global_quality` 是 ICQ,NVENC/AMF 用 CQP):
|
||||
/// 实测同一段片子 `gq=23` 会输出 5.85MB(比 crf23 的 3.72MB 大 57%),
|
||||
/// **成片还要上传云端**,所以退到 26 —— 4.01MB,和原来基本持平,编码仍然快 37%。
|
||||
/// </summary>
|
||||
private static readonly (string Name, string[] Args)[] Candidates =
|
||||
{
|
||||
("h264_qsv", new[] { "-c:v", "h264_qsv", "-preset", "veryfast", "-global_quality", "26" }),
|
||||
("h264_nvenc", new[] { "-c:v", "h264_nvenc", "-preset", "p4", "-rc", "constqp", "-qp", "26" }),
|
||||
("h264_amf", new[] { "-c:v", "h264_amf", "-quality", "speed", "-rc", "cqp", "-qp_i", "26", "-qp_p", "26" }),
|
||||
(Software, new[] { "-c:v", Software, "-preset", "veryfast", "-crf", "23" }),
|
||||
};
|
||||
|
||||
private static readonly object Gate = new();
|
||||
private static string? _picked;
|
||||
private static long _probeMs;
|
||||
|
||||
/// <summary>
|
||||
/// 这台机器上合并该用哪个编码器(进程内只探测一次)。
|
||||
/// 探测 = 拿 0.2 秒黑场真编一帧,光看 `-encoders` 列表不够:装了 nvenc 但没 N 卡也一样会失败。
|
||||
/// </summary>
|
||||
public static string Resolve(string ffmpeg)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
if (_picked is not null) return _picked;
|
||||
|
||||
var forced = Environment.GetEnvironmentVariable(OverrideVariable)?.Trim();
|
||||
if (!string.IsNullOrEmpty(forced))
|
||||
{
|
||||
// 只认列出来的这几个:写错名字要是当硬件编码用,会「探测跳过 → 合并失败 → 白重试一轮」
|
||||
if (!Candidates.Any(item => string.Equals(item.Name, forced, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
AppLog.Write($"[playback] {OverrideVariable}={forced} 不认识,按 libx264 处理(可选:{string.Join('/', Candidates.Select(item => item.Name))})");
|
||||
_picked = Software;
|
||||
return _picked;
|
||||
}
|
||||
|
||||
_picked = forced;
|
||||
AppLog.Write($"[playback] 合并编码器按 {OverrideVariable} 指定:{forced}(不探测)");
|
||||
return _picked;
|
||||
}
|
||||
|
||||
foreach (var (name, args) in Candidates)
|
||||
{
|
||||
if (name == Software) break;
|
||||
|
||||
var started = Stopwatch.StartNew();
|
||||
var usable = Usable(ffmpeg, name, args);
|
||||
_probeMs += started.ElapsedMilliseconds;
|
||||
if (!usable) continue;
|
||||
|
||||
_picked = name;
|
||||
AppLog.Write($"[playback] 合并编码器:{name}(硬件编码,探测用时 {_probeMs}ms)");
|
||||
return _picked;
|
||||
}
|
||||
|
||||
_picked = Software;
|
||||
AppLog.Write($"[playback] 合并编码器:libx264(没有可用的硬件编码器,探测用时 {_probeMs}ms)");
|
||||
return _picked;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>该编码器对应的 ffmpeg 参数</summary>
|
||||
public static string[] EncoderArgs(string encoder)
|
||||
{
|
||||
foreach (var (name, args) in Candidates)
|
||||
{
|
||||
if (string.Equals(name, encoder, StringComparison.OrdinalIgnoreCase)) return args;
|
||||
}
|
||||
return Candidates[^1].Args;
|
||||
}
|
||||
|
||||
/// <summary>是不是软件编码(软件都失败就没得重试了)</summary>
|
||||
public static bool IsSoftware(string encoder)
|
||||
{
|
||||
return string.Equals(encoder, Software, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>真编一帧确认能用(驱动缺失 / 被独占 / 参数不支持都会在这里暴露)</summary>
|
||||
private static bool Usable(string ffmpeg, string name, string[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
var psi = new ProcessStartInfo
|
||||
{
|
||||
FileName = ffmpeg,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
};
|
||||
foreach (var arg in new[]
|
||||
{
|
||||
"-hide_banner", "-nostdin", "-loglevel", "error",
|
||||
"-f", "lavfi", "-i", "color=c=black:s=320x240:r=25:d=0.2",
|
||||
})
|
||||
{
|
||||
psi.ArgumentList.Add(arg);
|
||||
}
|
||||
foreach (var arg in args) psi.ArgumentList.Add(arg);
|
||||
psi.ArgumentList.Add("-f");
|
||||
psi.ArgumentList.Add("null");
|
||||
psi.ArgumentList.Add("-");
|
||||
|
||||
using var process = Process.Start(psi);
|
||||
if (process is null) return false;
|
||||
|
||||
// 两个流都要读掉,否则管道写满 ffmpeg 会卡住
|
||||
var stdout = process.StandardOutput.ReadToEndAsync();
|
||||
var stderr = process.StandardError.ReadToEndAsync();
|
||||
|
||||
if (!process.WaitForExit(4000))
|
||||
{
|
||||
try { process.Kill(entireProcessTree: true); } catch { /* 已经退了 */ }
|
||||
AppLog.Write($"[playback] 硬件编码 {name} 探测超时(4s),跳过");
|
||||
return false;
|
||||
}
|
||||
|
||||
var ok = process.ExitCode == 0;
|
||||
if (!ok)
|
||||
{
|
||||
var firstError = (stderr.Result ?? string.Empty)
|
||||
.Split('\n')
|
||||
.Select(line => line.Trim())
|
||||
.FirstOrDefault(line => line.Length > 0) ?? "未知原因";
|
||||
AppLog.Write($"[playback] 硬件编码 {name} 不可用:{firstError}");
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Write($"[playback] 硬件编码 {name} 探测失败:{ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -530,14 +530,18 @@ public sealed class HikPlaybackService : IDisposable
|
||||
/// <summary>
|
||||
/// 把多路下载好的片段**按工作台画布布局合并成一个视频**
|
||||
///
|
||||
/// 做法:先铺一张黑画布(`color` 虚拟输入),每路 `scale` 到它在快照里的尺寸,
|
||||
/// 再用 `overlay=x:y` 摆到对应位置 —— 与工作台页面上的画面摆放一致。
|
||||
/// 做法:每路先 `scale` 到它在快照里的尺寸,再用**一条 `xstack`** 按 `layout=x_y|…`
|
||||
/// 一次合成(画布不够大就 `pad` 补黑、摆位越界就 `crop` 裁掉)—— 与工作台页面上的画面摆放一致。
|
||||
///
|
||||
/// 为什么不用「黑画布 + 逐个 `overlay`」:链式 overlay 在 1080p 上要走 N−1 遍整帧混合,
|
||||
/// 实测 4 路场景 xstack 快 ~30%(120s 片段:36.3s → 25.2s),输出逐像素一致。
|
||||
///
|
||||
/// ⚠️ 踩过的坑:**不要**把每路先 <c>pad</c> 成整张画布再叠加 ——
|
||||
/// 补边是黑底,叠上去会把下面那路的画面整块盖住(表现是「合成完只剩一个小窗,其余全黑」)。
|
||||
///
|
||||
/// 为什么要重新编码:多路叠加没法 `-c:v copy`(要重画每个像素),所以这一步比下载慢,
|
||||
/// 用 <c>veryfast</c> + <c>crf 23</c> 折中。
|
||||
/// 为什么要重新编码:多路合成没法 `-c:v copy`(要重画每个像素),所以这一步比下载慢。
|
||||
/// 编码器由 <see cref="FfmpegVideoEncoder"/> 选:有核显/独显就用硬件编码(`h264_qsv` 等),
|
||||
/// 没有或跑不起来回落 `libx264 -preset veryfast -crf 23`。
|
||||
/// </summary>
|
||||
/// <param name="segments">各路下载好的文件(顺序与 <paramref name="streams"/> 一一对应)</param>
|
||||
/// <param name="startOffsets">
|
||||
@ -599,57 +603,92 @@ public sealed class HikPlaybackService : IDisposable
|
||||
var totalSec = longestSec + Math.Max(maxDelaySec, 0);
|
||||
|
||||
var filters = new List<string>();
|
||||
var layoutParts = new List<string>();
|
||||
var boxRight = 0;
|
||||
var boxBottom = 0;
|
||||
for (var i = 0; i < streams.Count; i++)
|
||||
{
|
||||
var stream = streams[i];
|
||||
var width = stream.Layout.Width > 0 ? stream.Layout.Width : canvasWidth;
|
||||
var height = stream.Layout.Height > 0 ? stream.Layout.Height : canvasHeight;
|
||||
var x = Math.Max(stream.Layout.X, 0);
|
||||
var y = Math.Max(stream.Layout.Y, 0);
|
||||
|
||||
// 帧率统一到 25(各路帧率不一样,overlay 会互相等待并对不齐)
|
||||
filters.Add($"[{i + 1}:v]{TimingFilter(offsets[i])}"
|
||||
// 帧率统一到 25(各路帧率不一样,合成时会互相等待并对不齐)
|
||||
filters.Add($"[{i}:v]{TimingFilter(offsets[i])}"
|
||||
+ $"scale={width}:{height}:force_original_aspect_ratio=decrease,"
|
||||
+ $"fps=25,format=yuv420p,setsar=1[v{i}]");
|
||||
|
||||
layoutParts.Add($"{x}_{y}");
|
||||
boxRight = Math.Max(boxRight, x + width);
|
||||
boxBottom = Math.Max(boxBottom, y + height);
|
||||
}
|
||||
|
||||
var current = "[0:v]";
|
||||
for (var i = 0; i < streams.Count; i++)
|
||||
{
|
||||
var label = i == streams.Count - 1 ? "[out]" : $"[c{i}]";
|
||||
filters.Add($"{current}[v{i}]overlay={streams[i].Layout.X}:{streams[i].Layout.Y}{label}");
|
||||
current = label;
|
||||
}
|
||||
// 一次性合成(`xstack`)替代逐个 `overlay`:
|
||||
// 4 路 1080p 画布上链式 overlay 要走 3 遍整帧混合,xstack 只做一遍。
|
||||
// 实测 60s × 4 路:墙钟 24.7s → 16.1s(libx264)、26.5s → 16.5s(qsv),CPU 也降 16%~27%;
|
||||
// 输出与链式 overlay **逐像素一致**(PSNR inf,含空隙 / 混合尺寸 / 重叠的 z-order)。
|
||||
filters.Add($"[v0]{(streams.Count > 1 ? string.Concat(Enumerable.Range(1, streams.Count - 1).Select(i => $"[v{i}]")) : string.Empty)}"
|
||||
+ $"xstack=inputs={streams.Count}:layout={string.Join('|', layoutParts)}:fill=black"
|
||||
// xstack 的输出只到「矩形并集」那么大:比画布小的补黑,比画布大的裁掉(等价于原来叠在黑画布上)
|
||||
+ (boxRight < canvasWidth || boxBottom < canvasHeight
|
||||
? $",pad={canvasWidth}:{canvasHeight}:0:0:black"
|
||||
: string.Empty)
|
||||
+ (boxRight > canvasWidth || boxBottom > canvasHeight
|
||||
? $",crop={canvasWidth}:{canvasHeight}:0:0"
|
||||
: string.Empty)
|
||||
+ "[out]");
|
||||
|
||||
var args = new List<string>
|
||||
{
|
||||
"-hide_banner", "-nostdin", "-loglevel", "error",
|
||||
// 黑画布当底板(d 与录像时长一致);索引 0,各路视频从 1 开始
|
||||
"-f", "lavfi", "-i",
|
||||
$"color=c=black:s={canvasWidth}x{canvasHeight}:r=25:d={totalSec.ToString("0", CultureInfo.InvariantCulture)}",
|
||||
};
|
||||
var args = new List<string> { "-hide_banner", "-nostdin", "-loglevel", "error" };
|
||||
foreach (var segment in segments)
|
||||
{
|
||||
args.Add("-i");
|
||||
args.Add(segment);
|
||||
}
|
||||
|
||||
args.AddRange(new[]
|
||||
{
|
||||
"-filter_complex", string.Join(';', filters),
|
||||
"-map", current,
|
||||
"-c:v", "libx264", "-preset", "veryfast", "-crf", "23",
|
||||
"-an", "-movflags", "+faststart",
|
||||
"-t", totalSec.ToString("0", CultureInfo.InvariantCulture),
|
||||
"-progress", "pipe:2", "-nostats",
|
||||
"-y", outputPath,
|
||||
});
|
||||
// 编码器:有核显/独显的硬件编码就用(见 FfmpegVideoEncoder),没有就 libx264
|
||||
var encoder = FfmpegVideoEncoder.Resolve(ffmpeg);
|
||||
|
||||
string[] BuildArgs(string name) => args
|
||||
.Concat(new[] { "-filter_complex", string.Join(';', filters), "-map", "[out]" })
|
||||
.Concat(FfmpegVideoEncoder.EncoderArgs(name))
|
||||
.Concat(new[]
|
||||
{
|
||||
"-an", "-movflags", "+faststart",
|
||||
"-t", totalSec.ToString("0", CultureInfo.InvariantCulture),
|
||||
"-progress", "pipe:2", "-nostats",
|
||||
"-y", outputPath,
|
||||
})
|
||||
.ToArray();
|
||||
|
||||
progress?.Report(new PlaybackProgress(0, "正在合并(按工作台布局)…"));
|
||||
|
||||
var totalMs = totalSec * 1000;
|
||||
var exit = await RunAsync(ffmpeg, args.ToArray(),
|
||||
|
||||
// 成片是业务交付物:**退出码 0 也不算数**,还得真有像样的文件。
|
||||
// 少数硬件编码器会「成功退出但没写出来」,不能拿它当成功。
|
||||
static bool Usable(string path, int exitCode)
|
||||
{
|
||||
if (exitCode != 0 || !File.Exists(path)) return false;
|
||||
return new FileInfo(path).Length >= 16 * 1024;
|
||||
}
|
||||
|
||||
var exit = await RunAsync(ffmpeg, BuildArgs(encoder),
|
||||
line => ReportProgress(progress, line, totalMs, "合并中"), ct).ConfigureAwait(false);
|
||||
|
||||
if (exit != 0 || !File.Exists(outputPath) || new FileInfo(outputPath).Length < 16 * 1024)
|
||||
// 硬件编码探测过了也可能在长片上翻车(驱动被独占 / 参数组合不支持 / 空输出):
|
||||
// 直接退回软件编码重来一次,不让用户白等一轮再看到「合并失败」。
|
||||
if (!Usable(outputPath, exit) && !FfmpegVideoEncoder.IsSoftware(encoder))
|
||||
{
|
||||
AppLog.Write($"[playback] 合并用 {encoder} 失败(退出码 {exit}),改用 libx264 重试");
|
||||
TryDelete(outputPath);
|
||||
encoder = FfmpegVideoEncoder.Software;
|
||||
progress?.Report(new PlaybackProgress(0, "正在合并(按工作台布局,软件编码重试)…"));
|
||||
exit = await RunAsync(ffmpeg, BuildArgs(encoder),
|
||||
line => ReportProgress(progress, line, totalMs, "合并中"), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!Usable(outputPath, exit))
|
||||
{
|
||||
throw new HikException(uint.MaxValue, $"合并失败(ffmpeg 退出码 {exit})");
|
||||
}
|
||||
|
||||
@ -6,7 +6,7 @@ using System.Threading;
|
||||
namespace YuncangTrace.LocalService.Services.Hik;
|
||||
|
||||
/// <summary>
|
||||
/// 预览会话管理(实时预览唯一入口,由 WS 17301 驱动)。
|
||||
/// 预览会话管理(实时预览唯一入口,由 WS 16001 驱动)。
|
||||
///
|
||||
/// 为什么要有「会话」这层:
|
||||
/// - 网页预览时凭据只发一次(走 WS 的 <c>start_preview</c>),之后每帧按 <c>sid</c> 区分,
|
||||
|
||||
@ -26,13 +26,13 @@ namespace YuncangTrace.LocalService.Services;
|
||||
/// </summary>
|
||||
public sealed class LocalHttpServer : IDisposable
|
||||
{
|
||||
/// <summary>监听端口(前端/插件里写死的 17300;可用 <c>YUNCANG_LOCAL_PORT</c> 临时覆盖,便于自测)</summary>
|
||||
/// <summary>监听端口(前端/插件里写死的 16000;可用 <c>YUNCANG_LOCAL_PORT</c> 临时覆盖,便于自测)</summary>
|
||||
public static int Port { get; } = ResolvePort();
|
||||
|
||||
private static int ResolvePort()
|
||||
{
|
||||
var raw = Environment.GetEnvironmentVariable("YUNCANG_LOCAL_PORT");
|
||||
return int.TryParse(raw, out var port) && port is > 0 and < 65536 ? port : 17300;
|
||||
return int.TryParse(raw, out var port) && port is > 0 and < 65536 ? port : 16000;
|
||||
}
|
||||
|
||||
private readonly LoopbackHttpServer _listener;
|
||||
@ -140,7 +140,7 @@ public sealed class LocalHttpServer : IDisposable
|
||||
return;
|
||||
}
|
||||
|
||||
// ⚠️ 海康相关(拉通道 / 实时预览 / 云台 / 满帧率窗口)已全部迁到 WS 17301(LocalWsServer),这里不再提供。
|
||||
// ⚠️ 海康相关(拉通道 / 实时预览 / 云台 / 满帧率窗口)已全部迁到 WS 16001(LocalWsServer),这里不再提供。
|
||||
|
||||
// 按运单下载录像:POST /api/playback/download { code }
|
||||
// 网页查件页(/local?code=)用 —— 任何装了本机软件的电脑都能下,存到本机设置的目录
|
||||
@ -152,12 +152,12 @@ public sealed class LocalHttpServer : IDisposable
|
||||
|
||||
if (!request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// 只剩 GET 接口了;旧的 POST /api/hik/* 会走到这里(预览/云台/拉通道已迁到 WS 17301)
|
||||
// 只剩 GET 接口了;旧的 POST /api/hik/* 会走到这里(预览/云台/拉通道已迁到 WS 16001)
|
||||
await WriteJsonAsync(response, 404, new
|
||||
{
|
||||
ok = false,
|
||||
state = "not-found",
|
||||
message = "接口不存在(拉通道 / 预览 / 云台已迁到 WebSocket 17301)",
|
||||
message = "接口不存在(拉通道 / 预览 / 云台已迁到 WebSocket 16001)",
|
||||
}).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
@ -238,13 +238,13 @@ public sealed class LocalHttpServer : IDisposable
|
||||
<style>body{font:14px/1.7 "Microsoft YaHei UI",sans-serif;margin:40px;color:#1f2430}
|
||||
code{background:#f3f4f6;padding:1px 6px;border-radius:5px}a{color:#2563eb}</style>
|
||||
<h2>云仓视频溯源软件(本机服务)</h2>
|
||||
<p>服务运行中,只监听本机(127.0.0.1:17300)。</p>
|
||||
<p>服务运行中,只监听本机(127.0.0.1:16000)。</p>
|
||||
<ul>
|
||||
<li><code>/api/query/{运单号}</code> 查询(同时返回服务/登录状态;没登录回 401)</li>
|
||||
<li><code>POST /api/activate-login</code> 把登录窗叫到前台</li>
|
||||
<li><code>POST /api/playback/download</code> 按运单下载录像</li>
|
||||
</ul>
|
||||
<p>拉通道 / 实时预览 / 云台 / 满帧率窗口走 WebSocket:<code>ws://127.0.0.1:17301</code></p>
|
||||
<p>拉通道 / 实时预览 / 云台 / 满帧率窗口走 WebSocket:<code>ws://127.0.0.1:16001</code></p>
|
||||
""";
|
||||
await WriteHtmlAsync(response, 200, html).ConfigureAwait(false);
|
||||
return;
|
||||
|
||||
@ -13,7 +13,7 @@ using YuncangTrace.LocalService.Services.Hik;
|
||||
namespace YuncangTrace.LocalService.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 本机 WebSocket 服务(只监听 127.0.0.1,默认端口 <b>17301</b>)
|
||||
/// 本机 WebSocket 服务(只监听 127.0.0.1,默认端口 <b>16001</b>)
|
||||
///
|
||||
/// 给网页的实时预览 / 云台 / 拉通道用:以前走 HTTP(先 POST 建会话、再用 <img> 拉 MJPEG),
|
||||
/// 跨域/代理/多标签场景下都要多一次请求,而且浏览器对 MJPEG 的复用不总是如意;WS 下一条连接可以:
|
||||
@ -40,7 +40,7 @@ public sealed class LocalWsServer : IDisposable
|
||||
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;
|
||||
return int.TryParse(raw, out var port) && port is > 0 and < 65536 ? port : 16001;
|
||||
}
|
||||
|
||||
/// <summary>RFC 6455 规定的握手固定串</summary>
|
||||
@ -121,7 +121,7 @@ public sealed class LocalWsServer : IDisposable
|
||||
|
||||
private async Task HandleContextAsync(LocalHttpRequest request, LocalHttpResponse response)
|
||||
{
|
||||
// 非 WS 请求:给网页/排障一个轻量探活(浏览器直接打开 ws://127.0.0.1:17301/ 就看这个)
|
||||
// 非 WS 请求:给网页/排障一个轻量探活(浏览器直接打开 ws://127.0.0.1:16001/ 就看这个)
|
||||
if (!request.IsWebSocketRequest)
|
||||
{
|
||||
await WriteProbeAsync(response).ConfigureAwait(false);
|
||||
|
||||
@ -11,7 +11,7 @@ namespace YuncangTrace.LocalService.Services;
|
||||
/// 单实例 + 参数转发(命名管道)
|
||||
///
|
||||
/// 场景:窗口已经开着,用户又点了一次 WMS 页面上的「查看打包视频」→ 系统按协议再启动一次本程序。
|
||||
/// 这时第二个实例**不应该**去抢 17300 端口,而是把 `yuncang://open?code=xxx` 通过管道送给第一个实例,
|
||||
/// 这时第二个实例**不应该**去抢 16000 端口,而是把 `yuncang://open?code=xxx` 通过管道送给第一个实例,
|
||||
/// 由它把窗口激活并查询那个运单号。
|
||||
/// </summary>
|
||||
public sealed class SingleInstance : IDisposable
|
||||
|
||||
@ -68,13 +68,12 @@
|
||||
</DockPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 发现到的设备(状态 + 按钮都在标题行) -->
|
||||
<!-- 发现到的设备:扫描开关在标题行,「添加」在每行的操作列(列表会刷新,靠选中项不可靠) -->
|
||||
<DockPanel Grid.Row="1" Margin="0,10,0,6" LastChildFill="False">
|
||||
<TextBlock DockPanel.Dock="Left" Text="发现到的设备(局域网 UDP 48899)" FontWeight="SemiBold"
|
||||
VerticalAlignment="Center" />
|
||||
<StackPanel DockPanel.Dock="Left" Orientation="Horizontal" Margin="12,0,0,0">
|
||||
<ToggleButton x:Name="DiscoverToggle" Content="开始扫描" Padding="10,3" Click="Discover_Toggle" />
|
||||
<Button x:Name="AddButton" Content="添加为通道" Padding="10,3" Margin="8,0,0,0" Click="Add_Click" />
|
||||
</StackPanel>
|
||||
<TextBlock x:Name="DiscoverStatusText" DockPanel.Dock="Right" Foreground="{StaticResource MutedBrush}"
|
||||
VerticalAlignment="Center" HorizontalAlignment="Right" TextTrimming="CharacterEllipsis"
|
||||
@ -98,6 +97,14 @@
|
||||
<GridViewColumn Header="MAC" Width="130" DisplayMemberBinding="{Binding Mac}" />
|
||||
<GridViewColumn Header="型号" Width="90" DisplayMemberBinding="{Binding Model}" />
|
||||
<GridViewColumn Header="版本" Width="90" DisplayMemberBinding="{Binding Version}" />
|
||||
<GridViewColumn Header="操作" Width="90">
|
||||
<GridViewColumn.CellTemplate>
|
||||
<DataTemplate>
|
||||
<Button Content="添加" Padding="10,2" Click="AddRow_Click"
|
||||
ToolTip="把这台设备添加为扫码通道(弹窗里再定通道号与设备名)" />
|
||||
</DataTemplate>
|
||||
</GridViewColumn.CellTemplate>
|
||||
</GridViewColumn>
|
||||
</GridView>
|
||||
</ListView.View>
|
||||
</ListView>
|
||||
|
||||
@ -89,11 +89,9 @@ public partial class ScanTabView : UserControl
|
||||
}
|
||||
|
||||
var discovered = AgentFiles.LoadDiscovered();
|
||||
_allDevices.Clear();
|
||||
foreach (var item in discovered)
|
||||
{
|
||||
_allDevices.Add(new DiscoveredDevice(item.Mac, item.Ip, item.HostName, item.Model, item.Firmware, "online"));
|
||||
}
|
||||
SyncDevices(_allDevices, discovered
|
||||
.Select(item => new DiscoveredDevice(item.Mac, item.Ip, item.HostName, item.Model, item.Firmware, "online"))
|
||||
.ToList());
|
||||
|
||||
Refresh();
|
||||
}
|
||||
@ -215,11 +213,15 @@ public partial class ScanTabView : UserControl
|
||||
private void ApplyDeviceFilter()
|
||||
{
|
||||
var added = new HashSet<string>(_scan.Channels.Select(item => item.Mac), StringComparer.OrdinalIgnoreCase);
|
||||
var selectedMac = (DeviceList.SelectedItem as DiscoveredDevice)?.Mac;
|
||||
|
||||
_devices.Clear();
|
||||
foreach (var device in _allDevices.Where(item => !added.Contains(item.Mac)))
|
||||
// 就地合并(不能用 Clear)—— 否则每次刷新都会把用户刚选中的行清掉
|
||||
SyncDevices(_devices, _allDevices.Where(item => !added.Contains(item.Mac)).ToList());
|
||||
|
||||
if (selectedMac is not null)
|
||||
{
|
||||
_devices.Add(device);
|
||||
var hit = _devices.FirstOrDefault(item => item.Mac.Equals(selectedMac, StringComparison.OrdinalIgnoreCase));
|
||||
if (hit is not null) DeviceList.SelectedItem = hit;
|
||||
}
|
||||
|
||||
var hidden = _allDevices.Count - _devices.Count;
|
||||
@ -272,31 +274,76 @@ public partial class ScanTabView : UserControl
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>发现列表变了:整表替换成服务里的当前快照(已按 MAC 去重、已踢掉掉线设备)</summary>
|
||||
/// <summary>发现列表变了:按 MAC 就地合并服务里的当前快照(已去重、已踢掉掉线设备)</summary>
|
||||
private void OnDiscoveredChanged() => Dispatcher.Invoke(() =>
|
||||
{
|
||||
var latest = _scan.DiscoveredDevices;
|
||||
|
||||
_allDevices.Clear();
|
||||
foreach (var device in latest) _allDevices.Add(device);
|
||||
|
||||
SyncDevices(_allDevices, _scan.DiscoveredDevices);
|
||||
ApplyDeviceFilter();
|
||||
});
|
||||
|
||||
private async void Add_Click(object sender, RoutedEventArgs e)
|
||||
/// <summary>
|
||||
/// 按 MAC 就地同步集合:能复用的对象不重建。
|
||||
///
|
||||
/// 发现列表每 3 秒刷一次,以前是 `Clear()` 后整表重填 —— ListView 的选中项会跟着被清空,
|
||||
/// 现场表现就是「列表一直在刷新,设备根本选不中」。就地合并后选中项、滚动位置都能保住。
|
||||
/// </summary>
|
||||
private static void SyncDevices(ObservableCollection<DiscoveredDevice> target, IReadOnlyList<DiscoveredDevice> latest)
|
||||
{
|
||||
if (DeviceList.SelectedItem is not DiscoveredDevice device)
|
||||
var wanted = new HashSet<string>(latest.Select(item => item.Mac), StringComparer.OrdinalIgnoreCase);
|
||||
for (var index = target.Count - 1; index >= 0; index--)
|
||||
{
|
||||
MessageBox.Show(Window.GetWindow(this)!, "请先在下面的列表里选中一台设备", "添加通道",
|
||||
MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
return;
|
||||
if (!wanted.Contains(target[index].Mac)) target.RemoveAt(index);
|
||||
}
|
||||
|
||||
// 先让用户定通道号 + 设备名(与 AndroidScanCenter 的添加流程一致)
|
||||
for (var index = 0; index < latest.Count; index++)
|
||||
{
|
||||
var device = latest[index];
|
||||
if (index < target.Count && target[index].Mac.Equals(device.Mac, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// 内容没变就保留原对象(ListView 里的行不会被重建)
|
||||
if (!target[index].Equals(device)) target[index] = device;
|
||||
continue;
|
||||
}
|
||||
|
||||
var existing = -1;
|
||||
for (var probe = index; probe < target.Count; probe++)
|
||||
{
|
||||
if (target[probe].Mac.Equals(device.Mac, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
existing = probe;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (existing >= 0) target.Move(existing, index);
|
||||
else target.Insert(index, device);
|
||||
|
||||
if (!target[index].Equals(device)) target[index] = device;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>列表行里的「添加」:设备来自该行的 DataContext,不依赖选中项(刷新时选中会丢)</summary>
|
||||
private async void AddRow_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (sender is not FrameworkElement element || element.DataContext is not DiscoveredDevice device) return;
|
||||
|
||||
if (element is Button button) button.IsEnabled = false;
|
||||
try
|
||||
{
|
||||
await AddDeviceAsync(device);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (element is Button restore) restore.IsEnabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>添加一台发现到的设备为通道(弹窗定通道号 + 设备名,与 AndroidScanCenter 一致)</summary>
|
||||
private async Task AddDeviceAsync(DiscoveredDevice device)
|
||||
{
|
||||
var dialog = new AddChannelWindow(device, _scan.Channels) { Owner = Window.GetWindow(this) };
|
||||
if (dialog.ShowDialog() != true) return;
|
||||
|
||||
AddButton.IsEnabled = false;
|
||||
AddChannelWindow_ShowStage($"正在添加通道 {dialog.ChannelNumber}…");
|
||||
try
|
||||
{
|
||||
@ -335,10 +382,6 @@ public partial class ScanTabView : UserControl
|
||||
MessageBox.Show(Window.GetWindow(this)!, $"添加通道失败:{ex.Message}", "添加通道",
|
||||
MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
AddButton.IsEnabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>添加通道过程中的进度文案(回到界面线程再写控件)</summary>
|
||||
|
||||
@ -42,7 +42,7 @@
|
||||
<ServerBaseUrl Condition="'$(Configuration)' == 'Debug' and '$(ServerBaseUrl)' == ''">http://127.0.0.1:7300</ServerBaseUrl>
|
||||
<ServerBaseUrl Condition="'$(Configuration)' == 'Release' and '$(ServerBaseUrl)' == ''">https://packs.example.com</ServerBaseUrl>
|
||||
|
||||
<Version>1.0.112</Version>
|
||||
<Version>1.0.162</Version>
|
||||
<Product>云仓视频溯源软件</Product>
|
||||
<Company>云仓</Company>
|
||||
<AssemblyTitle>云仓视频溯源软件(本机服务)</AssemblyTitle>
|
||||
|
||||
@ -12,7 +12,7 @@
|
||||
3. 关掉正在运行的软件(含单文件自解压出来的真实进程);
|
||||
4. 启动**旧版本**,并设置 YUNCANG_AUTO_UPDATE=1(更新窗口出现后自动开始下载);
|
||||
5. 轮询安装目录的 ProductVersion,直到变成目标版本(或超时);
|
||||
6. 检查本机服务 17300 是否有响应、进程是否已恢复。
|
||||
6. 检查本机服务 16000 是否有响应、进程是否已恢复。
|
||||
|
||||
.PARAMETER TimeoutSeconds
|
||||
等更新完成的最长时间,默认 180 秒。
|
||||
@ -112,16 +112,16 @@ $probeDeadline = (Get-Date).AddSeconds(60)
|
||||
$localCode = $null
|
||||
$processes = @()
|
||||
while ((Get-Date) -lt $probeDeadline) {
|
||||
$localCode = & curl.exe -s -o NUL -w "%{http_code}" --max-time 3 "http://127.0.0.1:17300/api/query/"
|
||||
$localCode = & curl.exe -s -o NUL -w "%{http_code}" --max-time 3 "http://127.0.0.1:16000/api/query/"
|
||||
$processes = @(Get-CimInstance Win32_Process | Where-Object { $_.Name -like '*Yuncang*' })
|
||||
if ($processes.Count -gt 0 -and $localCode -and $localCode -ne '000') { break }
|
||||
Start-Sleep -Seconds 3
|
||||
}
|
||||
|
||||
if ($localCode -and $localCode -ne '000') {
|
||||
Write-Host "✔ 本机服务 17300 有响应(HTTP $localCode)" -ForegroundColor Green
|
||||
Write-Host "✔ 本机服务 16000 有响应(HTTP $localCode)" -ForegroundColor Green
|
||||
} else {
|
||||
Write-Host "✘ 本机服务 17300 无响应" -ForegroundColor Red
|
||||
Write-Host "✘ 本机服务 16000 无响应" -ForegroundColor Red
|
||||
}
|
||||
|
||||
if ($processes.Count -gt 0) {
|
||||
|
||||
@ -1,7 +1,9 @@
|
||||
# native\ffmpeg —— 内置 ffmpeg(随安装包一起发)
|
||||
|
||||
> **当前内置**:`ffmpeg version 9.0.2-essentials_build`(gyan.dev),100.5 MB,静态单文件,
|
||||
> 含 `libx264`(合并要重新编码)。安装包里就是这一份,客户机不需要自己装 ffmpeg。
|
||||
> 含 `libx264`(合并要重新编码),也带 `h264_qsv` / `h264_nvenc` / `h264_amf` 硬件编码器
|
||||
> (合并时优先用核显/独显编码,见 [../../README.md](../../README.md) 的「合并用的编码器」)。
|
||||
> 安装包里就是这一份,客户机不需要自己装 ffmpeg。
|
||||
|
||||
## 为什么放在这里
|
||||
|
||||
|
||||
@ -265,11 +265,11 @@ npx --yes http-server extension/test -p 7310 # → http://127.0.0.1:7310/wms
|
||||
| `storage` | 存下发下来的配置(优先 `storage.sync`,超 8KB 自动退到 `storage.local`) |
|
||||
| `alarms` | 每 5 分钟定时拉配置(MV3 的 service worker 会被回收,不能用 `setInterval`) |
|
||||
| `host_permissions: https://pack.wms.gztbyc.com/*` | 拉 `GET /api/web/extension/config` |
|
||||
| `host_permissions: http(s)://localhost:17300/*` | 探测本机软件是否在跑(协议唤起兜底) |
|
||||
| `host_permissions: http(s)://localhost:16000/*` | 探测本机软件是否在跑(协议唤起兜底) |
|
||||
| content script `matches: http(s)://*/*` | 需要注入任意第三方系统,无法预先枚举域名 |
|
||||
|
||||
- 不请求 `tabs` / `scripting` / `cookies`,**不读页面 cookie**;唯一的出站请求就是上面那个配置接口
|
||||
(以及本机 17300 的探测)。点击只是把算好的 URL 交给 `chrome.tabs.create` / `chrome.windows.create`。
|
||||
(以及本机 16000 的探测)。点击只是把算好的 URL 交给 `chrome.tabs.create` / `chrome.windows.create`。
|
||||
- 注入走隔离世界(ISOLATED),不注入页面上下文,不受宿主页 CSP 影响。
|
||||
- 想收窄范围:改 `manifest.json` 里 `content_scripts[0].matches` 为具体域名(如 `https://wms.wms.gztbyc.com/*`),
|
||||
重新加载扩展即可;规则层面的范围由「生效站点」控制。
|
||||
|
||||
@ -117,7 +117,7 @@ Policy: https://pack.wms.gztbyc.com/extension-privacy.html
|
||||
| `alarms` | 每 5 分钟拉取一次配置,保证管理员改完尽快生效。 | Periodic (5 min) refresh of the read-only configuration. |
|
||||
| `content_scripts` 全站(`http://*/*`, `https://*/*`) | 客户的 WMS 域名/内网地址无法预知,需在页面上识别运单号;实际只在白名单站点工作,其它站点立即退出且不读取 DOM。 | Customers' WMS hosts cannot be enumerated in advance. Matching only runs on an allow-listed site; otherwise the script exits without reading the DOM. |
|
||||
| `host_permissions: https://pack.wms.gztbyc.com/*` | 只用于拉取只读配置与最新客户端版本信息。 | Fetches read-only configuration and the latest client version info. |
|
||||
| `host_permissions: http://localhost:17300/*`、`http://127.0.0.1:17300/*` | 与本机安装的桌面客户端通信(判断是否安装、传递运单号)。 | Talks to the desktop client installed on the same machine (availability probe and tracking-number hand-off). |
|
||||
| `host_permissions: http://localhost:16000/*`、`http://127.0.0.1:16000/*` | 与本机安装的桌面客户端通信(判断是否安装、传递运单号)。 | Talks to the desktop client installed on the same machine (availability probe and tracking-number hand-off). |
|
||||
|
||||
**数据使用声明(Data usage 表单)**:全部选「不收集」——
|
||||
只做本地匹配;不收集浏览历史、页面内容、个人身份信息、位置、财务信息;
|
||||
@ -166,7 +166,7 @@ Policy: https://pack.wms.gztbyc.com/extension-privacy.html
|
||||
## 8. 提交时逐字段对照表(Package 上传之后)
|
||||
|
||||
上传包后,`Packages` 那张表应显示:`YuncangTraceExtension-<version>.zip`、版本号、**Status = Complete**、
|
||||
权限识别为 `storage, alarms, http://localhost:17300/*, http://127.0.0.1:17300/*, https://pack.wms.gztbyc.com/*`。
|
||||
权限识别为 `storage, alarms, http://localhost:16000/*, http://127.0.0.1:16000/*, https://pack.wms.gztbyc.com/*`。
|
||||
|
||||
> `Languages in package:` 为空是**正常**的(包内没有 `_locales` 多语言资源);商店页面的语言在
|
||||
> Store listing 里单独选,不影响审核。
|
||||
|
||||
@ -15,8 +15,8 @@
|
||||
"permissions": ["storage", "alarms"],
|
||||
|
||||
"host_permissions": [
|
||||
"http://localhost:17300/*",
|
||||
"http://127.0.0.1:17300/*",
|
||||
"http://localhost:16000/*",
|
||||
"http://127.0.0.1:16000/*",
|
||||
"https://pack.wms.gztbyc.com/*"
|
||||
],
|
||||
|
||||
|
||||
@ -73,13 +73,13 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
|
||||
*
|
||||
* 为什么不去看「页面有没有失焦」:软件已经在跑时,协议只是把参数转给已有实例,
|
||||
* 窗口可能不抢焦点;冷启动也可能超过几秒 —— 两种都会误报「没打开」。
|
||||
* 但软件只要在跑就一定监听 17300,**任何 HTTP 响应(200/400/401)都算成功**。
|
||||
* 但软件只要在跑就一定监听 16000,**任何 HTTP 响应(200/400/401)都算成功**。
|
||||
*/
|
||||
async function probeLocalService(timeoutMs = 1500) {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
try {
|
||||
const res = await fetch('http://localhost:17300/api/query/', {
|
||||
const res = await fetch('http://localhost:16000/api/query/', {
|
||||
cache: 'no-store',
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
@ -248,7 +248,7 @@
|
||||
window.addEventListener('blur', onLeave);
|
||||
document.addEventListener('visibilitychange', onLeave);
|
||||
|
||||
// 更可靠的判据:本机服务是否有响应(软件在跑就一定监听 17300)。
|
||||
// 更可靠的判据:本机服务是否有响应(软件在跑就一定监听 16000)。
|
||||
// 仅看「页面失焦」会误报:软件本来就在跑时只是转发参数,窗口不一定抢焦点。
|
||||
const timer = setInterval(async () => {
|
||||
if (settled) return;
|
||||
|
||||
@ -3,10 +3,10 @@
|
||||
# 生产由后端同源托管页面与 /api,所以 API_BASE 留空即可。
|
||||
VITE_API_BASE=
|
||||
|
||||
# 本机桌面端约定:yuncang:// 协议 + HTTP 17300 + WebSocket 17301
|
||||
# 本机桌面端约定:yuncang:// 协议 + HTTP 16000 + WebSocket 16001
|
||||
VITE_APP_PROTOCOL=yuncang
|
||||
VITE_LOCAL_SERVICE=http://localhost:17300
|
||||
VITE_LOCAL_WS=ws://127.0.0.1:17301/
|
||||
VITE_LOCAL_SERVICE=http://localhost:16000
|
||||
VITE_LOCAL_WS=ws://127.0.0.1:16001/
|
||||
|
||||
# /download/version.json 取不到时的兜底安装包地址(留空则只依赖 version.json)
|
||||
VITE_SOFTWARE_DOWNLOAD_URL=
|
||||
|
||||
@ -53,7 +53,7 @@
|
||||
</tr>
|
||||
<tr>
|
||||
<td>匹配到的运单号</td>
|
||||
<td>当你点击该运单号时,运单号会通过本机回环地址 <code>http://localhost:17300</code>
|
||||
<td>当你点击该运单号时,运单号会通过本机回环地址 <code>http://localhost:16000</code>
|
||||
交给<strong>同一台电脑上</strong>已安装的「云仓视频溯源」桌面客户端(不经过互联网)。
|
||||
若未安装客户端,则按管理员配置的模板在浏览器里打开溯源页面。</td>
|
||||
</tr>
|
||||
@ -88,7 +88,7 @@
|
||||
因此需要在页面上识别运单号。<strong>只有在管理员配置的站点白名单内才会工作</strong>;
|
||||
其它站点上脚本立即退出,不读取也不改动页面。</td></tr>
|
||||
<tr><td><code>https://pack.wms.gztbyc.com</code></td><td>拉取上述只读配置与客户端版本信息。</td></tr>
|
||||
<tr><td><code>http://localhost:17300</code>、<code>http://127.0.0.1:17300</code></td>
|
||||
<tr><td><code>http://localhost:16000</code>、<code>http://127.0.0.1:16000</code></td>
|
||||
<td>与本机安装的桌面客户端通信(判断是否已安装、传递运单号)。</td></tr>
|
||||
</table>
|
||||
|
||||
|
||||
@ -1,19 +1,19 @@
|
||||
/**
|
||||
* 本机软件 HTTP 客户端(17300)
|
||||
* 本机软件 HTTP 客户端(16000)
|
||||
*
|
||||
* 现在 HTTP 只负责**低频、无状态**的事,剩三个接口:
|
||||
* - `GET /api/query/{code}` 查信息,**同时返回服务/登录状态**(没登录回 401 `state:need-login`)
|
||||
* - `POST /api/activate-login` 把本机软件的登录窗/主界面叫到前台
|
||||
* - `POST /api/playback/download` 按运单下载录像
|
||||
*
|
||||
* ⚠️ 海康相关(拉通道 / 实时预览 / 云台 / 满帧率窗口)**全部走 WebSocket 17301**,
|
||||
* ⚠️ 海康相关(拉通道 / 实时预览 / 云台 / 满帧率窗口)**全部走 WebSocket 16001**,
|
||||
* 见 {@link ./localWs.ts};这里只留通道列表的类型,供那边的返回值复用。
|
||||
*
|
||||
* 为什么不再单独做探活接口:探活通过 ≠ 真正查询时软件还在(用户可能中途退了),
|
||||
* 两次请求之间的状态可能已经变了。合并成一个接口后,页面只发一次请求就能决定
|
||||
* 「展示结果」还是「提示可以唤起」。
|
||||
*
|
||||
* ⚠️ 这是**跨域**请求(页面同源是我们的站点,目标是 localhost:17300):
|
||||
* ⚠️ 这是**跨域**请求(页面同源是我们的站点,目标是 localhost:16000):
|
||||
* 本机软件必须允许 CORS(`Access-Control-Allow-Origin` 放行站点来源),否则浏览器会拦掉,
|
||||
* 表现和「软件没启动」一样 —— 页面统一提示「服务暂不可用」。
|
||||
*
|
||||
@ -21,7 +21,7 @@
|
||||
*/
|
||||
|
||||
/** 本机服务地址(去掉末尾斜杠) */
|
||||
export const LOCAL_BASE = ((import.meta.env.VITE_LOCAL_SERVICE as string | undefined) || 'http://localhost:17300')
|
||||
export const LOCAL_BASE = ((import.meta.env.VITE_LOCAL_SERVICE as string | undefined) || 'http://localhost:16000')
|
||||
.replace(/\/+$/, '');
|
||||
|
||||
/** 本机服务返回非 2xx / 超时 / 跨域失败时抛它 */
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
/**
|
||||
* 本机软件的 WebSocket 通道(实时预览 / 云台 / 拉通道)
|
||||
*
|
||||
* 端口约定:本机桌面端 `LocalWsServer` 监听 **17301**(可用 `VITE_LOCAL_WS` 覆盖)。
|
||||
* 端口约定:本机桌面端 `LocalWsServer` 监听 **16001**(可用 `VITE_LOCAL_WS` 覆盖)。
|
||||
*
|
||||
* 协议(服务端见 `desktop/Services/LocalWsServer.cs`):
|
||||
* - 文本:`{ id, action, ... }` → 回复 `{ id, ok, data | message }`
|
||||
@ -16,7 +16,7 @@ import { launchApp } from '@/api/local';
|
||||
import type { HikChannelsPayload } from '@/api/local';
|
||||
|
||||
/** WS 地址 */
|
||||
export const LOCAL_WS = (import.meta.env.VITE_LOCAL_WS as string | undefined) || 'ws://127.0.0.1:17301/';
|
||||
export const LOCAL_WS = (import.meta.env.VITE_LOCAL_WS as string | undefined) || 'ws://127.0.0.1:16001/';
|
||||
|
||||
/** 云台连续动作(方向 / 变倍 / 聚焦 / 光圈 / 自动扫描) */
|
||||
export type WsPtzCommand =
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
/**
|
||||
* 「连接不上本机软件」统一提示窗
|
||||
*
|
||||
* 网页的拉通道 / 实时预览 / 云台都依赖本机软件(HTTP 17300 + WebSocket 17301),
|
||||
* 网页的拉通道 / 实时预览 / 云台都依赖本机软件(HTTP 16000 + WebSocket 16001),
|
||||
* 浏览器没法判断到底是「没安装」还是「装了没启动」,所以统一弹这个:
|
||||
* - **启动本机软件**:用 `yuncang://` 协议唤起,再等 WS 连上(连上就 emit `ready` 让调用方重试);
|
||||
* - **立即下载**:后端 `version.json` 里的最新安装包(拿不到就退回环境变量兜底地址)。
|
||||
@ -25,7 +25,7 @@ const props = withDefaults(defineProps<{
|
||||
message?: string;
|
||||
/** 唤起后最多等多久(毫秒) */
|
||||
waitMs?: number;
|
||||
/** 探活方式:ws = WebSocket 17301(预览类);http = HTTP 17300 根路径(查件页,兼容老版本) */
|
||||
/** 探活方式:ws = WebSocket 16001(预览类);http = HTTP 16000 根路径(查件页,兼容老版本) */
|
||||
probe?: 'ws' | 'http';
|
||||
}>(), {
|
||||
title: '连接不上本机软件',
|
||||
@ -56,7 +56,7 @@ watch(() => props.open, async open => {
|
||||
|
||||
async function probeReady(): Promise<boolean> {
|
||||
if (props.probe === 'http') {
|
||||
// 查件页走 HTTP 17300(老版本软件也有这个端口,但不一定有 WS)
|
||||
// 查件页走 HTTP 16000(老版本软件也有这个端口,但不一定有 WS)
|
||||
const deadline = Date.now() + props.waitMs;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
|
||||
@ -3,18 +3,33 @@
|
||||
* 通用弹窗:遮罩 + 居中面板 + 标题栏 + 底部按钮插槽
|
||||
*
|
||||
* 用 Teleport 挂到 body,避免被列表容器的 `overflow: hidden` 裁掉。
|
||||
*
|
||||
* **点遮罩默认不关闭**:弹窗里基本都在填表单/编辑内容,
|
||||
* 手一滑点外面就把整屏输入丢掉太容易发生(编辑中尤其明显)。
|
||||
* 只有纯展示类弹窗(例如实时预览)才显式加 `mask-closable`。
|
||||
*/
|
||||
withDefaults(defineProps<{ open: boolean; title?: string; width?: string }>(), {
|
||||
const props = withDefaults(defineProps<{
|
||||
open: boolean;
|
||||
title?: string;
|
||||
width?: string;
|
||||
/** 点遮罩是否关闭(默认 false) */
|
||||
maskClosable?: boolean;
|
||||
}>(), {
|
||||
title: '',
|
||||
width: '560px',
|
||||
maskClosable: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{ (e: 'close'): void }>();
|
||||
|
||||
function onMaskClick() {
|
||||
if (props.maskClosable) emit('close');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div v-if="open" class="modal-mask" @click.self="emit('close')">
|
||||
<div v-if="open" class="modal-mask" @click.self="onMaskClick">
|
||||
<div class="modal-box" :style="{ width }">
|
||||
<header class="modal-head">
|
||||
<strong>{{ title }}</strong>
|
||||
|
||||
@ -24,7 +24,7 @@ const routes: RouteRecordRaw[] = [
|
||||
// 手机扫码后打开:确认登录(公开)
|
||||
{ path: '/wechat', name: 'wechat-confirm', component: () => import('@/views/WechatConfirmView.vue'), meta: { public: true, bare: true } },
|
||||
// 本机软件(打印服务)公共页:**不需要登录**,Chrome 插件打开 `/local?code=<运单号>`
|
||||
// 页面自己查 http://localhost:17300/api/query/{code}(状态和结果一起回来),
|
||||
// 页面自己查 http://localhost:16000/api/query/{code}(状态和结果一起回来),
|
||||
// 没启动就提示下载/唤起,没登录就唤起软件登录
|
||||
{
|
||||
path: '/local',
|
||||
|
||||
@ -29,8 +29,8 @@ export interface SoftwareRelease {
|
||||
/** 兜底下载地址(后端没放 version.json 时用) */
|
||||
const FALLBACK_DOWNLOAD_URL = (import.meta.env.VITE_SOFTWARE_DOWNLOAD_URL as string | undefined) || '';
|
||||
|
||||
// 探活统一走 `waitForLocalWs()`(api/localWs.ts):预览/云台/拉通道都在 17301,
|
||||
// 还走 HTTP 17300 探活会出现「HTTP 起来了但预览通道没起来」的错位。
|
||||
// 探活统一走 `waitForLocalWs()`(api/localWs.ts):预览/云台/拉通道都在 16001,
|
||||
// 还走 HTTP 16000 探活会出现「HTTP 起来了但预览通道没起来」的错位。
|
||||
|
||||
/** 用自定义协议唤起本机软件(必须在用户手势里调用) */
|
||||
export function launchLocalSoftware(): void {
|
||||
|
||||
@ -341,7 +341,7 @@ async function openPreview(camera: Camera, streamType = previewStreamType.value)
|
||||
// 子码流走 SDK 取流 + PlayM4 解码(640×360、25fps)。
|
||||
const mode = streamType === 0 ? 'ffmpeg' : 'stream';
|
||||
|
||||
// 预览**只走本机 WebSocket(17301)**:二进制 JPEG 帧,一条连接可同时推多路。
|
||||
// 预览**只走本机 WebSocket(16001)**:二进制 JPEG 帧,一条连接可同时推多路。
|
||||
try {
|
||||
await localWs.connect(2500);
|
||||
} catch {
|
||||
@ -715,7 +715,7 @@ async function doPreset(action: 'set' | 'goto' | 'clear') {
|
||||
</template>
|
||||
</ModalBox>
|
||||
|
||||
<ModalBox :open="previewOpen" title="实时预览" width="820px" @close="closePreview">
|
||||
<ModalBox :open="previewOpen" title="实时预览" width="820px" mask-closable @close="closePreview">
|
||||
<div class="preview-head">
|
||||
<strong>{{ previewCamera?.name || '通道 ' + previewCamera?.channelNo }}</strong>
|
||||
<span class="hint">
|
||||
|
||||
@ -312,7 +312,7 @@ onMounted(load);
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- 连不上本机软件:统一提示窗(启动 / 下载);查件页用 HTTP 17300 探活,兼容老版本 -->
|
||||
<!-- 连不上本机软件:统一提示窗(启动 / 下载);查件页用 HTTP 16000 探活,兼容老版本 -->
|
||||
<LocalServiceGate
|
||||
:open="gateOpen"
|
||||
title="服务暂不可用"
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
* NVR 录像机管理
|
||||
*
|
||||
* 两段式添加摄像头:
|
||||
* 1. 点「拉取通道」:**页面直接调本机软件**(WebSocket 17301 的 `get_channels`),
|
||||
* 1. 点「拉取通道」:**页面直接调本机软件**(WebSocket 16001 的 `get_channels`),
|
||||
* 走 8000 私有协议登录设备拿到通道列表;已存过密码的直接就拉,不用再点一次按钮;
|
||||
* 2. 勾选通道 → 提交到后端 `/api/web/nvrs/:id/channels` 落库成摄像头。
|
||||
*
|
||||
|
||||
@ -911,7 +911,7 @@ onBeforeUnmount(() => {
|
||||
</ModalBox>
|
||||
|
||||
<!-- 合并输出预览(按布局合成的输出画面) -->
|
||||
<ModalBox :open="showMergedPreview" :title="`合并输出预览 · ${previewDetail?.name || previewDetail?.code || ''}`" width="1000px" @close="showMergedPreview = false">
|
||||
<ModalBox :open="showMergedPreview" :title="`合并输出预览 · ${previewDetail?.name || previewDetail?.code || ''}`" width="1000px" mask-closable @close="showMergedPreview = false">
|
||||
<div v-if="previewError" class="alert alert-error">{{ previewError }}</div>
|
||||
<p v-if="previewLoading" class="hint">加载布局…</p>
|
||||
<template v-else-if="previewDetail">
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user