Class Hardware

java.lang.Object
com.codename1.hardware.Hardware
Direct Known Subclasses:
com.codename1.impl.KernelHardware

public class Hardware extends Object

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.

  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    protected static final int
    Edge-wait result: a falling edge.
    protected static final int
    Edge-wait result: a rising edge.
    protected static final int
    Edge-wait result: the wait timed out.
    static final int
    Display backlight brightness control.
    static final int
    CAN buses.
    static final int
    GPIO lines through the GPIO character device.
    static final int
    I2C buses.
    static final int
    Hardware PWM channels.
    static final int
    Serial ports (UART, USB serial adapters).
    static final int
    SPI buses.
    static final int
    The hardware watchdog.
  • Constructor Summary

    Constructors
    Modifier
    Constructor
    Description
    protected
    Ports construct subclasses; applications call getInstance().
  • Method Summary

    Modifier and Type
    Method
    Description
    protected int
    canOpen(String iface)
    Opens a CAN interface and returns its handle.
    protected int
    canReceive(int handle, int[] idOut, byte[] data, int timeoutMs)
    Waits up to timeoutMs for a CAN frame.
    protected void
    canSend(int handle, int id, boolean extended, byte[] data, int len)
    Sends one CAN frame.
    protected void
    close(int handle, boolean disarm)
    Closes any handle.
    protected void
    deliver(Runnable callback)
    Hands a listener callback to the thread listeners run on.
    int
    The current backlight brightness, from 0 to getMaxBacklightBrightness(), or -1 when not supported.
    static Hardware
    Returns the hardware entry point of the current port.
    int
    The highest backlight brightness value, or -1 when not supported.
    protected int
    Bit mask of the FEATURE_ constants this port implements.
    protected int
    gpioOpen(String chip, int line, boolean output, boolean initialHigh, int bias, int edges)
    Claims a GPIO line and returns its handle.
    protected boolean
    gpioRead(int handle)
    Reads a GPIO line: true for high.
    protected int
    gpioWaitEdge(int handle, int timeoutMs, long[] timestampOut)
    Waits up to timeoutMs for an edge on an input line.
    protected void
    gpioWrite(int handle, boolean high)
    Drives an output GPIO line.
    protected int
    i2cOpen(int bus, int address)
    Opens an I2C device and returns its handle.
    protected void
    i2cTransfer(int handle, byte[] write, int writeLen, byte[] read, int readLen)
    Performs one combined I2C transaction: writes writeLen bytes from write, then, with a repeated start and no stop between, reads readLen bytes into read.
    static void
    install(Hardware hardware)
    Makes hardware the instance getInstance() returns; null restores the unsupported default.
    boolean
    true when the port supports at least one hardware feature.
    boolean
    isSupported(int feature)
    true when the port supports the given feature, one of the FEATURE_ constants.
    Names of the CAN network interfaces, for example can0.
    Names of the GPIO controllers on this device, for example gpiochip0.
    int[]
    Numbers of the I2C buses on this device (/dev/i2c-N on Linux).
    Device paths of the serial ports on this device, for example /dev/ttyAMA0 or /dev/ttyUSB0.
    SPI devices as bus.chipSelect strings, for example 0.1.
    openCan(String iface)
    Opens a CAN network interface.
    openGpioInput(String chip, int line, int bias, int edges)
    Claims a GPIO line as an input.
    openGpioOutput(String chip, int line, boolean initialHigh)
    Claims a GPIO line as an output.
    openI2c(int bus, int address)
    Opens the device at a 7-bit address on an I2C bus.
    openPwm(int chip, int channel)
    Opens a hardware PWM channel.
    openSerial(String device, int baud, int dataBits, int parity, int stopBits)
    Opens a serial port in raw mode.
    openSpi(int bus, int chipSelect, int mode, int speedHz, int bitsPerWord)
    Opens an SPI device.
    openWatchdog(int timeoutSeconds)
    Opens and starts the hardware watchdog.
    protected void
    pwmConfigure(int handle, long periodNanos, long dutyNanos, boolean enabled)
    Configures a PWM channel.
    protected int
    pwmOpen(int chip, int channel)
    Opens a PWM channel and returns its handle.
    protected int
    serialOpen(String device, int baud, int dataBits, int parity, int stopBits)
    Opens and configures a serial port and returns its handle.
    protected int
    serialRead(int handle, byte[] buf, int off, int len, int timeoutMs)
    Reads 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)
    Writes all len bytes.
    void
    Sets the backlight brightness, clamped to the valid range.
    protected int
    spiOpen(int bus, int chipSelect, int mode, int speedHz, int bitsPerWord)
    Opens and configures an SPI device and returns its handle.
    protected void
    spiTransfer(int handle, byte[] tx, byte[] rx, int len)
    Performs one full-duplex SPI transfer of len bytes.
    protected static HardwareException
    Creates the exception the default primitives throw.
    protected void
    watchdogKick(int handle)
    Resets the watchdog timer.
    protected int
    watchdogOpen(int timeoutSeconds)
    Opens the watchdog with a timeout and returns its handle.

    Methods inherited from class Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • FEATURE_GPIO

      public static final int FEATURE_GPIO
      GPIO lines through the GPIO character device.
      See Also:
    • FEATURE_I2C

      public static final int FEATURE_I2C
      I2C buses.
      See Also:
    • FEATURE_SPI

      public static final int FEATURE_SPI
      SPI buses.
      See Also:
    • FEATURE_SERIAL

      public static final int FEATURE_SERIAL
      Serial ports (UART, USB serial adapters).
      See Also:
    • FEATURE_PWM

      public static final int FEATURE_PWM
      Hardware PWM channels.
      See Also:
    • FEATURE_CAN

      public static final int FEATURE_CAN
      CAN buses.
      See Also:
    • FEATURE_WATCHDOG

      public static final int FEATURE_WATCHDOG
      The hardware watchdog.
      See Also:
    • FEATURE_BACKLIGHT

      public static final int FEATURE_BACKLIGHT
      Display backlight brightness control.
      See Also:
    • EDGE_TIMEOUT

      protected static final int EDGE_TIMEOUT
      Edge-wait result: the wait timed out.
      See Also:
    • EDGE_RESULT_FALLING

      protected static final int EDGE_RESULT_FALLING
      Edge-wait result: a falling edge.
      See Also:
    • EDGE_RESULT_RISING

      protected static final int EDGE_RESULT_RISING
      Edge-wait result: a rising edge.
      See Also:
  • 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: the controller name from listGpioChips()

      • line: the line offset within the controller (the BCM number on a Raspberry Pi's gpiochip0)

      • initialHigh: 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
      Throws:
      HardwareException
    • openGpioInput

      public GpioPin openGpioInput(String chip, int line, int bias, int edges) throws HardwareException

      Claims a GPIO line as an input.

      Parameters
      Throws
      • HardwareException: when the line cannot be claimed
      Throws:
      HardwareException
    • 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
      Throws:
      HardwareException
    • openSpi

      public SpiDevice openSpi(int bus, int chipSelect, int mode, int speedHz, int bitsPerWord) throws HardwareException

      Opens an SPI device.

      Parameters
      • bus: the SPI controller number

      • chipSelect: the chip-select line

      • mode: SPI mode 0 to 3 (clock polarity and phase)

      • speedHz: the clock rate

      • bitsPerWord: the word size, usually 8

      Throws
      • HardwareException: when the device does not exist or rejects the configuration
      Throws:
      HardwareException
    • 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: the port, from listSerialPorts()

      • baud: the baud rate, for example 9600 or 115200

      • dataBits: 5 to 8

      • parity: one of the SerialPort.PARITY_ constants

      • stopBits: 1 or 2

      Throws
      • HardwareException: when the port cannot be opened or the rate is not supported
      Throws:
      HardwareException
    • 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
      Throws:
      HardwareException
    • 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
      Throws:
      HardwareException
    • 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
      Throws:
      HardwareException
    • 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
      Throws:
      HardwareException
    • 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.
      Throws:
      HardwareException
    • gpioRead

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

      protected void gpioWrite(int handle, boolean high) throws HardwareException
      Drives an output GPIO line.
      Throws:
      HardwareException
    • 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.
      Throws:
      HardwareException
    • i2cOpen

      protected int i2cOpen(int bus, int address) throws HardwareException
      Opens an I2C device and returns its handle.
      Throws:
      HardwareException
    • 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.
      Throws:
      HardwareException
    • 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.
      Throws:
      HardwareException
    • 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.
      Throws:
      HardwareException
    • 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.
      Throws:
      HardwareException
    • 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.
      Throws:
      HardwareException
    • serialWrite

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

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

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

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

      protected void canSend(int handle, int id, boolean extended, byte[] data, int len) throws HardwareException
      Sends one CAN frame.
      Throws:
      HardwareException
    • 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.
      Throws:
      HardwareException
    • watchdogOpen

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

      protected void watchdogKick(int handle) throws HardwareException
      Resets the watchdog timer.
      Throws:
      HardwareException
    • 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.