-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRaspberryI2CBus.java
More file actions
69 lines (59 loc) · 1.76 KB
/
RaspberryI2CBus.java
File metadata and controls
69 lines (59 loc) · 1.76 KB
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
package com.easternedgerobotics.rov.io.rpi;
import com.easternedgerobotics.rov.io.devices.I2C;
import com.pi4j.io.i2c.I2CBus;
import com.pi4j.io.i2c.I2CFactory;
import com.pi4j.io.i2c.I2CFactory.UnsupportedBusNumberException;
import org.pmw.tinylog.Logger;
import java.io.IOException;
import java.util.AbstractList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public final class RaspberryI2CBus extends AbstractList<I2C> {
/**
* Cache the i2c devices for further lookups.
*/
private final Map<Integer, I2C> lookup = new ConcurrentHashMap<>();
/**
* The physical bus.
*/
private final I2CBus bus;
/**
* Make i2c devices thread safe.
*/
private final Lock lock = new ReentrantLock();
/**
* Create a raspberry pi i2c bus with this channel.
* Returns empty channels if device does not exits or
* the device cannot be found.
*
* @param channel the bus id.
*/
public RaspberryI2CBus(final int channel) {
I2CBus bus;
try {
bus = I2CFactory.getInstance(channel);
} catch (final IOException | UnsupportedBusNumberException e) {
bus = null;
}
this.bus = bus;
}
@Override
public I2C get(final int index) {
return lookup.computeIfAbsent(index, i -> {
if (bus != null) {
try {
return new RaspberryI2C(bus.getDevice(i), lock);
} catch (final IOException e) {
Logger.warn(e);
}
}
return new I2C() { };
});
}
@Override
public int size() {
return Byte.MAX_VALUE;
}
}