tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/tester/device8.go (about) 1 package tester 2 3 // I2CDevice represents a mock I2C device on a mock I2C bus with 8-bit registers. 4 type I2CDevice8 struct { 5 c Failer 6 // addr is the i2c device address. 7 addr uint8 8 // Registers holds the device registers. It can be inspected 9 // or changed as desired for testing. 10 Registers [MaxRegisters]uint8 11 // If Err is non-nil, it will be returned as the error from the 12 // I2C methods. 13 Err error 14 } 15 16 // NewI2CDevice returns a new mock I2C device. 17 // 18 // For compatibility, this creates an instance of NewI2CDevice8 19 func NewI2CDevice(c Failer, addr uint8) *I2CDevice8 { 20 return NewI2CDevice8(c, addr) 21 } 22 23 // NewI2CDevice8 returns a new mock I2C device. 24 func NewI2CDevice8(c Failer, addr uint8) *I2CDevice8 { 25 return &I2CDevice8{ 26 c: c, 27 addr: addr, 28 } 29 } 30 31 // Addr returns the Device address. 32 func (d *I2CDevice8) Addr() uint8 { 33 return d.addr 34 } 35 36 // ReadRegister implements I2C.ReadRegister. 37 func (d *I2CDevice8) readRegister(r uint8, buf []byte) error { 38 if d.Err != nil { 39 return d.Err 40 } 41 if len(buf) == 0 { 42 d.c.Fatalf("no register buffer to read into") 43 } 44 d.assertRegisterRange(r, buf) 45 copy(buf, d.Registers[r:]) 46 return nil 47 } 48 49 // WriteRegister implements I2C.WriteRegister. 50 func (d *I2CDevice8) writeRegister(r uint8, buf []byte) error { 51 if d.Err != nil { 52 return d.Err 53 } 54 d.assertRegisterRange(r, buf) 55 copy(d.Registers[r:], buf) 56 return nil 57 } 58 59 // Tx implements I2C.Tx. 60 func (bus *I2CDevice8) Tx(w, r []byte) error { 61 switch len(w) { 62 case 0: 63 bus.c.Fatalf("i2c mock: need a write byte") 64 return nil 65 case 1: 66 return bus.readRegister(w[0], r) 67 default: 68 if len(r) > 0 || len(w) == 1 { 69 bus.c.Fatalf("i2c mock: unsupported lengths in Tx(%d, %d)", len(w), len(r)) 70 } 71 return bus.writeRegister(w[0], w[1:]) 72 } 73 } 74 75 // assertRegisterRange asserts that reading or writing the given 76 // register and subsequent registers is in range of the available registers. 77 func (d *I2CDevice8) assertRegisterRange(r uint8, buf []byte) { 78 if int(r) >= len(d.Registers) { 79 d.c.Fatalf("register read/write [%#x, %#x] start out of range", r, int(r)+len(buf)) 80 } 81 if int(r)+len(buf) > len(d.Registers) { 82 d.c.Fatalf("register read/write [%#x, %#x] end out of range", r, int(r)+len(buf)) 83 } 84 }