gobot.io/x/gobot@v1.16.0/drivers/i2c/i2c_config.go (about)

     1  package i2c
     2  
     3  type i2cConfig struct {
     4  	bus     int
     5  	address int
     6  }
     7  
     8  // Config is the interface which describes how a Driver can specify
     9  // optional I2C params such as which I2C bus it wants to use.
    10  type Config interface {
    11  	// WithBus sets which bus to use
    12  	WithBus(bus int)
    13  
    14  	// GetBusOrDefault gets which bus to use
    15  	GetBusOrDefault(def int) int
    16  
    17  	// WithAddress sets which address to use
    18  	WithAddress(address int)
    19  
    20  	// GetAddressOrDefault gets which address to use
    21  	GetAddressOrDefault(def int) int
    22  }
    23  
    24  // NewConfig returns a new I2c Config.
    25  func NewConfig() Config {
    26  	return &i2cConfig{bus: BusNotInitialized, address: AddressNotInitialized}
    27  }
    28  
    29  // WithBus sets preferred bus to use.
    30  func (i *i2cConfig) WithBus(bus int) {
    31  	i.bus = bus
    32  }
    33  
    34  // GetBusOrDefault returns which bus to use, either the one set using WithBus(),
    35  // or the default value which is passed in as the one param.
    36  func (i *i2cConfig) GetBusOrDefault(d int) int {
    37  	if i.bus == BusNotInitialized {
    38  		return d
    39  	}
    40  
    41  	return i.bus
    42  }
    43  
    44  // WithBus sets which bus to use as a optional param.
    45  func WithBus(bus int) func(Config) {
    46  	return func(i Config) {
    47  		i.WithBus(bus)
    48  	}
    49  }
    50  
    51  // WithAddress sets which address to use.
    52  func (i *i2cConfig) WithAddress(address int) {
    53  	i.address = address
    54  }
    55  
    56  // GetAddressOrDefault returns which address to use, either
    57  // the one set using WithBus(), or the default value which
    58  // is passed in as the param.
    59  func (i *i2cConfig) GetAddressOrDefault(a int) int {
    60  	if i.address == AddressNotInitialized {
    61  		return a
    62  	}
    63  
    64  	return i.address
    65  }
    66  
    67  // WithAddress sets which address to use as a optional param.
    68  func WithAddress(address int) func(Config) {
    69  	return func(i Config) {
    70  		i.WithAddress(address)
    71  	}
    72  }