Add channel based interface.

This commit is contained in:
Hendrik van Wyk
2017-09-16 13:13:23 +02:00
parent 7eb7037476
commit 58f446de81
3 changed files with 13 additions and 3 deletions

View File

@@ -9,7 +9,6 @@ import (
"log" "log"
"net" "net"
"sync" "sync"
"time"
) )
// Basic CLI to serve as example lib usage // Basic CLI to serve as example lib usage
@@ -49,13 +48,13 @@ func main() {
if err != nil { if err != nil {
panic(err) panic(err)
} }
c := mk2.C()
wg.Add(1) wg.Add(1)
for { for {
tmp := mk2.GetMk2Info() tmp := <-c
if tmp.Valid { if tmp.Valid {
PrintInfo(tmp) PrintInfo(tmp)
} }
time.Sleep(2 * time.Second)
} }
log.Printf("Closing connection") log.Printf("Closing connection")
wg.Wait() wg.Wait()

View File

@@ -24,6 +24,7 @@ type mk2Ser struct {
run chan struct{} run chan struct{}
locked bool locked bool
sync.RWMutex sync.RWMutex
infochan chan *Mk2Info
} }
func NewMk2Connection(dev io.ReadWriter) (Mk2If, error) { func NewMk2Connection(dev io.ReadWriter) (Mk2If, error) {
@@ -36,6 +37,7 @@ func NewMk2Connection(dev io.ReadWriter) (Mk2If, error) {
mk2.sc = make([]scaling, 0) mk2.sc = make([]scaling, 0)
mk2.setTarget() mk2.setTarget()
mk2.run = make(chan struct{}) mk2.run = make(chan struct{})
mk2.infochan = make(chan *Mk2Info)
go mk2.frameLock() go mk2.frameLock()
return mk2, nil return mk2, nil
} }
@@ -97,6 +99,10 @@ func (mk2 *mk2Ser) GetMk2Info() *Mk2Info {
return mk2.report return mk2.report
} }
func (mk2 *mk2Ser) C() chan *Mk2Info {
return mk2.infochan
}
func (mk2 *mk2Ser) readByte() byte { func (mk2 *mk2Ser) readByte() byte {
buffer := make([]byte, 1) buffer := make([]byte, 1)
_, err := io.ReadFull(mk2.p, buffer) _, err := io.ReadFull(mk2.p, buffer)
@@ -121,6 +127,10 @@ func (mk2 *mk2Ser) updateReport() {
mk2.Lock() mk2.Lock()
defer mk2.Unlock() defer mk2.Unlock()
mk2.report = mk2.info mk2.report = mk2.info
select {
case mk2.infochan <- mk2.info:
default:
}
mk2.info = &Mk2Info{} mk2.info = &Mk2Info{}
} }

View File

@@ -55,5 +55,6 @@ type Mk2Info struct {
type Mk2If interface { type Mk2If interface {
GetMk2Info() *Mk2Info GetMk2Info() *Mk2Info
C() chan *Mk2Info
Close() Close()
} }