Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add locking capabilities and simple test #130

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
31 changes: 31 additions & 0 deletions basic_test.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,41 @@
//go:build linux
// +build linux

/*
How to run tests
// socat virtual serial ports
socat -d -d pty,rawer,echo=0,link=/tmp/ttyV0 pty,rawer,echo=0,link=/tmp/ttyV1
// run test
PORT0=/tmp/ttyV0 PORT1=/tmp/ttyV1 go test -tags=linux -p 1 -v .
*/
package serial

import (
"errors"
"os"
"testing"
"time"
)

func TestLocking(t *testing.T) {
port0 := "/tmp/ttyV0" //os.Getenv("PORT0")
if port0 == "" {
t.Skip("Skipping test because PORT0 environment variable is not set")
}
c0 := &Config{Name: port0, Baud: 115200}

s1, err := OpenPort(c0)
if err != nil {
t.Fatal(err)
}

_, err = OpenPort(c0)
if !errors.Is(ErrAlreadyLocked, err) {
t.Fatal(err)
}
s1.Close()
}

func TestConnection(t *testing.T) {
port0 := os.Getenv("PORT0")
port1 := os.Getenv("PORT1")
Expand Down Expand Up @@ -66,4 +94,7 @@ func TestConnection(t *testing.T) {
if c >= exp {
t.Fatalf("Expected less than %v read, got %v", exp, c)
}
// these close() may cause some issues
// s1.Close()
// s2.Close()
}
7 changes: 7 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module github.com/mv-kan/serial

go 1.20

require golang.org/x/sys v0.13.0

require github.com/gofrs/flock v0.8.1 // indirect
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw=
github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU=
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
13 changes: 13 additions & 0 deletions hashing.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package serial

import (
"crypto/sha256"
"encoding/hex"
)

// 6 letter hash
func shortHash(str string) string {
bs := sha256.Sum256([]byte(str))
hash := hex.EncodeToString(bs[:])[:6]
return hash
}
41 changes: 36 additions & 5 deletions serial_linux.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
//go:build linux
// +build linux

package serial

import (
"errors"
"fmt"
"os"
"path"
"path/filepath"
"time"
"unsafe"

"github.com/gofrs/flock"
"golang.org/x/sys/unix"
)

var (
ErrAlreadyLocked = errors.New("this port already has locked file")
)

func openPort(name string, baud int, databits byte, parity Parity, stopbits StopBits, readTimeout time.Duration) (p *Port, err error) {
var bauds = map[int]uint32{
50: unix.B50,
Expand Down Expand Up @@ -46,17 +55,36 @@ func openPort(name string, baud int, databits byte, parity Parity, stopbits Stop
}

rate, ok := bauds[baud]

if !ok {
return nil, fmt.Errorf("Unrecognized baud rate")
return nil, fmt.Errorf("unrecognized baud rate")
}

f, err := os.OpenFile(name, unix.O_RDWR|unix.O_NOCTTY|unix.O_NONBLOCK, 0666)
fpath, err := filepath.Abs(name)
if err != nil {
return nil, err
}
lockdir := "/var/lock"
lockpath := path.Join(lockdir, fmt.Sprintf("%s_%s.lock", filepath.Base(fpath), shortHash(fpath)))
lock := flock.New(lockpath)

locked, err := lock.TryLock()
if err != nil {
return nil, err
}
if !locked {
return nil, ErrAlreadyLocked
}

f, err := os.OpenFile(fpath, unix.O_RDWR|unix.O_NOCTTY|unix.O_NONBLOCK, 0666)
if err != nil {
return nil, err
}

defer func() {
if err != nil {
lock.Unlock()
os.Remove(lockpath)
}
if err != nil && f != nil {
f.Close()
}
Expand Down Expand Up @@ -125,13 +153,14 @@ func openPort(name string, baud int, databits byte, parity Parity, stopbits Stop
return
}

return &Port{f: f}, nil
return &Port{f: f, lock: lock}, nil
}

type Port struct {
// We intentionly do not use an "embedded" struct so that we
// don't export File
f *os.File
f *os.File
lock *flock.Flock
}

func (p *Port) Read(b []byte) (n int, err error) {
Expand Down Expand Up @@ -160,5 +189,7 @@ func (p *Port) Flush() error {
}

func (p *Port) Close() (err error) {
p.lock.Unlock()
os.Remove(p.lock.Path())
return p.f.Close()
}