Client and backend. This class is shared: the same code is compiled into your app and into your server, so everything on this page works in both.

public class Hardware

  1. Object
  2. Hardware

Entry point to the buses and pins of the device the application runs on: GPIO lines, I2C, SPI, serial ports, PWM, CAN, the hardware watchdog and the display backlight.

This is the API for boards such as the Raspberry Pi, i.MX, Rockchip and other embedded Linux devices. Every method is available on every platform; a port without the hardware reports it through isSupported(int) and its open methods throw HardwareException, so the same application runs on a phone, a desktop or the simulator.

Hardware hw = Hardware.getInstance();
try {
    if (hw.isSupported(Hardware.FEATURE_GPIO)) {
        final GpioPin led = hw.openGpioOutput("gpiochip0", 17, false);
        led.setHigh(true);

        GpioPin button = hw.openGpioInput("gpiochip0", 27, GpioPin.BIAS_PULL_UP, GpioPin.EDGE_FALLING);
        button.setListener(new GpioListener() {
            public void edgeDetected(GpioPin pin, boolean rising, long timestampNanos) {
                try {
                    led.setHigh(!led.isHigh());
                } catch (HardwareException e) {
                    Log.e(e);
                }
            }
        });
    }
} catch (HardwareException e) {
    Log.e(e);
}

Threading

The transfer methods block for the duration of the bus transaction, which is microseconds for GPIO, I2C and SPI. Serial and CAN reads can wait for data; call them off the event dispatch thread, or use their timeout arguments. Listener callbacks always arrive on the event dispatch thread.

For port implementors

A port subclasses this class and overrides the protected primitives, which take and return integer handles. The device classes (GpioPin, I2cDevice, …) are written once over those primitives, so a port never subclasses them. Every primitive’s default throws HardwareException.

Fields

public static final int FEATURE_GPIO = 1GPIO lines through the GPIO character device.
public static final int FEATURE_I2C = 2I2C buses.
public static final int FEATURE_SPI = 4SPI buses.
public static final int FEATURE_SERIAL = 8Serial ports (UART, USB serial adapters).
public static final int FEATURE_PWM = 16Hardware PWM channels.
public static final int FEATURE_CAN = 32CAN buses.
public static final int FEATURE_WATCHDOG = 64The hardware watchdog.
public static final int FEATURE_BACKLIGHT = 128Display backlight brightness control.
protected static final int EDGE_TIMEOUT = -1Edge-wait result: the wait timed out.
protected static final int EDGE_RESULT_FALLING = 0Edge-wait result: a falling edge.
protected static final int EDGE_RESULT_RISING = 1Edge-wait result: a rising edge.

Constructors

protected Hardware()Ports construct subclasses; applications call getInstance().

Methods

public static Hardware getInstance()Returns the hardware entry point of the current port.
public static void install(Hardware hardware)Makes hardware the instance getInstance() returns; null restores the unsupported default.
protected void deliver(Runnable callback)Hands a listener callback to the thread listeners run on.
public boolean isSupported()true when the port supports at least one hardware feature.
public boolean isSupported(int feature)true when the port supports the given feature, one of the FEATURE_ constants.
protected int getSupportedFeatures()Bit mask of the FEATURE_ constants this port implements.
public String[] listGpioChips()Names of the GPIO controllers on this device, for example gpiochip0.
public int[] listI2cBuses()Numbers of the I2C buses on this device (/dev/i2c-N on Linux).
public String[] listSpiDevices()SPI devices as bus.chipSelect strings, for example 0.1.
public String[] listSerialPorts()Device paths of the serial ports on this device, for example /dev/ttyAMA0 or /dev/ttyUSB0.
public String[] listCanInterfaces()Names of the CAN network interfaces, for example can0.
public GpioPin openGpioOutput(String chip, int line, boolean initialHigh) throws HardwareExceptionClaims a GPIO line as an output.
public GpioPin openGpioInput(String chip, int line, int bias, int edges) throws HardwareExceptionClaims a GPIO line as an input.
public I2cDevice openI2c(int bus, int address) throws HardwareExceptionOpens the device at a 7-bit address on an I2C bus.
public SpiDevice openSpi(int bus, int chipSelect, int mode, int speedHz, int bitsPerWord) throws HardwareExceptionOpens an SPI device.
public SerialPort openSerial(String device, int baud, int dataBits, int parity, int stopBits) throws HardwareExceptionOpens a serial port in raw mode.
public PwmChannel openPwm(int chip, int channel) throws HardwareExceptionOpens a hardware PWM channel.
public CanBus openCan(String iface) throws HardwareExceptionOpens a CAN network interface.
public Watchdog openWatchdog(int timeoutSeconds) throws HardwareExceptionOpens and starts the hardware watchdog.
public int getBacklightBrightness()The current backlight brightness, from 0 to getMaxBacklightBrightness(), or -1 when not supported.
public int getMaxBacklightBrightness()The highest backlight brightness value, or -1 when not supported.
public void setBacklightBrightness(int value) throws HardwareExceptionSets the backlight brightness, clamped to the valid range.
protected static HardwareException unsupported(String what)Creates the exception the default primitives throw.
protected int gpioOpen(String chip, int line, boolean output, boolean initialHigh, int bias, int edges) throws HardwareExceptionClaims a GPIO line and returns its handle.
protected boolean gpioRead(int handle) throws HardwareExceptionReads a GPIO line: true for high.
protected void gpioWrite(int handle, boolean high) throws HardwareExceptionDrives an output GPIO line.
protected int gpioWaitEdge(int handle, int timeoutMs, long[] timestampOut) throws HardwareExceptionWaits up to timeoutMs for an edge on an input line.
protected int i2cOpen(int bus, int address) throws HardwareExceptionOpens an I2C device and returns its handle.
protected void i2cTransfer(int handle, byte[] write, int writeLen, byte[] read, int readLen) throws HardwareExceptionPerforms one combined I2C transaction: writes writeLen bytes from write, then, with a repeated start and no stop between, reads readLen bytes into read.
protected int spiOpen(int bus, int chipSelect, int mode, int speedHz, int bitsPerWord) throws HardwareExceptionOpens and configures an SPI device and returns its handle.
protected void spiTransfer(int handle, byte[] tx, byte[] rx, int len) throws HardwareExceptionPerforms one full-duplex SPI transfer of len bytes.
protected int serialOpen(String device, int baud, int dataBits, int parity, int stopBits) throws HardwareExceptionOpens and configures a serial port and returns its handle.
protected int serialRead(int handle, byte[] buf, int off, int len, int timeoutMs) throws HardwareExceptionReads up to len bytes, waiting at most timeoutMs (negative waits forever) for the first one.
protected void serialWrite(int handle, byte[] buf, int off, int len) throws HardwareExceptionWrites all len bytes.
protected int pwmOpen(int chip, int channel) throws HardwareExceptionOpens a PWM channel and returns its handle.
protected void pwmConfigure(int handle, long periodNanos, long dutyNanos, boolean enabled) throws HardwareExceptionConfigures a PWM channel.
protected int canOpen(String iface) throws HardwareExceptionOpens a CAN interface and returns its handle.
protected void canSend(int handle, int id, boolean extended, byte[] data, int len) throws HardwareExceptionSends one CAN frame.
protected int canReceive(int handle, int[] idOut, byte[] data, int timeoutMs) throws HardwareExceptionWaits up to timeoutMs for a CAN frame.
protected int watchdogOpen(int timeoutSeconds) throws HardwareExceptionOpens the watchdog with a timeout and returns its handle.
protected void watchdogKick(int handle) throws HardwareExceptionResets the watchdog timer.
protected void close(int handle, boolean disarm)Closes any handle.

Inherited methods

Field details

FEATURE_GPIO

public static final int FEATURE_GPIO = 1
GPIO lines through the GPIO character device.

FEATURE_I2C

public static final int FEATURE_I2C = 2
I2C buses.

FEATURE_SPI

public static final int FEATURE_SPI = 4
SPI buses.

FEATURE_SERIAL

public static final int FEATURE_SERIAL = 8
Serial ports (UART, USB serial adapters).

FEATURE_PWM

public static final int FEATURE_PWM = 16
Hardware PWM channels.

FEATURE_CAN

public static final int FEATURE_CAN = 32
CAN buses.

FEATURE_WATCHDOG

public static final int FEATURE_WATCHDOG = 64
The hardware watchdog.

FEATURE_BACKLIGHT

public static final int FEATURE_BACKLIGHT = 128
Display backlight brightness control.

EDGE_TIMEOUT

protected static final int EDGE_TIMEOUT = -1
Edge-wait result: the wait timed out.

EDGE_RESULT_FALLING

protected static final int EDGE_RESULT_FALLING = 0
Edge-wait result: a falling edge.

EDGE_RESULT_RISING

protected static final int EDGE_RESULT_RISING = 1
Edge-wait result: a rising edge.

Constructor details

Hardware

protected Hardware()
Ports construct subclasses; applications call getInstance().

Method details

getInstance

public static Hardware getInstance()
Returns the hardware entry point of the current port. On a port without hardware access this is a base instance that supports nothing, so callers never need a null check.

install

public static void install(Hardware hardware)
Makes hardware the instance getInstance() returns; null restores the unsupported default. Display installs the port’s instance when it starts, and the backend runtime installs its own, which is why this class never names Display itself.

deliver

protected void deliver(Runnable callback)
Hands a listener callback to the thread listeners run on. The client ports post it to the event dispatch thread; the default, used by the headless backend, runs it on the calling thread.

isSupported

public boolean isSupported()
true when the port supports at least one hardware feature.

isSupported

public boolean isSupported(int feature)
true when the port supports the given feature, one of the FEATURE_ constants. Support means the port can drive the bus; whether the board exposes one is answered by the matching list method.

getSupportedFeatures

protected int getSupportedFeatures()
Bit mask of the FEATURE_ constants this port implements. Ports override this; the default supports nothing.

listGpioChips

public String[] listGpioChips()
Names of the GPIO controllers on this device, for example gpiochip0. Empty when there are none or GPIO is unsupported.

listI2cBuses

public int[] listI2cBuses()
Numbers of the I2C buses on this device (/dev/i2c-N on Linux).

listSpiDevices

public String[] listSpiDevices()
SPI devices as bus.chipSelect strings, for example 0.1.

listSerialPorts

public String[] listSerialPorts()
Device paths of the serial ports on this device, for example /dev/ttyAMA0 or /dev/ttyUSB0.

listCanInterfaces

public String[] listCanInterfaces()
Names of the CAN network interfaces, for example can0.

openGpioOutput

public GpioPin openGpioOutput(String chip, int line, boolean initialHigh) throws HardwareException
Claims a GPIO line as an output.

Parameters

chip String
the controller name from listGpioChips()
line int
the line offset within the controller (the BCM number on a Raspberry Pi’s gpiochip0)
initialHigh boolean
the level the line is driven to when claimed

Throws

HardwareException
when the line does not exist, is claimed by another consumer, or GPIO is unsupported

openGpioInput

public GpioPin openGpioInput(String chip, int line, int bias, int edges) throws HardwareException
Claims a GPIO line as an input.

Parameters

chip String
the controller name from listGpioChips()
line int
the line offset within the controller
bias int
one of the GpioPin.BIAS_ constants
edges int
which edges GpioPin.setListener(GpioListener) reports, one of the GpioPin.EDGE_ constants

Throws

HardwareException
when the line cannot be claimed

openI2c

public I2cDevice openI2c(int bus, int address) throws HardwareException
Opens the device at a 7-bit address on an I2C bus.

Throws

HardwareException
when the bus does not exist or I2C is unsupported

openSpi

public SpiDevice openSpi(int bus, int chipSelect, int mode, int speedHz, int bitsPerWord) throws HardwareException
Opens an SPI device.

Parameters

bus int
the SPI controller number
chipSelect int
the chip-select line
mode int
SPI mode 0 to 3 (clock polarity and phase)
speedHz int
the clock rate
bitsPerWord int
the word size, usually 8

Throws

HardwareException
when the device does not exist or rejects the configuration

openSerial

public SerialPort openSerial(String device, int baud, int dataBits, int parity, int stopBits) throws HardwareException
Opens a serial port in raw mode.

Parameters

device String
the port, from listSerialPorts()
baud int
the baud rate, for example 9600 or 115200
dataBits int
5 to 8
parity int
one of the SerialPort.PARITY_ constants
stopBits int
1 or 2

Throws

HardwareException
when the port cannot be opened or the rate is not supported

openPwm

public PwmChannel openPwm(int chip, int channel) throws HardwareException
Opens a hardware PWM channel. The channel starts disabled.

Throws

HardwareException
when the channel does not exist

openCan

public CanBus openCan(String iface) throws HardwareException
Opens a CAN network interface. The interface must already be up and configured with its bit rate (ip link set can0 up type can bitrate 500000), which needs privileges an application normally lacks.

Throws

HardwareException
when the interface does not exist

openWatchdog

public Watchdog openWatchdog(int timeoutSeconds) throws HardwareException
Opens and starts the hardware watchdog. From this call on the device resets unless Watchdog.kick() is called within the timeout.

Throws

HardwareException
when there is no watchdog or it is in use

getBacklightBrightness

public int getBacklightBrightness()
The current backlight brightness, from 0 to getMaxBacklightBrightness(), or -1 when not supported.

getMaxBacklightBrightness

public int getMaxBacklightBrightness()
The highest backlight brightness value, or -1 when not supported.

setBacklightBrightness

public void setBacklightBrightness(int value) throws HardwareException
Sets the backlight brightness, clamped to the valid range.

Throws

HardwareException
when not supported or not permitted

unsupported

protected static HardwareException unsupported(String what)
Creates the exception the default primitives throw.

gpioOpen

protected int gpioOpen(String chip, int line, boolean output, boolean initialHigh, int bias, int edges) throws HardwareException
Claims a GPIO line and returns its handle.

gpioRead

protected boolean gpioRead(int handle) throws HardwareException
Reads a GPIO line: true for high.

gpioWrite

protected void gpioWrite(int handle, boolean high) throws HardwareException
Drives an output GPIO line.

gpioWaitEdge

protected int gpioWaitEdge(int handle, int timeoutMs, long[] timestampOut) throws HardwareException
Waits up to timeoutMs for an edge on an input line. Returns one of EDGE_TIMEOUT, EDGE_RESULT_FALLING or EDGE_RESULT_RISING and stores the edge’s timestamp in nanoseconds in timestampOut[0]. Called from a background thread, never the event dispatch thread.

i2cOpen

protected int i2cOpen(int bus, int address) throws HardwareException
Opens an I2C device and returns its handle.

i2cTransfer

protected void i2cTransfer(int handle, byte[] write, int writeLen, byte[] read, int readLen) throws HardwareException
Performs one combined I2C transaction: writes writeLen bytes from write, then, with a repeated start and no stop between, reads readLen bytes into read. Either length may be zero.

spiOpen

protected int spiOpen(int bus, int chipSelect, int mode, int speedHz, int bitsPerWord) throws HardwareException
Opens and configures an SPI device and returns its handle.

spiTransfer

protected void spiTransfer(int handle, byte[] tx, byte[] rx, int len) throws HardwareException
Performs one full-duplex SPI transfer of len bytes. rx may be the same array as tx.

serialOpen

protected int serialOpen(String device, int baud, int dataBits, int parity, int stopBits) throws HardwareException
Opens and configures a serial port and returns its handle.

serialRead

protected int serialRead(int handle, byte[] buf, int off, int len, int timeoutMs) throws HardwareException
Reads up to len bytes, waiting at most timeoutMs (negative waits forever) for the first one. Returns the count read, 0 on timeout.

serialWrite

protected void serialWrite(int handle, byte[] buf, int off, int len) throws HardwareException
Writes all len bytes.

pwmOpen

protected int pwmOpen(int chip, int channel) throws HardwareException
Opens a PWM channel and returns its handle.

pwmConfigure

protected void pwmConfigure(int handle, long periodNanos, long dutyNanos, boolean enabled) throws HardwareException
Configures a PWM channel. Duty may not exceed the period.

canOpen

protected int canOpen(String iface) throws HardwareException
Opens a CAN interface and returns its handle.

canSend

protected void canSend(int handle, int id, boolean extended, byte[] data, int len) throws HardwareException
Sends one CAN frame.

canReceive

protected int canReceive(int handle, int[] idOut, byte[] data, int timeoutMs) throws HardwareException
Waits up to timeoutMs for a CAN frame. Returns the payload length, or -1 on timeout; the identifier goes into idOut[0] and idOut[1] is 1 for an extended identifier.

watchdogOpen

protected int watchdogOpen(int timeoutSeconds) throws HardwareException
Opens the watchdog with a timeout and returns its handle.

watchdogKick

protected void watchdogKick(int handle) throws HardwareException
Resets the watchdog timer.

close

protected void close(int handle, boolean disarm)
Closes any handle. disarm applies to a watchdog only: true stops it where the driver allows, false leaves it running so the device resets.