github.com/martinohmann/rfoutlet@v1.2.1-0.20220707195255-8a66aa411105/pkg/gpio/watcher.go (about)

     1  package gpio
     2  
     3  import "github.com/warthog618/gpiod"
     4  
     5  type watcher struct {
     6  	pin    Closer
     7  	events chan gpiod.LineEvent
     8  }
     9  
    10  // NewWatcher creates a new Watcher for the given pin offset of chip.
    11  func NewWatcher(chip *gpiod.Chip, offset int) (Watcher, error) {
    12  	w := &watcher{
    13  		events: make(chan gpiod.LineEvent),
    14  	}
    15  
    16  	pin, err := chip.RequestLine(offset, gpiod.WithEventHandler(w.handleEvent), gpiod.WithBothEdges)
    17  	if err != nil {
    18  		return nil, err
    19  	}
    20  
    21  	w.pin = pin
    22  
    23  	return w, nil
    24  }
    25  
    26  // handleEvent is the event handler that is invoked by gpiod whether the signal
    27  // edge changes.
    28  func (w *watcher) handleEvent(event gpiod.LineEvent) {
    29  	w.events <- event
    30  }
    31  
    32  // Watch implements Watcher.
    33  func (w *watcher) Watch() <-chan gpiod.LineEvent {
    34  	return w.events
    35  }
    36  
    37  // Close implements Closer.
    38  func (w *watcher) Close() error {
    39  	defer close(w.events)
    40  	return w.pin.Close()
    41  }