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