package main import ( "log" "strconv" "time" "github.com/simonvetter/modbus" ) var ( tcp_server *modbus.ModbusServer rtu_client *modbus.ModbusClient Logger log.Logger = *log.Default() ) const ( SERVER = "[::]" PORT = 502 SERIAL_INTERFACE = "/dev/ttyUSB0" BAUD = 9600 ) func init() { Logger.SetPrefix("modbus_bridge: ") Logger.Println("Starting") // create modbus tcp server timeout := 30 * time.Second var server_cfg = modbus.ServerConfiguration{ URL: "tcp://" + SERVER + ":" + strconv.Itoa(PORT), Timeout: timeout, MaxClients: 5, } var err error handler := &modbusTcpHandler{} tcp_server, err = modbus.NewServer(&server_cfg, handler) if err != nil { Logger.Printf("failed to create server: %v\n", err) return } // create modbus rtu client url := "rtu://" + SERIAL_INTERFACE rtu_client, err = modbus.NewClient(&modbus.ClientConfiguration{ URL: url, Speed: BAUD, DataBits: 8, Parity: modbus.PARITY_NONE, StopBits: 1, Timeout: 300 * time.Millisecond, }) if err != nil { Logger.Printf("Could not create new modbus rtu client on %s (%s).", url, err.Error()) err = modbus.ErrConfigurationError return } err = rtu_client.Open() if err != nil { Logger.Printf("Could not open new modbus rtu client on %s (%s).", url, err.Error()) err = modbus.ErrConfigurationError return } } func main() { if tcp_server != nil { Logger.Print("Starting modbus tcp server") err := tcp_server.Start() if err != nil { Logger.Printf("Unable to start modbus tcp server: %s", err.Error()) } } for { time.Sleep(time.Millisecond * 500) } }