修复设备WebSocket重复连接并改进应用分配为单选

- WebSocket: 新设备连接前关闭同设备的旧连接,避免重复连接
- 设备页: 分配内容由多选改为单选(radio),并加载已分配应用
- ApiClient: 新增 GetDeviceContentAsync 获取设备已分配内容
- .gitignore: 简化 bin/obj 规则,新增 data.db/ref/temp

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Zhanghu
2026-07-31 17:30:14 +08:00
parent 13e6046b41
commit bd5e7b91d3
5 changed files with 78 additions and 22 deletions

15
.gitignore vendored
View File

@@ -1,10 +1,5 @@
src/DRS9.Dashboard.Application/bin/
src/DRS9.Dashboard.Application/obj/
src/DRS9.Dashboard.Domain/bin/
src/DRS9.Dashboard.Domain/obj/
src/DRS9.Dashboard.Infrastructure/bin/
src/DRS9.Dashboard.Infrastructure/obj/
src/DRS9.Dashboard.Server/bin/
src/DRS9.Dashboard.Server/obj/
src/DRS9.Dashboard.Server/dashboard.db-shm
src/DRS9.Dashboard.Server/dashboard.db-wal
*/*/bin/
*/*/obj/
src/DRS9.Dashboard.Server/data.db*
ref
temp

View File

@@ -115,4 +115,31 @@ public class DashboardWebSocketManager
{
return GetConnectionsByDevice(deviceId).Count();
}
/// <summary>
/// 关闭指定设备的所有现有连接
/// </summary>
public async Task CloseDeviceConnectionsAsync(int deviceId, string? excludeConnectionId = null)
{
var existingConnections = GetConnectionsByDevice(deviceId).ToList();
foreach (var conn in existingConnections)
{
if (conn.ConnectionId != excludeConnectionId && conn.WebSocket.State == WebSocketState.Open)
{
_logger.LogInformation("Closing existing connection for device {DeviceId}: {ConnectionId}", deviceId, conn.ConnectionId);
try
{
await conn.WebSocket.CloseAsync(
WebSocketCloseStatus.NormalClosure,
"New connection established",
CancellationToken.None);
_connections.TryRemove(conn.ConnectionId, out _);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error closing connection {ConnectionId}", conn.ConnectionId);
}
}
}
}
}

View File

@@ -255,14 +255,14 @@
</div>
}
<!-- 分配内容 Modal -->
<!-- 分配应用 Modal -->
@if (_assigningDevice != null)
{
<div class="modal fade show d-block" style="background-color: rgba(0,0,0,0.5)" tabindex="-1" @onclick="CloseAssignModal">
<div class="modal-dialog modal-lg" @onclick:stopPropagation="true">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">分配内容 - @_assigningDevice.DeviceName</h5>
<h5 class="modal-title">分配应用 - @_assigningDevice.DeviceName</h5>
<button type="button" class="btn-close" @onclick="CloseAssignModal"></button>
</div>
<div class="modal-body">
@@ -274,20 +274,23 @@
}
else if (_applications.Count == 0)
{
<p class="text-muted">暂无可用内容</p>
<p class="text-muted">暂无可用应用</p>
}
else
{
<div class="row">
@foreach (var app in _applications)
{
var index = app.Id; // 闭包修复
<div class="col-md-4 mb-2">
<div class="card">
<div class="card-body">
<div class="form-check">
<input type="checkbox" class="form-check-input"
<input type="radio" class="form-check-input" name="app-selection"
id="app-@app.Id"
@bind="@_selectedAppIds[app.Id]" />
value="@app.Id"
@onchange="@((ChangeEventArgs e) => _selectedAppId = int.Parse(e.Value?.ToString() ?? "0"))"
checked="@(_selectedAppId == app.Id)" />
<label class="form-check-label" for="app-@app.Id">
@app.Name
</label>
@@ -316,7 +319,7 @@
private List<ApplicationDto> _applications = new();
private DeviceDto? _editingDevice;
private DeviceDto? _assigningDevice;
private Dictionary<int, bool> _selectedAppIds = new();
private int? _selectedAppId;
private string _newGroupName = "";
private string _newGroupDesc = "";
private string _editDeviceName = "";
@@ -452,35 +455,50 @@
private async Task AssignContent(DeviceDto device)
{
_assigningDevice = device;
_selectedAppIds = _applications.ToDictionary(a => a.Id, _ => false);
_selectedAppId = null;
await LoadAssignedContent(device.Id);
}
private async Task LoadAssignedContent(int deviceId)
{
// TODO: 从 API 获取已分配的内容
var assignments = await ApiClient.GetDeviceContentAsync(deviceId);
if (assignments.Any())
{
// 获取第一个(也是唯一一个)已分配的应用ID
_selectedAppId = assignments.First().ApplicationId;
}
}
private void CloseAssignModal()
{
_assigningDevice = null;
_selectedAppIds.Clear();
_selectedAppId = null;
}
private async Task SaveAssignment()
{
if (_assigningDevice != null)
{
var selectedIds = _selectedAppIds.Where(kvp => kvp.Value).Select(kvp => kvp.Key).ToList();
List<int> selectedIds;
if (_selectedAppId.HasValue)
{
selectedIds = new List<int> { _selectedAppId.Value };
}
else
{
// 如果没有选择任何应用,清空设备的分配
selectedIds = new List<int>();
}
var success = await ApiClient.AssignContentAsync(_assigningDevice.Id, selectedIds);
if (success)
{
CloseAssignModal();
await JSRuntime.InvokeVoidAsync("alert", "内容分配成功");
await JSRuntime.InvokeVoidAsync("alert", "应用分配成功");
}
else
{
await JSRuntime.InvokeVoidAsync("alert", "内容分配失败");
await JSRuntime.InvokeVoidAsync("alert", "应用分配失败");
}
}
}

View File

@@ -31,6 +31,13 @@ public class WebSocketMiddleware
var parsedDeviceId = int.TryParse(deviceId, out var id) ? id : (int?)null;
using var webSocket = await context.WebSockets.AcceptWebSocketAsync();
// 如果这是一个已认证的设备连接,在添加新连接前先关闭该设备的旧连接
if (parsedDeviceId.HasValue)
{
await _wsManager.CloseDeviceConnectionsAsync(parsedDeviceId.Value);
}
var connection = _wsManager.AddConnection(webSocket, parsedDeviceId);
_logger.LogInformation("WebSocket connection established: {ConnectionId}", connection.ConnectionId);

View File

@@ -65,6 +65,15 @@ public class ApiClientService
return response.IsSuccessStatusCode;
}
public async Task<List<DeviceAssignmentDto>> GetDeviceContentAsync(int deviceId)
{
AddAuthHeader();
var response = await _httpClient.GetAsync($"/api/admin/devices/{deviceId}/content");
if (!response.IsSuccessStatusCode) return new List<DeviceAssignmentDto>();
var result = await response.Content.ReadFromJsonAsync<DeviceContentResponse>();
return result?.Data ?? new List<DeviceAssignmentDto>();
}
public async Task<bool> PushToDeviceAsync(int deviceId, string messageType)
{
AddAuthHeader();