Class Hardware
- Direct Known Subclasses:
com.codename1.impl.KernelHardware
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
FieldsModifier and TypeFieldDescriptionprotected static final intEdge-wait result: a falling edge.protected static final intEdge-wait result: a rising edge.protected static final intEdge-wait result: the wait timed out.static final intDisplay backlight brightness control.static final intCAN buses.static final intGPIO lines through the GPIO character device.static final intI2C buses.static final intHardware PWM channels.static final intSerial ports (UART, USB serial adapters).static final intSPI buses.static final intThe hardware watchdog. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedHardware()Ports construct subclasses; applications callgetInstance(). -
Method Summary
Modifier and TypeMethodDescriptionprotected intOpens a CAN interface and returns its handle.protected intcanReceive(int handle, int[] idOut, byte[] data, int timeoutMs) Waits up totimeoutMsfor a CAN frame.protected voidcanSend(int handle, int id, boolean extended, byte[] data, int len) Sends one CAN frame.protected voidclose(int handle, boolean disarm) Closes any handle.protected voidHands a listener callback to the thread listeners run on.intstatic HardwareReturns the hardware entry point of the current port.intThe highest backlight brightness value, or-1when not supported.protected intBit mask of theFEATURE_constants this port implements.protected intClaims a GPIO line and returns its handle.protected booleangpioRead(int handle) Reads a GPIO line:truefor high.protected intgpioWaitEdge(int handle, int timeoutMs, long[] timestampOut) Waits up totimeoutMsfor an edge on an input line.protected voidgpioWrite(int handle, boolean high) Drives an output GPIO line.protected inti2cOpen(int bus, int address) Opens an I2C device and returns its handle.protected voidi2cTransfer(int handle, byte[] write, int writeLen, byte[] read, int readLen) Performs one combined I2C transaction: writeswriteLenbytes fromwrite, then, with a repeated start and no stop between, readsreadLenbytes intoread.static voidbooleantruewhen the port supports at least one hardware feature.booleanisSupported(int feature) truewhen the port supports the given feature, one of theFEATURE_constants.String[]Names of the CAN network interfaces, for examplecan0.String[]Names of the GPIO controllers on this device, for examplegpiochip0.int[]Numbers of the I2C buses on this device (/dev/i2c-Non Linux).String[]Device paths of the serial ports on this device, for example/dev/ttyAMA0or/dev/ttyUSB0.String[]SPI devices asbus.chipSelectstrings, for example0.1.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 voidpwmConfigure(int handle, long periodNanos, long dutyNanos, boolean enabled) Configures a PWM channel.protected intpwmOpen(int chip, int channel) Opens a PWM channel and returns its handle.protected intserialOpen(String device, int baud, int dataBits, int parity, int stopBits) Opens and configures a serial port and returns its handle.protected intserialRead(int handle, byte[] buf, int off, int len, int timeoutMs) Reads up tolenbytes, waiting at mosttimeoutMs(negative waits forever) for the first one.protected voidserialWrite(int handle, byte[] buf, int off, int len) Writes alllenbytes.voidsetBacklightBrightness(int value) Sets the backlight brightness, clamped to the valid range.protected intspiOpen(int bus, int chipSelect, int mode, int speedHz, int bitsPerWord) Opens and configures an SPI device and returns its handle.protected voidspiTransfer(int handle, byte[] tx, byte[] rx, int len) Performs one full-duplex SPI transfer oflenbytes.protected static HardwareExceptionunsupported(String what) Creates the exception the default primitives throw.protected voidwatchdogKick(int handle) Resets the watchdog timer.protected intwatchdogOpen(int timeoutSeconds) Opens the watchdog with a timeout and returns its handle.
-
Field Details
-
FEATURE_GPIO
public static final int FEATURE_GPIOGPIO lines through the GPIO character device.- See Also:
-
FEATURE_I2C
public static final int FEATURE_I2CI2C buses.- See Also:
-
FEATURE_SPI
public static final int FEATURE_SPISPI buses.- See Also:
-
FEATURE_SERIAL
public static final int FEATURE_SERIALSerial ports (UART, USB serial adapters).- See Also:
-
FEATURE_PWM
public static final int FEATURE_PWMHardware PWM channels.- See Also:
-
FEATURE_CAN
public static final int FEATURE_CANCAN buses.- See Also:
-
FEATURE_WATCHDOG
public static final int FEATURE_WATCHDOGThe hardware watchdog.- See Also:
-
FEATURE_BACKLIGHT
public static final int FEATURE_BACKLIGHTDisplay backlight brightness control.- See Also:
-
EDGE_TIMEOUT
protected static final int EDGE_TIMEOUTEdge-wait result: the wait timed out.- See Also:
-
EDGE_RESULT_FALLING
protected static final int EDGE_RESULT_FALLINGEdge-wait result: a falling edge.- See Also:
-
EDGE_RESULT_RISING
protected static final int EDGE_RESULT_RISINGEdge-wait result: a rising edge.- See Also:
-
-
Constructor Details
-
Hardware
protected Hardware()Ports construct subclasses; applications callgetInstance().
-
-
Method Details
-
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 anullcheck. -
install
Makeshardwarethe instancegetInstance()returns;nullrestores the unsupported default.Displayinstalls the port's instance when it starts, and the backend runtime installs its own, which is why this class never namesDisplayitself. -
deliver
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()truewhen the port supports at least one hardware feature. -
isSupported
public boolean isSupported(int feature) truewhen the port supports the given feature, one of theFEATURE_constants. Support means the port can drive the bus; whether the board exposes one is answered by the matchinglistmethod. -
getSupportedFeatures
protected int getSupportedFeatures()Bit mask of theFEATURE_constants this port implements. Ports override this; the default supports nothing. -
listGpioChips
Names of the GPIO controllers on this device, for examplegpiochip0. Empty when there are none or GPIO is unsupported. -
listI2cBuses
public int[] listI2cBuses()Numbers of the I2C buses on this device (/dev/i2c-Non Linux). -
listSpiDevices
SPI devices asbus.chipSelectstrings, for example0.1. -
listSerialPorts
Device paths of the serial ports on this device, for example/dev/ttyAMA0or/dev/ttyUSB0. -
listCanInterfaces
Names of the CAN network interfaces, for examplecan0. -
openGpioOutput
Claims a GPIO line as an output.
Parameters
-
chip: the controller name fromlistGpioChips() -
line: the line offset within the controller (the BCM number on a Raspberry Pi'sgpiochip0) -
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
Claims a GPIO line as an input.
Parameters
-
chip: the controller name fromlistGpioChips() -
line: the line offset within the controller -
bias: one of theGpioPin.BIAS_constants -
edges: which edgesGpioPin.setListener(GpioListener)reports, one of theGpioPin.EDGE_constants
Throws
HardwareException: when the line cannot be claimed
- Throws:
HardwareException
-
-
openI2c
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, fromlistSerialPorts() -
baud: the baud rate, for example 9600 or 115200 -
dataBits: 5 to 8 -
parity: one of theSerialPort.PARITY_constants -
stopBits: 1 or 2
Throws
HardwareException: when the port cannot be opened or the rate is not supported
- Throws:
HardwareException
-
-
openPwm
Opens a hardware PWM channel. The channel starts disabled.
Throws
HardwareException: when the channel does not exist
- Throws:
HardwareException
-
openCan
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
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() -
getMaxBacklightBrightness
public int getMaxBacklightBrightness()The highest backlight brightness value, or-1when not supported. -
setBacklightBrightness
Sets the backlight brightness, clamped to the valid range.
Throws
HardwareException: when not supported or not permitted
- Throws:
HardwareException
-
unsupported
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
Reads a GPIO line:truefor high.- Throws:
HardwareException
-
gpioWrite
Drives an output GPIO line.- Throws:
HardwareException
-
gpioWaitEdge
Waits up totimeoutMsfor an edge on an input line. Returns one ofEDGE_TIMEOUT,EDGE_RESULT_FALLINGorEDGE_RESULT_RISINGand stores the edge's timestamp in nanoseconds intimestampOut[0]. Called from a background thread, never the event dispatch thread.- Throws:
HardwareException
-
i2cOpen
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: writeswriteLenbytes fromwrite, then, with a repeated start and no stop between, readsreadLenbytes intoread. 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
Performs one full-duplex SPI transfer oflenbytes.rxmay be the same array astx.- 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 tolenbytes, waiting at mosttimeoutMs(negative waits forever) for the first one. Returns the count read,0on timeout.- Throws:
HardwareException
-
serialWrite
Writes alllenbytes.- Throws:
HardwareException
-
pwmOpen
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
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 totimeoutMsfor a CAN frame. Returns the payload length, or-1on timeout; the identifier goes intoidOut[0]andidOut[1]is1for an extended identifier.- Throws:
HardwareException
-
watchdogOpen
Opens the watchdog with a timeout and returns its handle.- Throws:
HardwareException
-
watchdogKick
Resets the watchdog timer.- Throws:
HardwareException
-
close
protected void close(int handle, boolean disarm) Closes any handle.disarmapplies to a watchdog only:truestops it where the driver allows,falseleaves it running so the device resets.
-