
net.freeutils.scrollphat.Pi4JDevice Maven / Gradle / Ivy
/*
* Copyright © 2016 Amichai Rothman
*
* This file is part of JScrollPhat - the Java Scroll pHAT package.
*
* JScrollPhat is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* JScrollPhat is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JScrollPhat. If not, see .
*
* For additional info see http://www.freeutils.net/source/jscrollphat/
*/
package net.freeutils.scrollphat;
import java.io.IOException;
import com.pi4j.io.i2c.I2CBus;
import com.pi4j.io.i2c.I2CDevice;
import com.pi4j.io.i2c.I2CFactory;
/**
* A Device implementation that uses Pi4J for the
* low-level I2C communications with the device.
*
* This implementation requires the Pi4J library to be
* available on the classpath (its native JNI library
* is conveniently embedded in the jar itself.)
*
* @see Pi4J Website
*/
public class Pi4JDevice extends Device {
protected I2CBus bus;
protected I2CDevice device;
@Override
protected Device openImpl(int busNumber, int address) throws IOException {
try {
this.bus = I2CFactory.getInstance(busNumber);
this.device = bus.getDevice(address);
} catch (I2CFactory.UnsupportedBusNumberException ubne) {
throw new IOException("error getting I2C bus: " + ubne);
}
return this;
}
@Override
protected void closeImpl() throws IOException {
if (device != null)
reset();
device = null;
if (bus != null)
bus.close();
bus = null;
}
@Override
protected void writeImpl(byte register, int data) throws IOException {
device.write(register, (byte)data);
}
@Override
protected void writeImpl(byte register, byte[] data, int offset, int length) throws IOException {
device.write(register, data, offset, length);
}
}