Skip to content

Commit

Permalink
export Watcher.Notification
Browse files Browse the repository at this point in the history
  • Loading branch information
brian-armstrong committed Dec 30, 2017
1 parent 8a6b03e commit 3846dfc
Showing 1 changed file with 22 additions and 18 deletions.
40 changes: 22 additions & 18 deletions watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@ type watcherCmd struct {
action watcherAction
}

type watcherNotify struct {
pin Pin
value uint
// WatcherNotification represents a single pin change
// The new value of the pin numbered by Pin is Value
type WatcherNotification struct {
Pin uint
Value uint
}

type fdHeap []uintptr
Expand Down Expand Up @@ -56,24 +58,25 @@ func (h fdHeap) FdSet() *syscall.FdSet {
}

const watcherCmdChanLen = 32
const notifyChanLen = 32
const notificationLen = 32

// Watcher provides asynchronous notifications on input changes
// The user should supply it pins to watch with AddPin and then wait for changes with Watch
// Alternately, users may receive directly from the Notification channel
type Watcher struct {
pins map[uintptr]Pin
fds fdHeap
cmdChan chan watcherCmd
notifyChan chan watcherNotify
pins map[uintptr]Pin
fds fdHeap
cmdChan chan watcherCmd
Notification chan WatcherNotification
}

// NewWatcher creates a new Watcher instance for asynchronous inputs
func NewWatcher() *Watcher {
w := &Watcher{
pins: make(map[uintptr]Pin),
fds: fdHeap{},
cmdChan: make(chan watcherCmd, watcherCmdChanLen),
notifyChan: make(chan watcherNotify, notifyChanLen),
pins: make(map[uintptr]Pin),
fds: fdHeap{},
cmdChan: make(chan watcherCmd, watcherCmdChanLen),
Notification: make(chan WatcherNotification, notificationLen),
}
heap.Init(&w.fds)
go w.watch()
Expand All @@ -93,12 +96,12 @@ func (w *Watcher) notify(fdset *syscall.FdSet) {
fmt.Printf("failed to read pinfile, %s", err)
os.Exit(1)
}
msg := watcherNotify{
pin: pin,
value: val,
msg := WatcherNotification{
Pin: pin.Number,
Value: val,
}
select {
case w.notifyChan <- msg:
case w.Notification <- msg:
default:
}
}
Expand Down Expand Up @@ -223,9 +226,10 @@ func (w *Watcher) RemovePin(p uint) {
// Because the Watcher is not perfectly realtime it may miss very high frequency changes
// If that happens, it's possible to see consecutive changes with the same value
// Also, if the input is connected to a mechanical switch, the user of this library must deal with debouncing
// Users can either use Watch() or receive from Watcher.Notification directly
func (w *Watcher) Watch() (p uint, v uint) {
notification := <-w.notifyChan
return notification.pin.Number, notification.value
notification := <-w.Notification
return notification.Pin, notification.Value
}

// Close stops the watcher and releases all resources
Expand Down

0 comments on commit 3846dfc

Please sign in to comment.