/
i2c.dart
58 lines (46 loc) · 1.64 KB
/
i2c.dart
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
/// Base I2C interface supported by all I2C implementations.
abstract class I2C {
final _allocatedAddresses = <int>[];
/// Check that the address can be used for I2C
/// and that is has not already been allocated.
/// This should be called by subclasses not clients.
void allocateAddress(int address) {
if (_allocatedAddresses.contains(address)) {
throw I2CException('Already allocated', address);
}
_allocatedAddresses.add(address);
}
/// Return the [I2CDevice] for communicating with the device at [address].
I2CDevice device(int address);
/// Call dispose before exiting your application to cleanup native resources.
void dispose();
}
/// An I2C Device
abstract class I2CDevice {
final int address;
I2CDevice(this.address);
/// Read a byte from register #[register].
int readByte(int register);
/// Read a 16 bit value from register #[register] or two consecutive registers.
int readWord(int register);
/// Read [values].length # of bytes from the device (no register)
/// into [values] where the [values].length is between 1 and 32 inclusive.
/// Return the # of bytes read.
int readBytes(List<int> values);
/// Write a byte to register #[register].
void writeByte(int register, int value);
}
/// Exceptions thrown by I2C.
class I2CException {
final String message;
final int? address;
final int? errorNumber;
I2CException(this.message, [this.address, this.errorNumber]);
@override
String toString() {
var msg = message;
if (address != null) msg = '$msg, address: $address';
if (errorNumber != null) msg = '$msg, error: $errorNumber';
return 'I2CException: $msg';
}
}