Skip to content

Commit

Permalink
Prevent multiple request to be made to the same device before a respo…
Browse files Browse the repository at this point in the history
…nse is returned
  • Loading branch information
Fabian Petersen committed Nov 5, 2021
1 parent c722814 commit 8f397a2
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 7 deletions.
12 changes: 10 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package canopen

import (
"time"

"github.com/FabianPetersen/can"
"github.com/jpillora/maplock"
"strconv"
"time"
)

var m = maplock.New()

// A Client handles message communication by sending a request
// and waiting for the response.
type Client struct {
Expand All @@ -16,6 +19,11 @@ type Client struct {
// Do sends a request and waits for a response.
// If the response frame doesn't arrive on time, an error is returned.
func (c *Client) Do(req *Request) (*Response, error) {
// Do not allow multiple messages for the same device
key := strconv.Itoa(int(req.ResponseID))
m.Lock(key)
defer m.Unlock(key)

rch := can.Wait(c.Bus, req.ResponseID, c.Timeout)

if err := c.Bus.Publish(req.Frame.CANFrame()); err != nil {
Expand Down
5 changes: 4 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@ module github.com/FabianPetersen/canopen

go 1.15

require github.com/FabianPetersen/can v0.0.3
require (
github.com/FabianPetersen/can v0.0.3
github.com/jpillora/maplock v0.0.0-20160420012925-5c725ac6e22a
)
6 changes: 2 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
github.com/FabianPetersen/can v0.0.3 h1:AvNdtYRx/Qqd9ecVmPPk4/U27GT5kyvurtriWyASoMU=
github.com/FabianPetersen/can v0.0.3/go.mod h1:K+0T7NSTiAhcH/zIYFPj4o256RKIwQ1Y/uHTC9MyK4I=
github.com/brutella/can v0.0.1 h1:Rz+2Zuje3NT79daon8wPN9+VphH3/kl1DP8Dhf/k1NI=
github.com/brutella/can v0.0.1/go.mod h1:NYDxbQito3w4+4DcjWs/fpQ3xyaFdpXw/KYqtZFU98k=
golang.org/x/sys v0.0.0-20181213200352-4d1cda033e06 h1:0oC8rFnE+74kEmuHZ46F6KHsMr5Gx2gUQPuNz28iQZM=
golang.org/x/sys v0.0.0-20181213200352-4d1cda033e06/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
github.com/jpillora/maplock v0.0.0-20160420012925-5c725ac6e22a h1:40K0UjFKjfaXcJaGMgf9C0fOzwDxPZMOI0CPbNP89cQ=
github.com/jpillora/maplock v0.0.0-20160420012925-5c725ac6e22a/go.mod h1:bn3xq9G+QDq2j6fczyaTq47L6980t7/NnqCnCK7kqD0=
golang.org/x/sys v0.0.0-20190429190828-d89cdac9e872 h1:cGjJzUd8RgBw428LXP65YXni0aiGNA4Bl+ls8SmLOm8=
golang.org/x/sys v0.0.0-20190429190828-d89cdac9e872/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=

0 comments on commit 8f397a2

Please sign in to comment.