Skip to content

Commit

Permalink
Finish removing logrus (#18)
Browse files Browse the repository at this point in the history
* Changed : renamed to NewNodeProcessor for consistency with type

* Refactored : continue changes to remove logrus
Changed : removed MainCallback for now

* Refactored : add slog to fileobject

* Changed : removed logrus from http gateway & added slog
Changed : minor coherence refactor for naming

* Fixed : error in gateway example, should now work + slog

* Changed : removed logrus from CAN drivers, replaced by slog

* Changed : removed logrus from SDO client

* Fixed : forgot to add logger to virtual can

* Removed : logrus in commented server test http

* Changed : bus manager doesn't use logrus
Changed : .gitignore remove created file during testing
Changed : removed last references to logrus & run log tidy
  • Loading branch information
samsamfire authored Dec 9, 2024
1 parent 53145aa commit e1b8a2b
Show file tree
Hide file tree
Showing 21 changed files with 765 additions and 626 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ __pycache__/
*.vscode
node_modules
*.code-workspace
site
site
examples/test/example.bin
Binary file modified README.md
Binary file not shown.
9 changes: 5 additions & 4 deletions bus_manager.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package canopen

import (
"log/slog"
"sync"

log "github.com/sirupsen/logrus"
)

// Bus manager is a wrapper around the CAN bus interface
// Used by the CANopen stack to control errors, callbacks for specific IDs, etc.
type BusManager struct {
logger *slog.Logger
mu sync.Mutex
bus Bus // Bus interface that can be adapted
frameListeners map[uint32][]FrameListener
Expand Down Expand Up @@ -48,7 +48,7 @@ func (bm *BusManager) Bus() Bus {
func (bm *BusManager) Send(frame Frame) error {
err := bm.bus.Send(frame)
if err != nil {
log.Warnf("[CAN] %v", err)
bm.logger.Warn("error sending frame", "err", err)
}
return err
}
Expand Down Expand Up @@ -78,7 +78,7 @@ func (bm *BusManager) Subscribe(ident uint32, mask uint32, rtr bool, callback Fr
// Iterate over all callbacks and verify that we are not adding the same one twice
for _, cb := range bm.frameListeners[ident] {
if cb == callback {
log.Warnf("[CAN] callback for frame id %x already added", ident)
bm.logger.Warn("callback for frame already present", "id", ident)
return nil
}
}
Expand All @@ -96,6 +96,7 @@ func (bm *BusManager) Error() uint16 {
func NewBusManager(bus Bus) *BusManager {
bm := &BusManager{
bus: bus,
logger: slog.Default(),
frameListeners: make(map[uint32][]FrameListener),
canError: 0,
}
Expand Down
25 changes: 12 additions & 13 deletions examples/http/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,33 @@ package main
import (
"flag"
"fmt"
"log/slog"
"os"

"github.com/samsamfire/gocanopen/pkg/gateway/http"
"github.com/samsamfire/gocanopen/pkg/network"
log "github.com/sirupsen/logrus"
)

var DEFAULT_NODE_ID = 0x20
var DEFAULT_CAN_INTERFACE = "vcan0"
var DEFAULT_HTTP_PORT = 8090

const (
INIT = 0
RUNNING = 1
RESETING = 2
NodeId = 0x20
Interface = "vcan0"
Port = 8090
)

func main() {
log.SetLevel(log.DebugLevel)

logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
// Command line arguments
channel := flag.String("i", DEFAULT_CAN_INTERFACE, "socketcan channel e.g. can0,vcan0")
channel := flag.String("i", Interface, "socketcan channel e.g. can0,vcan0")
flag.Parse()

network := network.NewNetwork(nil)
e := network.Connect("", *channel, 500000)
network.SetLogger(logger)
e := network.Connect("socketcan", *channel, 500000)
if e != nil {
panic(e)
}
gateway := http.NewGatewayServer(&network, 1, 1, 1000)
gateway.ListenAndServe(fmt.Sprintf(":%d", DEFAULT_HTTP_PORT))
gateway := http.NewGatewayServer(&network, logger, 1, 1, 1000)
gateway.ListenAndServe(fmt.Sprintf(":%d", Port))

}
12 changes: 8 additions & 4 deletions examples/master/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
package main

import (
"log/slog"
"os"

"github.com/samsamfire/gocanopen/pkg/network"
log "github.com/sirupsen/logrus"
)

var DEFAULT_NODE_ID = uint8(0x20)
Expand All @@ -12,9 +14,11 @@ var DEFAULT_CAN_BITRATE = 500_000
var EDS_PATH = "../../testdata/base.eds"

func main() {
log.SetLevel(log.DebugLevel)

logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
network := network.NewNetwork(nil)
network.SetLogger(logger)

err := network.Connect("socketcan", DEFAULT_CAN_INTERFACE, DEFAULT_CAN_BITRATE)
if err != nil {
panic(err)
Expand All @@ -30,11 +34,11 @@ func main() {
// Read values via SDO
val, err := node.ReadUint("UNSIGNED32 value", "")
if err == nil {
log.Infof("read : %v", val)
logger.Info("read", "value", val)
}
// Or write values via SDO
err = node.Write("UNSIGNED64 value", "", uint64(10))
if err != nil {
log.Info("failed to write", err)
logger.Info("failed to write", "err", err)
}
}
8 changes: 4 additions & 4 deletions examples/test/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (

"github.com/samsamfire/gocanopen/pkg/network"
"github.com/samsamfire/gocanopen/pkg/od"
log "github.com/sirupsen/logrus"
)

var DEFAULT_NODE_ID = 0x10
Expand All @@ -24,19 +23,20 @@ const (
)

func main() {
log.SetLevel(log.DebugLevel)

go func() {
http.ListenAndServe("localhost:6060", nil)
}()

logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
network := network.NewNetwork(nil)
network.SetLogger(logger)

err := network.Connect("virtualcan", "127.0.0.1:18889", 500000)
if err != nil {
panic(err)
}
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
network.SetLogger(logger)

// Load node EDS, this will be used to generate all the CANopen objects
// Basic template can be found in the current directory
node, err := network.CreateLocalNode(uint8(DEFAULT_NODE_ID), od.Default())
Expand Down
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ module github.com/samsamfire/gocanopen
go 1.22

require (
github.com/sirupsen/logrus v1.9.0
github.com/stretchr/testify v1.8.4
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8
gopkg.in/ini.v1 v1.67.0
Expand Down
6 changes: 0 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ=
Expand All @@ -15,6 +10,5 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
7 changes: 4 additions & 3 deletions pkg/can/kvaser/kvaser.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,11 @@ import "C"
import (
"errors"
"fmt"
"log/slog"
"unsafe"

canopen "github.com/samsamfire/gocanopen"
"github.com/samsamfire/gocanopen/pkg/can"

log "github.com/sirupsen/logrus"
)

const (
Expand Down Expand Up @@ -52,6 +51,7 @@ func init() {

type KvaserBus struct {
handle C.canHandle
logger *slog.Logger
rxCallback canopen.FrameListener
timeoutRead int
timeoutWrite int
Expand Down Expand Up @@ -83,6 +83,7 @@ func NewKvaserBus(name string) (canopen.Bus, error) {
bus := &KvaserBus{}
bus.timeoutRead = defaultReadTimeoutMs
bus.timeoutWrite = defaultWriteTimeoutMs
bus.logger = slog.Default()
bus.exit = make(chan bool)
// Call lib init, any error here is silent
// and will happen when trying to open port
Expand Down Expand Up @@ -166,7 +167,7 @@ func (k *KvaserBus) handleReception() {
default:
frame, err := k.Recv()
if err != nil && err.Error() != ErrNoMsg.Error() {
log.Errorf("[KVASER DRIVER] listening routine has closed because : %v", err)
k.logger.Error("listening routine has closed because", "err", err)
return
}
if k.rxCallback != nil {
Expand Down
11 changes: 8 additions & 3 deletions pkg/can/virtual/virtual.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import (
"encoding/binary"
"errors"
"fmt"
"log/slog"
"net"
"sync"
"time"

canopen "github.com/samsamfire/gocanopen"
can "github.com/samsamfire/gocanopen/pkg/can"
log "github.com/sirupsen/logrus"
)

// Virtual CAN bus implementation with TCP primarily used for testing
Expand All @@ -24,6 +24,7 @@ func init() {
}

type Bus struct {
logger *slog.Logger
mu sync.Mutex
channel string
conn net.Conn
Expand All @@ -36,7 +37,11 @@ type Bus struct {
}

func NewVirtualCanBus(channel string) (canopen.Bus, error) {
return &Bus{channel: channel, stopChan: make(chan bool), isRunning: false}, nil
return &Bus{
channel: channel,
logger: slog.Default(),
stopChan: make(chan bool),
isRunning: false}, nil
}

// Helper function for serializing a CAN frame into the expected binary format
Expand Down Expand Up @@ -181,7 +186,7 @@ func (client *Bus) handleReception() {
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
// No message received, this is OK
} else if err != nil {
log.Errorf("[VIRTUAL DRIVER] listening routine has closed because : %v", err)
client.logger.Error("listening routine has closed because", "err", err)
client.errSubscriber = true
client.mu.Unlock()
return
Expand Down
14 changes: 11 additions & 3 deletions pkg/gateway/gateway.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package gateway

import (
"log/slog"

"github.com/samsamfire/gocanopen/pkg/network"
"github.com/samsamfire/gocanopen/pkg/nmt"
"github.com/samsamfire/gocanopen/pkg/od"
"github.com/samsamfire/gocanopen/pkg/sdo"
log "github.com/sirupsen/logrus"
)

// BaseGateway implements the basic gateway features defined by CiA 309
Expand All @@ -16,14 +17,21 @@ import (
// CiA 309-5 : HTTP / Websocket
// Each gateway maps its own parsing logic to this base gateway
type BaseGateway struct {
logger *slog.Logger
network *network.Network
defaultNetwork uint16
defaultNodeId uint8
sdoBuffer []byte
}

func NewBaseGateway(network *network.Network, defaultNetwork uint16, defaultNodeId uint8, sdoUploadBufferSize int) *BaseGateway {
func NewBaseGateway(network *network.Network, logger *slog.Logger, defaultNetwork uint16, defaultNodeId uint8, sdoUploadBufferSize int) *BaseGateway {

if logger == nil {
logger = slog.Default()
}

return &BaseGateway{
logger: logger,
network: network,
defaultNetwork: defaultNetwork,
defaultNodeId: defaultNodeId,
Expand Down Expand Up @@ -87,7 +95,7 @@ func (gw *BaseGateway) SetSDOTimeout(timeoutMs uint32) error {
// TODO : maybe add mutex in case ongoing transfer
gw.network.SDOClient.SetTimeout(timeoutMs)
gw.network.SDOClient.SetTimeoutBlockTransfer(timeoutMs)
log.Debugf("[HTTP][SERVER] changing sdo client timeout to %vms", timeoutMs)
gw.logger.Debug("changing sdo client timeout", "timeoutMs", timeoutMs)
return nil
}

Expand Down
18 changes: 12 additions & 6 deletions pkg/gateway/http/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,29 @@ import (
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"strconv"

"github.com/samsamfire/gocanopen/pkg/gateway"
log "github.com/sirupsen/logrus"
)

type GatewayClient struct {
http.Client
logger *slog.Logger
baseURL string
apiVersion string
currentSequenceNb int
networkId int
}

func NewGatewayClient(baseURL string, apiVersion string, networkId int) *GatewayClient {
func NewGatewayClient(baseURL string, apiVersion string, networkId int, logger *slog.Logger) *GatewayClient {

if logger == nil {
logger = slog.Default()
}
return &GatewayClient{
logger: logger.With("service", "[HTTP client]"),
Client: http.Client{},
baseURL: baseURL,
networkId: networkId,
Expand All @@ -37,19 +43,19 @@ func (client *GatewayClient) Do(method string, uri string, body io.Reader, respo
baseUri := client.baseURL + "/cia309-5" + fmt.Sprintf("/%s/%d/%d", client.apiVersion, client.currentSequenceNb, client.networkId)
req, err := http.NewRequest(method, baseUri+uri, body)
if err != nil {
log.Errorf("[HTTP][CLIENT] http error : %v", err)
client.logger.Error("failed to create request", "err", err)
return err
}
// HTTP request
httpResp, err := client.Client.Do(req)
if err != nil {
log.Errorf("[HTTP][CLIENT] http error : %v", err)
client.logger.Error("failed request", "err", err)
return err
}
// Decode JSON "generic" response
err = json.NewDecoder(httpResp.Body).Decode(response)
if err != nil {
log.Errorf("[HTTP][CLIENT] error decoding json response : %v", err)
client.logger.Error("failed to decode response", "err", err)
return err
}
// Check for gateway errors
Expand All @@ -60,7 +66,7 @@ func (client *GatewayClient) Do(method string, uri string, body io.Reader, respo
// Check for sequence nb mismatch
sequence := response.GetSequenceNb()
if client.currentSequenceNb != sequence {
log.Errorf("[HTTP][CLIENT][SEQ:%v] sequence number does not match expected value (%v)", sequence, client.currentSequenceNb)
client.logger.Error("wrong sequence number", "sequence", sequence, "expected", client.currentSequenceNb)
return fmt.Errorf("error in sequence number")
}
return nil
Expand Down
Loading

0 comments on commit e1b8a2b

Please sign in to comment.