package handler import ( "git.noahlan.cn/noahlan/ntool-biz/nmodbus/protocol" "git.noahlan.cn/noahlan/ntool-biz/nmodbus/serialize" ) type ReadDiscreteInputs struct { fnCode uint8 } func NewReadDiscreteInputs(fnCode uint8) FunctionHandler { return &ReadDiscreteInputs{fnCode: fnCode} } func (r *ReadDiscreteInputs) FnCode() uint8 { return r.fnCode } // Function 读离散输入 功能码 0x04 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 }