|
![](static/image/common/ico_lz.png)
楼主 |
发表于 2020-3-9 22:20:57
|
显示全部楼层
我没有用tcpSever,刚看了源代码,这个NodeRegister的构造函数NewNodeRegister返回的是NodeRegister结构体指针,应该调用它的写保持寄存器方法应该就可以设置寄存器的值了;
-------------构造函数--------------
- // NewNodeRegister 创建一个modbus子节点寄存器列表
- func NewNodeRegister(slaveID byte,
- coilsAddrStart, coilsQuantity,
- discreteAddrStart, discreteQuantity,
- inputAddrStart, inputQuantity,
- holdingAddrStart, holdingQuantity uint16) *NodeRegister {
- coilsBytes := (int(coilsQuantity) + 7) / 8
- discreteBytes := (int(discreteQuantity) + 7) / 8
- b := make([]byte, coilsBytes+discreteBytes)
- w := make([]uint16, int(inputQuantity)+int(holdingQuantity))
- return &NodeRegister{
- slaveID: slaveID,
- coilsAddrStart: coilsAddrStart,
- coilsQuantity: coilsQuantity,
- coils: b[:coilsBytes],
- discreteAddrStart: discreteAddrStart,
- discreteQuantity: discreteQuantity,
- discrete: b[coilsBytes:],
- inputAddrStart: inputAddrStart,
- input: w[:inputQuantity],
- holdingAddrStart: holdingAddrStart,
- holding: w[inputQuantity:],
- }
- }
复制代码
------------------写保持寄存器方法--------------
- // WriteHoldings 写保持寄存器
- func (sf *NodeRegister) WriteHoldings(address uint16, valBuf []uint16) error {
- quality := uint16(len(valBuf))
- sf.rw.Lock()
- if (address >= sf.holdingAddrStart) &&
- ((address + quality) <= (sf.holdingAddrStart + uint16(len(sf.holding)))) {
- start := address - sf.holdingAddrStart
- end := start + quality
- copy(sf.holding[start:end], valBuf)
- sf.rw.Unlock()
- return nil
- }
- sf.rw.Unlock()
- return &ExceptionError{ExceptionCodeIllegalDataAddress}
- }
复制代码
WriteHoldings这个方法有2个参数,寄存器地址和切片类型的寄存器值;
函数内不通过copy进行了赋值拷贝
- copy(sf.holding[start:end], valBuf)
复制代码
你先试试看 |
|