You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ntool-biz/nmodbus/handler/fn_discreteinputs.go

50 lines
1.2 KiB
Go

package handler
import (
"git.noahlan.cn/noahlan/ntool-biz/nmodbus/protocol"
"git.noahlan.cn/noahlan/ntool-biz/nmodbus/serialize"
)
// ReadDiscreteInputs 读离散输入 功能码 0x02
type ReadDiscreteInputs struct {
fnCode uint8
}
func NewReadDiscreteInputs(fnCode uint8) FunctionHandler {
return &ReadDiscreteInputs{fnCode: fnCode}
}
func (r *ReadDiscreteInputs) FnCode() uint8 {
return r.fnCode
}
// Function 读离散输入 功能码 0x02
func (r *ReadDiscreteInputs) Function(s *Handler, req protocol.Packet, resp protocol.Packet) *protocol.MError {
register, numRegs, endRegister := serialize.RegisterAddressAndNumber(req.GetBody())
if endRegister > 65535 {
resp.SetBody([]byte{})
return &protocol.IllegalDataAddress
}
dataSize := numRegs / 8
if (numRegs % 8) != 0 {
dataSize++
}
data := make([]byte, 1+dataSize)
data[0] = byte(dataSize)
dataMgr := s.DataManager(req.GetAddress())
discreteInputs := dataMgr.ReadDiscreteInputs(register, endRegister)
for i, value := range discreteInputs {
if value != 0 {
shift := uint(i) % 8
data[1+i/8] |= byte(1 << shift)
}
}
s.HandleLogic(r.fnCode, req, register, numRegs, data)
resp.SetBody(data)
return &protocol.Success
}