i2c: add interface and implementation to allow i2c devices to be connected to alternate i2c buses than default

Signed-off-by: deadprogram <ron@hybridgroup.com>
This commit is contained in:
deadprogram 2017-02-09 09:41:12 +01:00
parent b0a8bda83f
commit 4ebb3b8597
3 changed files with 54 additions and 5 deletions

View File

@ -13,6 +13,7 @@ type BlinkMDriver struct {
name string
connector I2cConnector
connection I2cConnection
I2cBusser
gobot.Commander
}
@ -23,11 +24,16 @@ type BlinkMDriver struct {
// Fade - fades the RGB color
// FirmwareVersion - returns the version of the current Frimware
// Color - returns the color of the LED.
func NewBlinkMDriver(a I2cConnector) *BlinkMDriver {
func NewBlinkMDriver(a I2cConnector, options ...func(I2cBusser)) *BlinkMDriver {
b := &BlinkMDriver{
name: gobot.DefaultName("BlinkM"),
Commander: gobot.NewCommander(),
connector: a,
I2cBusser: NewI2cBusser(),
}
for _, option := range options {
option(b)
}
b.AddCommand("Rgb", func(params map[string]interface{}) interface{} {
@ -65,8 +71,11 @@ func (b *BlinkMDriver) Connection() gobot.Connection { return b.connection.(gobo
// Start starts the Driver up, and writes start command
func (b *BlinkMDriver) Start() (err error) {
bus := b.connector.I2cGetDefaultBus()
b.connection, err = b.connector.I2cGetConnection(blinkmAddress, bus)
if b.GetBus() == BusNotInitialized {
b.Bus(b.connector.I2cGetDefaultBus())
}
b.connection, err = b.connector.I2cGetConnection(blinkmAddress, b.GetBus())
if err != nil {
return
}

View File

@ -20,6 +20,10 @@ const (
Z = "z"
)
const (
BusNotInitialized = -1
)
// I2cConnection is a connection to an I2C device with a specified address
// on a specific bus. Used as an alternative to the I2c interface.
// Implements sysfs.I2cOperations to talk to the device, wrapping the
@ -121,3 +125,39 @@ type I2cConnector interface {
// I2cGetDefaultBus returns the default I2C bus index
I2cGetDefaultBus() int
}
type i2cBusser struct {
bus int
}
// I2cBusser is the interface which describes how a Driver can specify
// which I2C bus it wants to use
type I2cBusser interface {
// Bus sets which bus to use
Bus(bus int)
// GetBus gets which bus to use
GetBus() int
}
// NewI2cBusser returns a new I2cBusser.
func NewI2cBusser() I2cBusser {
return &i2cBusser{}
}
// Bus sets which bus to use
func (i *i2cBusser) Bus(bus int) {
i.bus = bus
}
// GetBus gets which bus to use
func (i *i2cBusser) GetBus() int {
return i.bus
}
// Bus sets which bus to use as a optional param
func Bus(bus int) func(I2cBusser) {
return func(i I2cBusser) {
i.Bus(bus)
}
}

View File

@ -11,10 +11,10 @@ import (
func main() {
e := joule.NewAdaptor()
blinkm := i2c.NewBlinkMDriver(e)
blinkm := i2c.NewBlinkMDriver(e, i2c.Bus(2))
work := func() {
gobot.Every(3*time.Second, func() {
gobot.Every(1*time.Second, func() {
r := byte(gobot.Rand(255))
g := byte(gobot.Rand(255))
b := byte(gobot.Rand(255))