tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/tester/i2c.go (about)

     1  package tester
     2  
     3  import "fmt"
     4  
     5  // I2CBus implements the I2C interface in memory for testing.
     6  type I2CBus struct {
     7  	c       Failer
     8  	devices []I2CDevice
     9  }
    10  
    11  // NewI2CBus returns an I2CBus mock I2C instance that uses c to flag errors
    12  // if they happen. After creating a I2C instance, add devices
    13  // to it with addDevice before using NewI2CBus interface.
    14  func NewI2CBus(c Failer) *I2CBus {
    15  	return &I2CBus{
    16  		c: c,
    17  	}
    18  }
    19  
    20  // AddDevice adds a new mock device to the mock I2C bus.
    21  // It panics if a device with the same address is added more than once.
    22  func (bus *I2CBus) AddDevice(d I2CDevice) {
    23  	for _, dev := range bus.devices {
    24  		if dev.Addr() == d.Addr() {
    25  			panic(fmt.Errorf("device already added at address %#x", d))
    26  		}
    27  	}
    28  	bus.devices = append(bus.devices, d)
    29  }
    30  
    31  // NewDevice creates a new device with the given address
    32  // and adds it to the mock I2C bus.
    33  func (bus *I2CBus) NewDevice(addr uint8) *I2CDevice8 {
    34  	dev := NewI2CDevice8(bus.c, addr)
    35  	bus.AddDevice(dev)
    36  	return dev
    37  }
    38  
    39  // ReadRegister implements I2C.ReadRegister.
    40  func (bus *I2CBus) ReadRegister(addr uint8, r uint8, buf []byte) error {
    41  	return bus.FindDevice(addr).readRegister(r, buf)
    42  }
    43  
    44  // WriteRegister implements I2C.WriteRegister.
    45  func (bus *I2CBus) WriteRegister(addr uint8, r uint8, buf []byte) error {
    46  	return bus.FindDevice(addr).writeRegister(r, buf)
    47  }
    48  
    49  // Tx implements I2C.Tx.
    50  func (bus *I2CBus) Tx(addr uint16, w, r []byte) error {
    51  	return bus.FindDevice(uint8(addr)).Tx(w, r)
    52  }
    53  
    54  // FindDevice returns the device with the given address.
    55  func (bus *I2CBus) FindDevice(addr uint8) I2CDevice {
    56  	for _, dev := range bus.devices {
    57  		if dev.Addr() == addr {
    58  			return dev
    59  		}
    60  	}
    61  	bus.c.Fatalf("invalid device addr %#x passed to i2c bus", addr)
    62  	panic("unreachable")
    63  }