Java RXTX implementira serijsku komunikaciju

Java Rxtx Implements Serial Communication



sadržaj

Pregled serijskog porta



Pomoćnik za serijsko uklanjanje pogrešaka



Preuzimanje i ovisnost RXTX-a



Borba za razvoj


1, uporaba je također vrlo jednostavna, podijeljena u tri koraka:

1) Otvorite serijski priključak



2) Pošaljite podatke pomoću java.io.OutputStream ili pročitajte podatke pomoću java.io.InputStream

3) Zatvorite serijski priključak

2. Cjeloviti sadržaj je sljedeći:

import gnu.io.* import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.util.StringUtils import java.io.IOException import java.io.OutputStream import java.util.ArrayList import java.util.Arrays import java.util.Enumeration import java.util.List /** * Created by Administrator on 2019/3/18 0018. * Serial port tool class */ public class SerialPortTool { Private static final Logger logger = LoggerFactory.getLogger(SerialPortTool.class)//slf4j logger /** * Find all available com ports on your computer * * @return List of available port names, when not available List is empty */ public static final ArrayList findSystemAllComPort() { /** * getPortIdentifiers: Get all available serial ports of the computer motherboard */ Enumeration portList = CommPortIdentifier.getPortIdentifiers() ArrayList portNameList = new ArrayList() /** * Add the available serial port name to the List list */ while (portList.hasMoreElements()) { String portName = portList.nextElement().getName()//The name is COM1, COM2.... portNameList.add(portName) } return portNameList } /** * Open the specified serial port on the computer * * @param portName The port name, such as COM1, is null, defaults to the first of the available ports on the computer. * @param b baud rate (baudrate), such as 9600 * @param d data bits (datebits), such as SerialPort.DATABITS_8 = 8 * @param s stopbits, such as SerialPort.STOPBITS_1 = 1 * @param p parity, such as SerialPort.PARITY_NONE = 0 * @return Open serial port object, return null if open fails */ public static final SerialPort openComPort(String portName, int b, int d, int s, int p) { CommPort commPort = null try { //When no available com port is passed, the first one of the com ports available in the computer is used by default. if (StringUtils.isEmpty(portName)) { List comPortList = findSystemAllComPort() if (comPortList != null && comPortList.size() > 0) { portName = comPortList.get(0) } } Logger.info('Start to open serial port:portName=' + portName + ',baudrate=' + b + ',datebits=' + d + ',stopbits=' + s + ',parity=' + p) / / Identify the specified COM port by port name CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName) /** * open(String TheOwner, int i): open the port * TheOwner customizes a port name and can customize it. * i: Timeout for open port, in milliseconds, timeout throws an exception: PortInUseException if in use. * If the serial port is already occupied, an exception is thrown: gnu.io.PortInUseException: Unknown Application */ commPort = portIdentifier.open(portName, 5000) /** * Determine if the port is a serial port * public abstract class SerialPort extends CommPort */ if (commPort instanceof SerialPort) { SerialPort serialPort = (SerialPort) commPort /** * Set the serial port parameters: setSerialPortParams( int b, int d, int s, int p ) * b: baud rate (baudrate) * d: data bits (datebits), SerialPort support 5,6,7,8 * s: stopbits (stopbits), SerialPort support 1, 2, 3 * p: parity, SerialPort support 0,1,2,3,4 * If the parameter is set incorrectly, an exception is thrown: gnu.io.UnsupportedCommOperationException: Invalid Parameter * The serial port must be closed at this time, otherwise the serial port will not be opened the next time portIdentifier.open, because it is already occupied. */ serialPort.setSerialPortParams(b, d, s, p) Logger.info('Open Serial Port' + portName + 'success...') return serialPort } else { Logger.error('current port' + commPort.getName() + 'not serial port...') } } catch (NoSuchPortException e) { e.printStackTrace() } catch (PortInUseException e) { Logger.warn('serial port + portName + ' is already occupied, please dismiss it first...') e.printStackTrace() } catch (UnsupportedCommOperationException e) { Logger.warn('Serial port parameter setting error, close serial port, data bit [5-8], stop bit [1-3], verify bit [0-4]...') e.printStackTrace() If (commPort != null) {//The serial port must be closed at this time, otherwise the serial port will not open the next time portIdentifier.open, because it is already occupied commPort.close() } } Logger.error('Open Serial Port' + portName + 'Failed...') return null } /** * Send data to the serial port * * @param serialPort serial port object * @param order pending data */ public static void sendDataToComPort(SerialPort serialPort, byte[] orders) { OutputStream outputStream = null try { if (serialPort != null) { outputStream = serialPort.getOutputStream() outputStream.write(orders) outputStream.flush() Logger.info('to serial port' + serialPort.getName() + 'send data:' + Arrays.toString(orders) + 'complete...') } else { Logger.error('gnu.io.SerialPort is null, cancel data sending...') } } catch (IOException e) { e.printStackTrace() } finally { if (outputStream != null) { try { outputStream.close() } catch (IOException e) { e.printStackTrace() } } } } /** * Close the serial port * * @param serialport Serial port object to be closed */ public static void closeComPort(SerialPort serialPort) { if (serialPort != null) { serialPort.close() Logger.info('Close Serial Port' + serialPort.getName()) } } /** * hexadecimal string to decimal byte array * This is a commonly used method, such as some hardware communication instructions are provided hexadecimal strings, need to be converted to a byte array and then sent when sent * * @param strSource hex string, such as '455A432F5600', one decimal element in each two-bit corresponding byte array * By default, spaces in the parameter string are removed, so the parameter '45 5A 43 2F 56 00' is also possible. * @return a decimal byte array, such as [69, 90, 67, 47, 86, 0] */ public static byte[] hexString2Bytes(String strSource) { if (strSource == null || ''.equals(strSource.trim())) { System.out.println('hexString2Bytes parameter is empty, abandon conversion.') return null } strSource = strSource.replace(' ', '') int l = strSource.length() / 2 byte[] ret = new byte[l] for (int i = 0 i

Iako gore navedeno samo šalje podatke, ali očitanje je isto, ništa više nego da se ulazni tok pročita. Budući da očitanje nema stvarni testni scenarij, nije objavljeno.