fix(inputs/modbus): #11105 fix requests starting with an omitted field (#11202)

This commit is contained in:
TimurDela 2022-06-01 21:10:08 +02:00 committed by GitHub
parent 354b651bd9
commit 4d92fe4e5e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 71 additions and 3 deletions

View File

@ -1857,3 +1857,70 @@ func TestConfigurationPerRequestFail(t *testing.T) {
})
}
}
func TestRequestsStartingWithOmits(t *testing.T) {
modbus := Modbus{
Name: "Test",
Controller: "tcp://localhost:1502",
ConfigurationType: "request",
Log: testutil.Logger{},
}
modbus.Requests = []requestDefinition{
{SlaveID: 1,
ByteOrder: "ABCD",
RegisterType: "holding",
Fields: []requestFieldDefinition{
{
Name: "holding-0",
Address: uint16(0),
InputType: "INT16",
Omit: true,
},
{
Name: "holding-1",
Address: uint16(1),
InputType: "UINT16",
Omit: true,
},
{
Name: "holding-2",
Address: uint16(2),
InputType: "INT16",
},
},
},
}
require.NoError(t, modbus.Init())
require.NotEmpty(t, modbus.requests)
require.NotNil(t, modbus.requests[1])
require.Equal(t, uint16(0), modbus.requests[1].holding[0].address)
serv := mbserver.NewServer()
require.NoError(t, serv.ListenTCP("localhost:1502"))
defer serv.Close()
handler := mb.NewTCPClientHandler("localhost:1502")
require.NoError(t, handler.Connect())
defer handler.Close()
client := mb.NewClient(handler)
_, err := client.WriteMultipleRegisters(uint16(0), 3, []byte{0x00, 0x01, 0x00, 0x02, 0x00, 0x03})
require.NoError(t, err)
expected := []telegraf.Metric{
testutil.MustMetric(
"modbus",
map[string]string{
"type": cHoldingRegisters,
"slave_id": strconv.Itoa(int(modbus.Requests[0].SlaveID)),
"name": modbus.Name,
},
map[string]interface{}{"holding-2": int16(3)},
time.Unix(0, 0),
),
}
var acc testutil.Accumulator
require.NoError(t, modbus.Gather(&acc))
acc.Wait(len(expected))
testutil.RequireMetricsEqual(t, expected, acc.GetTelegrafMetrics(), testutil.IgnoreTime())
}

View File

@ -13,10 +13,12 @@ func newRequest(f field, tags map[string]string) request {
r := request{
address: f.address,
length: f.length,
fields: []field{f},
fields: []field{},
tags: map[string]string{},
}
if !f.omit {
r.fields = append(r.fields, f)
}
// Copy the tags
for k, v := range tags {
r.tags[k] = v
@ -63,6 +65,5 @@ func groupFieldsToRequests(fields []field, tags map[string]string, maxBatchSize
current = newRequest(f, tags)
}
requests = append(requests, current)
return requests
}