2014-04-06 03:20:09 +02:00
|
|
|
// Generic I²C driver.
|
2014-03-23 09:39:31 +01:00
|
|
|
|
2014-03-02 20:21:23 +01:00
|
|
|
package embd
|
2014-02-26 23:54:53 +01:00
|
|
|
|
2014-04-06 03:20:09 +02:00
|
|
|
import "sync"
|
|
|
|
|
|
|
|
type i2cBusFactory func(byte) I2CBus
|
2014-02-26 23:54:53 +01:00
|
|
|
|
2014-03-02 20:21:23 +01:00
|
|
|
type i2cDriver struct {
|
2014-04-06 03:20:09 +02:00
|
|
|
busMap map[byte]I2CBus
|
2014-03-02 20:21:23 +01:00
|
|
|
busMapLock sync.Mutex
|
2014-04-06 03:20:09 +02:00
|
|
|
|
|
|
|
ibf i2cBusFactory
|
2014-03-02 20:21:23 +01:00
|
|
|
}
|
|
|
|
|
2014-04-06 03:20:09 +02:00
|
|
|
// NewI2CDriver returns a I2CDriver interface which allows control
|
|
|
|
// over the I²C subsystem.
|
|
|
|
func NewI2CDriver(ibf i2cBusFactory) I2CDriver {
|
2014-03-02 20:21:23 +01:00
|
|
|
return &i2cDriver{
|
2014-04-06 03:20:09 +02:00
|
|
|
busMap: make(map[byte]I2CBus),
|
|
|
|
ibf: ibf,
|
2014-03-02 20:21:23 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (i *i2cDriver) Bus(l byte) I2CBus {
|
|
|
|
i.busMapLock.Lock()
|
|
|
|
defer i.busMapLock.Unlock()
|
|
|
|
|
2014-04-06 03:20:09 +02:00
|
|
|
if b, ok := i.busMap[l]; ok {
|
|
|
|
return b
|
2014-03-02 20:21:23 +01:00
|
|
|
}
|
|
|
|
|
2014-04-06 03:20:09 +02:00
|
|
|
b := i.ibf(l)
|
|
|
|
i.busMap[l] = b
|
2014-03-02 20:21:23 +01:00
|
|
|
return b
|
|
|
|
}
|
|
|
|
|
|
|
|
func (i *i2cDriver) Close() error {
|
|
|
|
for _, b := range i.busMap {
|
|
|
|
b.Close()
|
2014-02-26 23:54:53 +01:00
|
|
|
}
|
|
|
|
|
2014-03-23 00:39:13 +01:00
|
|
|
return nil
|
2014-02-26 23:54:53 +01:00
|
|
|
}
|