wanshenmean
8 天以前 559bb7b4be83575cc5fedee98484647243c96f89
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SqlSugar;
using WIDESEAWCS_S7Simulator.Application.DTOs;
 
namespace WIDESEAWCS_S7Simulator.Application;
 
/// <summary>
/// 读取 WCS 数据库设备数据
/// </summary>
public class DatabaseDeviceService : IDisposable
{
    private readonly WcsDbOptions _options;
    private readonly ILogger<DatabaseDeviceService> _logger;
    private readonly SqlSugarScope _db;
 
    public DatabaseDeviceService(IOptions<WcsDbOptions> options, ILogger<DatabaseDeviceService> logger)
    {
        _options = options.Value;
        _logger = logger;
 
        _db = new SqlSugarScope(new ConnectionConfig
        {
            ConnectionString = _options.ConnectionString,
            DbType = DbType.SqlServer,
            IsAutoCloseConnection = true,
            InitKeyType = InitKeyType.Attribute
        });
    }
 
    /// <summary>
    /// 获取所有 SiemensS7 类型的设备
    /// </summary>
    public async Task<List<WcsDeviceDto>> GetSiemensS7DevicesAsync()
    {
        try
        {
            var devices = await _db.Queryable<WcsDeviceDto>()
                .Where(d => d.DevicePlcType == "SiemensS7")
                .ToListAsync();
            _logger.LogInformation("从数据库获取到 {Count} 个 SiemensS7 设备", devices.Count);
            return devices;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "从数据库获取设备失败");
            return new List<WcsDeviceDto>();
        }
    }
 
    /// <summary>
    /// 获取指定设备的协议列表
    /// </summary>
    public async Task<List<WcsDeviceProtocolDto>> GetDeviceProtocolsAsync(int deviceId)
    {
        try
        {
            var protocols = await _db.Queryable<WcsDeviceProtocolDto>()
                .Where(p => p.DeviceId == deviceId)
                .ToListAsync();
            return protocols;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取设备协议失败 DeviceId={DeviceId}", deviceId);
            return new List<WcsDeviceProtocolDto>();
        }
    }
 
    public void Dispose()
    {
        _db.Dispose();
    }
}