package nmodbus import ( "git.noahlan.cn/noahlan/nnet" "git.noahlan.cn/noahlan/nnet/config" "git.noahlan.cn/noahlan/nnet/packet" "git.noahlan.cn/noahlan/ntool-biz/nmodbus/handler" "git.noahlan.cn/noahlan/ntool-biz/nmodbus/protocol" "git.noahlan.cn/noahlan/ntool-biz/nmodbus/serialize" "git.noahlan.cn/noahlan/ntool/npool" "math" "time" ) // NewModbusTCPEngine 新建modbus-tcp服务端引擎 // 默认行为:接收功能码为 0x01 0x02 0x03 0x04 0x05 0x06 0x15 0x16 的消息并自动按照Modbus协议进行处理 // // Usage: // ngin, handler := NewModbusTCPEngine(ModbusTCPConf{ByteOrder: binary.BigEndian, Mode: conf.DevMode, Name: "ModbusTCP"}) // defer ngin.Stop() // // handler.RegisterFunction(code, func()) // 自定义功能码对应的处理方法 // hr := handler.holdingRegisters[0] // 获取地址为0x00的保持寄存器 2字节 uint16 (也可以设置,但非线程安全的) // // ngin.ListenTCP(config.TCPServerConf{Protocol: "tcp", Addr: "0.0.0.0:5502"}) func NewModbusTCPEngine(conf ModbusTCPConf) (*nnet.Engine, *handler.Handler) { hd := handler.NewHandler(conf.ByteOrder) opts := []nnet.RunOption{ nnet.WithPoolCfg(npool.Config{ PoolSize: math.MaxInt32, ExpiryDuration: time.Second, PreAlloc: false, MaxBlockingTasks: 0, Nonblocking: false, DisablePurge: false, }), withPipeline(), nnet.WithPackerBuilder(func() packet.Packer { return protocol.NewTCPPacker(conf.ByteOrder) }), nnet.WithRouter(protocol.NewRouter(hd)), } // 设置字节序 serialize.SetByteOrder(conf.ByteOrder) ngin := nnet.NewEngine(config.EngineConf{ Mode: conf.Mode, Name: conf.Name, }, opts...) return ngin, hd }