diff --git a/rfm69d/rfm69d.go b/rfm69d/rfm69d.go index 6f186bd..a3b78a3 100644 --- a/rfm69d/rfm69d.go +++ b/rfm69d/rfm69d.go @@ -2,6 +2,7 @@ package main import ( "log" + "os" "github.com/fulr/rfm69" "github.com/kidoman/embd" @@ -40,5 +41,13 @@ func main() { } log.Print(rfm) - rfm.Loop() + quit := rfm.Loop() + + sigint := make(chan os.Signal) + os.Notify(sigint, os.Interrupt) + + <-sigint + + quit <- 1 + <-quit } diff --git a/rfm69handler.go b/rfm69handler.go index bbb9d03..b7117f9 100644 --- a/rfm69handler.go +++ b/rfm69handler.go @@ -7,34 +7,46 @@ import ( ) // Loop is the main receive and transmit handling loop -func (r *Device) Loop() error { +func (r *Device) Loop() chan int { + quit := make(chan int) c := make(chan Data) - irq := make(chan int) + go func() { + irq := make(chan int) - r.gpio.Watch(embd.EdgeRising, func(pin embd.DigitalPin) { - irq <- 1 - }) + r.gpio.Watch(embd.EdgeRising, func(pin embd.DigitalPin) { + irq <- 1 + }) - r.SetMode(RF_OPMODE_RECEIVER) + err := r.SetMode(RF_OPMODE_RECEIVER) + if err != nil { + log.Print(err) + return + } + defer r.SetMode(RF_OPMODE_STANDBY) - for { - select { - case dataToTransmit := <-c: - // can send? - r.SetMode(RF_OPMODE_STANDBY) - r.writeFifo(&dataToTransmit) - r.writeReg(REG_DIOMAPPING1, RF_DIOMAPPING1_DIO0_00) - r.SetMode(RF_OPMODE_TRANSMITTER) - <-irq - r.SetMode(RF_OPMODE_RECEIVER) - r.writeReg(REG_DIOMAPPING1, RF_DIOMAPPING1_DIO0_01) - case <-irq: - data, err := r.readFifo() - if err != nil { - log.Print(err) - return err + for { + select { + case dataToTransmit := <-c: + // can send? + r.SetMode(RF_OPMODE_STANDBY) + r.writeFifo(&dataToTransmit) + r.writeReg(REG_DIOMAPPING1, RF_DIOMAPPING1_DIO0_00) + r.SetMode(RF_OPMODE_TRANSMITTER) + <-irq + r.SetMode(RF_OPMODE_RECEIVER) + r.writeReg(REG_DIOMAPPING1, RF_DIOMAPPING1_DIO0_01) + case <-irq: + data, err := r.readFifo() + if err != nil { + log.Print(err) + return + } + log.Print(data) + case <-quit: + quit <- 1 + return } - log.Print(data) } - } + }() + return quit }