找回密码
 成为会员
搜索
热搜: 活动 交友 discuz
查看: 88|回复: 0

modbus rtu服务器 串口模式

[复制链接]

6

主题

8

回帖

62

积分

版主

积分
62
发表于 2024-12-17 08:42:43 | 显示全部楼层 |阅读模式
var modbus = import("modbus")
var fmt = import("fmt")
var binary = import("encoding/binary")
var time = import("time")


size = 200


discretes  =  make([]bool,size)
holdingRegisters=  make([]int64,size)
ReadCoilsForSignalingBuffer = make([]bool,size)


func fillAm3() {
        for{
                for i=0; i<len(holdingRegisters);i++ {
                        holdingRegisters = i
                }


                for i=0; i<len(ReadCoilsForSignalingBuffer);i++ {
                        ReadCoilsForSignalingBuffer = i
                }
                time.Sleep(4*time.Second)
        }
}


func ReadCoilsForSignaling (address, quantity){
        address = toInt(address)
        quantity = toInt(quantity)
        return ReadCoilsForSignalingBuffer[address : address+quantity], nil
}


func ReadHoldingRegisters(address, quantity) {
        address = toInt(address)
        quantity = toInt(quantity)
        return holdingRegisters[address : address+quantity], nil
}
func OnErrorImp(address, quantity) {
        Print("error received: %v from req: %v\n", errRep, req)
}
serialConfig = new(modbus.Config)
serialConfig.Name="COM11"
serialConfig.Baud=115200
serialConfig.StopBits=modbus.StopBits1
serialConfig.Parity=modbus.ParityNone


go fillAm3()


s, err = modbus.OpenPort(serialConfig)
if err != nil {
        Print("open serial error: %v\n", err)
}


com = modbus.NewSerialContext(s, 115200)
id, err = modbus.Uint64ToSlaveID(1)
if err != nil {
        Print("set slaveID error: %v\n", err)
}
device = modbus.NewRTUServer(com, id)


HandlerFunc = new(modbus.SimpleHandler)


HandlerFunc.ReadHoldingRegisters = ReadHoldingRegisters
HandlerFunc.ReadCoils = ReadCoilsForSignaling
HandlerFunc.OnErrorImp = OnErrorImp


err = device.Serve(HandlerFunc)
if err != nil {
        Print("serve error: %v\n", err)
}

您需要登录后才可以回帖 登录 | 成为会员

本版积分规则

快速回复 返回顶部 返回列表