github.com/martinohmann/rfoutlet@v1.2.1-0.20220707195255-8a66aa411105/cmd/chip.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  
     6  	log "github.com/sirupsen/logrus"
     7  	"github.com/spf13/cobra"
     8  	"github.com/warthog618/gpiod"
     9  	"github.com/warthog618/gpiod/mockup"
    10  )
    11  
    12  type device struct {
    13  	*gpiod.Chip
    14  	*mockup.Mockup
    15  }
    16  
    17  func (d *device) Close() error {
    18  	err := d.Chip.Close()
    19  	if err != nil {
    20  		return err
    21  	}
    22  
    23  	if d.Mockup != nil {
    24  		log.Debug("removing gpio mockup")
    25  		return d.Mockup.Close()
    26  	}
    27  
    28  	return nil
    29  }
    30  
    31  func openGPIODevice(cmd *cobra.Command) (*device, error) {
    32  	gpioChipName, _ := cmd.Flags().GetString("gpio-chip")
    33  	gpioMockup, _ := cmd.Flags().GetBool("gpio-mockup")
    34  
    35  	var (
    36  		dev *device = &device{}
    37  		err error
    38  	)
    39  
    40  	if gpioMockup {
    41  		log.Debug("creating gpio mockup")
    42  		dev.Mockup, err = mockup.New([]int{40}, false)
    43  		if err != nil {
    44  			return nil, fmt.Errorf("failed to create gpio mockup: %v", err)
    45  		}
    46  	}
    47  
    48  	dev.Chip, err = gpiod.NewChip(gpioChipName)
    49  	if err != nil {
    50  		return nil, fmt.Errorf("failed to open gpio device: %v", err)
    51  	}
    52  
    53  	return dev, nil
    54  }