fix: 扫码结束键按设备识别、发现列表就地刷新、NVR 唯一性按主体
AndroidStation - 有的扫码枪(Newtologic DW-8200,T95MAX/Android 12)用 KEYCODE_DPAD_CENTER 当结束键, 之前只认 ENTER/TAB:结束键会落到当前焦点按钮上(一扫就进「服务设置」,焦点在 「清空记录」时还会清空记录),而且扫码只能等 50ms 超时才提交。现在按 deviceId 认 “刚发过条码字符的那台设备”,DPAD_CENTER 也算结束键,遥控器 OK 键不受影响。 - 新增「播报走本机扬声器(AV / 3.5mm)」开关(默认关):个别机型插 HDMI 时 HAL 会把 媒体声音锁在 HDMI 声卡,需要显式指定内建扬声器。 桌面端 - 发现列表改为按 MAC 就地合并,不再整表 Clear(每 3 秒一次刷新会把 ListView 的选中项 和滚动位置清掉,现场表现为“设备选不中”)。 - 「添加为通道」从标题行移到列表行内「操作」列,不再依赖选中项。 后端 - NVR 唯一键由全局 (host, port, username) 改为 (subject_id, host, port, username): 不同仓库的内网地址经常相同,之前会报「已被其他主体添加」。查重也只查本主体。 - 新增迁移 20261116010000-scope-nvr-unique-to-subject 与按主体范围的测试。 构建 - android_client/build.ps1:gradle 把 javac 的 stderr 提示写出来时,PowerShell 的 $ErrorActionPreference='Stop' 会把它当终止错误,release 包必失败;改为只以退出码判定。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
21ffb6a54f
commit
c07d5c640b
@ -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 仍保持前台、服务不被挂起。
|
||||
|
||||
|
||||
@ -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>
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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,
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
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));
|
||||
});
|
||||
});
|
||||
@ -784,7 +784,8 @@ reg query "HKCU\Software\Classes\yuncang\shell\open\command"
|
||||
|
||||
### 添加通道(设备名 + 通道号)
|
||||
|
||||
`扫描设备 → 选中 → 添加为通道` 会弹窗让用户定**通道号**与**设备名**(与 AndroidScanCenter 一致):
|
||||
在「发现到的设备」列表里点该行**「操作」列的「添加」**,会弹窗让用户定**通道号**与**设备名**(与 AndroidScanCenter 一致)。
|
||||
入口放在行内、不依赖选中项 —— 发现列表每 3 秒刷新一次,靠「先选中再点标题行按钮」会因为选中项被刷新清掉而点不到:
|
||||
|
||||
- **通道号**:`1..50` 的下拉框,已占用的号照样列出来并标注「已被 xx 占用」,选中就提示、不关框;
|
||||
默认勾在最小空号上。没有「通道号」设备字段 —— 它是**本地概念**(现场认工位),上报时就是 `channelId`。
|
||||
@ -993,16 +994,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 条`。
|
||||
|
||||
@ -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>
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user