-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsplitter.go
410 lines (361 loc) · 11.1 KB
/
splitter.go
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
package modbus
import (
"errors"
"fmt"
"github.com/aldas/go-modbus-client/packet"
"net/url"
"sort"
"strconv"
"strings"
"time"
)
// split groups (by host:port+UnitID, "optimized" max amount of fields for max quantity) fields into packets
func split(fields []Field, functionCode uint8, protocol ProtocolType) ([]BuilderRequest, error) {
connectionGroup, err := groupForSingleConnection(fields, functionCode, protocol)
if err != nil {
return nil, err
}
batches, err := batchToRequests(connectionGroup)
if err != nil {
return nil, err
}
result := make([]BuilderRequest, 0, len(batches))
for _, b := range batches {
if b.Protocol == protocolAny || b.FunctionCode == 0 {
continue
}
var req packet.Request
var err error
switch b.FunctionCode {
case packet.FunctionReadCoils: // fc1
switch b.Protocol {
case ProtocolTCP:
req, err = packet.NewReadCoilsRequestTCP(b.UnitID, b.StartAddress, b.Quantity)
case ProtocolRTU:
req, err = packet.NewReadCoilsRequestRTU(b.UnitID, b.StartAddress, b.Quantity)
}
case packet.FunctionReadDiscreteInputs: // fc2
switch b.Protocol {
case ProtocolTCP:
req, err = packet.NewReadDiscreteInputsRequestTCP(b.UnitID, b.StartAddress, b.Quantity)
case ProtocolRTU:
req, err = packet.NewReadDiscreteInputsRequestRTU(b.UnitID, b.StartAddress, b.Quantity)
}
case packet.FunctionReadHoldingRegisters: // fc3
switch b.Protocol {
case ProtocolTCP:
req, err = packet.NewReadHoldingRegistersRequestTCP(b.UnitID, b.StartAddress, b.Quantity)
case ProtocolRTU:
req, err = packet.NewReadHoldingRegistersRequestRTU(b.UnitID, b.StartAddress, b.Quantity)
}
case packet.FunctionReadInputRegisters: // fc4
switch b.Protocol {
case ProtocolTCP:
req, err = packet.NewReadInputRegistersRequestTCP(b.UnitID, b.StartAddress, b.Quantity)
case ProtocolRTU:
req, err = packet.NewReadInputRegistersRequestRTU(b.UnitID, b.StartAddress, b.Quantity)
}
}
if err != nil {
return nil, err
}
var quantity uint16
switch r := req.(type) {
case *packet.ReadCoilsRequestTCP: // fc1
quantity = r.Quantity
case *packet.ReadCoilsRequestRTU: // fc1
quantity = r.Quantity
case *packet.ReadDiscreteInputsRequestTCP: // fc2
quantity = r.Quantity
case *packet.ReadDiscreteInputsRequestRTU: // fc2
quantity = r.Quantity
case *packet.ReadHoldingRegistersRequestTCP: // fc3
quantity = r.Quantity
case *packet.ReadHoldingRegistersRequestRTU: // fc3
quantity = r.Quantity
case *packet.ReadInputRegistersRequestTCP: // fc4
quantity = r.Quantity
case *packet.ReadInputRegistersRequestRTU: // fc4
quantity = r.Quantity
}
result = append(result, BuilderRequest{
Request: req,
ServerAddress: b.ServerAddress,
UnitID: b.UnitID,
StartAddress: b.StartAddress,
Quantity: quantity,
Protocol: b.Protocol,
RequestInterval: time.Duration(b.RequestInterval),
Fields: b.fields,
})
}
if len(result) == 0 {
return nil, errors.New("splitting resulted 0 requests")
}
return result, nil
}
// groupForSingleConnection groups fields into groups what can be requested potentially by same request
// (same server + function + unit ID + protocol + interval)
func groupForSingleConnection(fields []Field, functionCode uint8, protocol ProtocolType) ([]builderSlotGroup, error) {
onlyCoils := functionCode == packet.FunctionReadCoils || functionCode == packet.FunctionReadDiscreteInputs
groups := map[groupID]builderSlotGroup{}
for _, f := range fields {
// adjust field fc and protocol to any cases
isCoil := f.Type == FieldTypeCoil
if (!isCoil && functionCode != 0 && f.FunctionCode == 0) || (isCoil && onlyCoils) {
f.FunctionCode = functionCode
}
if protocol != protocolAny && f.Protocol == protocolAny {
f.Protocol = protocol
}
if err := f.Validate(); err != nil {
return nil, err
}
if !onlyCoils && functionCode != 0 && functionCode != f.FunctionCode {
// when functionCode is provided and field does not have it set - consider field included
continue
}
if protocol != protocolAny && f.Protocol != protocolAny && protocol != f.Protocol {
// when protocol is provided and field does not have it set - consider field included
continue
}
if onlyCoils && !isCoil {
continue
} else if !onlyCoils && isCoil {
continue
}
// create groups by modbus server ServerAddress + fc + unitID + isCoil
gID := groupID{
serverAddress: f.ServerAddress,
functionCode: f.FunctionCode,
unitID: f.UnitID,
protocol: f.Protocol,
interval: f.RequestInterval,
}
group, ok := groups[gID]
if !ok {
group = builderSlotGroup{
group: gID,
isForCoils: isCoil,
slots: make([]builderSlot, 0),
}
groups[gID] = group
}
group.AddField(f)
groups[gID] = group
}
// TODO: as of Go 1.23 this could be shortened to `slices.Collect(maps.Values(groups))`
result := make([]builderSlotGroup, 0, len(groups))
for _, g := range groups {
result = append(result, g)
}
return result, nil
}
func batchToRequests(slotGroups []builderSlotGroup) ([]requestBatch, error) {
// Coils are always grouped to separate requests (fc1/fc2) from fields suitable for registers (fc3/fc4)
//
// NB: is batching/grouping algorithm is very naive. It just sorts fields by register and creates N number
// of requests of them by limiting quantity to MaxRegistersInReadResponse. It does not try to optimise long caps
// between fields
// assumes that UnitID is same for all fields within group
var result = make([]requestBatch, 0)
for _, slotGroup := range slotGroups {
if len(slotGroup.slots) == 0 {
continue
}
config, err := addressToSplitterConfig(slotGroup.group.serverAddress)
if err != nil {
return nil, err
}
addressLimit := packet.MaxRegistersInReadResponse
if slotGroup.isForCoils {
addressLimit = packet.MaxCoilsInReadResponse
}
if config.MaxQuantityPerRequest > 0 && config.MaxQuantityPerRequest < addressLimit {
addressLimit = config.MaxQuantityPerRequest
}
sort.Sort(slotsSorter(slotGroup.slots))
firstAddress := slotGroup.slots[0].address
batch := requestBatch{
ServerAddress: slotGroup.group.serverAddress,
FunctionCode: slotGroup.group.functionCode,
UnitID: slotGroup.group.unitID,
Protocol: slotGroup.group.protocol,
RequestInterval: slotGroup.group.interval,
StartAddress: firstAddress,
Quantity: slotGroup.slots[0].size,
}
for _, slot := range slotGroup.slots {
slotAddress := slot.address
slotEndAddress := slotAddress + slot.size
addressDiff := slotEndAddress - firstAddress
isBiggerThanAddressLimit := addressDiff > addressLimit
isInvalidRangeOverlap, err := config.InvalidRange.Overlaps(firstAddress, slotAddress, slotEndAddress-1)
if err != nil {
return nil, err
}
if isBiggerThanAddressLimit || isInvalidRangeOverlap {
result = append(result, batch)
batch = requestBatch{
ServerAddress: slotGroup.group.serverAddress,
FunctionCode: slotGroup.group.functionCode,
UnitID: slotGroup.group.unitID,
Protocol: slotGroup.group.protocol,
RequestInterval: slotGroup.group.interval,
StartAddress: slotAddress,
Quantity: slot.size,
}
firstAddress = slotAddress
addressDiff = slot.size
}
if batch.Quantity < addressDiff {
batch.Quantity = addressDiff
}
batch.fields = append(batch.fields, slot.fields...)
}
result = append(result, batch)
}
return result, nil
}
type builderSlot struct {
address uint16
size uint16
fields Fields
}
type builderSlots []builderSlot
func (bs *builderSlots) IndexOf(address uint16) int {
for i, b := range *bs {
if b.address == address {
return i
}
}
return -1
}
type slotsSorter builderSlots
func (a slotsSorter) Len() int { return len(a) }
func (a slotsSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a slotsSorter) Less(i, j int) bool {
return a[i].address < a[j].address
}
type groupID struct {
serverAddress string
functionCode uint8
unitID uint8
protocol ProtocolType
interval Duration
}
type builderSlotGroup struct {
group groupID
isForCoils bool
slots builderSlots
}
func (g *builderSlotGroup) AddField(f Field) {
registerSize := f.registerSize()
i := g.slots.IndexOf(f.Address)
if i == -1 {
g.slots = append(g.slots, builderSlot{
address: f.Address,
size: registerSize,
fields: Fields{f},
})
return
}
slot := g.slots[i]
slot.fields = append(slot.fields, f)
if registerSize > slot.size {
slot.size = registerSize
}
g.slots[i] = slot
}
type requestBatch struct {
ServerAddress string
FunctionCode uint8
UnitID uint8
Protocol ProtocolType
StartAddress uint16
Quantity uint16
IsForCoils bool
RequestInterval Duration
fields Fields
}
// invalidAddress is (register/coil) range in between modbus server should not be requested
type invalidAddress struct {
from uint16
to uint16
}
type invalidRange []invalidAddress
func (r *invalidRange) Overlaps(requestStart uint16, slotStart uint16, slotEnd uint16) (bool, error) {
if r == nil || len(*r) == 0 {
return false, nil
}
for _, ir := range *r {
if ir.from <= slotEnd && slotStart <= ir.to {
return true, fmt.Errorf("field overlaps invalid address range, addr: %d, range: %d-%d", slotStart, ir.from, ir.to)
}
if ir.from <= slotEnd && requestStart <= ir.to {
return true, nil
}
}
return false, nil
}
type splitterConfig struct {
MaxQuantityPerRequest uint16
InvalidRange invalidRange
}
func addressToSplitterConfig(address string) (splitterConfig, error) {
if !strings.ContainsRune(address, '?') {
return splitterConfig{}, nil
}
url, err := url.Parse(address)
if err != nil {
return splitterConfig{}, fmt.Errorf("failed to parse server adddres for invalid range: %q, err: %w", address, err)
}
invalid, err := addressToInvalidRange(url)
if err != nil {
return splitterConfig{}, err
}
maxQuantityPerRequest := uint16(0)
if raw := url.Query().Get("max_quantity_per_request"); raw != "" {
tmpQ, err := strconv.ParseUint(raw, 10, 16)
if err != nil {
return splitterConfig{}, fmt.Errorf("failed to parse max_quantity_per_request, err: %w", err)
}
maxQuantityPerRequest = uint16(tmpQ)
}
return splitterConfig{
MaxQuantityPerRequest: maxQuantityPerRequest,
InvalidRange: invalid,
}, nil
}
func addressToInvalidRange(url *url.URL) (invalidRange, error) {
result := make(invalidRange, 0)
raw := url.Query()["invalid_addr"]
for _, addrParam := range raw {
for _, addr := range strings.Split(addrParam, ",") {
before, after, found := strings.Cut(addr, "-")
if !found {
before = addr
}
from, err := strconv.ParseUint(before, 10, 16)
if err != nil {
return nil, fmt.Errorf("failed to parse invalid range: %q, err: %w", addr, err)
}
tmp := invalidAddress{
from: uint16(from),
to: uint16(from),
}
if found {
to, err := strconv.ParseUint(after, 10, 16)
if err != nil {
return nil, fmt.Errorf("failed to parse invalid range: %q, err: %w", addr, err)
}
tmp.to = uint16(to)
}
result = append(result, tmp)
}
}
if len(result) == 0 {
return nil, nil
}
return result, nil
}