Skip to content

Commit

Permalink
新增modbus模拟能力
Browse files Browse the repository at this point in the history
  • Loading branch information
smthing committed May 28, 2024
1 parent 897e2a9 commit 6e2b032
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
16 changes: 14 additions & 2 deletions internal/plugins/modbus/connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,14 @@ func (c *connector) ensureInterval() {
}

func (c *connector) sendReadCommand(group *pointGroup) error {
values, err := c.read(group.UnitID, string(group.RegisterType), group.Address, group.Quantity)
var values []uint16
var err error
if c.virtual {
values, err = c.mockRead(group.UnitID, string(group.RegisterType), group.Address, group.Quantity)
} else {
values, err = c.read(group.UnitID, string(group.RegisterType), group.Address, group.Quantity)
}

if err != nil {
return err
}
Expand Down Expand Up @@ -375,7 +382,12 @@ func mergeBitsIntoUint16(num int, startPos, bitCount uint8, regValue uint16) uin
func (c *connector) sendWriteCommand(pc *writeValue) error {
var err error
for i := 0; i < c.config.Retry; i++ {
if err = c.write(pc.unitID, pc.RegisterType, pc.Address, pc.Value); err == nil {
if c.virtual {
err = c.mockWrite(pc.unitID, pc.RegisterType, pc.Address, pc.Value)
} else {
err = c.write(pc.unitID, pc.RegisterType, pc.Address, pc.Value)
}
if err == nil {
break
}
}
Expand Down
26 changes: 26 additions & 0 deletions internal/plugins/modbus/mock.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package modbus

import (
"encoding/json"
"github.com/ibuilding-x/driver-box/driverbox/helper"
lua "github.com/yuin/gopher-lua"
"go.uber.org/zap"
)

func (c *connector) mockRead(slaveId uint8, registerType string, address, quantity uint16) (values []uint16, err error) {
mockData, e := helper.CallLuaMethod(c.plugin.ls, "mockRead", lua.LNumber(slaveId), lua.LString(registerType), lua.LNumber(address), lua.LNumber(quantity))
e = json.Unmarshal([]byte(mockData), &values)
return values, e
}

func (c *connector) mockWrite(slaveID uint8, registerType primaryTable, address uint16, values []uint16) error {
valueTable := c.plugin.ls.NewTable()
for _, v := range values {
valueTable.Append(lua.LNumber(v))
}
result, err := helper.CallLuaMethod(c.plugin.ls, "mockWrite", lua.LNumber(slaveID), lua.LString(registerType), lua.LNumber(address), valueTable)
if err == nil {
helper.Logger.Info("mockWrite result", zap.Any("result", result))
}
return err
}

0 comments on commit 6e2b032

Please sign in to comment.