|
| 1 | +using System.Net.Sockets; |
| 2 | +using System.Text; |
| 3 | + |
| 4 | +namespace Helevn.OCV.DMM |
| 5 | +{ |
| 6 | + public class OcvCtrl(string name) |
| 7 | + { |
| 8 | + /// <summary> |
| 9 | + /// 名称 |
| 10 | + /// </summary> |
| 11 | + public readonly string Name = name; |
| 12 | + private TcpClient? _tcpClient = null; |
| 13 | + public bool Connect => _tcpClient?.Connected ?? false; |
| 14 | + |
| 15 | + /// <summary> |
| 16 | + /// 小数点保留位数 |
| 17 | + /// </summary> |
| 18 | + public int Digits { get; set; } = 5; |
| 19 | + /// <summary> |
| 20 | + /// 最大值限位 |
| 21 | + /// </summary> |
| 22 | + public int LimitMaxValue { get; set; } = 99999; |
| 23 | + /// <summary> |
| 24 | + /// 最小值限位 |
| 25 | + /// </summary> |
| 26 | + public int LimitMinValue { get; set; } = -99999; |
| 27 | + /// <summary> |
| 28 | + /// 读取超时限制 |
| 29 | + /// <para/> |
| 30 | + /// ms |
| 31 | + /// </summary> |
| 32 | + public int LimitOverTime { get; set; } = 1000; |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// IP地址 |
| 36 | + /// </summary> |
| 37 | + public string IpAddress { get; set; } = "127.0.0.1"; |
| 38 | + /// <summary> |
| 39 | + /// IP端口号 |
| 40 | + /// </summary> |
| 41 | + public int IpPort { get; set; } = 502; |
| 42 | + |
| 43 | + public async Task<double> ReadAsync(byte[] cmds) |
| 44 | + { |
| 45 | + try |
| 46 | + { |
| 47 | + var stream = _tcpClient!.GetStream(); |
| 48 | + await stream.WriteAsync(cmds); |
| 49 | + byte[] rbuffer = new byte[256]; |
| 50 | + var revleng = await stream.ReadAsync(rbuffer, new CancellationTokenSource(LimitOverTime).Token); |
| 51 | + byte[] recbuffer = new byte[revleng]; |
| 52 | + for (int i = 0; i < revleng; i++) |
| 53 | + { |
| 54 | + recbuffer[i] = rbuffer[i]; |
| 55 | + } |
| 56 | + var str = Encoding.Default.GetString(recbuffer); |
| 57 | + var r = double.TryParse(str, out double v); |
| 58 | + if (!r) |
| 59 | + v = double.NaN; |
| 60 | + v = Math.Round(v, Digits); |
| 61 | + v = Math.Min(v, LimitMaxValue); |
| 62 | + v = Math.Max(v, LimitMinValue); |
| 63 | + return v; |
| 64 | + } |
| 65 | + catch |
| 66 | + { |
| 67 | + throw; |
| 68 | + } |
| 69 | + } |
| 70 | + public async Task EnsureConnectAsync() |
| 71 | + { |
| 72 | + _tcpClient ??= new TcpClient(); |
| 73 | + if (!_tcpClient.Connected) |
| 74 | + { |
| 75 | + await _tcpClient.ConnectAsync(IpAddress, IpPort); |
| 76 | + } |
| 77 | + } |
| 78 | + public Task DisposeAsync() |
| 79 | + { |
| 80 | + if (_tcpClient != null) |
| 81 | + { |
| 82 | + _tcpClient.Close(); |
| 83 | + _tcpClient.Dispose(); |
| 84 | + _tcpClient = null; |
| 85 | + } |
| 86 | + return Task.CompletedTask; |
| 87 | + } |
| 88 | + } |
| 89 | +} |
0 commit comments