GoodWe / GoodWe / Protocol.cs
Code · 344 lines · 11645 bytes
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344using System.Net;
using System.Net.Sockets;

namespace GoodWe;

public class ProtocolResponse
{
    public byte[] RawData { get; }
    private readonly ProtocolCommand? _command;
    private int _position;
    private readonly byte[] _responseData;

    public ProtocolResponse(byte[] rawData, ProtocolCommand? command)
    {
        RawData = rawData;
        _command = command;
        _responseData = command?.TrimResponse(rawData) ?? rawData;
    }

    public void Seek(int address)
    {
        _position = _command?.GetOffset(address) ?? address;
    }

    public byte[] Read(int size)
    {
        var result = new byte[size];
        Array.Copy(_responseData, _position, result, 0, size);
        _position += size;
        return result;
    }

    public byte[] ResponseData => _responseData;
}

public abstract class ProtocolCommand
{
    protected byte[] Request { get; set; }
    public int FirstAddress { get; protected set; }
    public int Value { get; protected set; }
    public Func<byte[], bool> Validator { get; protected set; }

    protected ProtocolCommand(byte[] request, Func<byte[], bool> validator)
    {
        Request = request;
        Validator = validator;
    }

    public virtual byte[] RequestBytes() => Request;

    public abstract byte[] TrimResponse(byte[] raw);
    public abstract int GetOffset(int address);

    public override string ToString() => Convert.ToHexString(Request).ToLower();
}

public class ModbusRtuCommand : ProtocolCommand
{
    public ModbusRtuCommand(byte[] request, byte cmd, ushort offset, ushort value)
        : base(request, data => Modbus.ValidateRtuResponse(data, cmd, offset, value))
    {
        FirstAddress = offset;
        Value = value;
    }

    public override byte[] TrimResponse(byte[] raw) => raw[5..^2];
    public override int GetOffset(int address) => (address - FirstAddress) * 2;
}

public class ModbusRtuReadCommand : ModbusRtuCommand
{
    public ModbusRtuReadCommand(byte commAddr, ushort offset, ushort count)
        : base(Modbus.CreateRtuRequest(commAddr, Modbus.ReadCmd, offset, count), Modbus.ReadCmd, offset, count) { }
}

public class ModbusRtuWriteCommand : ModbusRtuCommand
{
    public ModbusRtuWriteCommand(byte commAddr, ushort register, ushort value)
        : base(Modbus.CreateRtuRequest(commAddr, Modbus.WriteCmd, register, value), Modbus.WriteCmd, register, value) { }
}

public class ModbusRtuWriteMultiCommand : ModbusRtuCommand
{
    public ModbusRtuWriteMultiCommand(byte commAddr, ushort offset, byte[] values)
        : base(Modbus.CreateRtuMultiRequest(commAddr, Modbus.WriteMultiCmd, offset, values),
               Modbus.WriteMultiCmd, offset, (ushort)(values.Length / 2)) { }
}

public class ModbusTcpCommand : ProtocolCommand
{
    private static int _tcpTx = 0;
    public ModbusTcpCommand(byte[] request, byte cmd, ushort offset, ushort value)
        : base(request, data => Modbus.ValidateTcpResponse(data, cmd, offset, value))
    {
        FirstAddress = offset;
        Value = value;
    }

    public override byte[] RequestBytes()
    {
        int tx = Interlocked.Increment(ref _tcpTx) & 0xFFFF;
        if (tx == 0) tx = 1;
        Request[0] = (byte)(tx >> 8);
        Request[1] = (byte)(tx & 0xFF);
        return Request;
    }

    public override byte[] TrimResponse(byte[] raw) => raw[9..];
    public override int GetOffset(int address) => (address - FirstAddress) * 2;
}

public class ModbusTcpReadCommand : ModbusTcpCommand
{
    public ModbusTcpReadCommand(byte commAddr, ushort offset, ushort count)
        : base(Modbus.CreateTcpRequest(commAddr, Modbus.ReadCmd, offset, count), Modbus.ReadCmd, offset, count) { }
}

public class ModbusTcpWriteCommand : ModbusTcpCommand
{
    public ModbusTcpWriteCommand(byte commAddr, ushort register, ushort value)
        : base(Modbus.CreateTcpRequest(commAddr, Modbus.WriteCmd, register, value), Modbus.WriteCmd, register, value) { }
}

public abstract class InverterProtocol : IAsyncDisposable
{
    protected readonly string Host;
    protected readonly int Port;
    protected readonly byte CommAddr;
    public int Timeout { get; set; }
    public int Retries { get; set; }

    protected InverterProtocol(string host, int port, byte commAddr, int timeout, int retries)
    {
        Host = host;
        Port = port;
        CommAddr = commAddr;
        Timeout = timeout;
        Retries = retries;
    }

    public abstract Task<ProtocolResponse> SendAsync(ProtocolCommand command, CancellationToken ct = default);
    public abstract ModbusRtuReadCommand ReadCommand(ushort offset, ushort count);
    public abstract ModbusRtuWriteCommand WriteCommand(ushort register, ushort value);

    public abstract ValueTask DisposeAsync();
}

public class UdpInverterProtocol : InverterProtocol
{
    private UdpClient? _udp;
    private readonly SemaphoreSlim _lock = new(1, 1);

    public UdpInverterProtocol(string host, int port, byte commAddr, int timeout = 1, int retries = 3)
        : base(host, port, commAddr, timeout, retries) { }

    public override ModbusRtuReadCommand ReadCommand(ushort offset, ushort count) =>
        new(CommAddr, offset, count);

    public override ModbusRtuWriteCommand WriteCommand(ushort register, ushort value) =>
        new(CommAddr, register, value);

    private UdpClient GetOrCreateUdp()
    {
        if (_udp == null)
        {
            _udp = new UdpClient();
            _udp.Connect(Host, Port);
        }
        return _udp;
    }

    public override async Task<ProtocolResponse> SendAsync(ProtocolCommand command, CancellationToken ct = default)
    {
        await _lock.WaitAsync(ct);
        try
        {
            byte[]? partialData = null;
            int partialMissing = 0;

            for (int attempt = 0; attempt <= Retries; attempt++)
            {
                var udp = GetOrCreateUdp();
                var payload = command.RequestBytes();
                await udp.SendAsync(payload, payload.Length);

                using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
                cts.CancelAfter(TimeSpan.FromSeconds(Timeout));

                try
                {
                    while (true)
                    {
                        var result = await udp.ReceiveAsync(cts.Token);
                        var data = result.Buffer;

                        if (partialData != null && partialMissing == data.Length)
                        {
                            var combined = new byte[partialData.Length + data.Length];
                            partialData.CopyTo(combined, 0);
                            data.CopyTo(combined, partialData.Length);
                            data = combined;
                            partialData = null;
                            partialMissing = 0;
                        }

                        try
                        {
                            if (command.Validator(data))
                                return new ProtocolResponse(data, command);
                        }
                        catch (PartialResponseException ex)
                        {
                            partialData = data;
                            partialMissing = ex.Expected - ex.Length;
                            cts.CancelAfter(TimeSpan.FromSeconds(Timeout));
                        }
                        catch (RequestRejectedException)
                        {
                            throw;
                        }
                    }
                }
                catch (OperationCanceledException) when (!ct.IsCancellationRequested)
                {
                    // timeout — retry
                }
            }

            throw new MaxRetriesException();
        }
        finally
        {
            _lock.Release();
        }
    }

    public override ValueTask DisposeAsync()
    {
        _udp?.Dispose();
        _udp = null;
        return ValueTask.CompletedTask;
    }
}

public class TcpInverterProtocol : InverterProtocol
{
    private TcpClient? _tcp;
    private NetworkStream? _stream;
    private readonly SemaphoreSlim _lock = new(1, 1);

    public TcpInverterProtocol(string host, int port, byte commAddr, int timeout = 5, int retries = 3)
        : base(host, port, commAddr, timeout, retries) { }

    public override ModbusRtuReadCommand ReadCommand(ushort offset, ushort count) =>
        new(CommAddr, offset, count);

    public override ModbusRtuWriteCommand WriteCommand(ushort register, ushort value) =>
        new(CommAddr, register, value);

    private async Task EnsureConnectedAsync(CancellationToken ct)
    {
        if (_tcp?.Connected == true) return;
        _tcp?.Dispose();
        _tcp = new TcpClient();
        using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
        cts.CancelAfter(TimeSpan.FromSeconds(5));
        await _tcp.ConnectAsync(Host, Port, cts.Token);
        _stream = _tcp.GetStream();
    }

    public override async Task<ProtocolResponse> SendAsync(ProtocolCommand command, CancellationToken ct = default)
    {
        await _lock.WaitAsync(ct);
        try
        {
            for (int attempt = 0; attempt <= Retries; attempt++)
            {
                try
                {
                    await EnsureConnectedAsync(ct);
                    var payload = command.RequestBytes();
                    await _stream!.WriteAsync(payload, ct);

                    using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
                    cts.CancelAfter(TimeSpan.FromSeconds(Timeout));

                    var buffer = new byte[1024];
                    byte[]? partialData = null;
                    int partialMissing = 0;

                    while (true)
                    {
                        int read = await _stream.ReadAsync(buffer, cts.Token);
                        if (read == 0) throw new RequestFailedException("Connection closed");

                        byte[] data = buffer[..read];
                        if (partialData != null && partialMissing == data.Length)
                        {
                            var combined = new byte[partialData.Length + data.Length];
                            partialData.CopyTo(combined, 0);
                            data.CopyTo(combined, partialData.Length);
                            data = combined;
                            partialData = null;
                        }

                        try
                        {
                            if (command.Validator(data))
                                return new ProtocolResponse(data, command);
                        }
                        catch (PartialResponseException ex)
                        {
                            partialData = data;
                            partialMissing = ex.Expected - ex.Length;
                            cts.CancelAfter(TimeSpan.FromSeconds(Timeout));
                        }
                    }
                }
                catch (OperationCanceledException) when (!ct.IsCancellationRequested)
                {
                    _tcp?.Dispose();
                    _tcp = null;
                }
                catch (IOException)
                {
                    _tcp?.Dispose();
                    _tcp = null;
                }
            }

            throw new MaxRetriesException();
        }
        finally
        {
            _lock.Release();
        }
    }

    public override ValueTask DisposeAsync()
    {
        _tcp?.Dispose();
        return ValueTask.CompletedTask;
    }
}