Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions ascii_over_tcp_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func (mb *asciiTCPTransporter) Send(aduRequest []byte) (aduResponse []byte, err
}

// Send the request
mb.logf("modbus: send %q\n", aduRequest)
mb.Debug("modbus: send %q\n", aduRequest)
if _, err = mb.conn.Write(aduRequest); err != nil {
return
}
Expand All @@ -78,6 +78,6 @@ func (mb *asciiTCPTransporter) Send(aduRequest []byte) (aduResponse []byte, err
}
}
aduResponse = data[:length]
mb.logf("modbus: recv %q\n", aduResponse)
mb.Debug("modbus: recv %q\n", aduResponse)
return
}
4 changes: 2 additions & 2 deletions asciiclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ func (mb *asciiSerialTransporter) Send(aduRequest []byte) (aduResponse []byte, e
mb.startCloseTimer()

// Send the request
mb.logf("modbus: send % x\n", aduRequest)
mb.Debug("modbus: send % x\n", aduRequest)
if _, err = mb.port.Write(aduRequest); err != nil {
return
}
Expand All @@ -204,7 +204,7 @@ func (mb *asciiSerialTransporter) Send(aduRequest []byte) (aduResponse []byte, e
}
}
aduResponse = data[:length]
mb.logf("modbus: recv % x\n", aduResponse)
mb.Debug("modbus: recv % x\n", aduResponse)
return
}

Expand Down
5 changes: 0 additions & 5 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,6 @@ import (
"fmt"
)

// logger is the interface to the required logging functions
type logger interface {
Printf(format string, v ...interface{})
}

// ClientHandler is the interface that groups the Packager and Transporter methods.
type ClientHandler interface {
Packager
Expand Down
40 changes: 22 additions & 18 deletions cmd/modbus-cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import (
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"log/slog"
"math"
"net/url"
"os"
"strconv"
"strings"
"text/tabwriter"
"time"
Expand Down Expand Up @@ -64,9 +64,11 @@ func main() {
return
}

logger := log.New(os.Stdout, "", 0)
logger := slog.Default()
if *register > math.MaxUint16 || *register < 0 {
logger.Fatalf("invalid register value: %d", *register)
intRegister := *register
logger.Error("invalid register value: " + strconv.Itoa(intRegister))
os.Exit(-1)
}

startReg := uint16(*register)
Expand All @@ -89,20 +91,23 @@ func main() {

handler, err := newHandler(opt)
if err != nil {
logger.Fatal(err)
logger.Error(err.Error())
os.Exit(-1)
}
if err := handler.Connect(); err != nil {
log.Fatal(err)
logger.Error(err.Error())
os.Exit(-1)
}
defer handler.Close()

client := modbus.NewClient(handler)

result, err := exec(client, eo, *writeParseOrder, *register, *fnCode, *writeValue, *eType, *quantity)
if err != nil && strings.Contains(err.Error(), "crc") && *ignoreCRCError {
logger.Printf("ignoring crc error: %+v\n", err)
logger.Info("ignoring crc error: %+v\n", err)
} else if err != nil {
logger.Fatal(err)
logger.Error(err.Error())
os.Exit(-1)
}

var res string
Expand All @@ -116,16 +121,19 @@ func main() {
}

if err != nil {
logger.Fatal(err)
logger.Error(err.Error())
os.Exit(-1)
}

logger.Println(res)
logger.Info(res)

if *filename != "" {
if err := resultToFile([]byte(res), *filename); err != nil {
logger.Fatal(err)
logger.Error(err.Error())
os.Exit(-1)
}
logger.Printf("%s successfully written\n", *filename)
fName := *filename
logger.Info(fName + " successfully written\n")
}
}

Expand Down Expand Up @@ -230,7 +238,7 @@ func convertToBytes(eType string, order binary.ByteOrder, forcedOrder string, va
}

func resultToFile(r []byte, filename string) error {
return ioutil.WriteFile(filename, r, 0644)
return os.WriteFile(filename, r, 0644)
}

func resultToRawString(r []byte, startReg int) (string, error) {
Expand Down Expand Up @@ -408,16 +416,12 @@ func resultToString(r []byte, order binary.ByteOrder, forcedOrder string, varTyp
return "", fmt.Errorf("unsupported datatype: %s", varType)
}

type logger interface {
Printf(format string, v ...interface{})
}

type option struct {
address string
slaveID int
timeout time.Duration

logger logger
logger *slog.Logger

rtu struct {
baudrate int
Expand Down
6 changes: 3 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/grid-x/modbus
go 1.21

require (
github.com/google/go-cmp v0.5.6
github.com/grid-x/serial v0.0.0-20191104121038-e24bc9bf6f08
pgregory.net/rapid v0.4.7
github.com/google/go-cmp v0.6.0
github.com/grid-x/serial v0.0.0-20211107191517-583c7356b3aa
pgregory.net/rapid v1.1.0
)
14 changes: 6 additions & 8 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/grid-x/serial v0.0.0-20191104121038-e24bc9bf6f08 h1:syBxnRYnSPUDdkdo5U4sy2roxBPQDjNiw4od7xlsABQ=
github.com/grid-x/serial v0.0.0-20191104121038-e24bc9bf6f08/go.mod h1:kdOd86/VGFWRrtkNwf1MPk0u1gIjc4Y7R2j7nhwc7Rk=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
pgregory.net/rapid v0.4.7 h1:MTNRktPuv5FNqOO151TM9mDTa+XHcX6ypYeISDVD14g=
pgregory.net/rapid v0.4.7/go.mod h1:UYpPVyjFHzYBGHIxLFoupi8vwk6rXNzRY9OMvVxFIOU=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/grid-x/serial v0.0.0-20211107191517-583c7356b3aa h1:Rsn6ARgNkXrsXJIzhkE4vQr5Gbx2LvtEMv4BJOK4LyU=
github.com/grid-x/serial v0.0.0-20211107191517-583c7356b3aa/go.mod h1:kdOd86/VGFWRrtkNwf1MPk0u1gIjc4Y7R2j7nhwc7Rk=
pgregory.net/rapid v1.1.0 h1:CMa0sjHSru3puNx+J0MIAuiiEV4N0qj8/cMWGBBCsjw=
pgregory.net/rapid v1.1.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04=
4 changes: 2 additions & 2 deletions rtu_over_tcp_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func (mb *rtuTCPTransporter) Send(aduRequest []byte) (aduResponse []byte, err er
}

// Send the request
mb.logf("modbus: send % x\n", aduRequest)
mb.Debug("modbus: send % x\n", aduRequest)
if _, err = mb.conn.Write(aduRequest); err != nil {
return
}
Expand Down Expand Up @@ -95,6 +95,6 @@ func (mb *rtuTCPTransporter) Send(aduRequest []byte) (aduResponse []byte, err er
return
}
aduResponse = data[:n]
mb.logf("modbus: recv % x\n", aduResponse)
mb.Debug("modbus: recv % x\n", aduResponse)
return
}
5 changes: 3 additions & 2 deletions rtu_over_udp_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package modbus
import (
"fmt"
"io"
logger "log/slog"
"net"
"sync"
)
Expand Down Expand Up @@ -45,7 +46,7 @@ type rtuUDPTransporter struct {
// Connect string
Address string
// Transmission logger
Logger logger
Logger *logger.Logger

// UDP connection
mu sync.Mutex
Expand Down Expand Up @@ -120,7 +121,7 @@ func (mb *rtuUDPTransporter) Send(aduRequest []byte) (aduResponse []byte, err er

func (mb *rtuUDPTransporter) logf(format string, v ...interface{}) {
if mb.Logger != nil {
mb.Logger.Printf(format, v...)
mb.Logger.Info(format, v...)
}
}

Expand Down
4 changes: 2 additions & 2 deletions rtuclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ func (mb *rtuSerialTransporter) Send(aduRequest []byte) (aduResponse []byte, err
mb.startCloseTimer()

// Send the request
mb.logf("modbus: send % x\n", aduRequest)
mb.Debug("modbus: send % x\n", aduRequest)
if _, err = mb.port.Write(aduRequest); err != nil {
return
}
Expand All @@ -271,7 +271,7 @@ func (mb *rtuSerialTransporter) Send(aduRequest []byte) (aduResponse []byte, err
time.Sleep(mb.calculateDelay(len(aduRequest) + bytesToRead))

data, err := readIncrementally(aduRequest[0], aduRequest[1], mb.port, time.Now().Add(mb.Config.Timeout))
mb.logf("modbus: recv % x\n", data[:])
mb.Debug("modbus: recv % x\n", data[:])
aduResponse = data
return
}
Expand Down
6 changes: 3 additions & 3 deletions rtuclient_prop_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ import (
func TestRTUEncodeDecode(t *testing.T) {
rapid.Check(t, func(t *rapid.T) {
packager := &rtuPackager{
SlaveID: rapid.Byte().Draw(t, "SlaveID").(byte),
SlaveID: rapid.Byte().Draw(t, "SlaveID"),
}

pdu := &ProtocolDataUnit{
FunctionCode: rapid.Byte().Draw(t, "FunctionCode").(byte),
Data: rapid.SliceOf(rapid.Byte()).Draw(t, "Data").([]byte),
FunctionCode: rapid.Byte().Draw(t, "FunctionCode"),
Data: rapid.SliceOf(rapid.Byte()).Draw(t, "Data"),
}

raw, err := packager.Encode(pdu)
Expand Down
40 changes: 36 additions & 4 deletions serial.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
package modbus

import (
"context"
"fmt"
"io"
"log/slog"
"sync"
"time"

Expand All @@ -24,7 +26,7 @@ type serialPort struct {
// Serial port configuration.
serial.Config

Logger logger
Logger *slog.Logger
IdleTimeout time.Duration

mu sync.Mutex
Expand Down Expand Up @@ -69,9 +71,39 @@ func (mb *serialPort) close() (err error) {
return
}

func (mb *serialPort) logf(format string, v ...interface{}) {
func (mb *serialPort) Debug(format string, v ...interface{}) {
if mb.Logger != nil {
mb.Logger.Printf(format, v...)
mb.Logger.Debug(format, v...)
}
}

func (mb *serialPort) Info(format string, v ...interface{}) {
if mb.Logger != nil {
mb.Logger.Info(format, v...)
}
}

func (mb *serialPort) Error(format string, v ...interface{}) {
if mb.Logger != nil {
mb.Logger.Error(format, v...)
}
}

func (mb *serialPort) DebugContext(ctx context.Context, format string, v ...interface{}) {
if mb.Logger != nil {
mb.Logger.DebugContext(ctx, format, v...)
}
}

func (mb *serialPort) InfoContext(ctx context.Context, format string, v ...interface{}) {
if mb.Logger != nil {
mb.Logger.InfoContext(ctx, format, v...)
}
}

func (mb *serialPort) ErrorContext(ctx context.Context, format string, v ...interface{}) {
if mb.Logger != nil {
mb.Logger.ErrorContext(ctx, format, v...)
}
}

Expand All @@ -96,7 +128,7 @@ func (mb *serialPort) closeIdle() {
}

if idle := time.Since(mb.lastActivity); idle >= mb.IdleTimeout {
mb.logf("modbus: closing connection due to idle timeout: %v", idle)
mb.Debug("modbus: closing connection due to idle timeout: %v", idle)
mb.close()
}
}
Loading