diff --git a/qmk-cmd.go b/qmk-cmd.go index 25815f9..f766b1b 100644 --- a/qmk-cmd.go +++ b/qmk-cmd.go @@ -285,6 +285,9 @@ func setCfg(dev *QEncDevice, cfg QEncCfg, val uint8) (err error) { } func sendDataWrapper(dev *QEncDevice, data []byte, cmd QEncCmd, id uint32) (ret []byte, err error) { + dev.Lock() + defer dev.UnLock() + done := make(chan bool) msgc := make(chan string) diff --git a/qmk-dev.go b/qmk-dev.go index f8bcfda..2d5dec9 100644 --- a/qmk-dev.go +++ b/qmk-dev.go @@ -3,6 +3,7 @@ package qmkenc import ( "encoding/binary" "fmt" + "os" "time" "github.com/sstallion/go-hid" @@ -21,6 +22,7 @@ type QEncDevice struct { timeout int retryTimeout int retryWait int + lockfile string } func (d *QEncDevice) GetPath() string { return d.path } @@ -42,9 +44,16 @@ func (d *QEncDevice) Open() (err error) { } func (d *QEncDevice) Close() (err error) { + if d.lockfile != "" { + os.Remove(d.lockfile) + } return d.dev.Close() } +func (d *QEncDevice) SetLockfile(lockfile string) { + d.lockfile = lockfile +} + func (d *QEncDevice) SendBuffer(data []byte, msg chan string) (ret []byte, err error) { startTime := time.Now() for { @@ -130,13 +139,41 @@ func (d *QEncDevice) setBufSize() (err error) { return fmt.Errorf("Unsupported device: '%w'", err) } -func QEncNewDevice(path string, bufSize uint8, timeout, retryTimeout, retryWait int) *QEncDevice { +func (d *QEncDevice) Lock() (err error) { + if d.lockfile == "" { + return nil + } + + for { + if _, err := os.Stat(d.lockfile); err == nil { + time.Sleep(time.Second * 1) + continue + } else if os.IsNotExist(err) { + file, err := os.Create(d.lockfile) + if err != nil { + return err + } + file.Close() + return nil + } + } +} + +func (d *QEncDevice) UnLock() { + if d.lockfile == "" { + return + } + os.Remove(d.lockfile) +} + +func QEncNewDevice(path string, bufSize uint8, timeout, retryTimeout, retryWait int, lockfile string) *QEncDevice { return &QEncDevice{ path: path, timeout: timeout, retryTimeout: retryTimeout, retryWait: retryWait, bufSize: bufSize, + lockfile: lockfile, } }