Serial port in java linux

Java Reading from serial port in Ubuntu

I am reading from and writing to a USB serial port in Ubuntu using the standard /dev/ttyUSB0 file that the operating system provides for me. I do all the hard work in a class that extends Thread:

public PacketHandlingThread(String fileName, PacketListener listener) < mListener = listener; //the filename points toward a serial port. Something like /dev/ttyUSB0 try < mOutputStream = new FileOutputStream(fileName); mInputStream = new FileInputStream(fileName); System.out.println("Created Serial Listener"); >catch (Exception e) < e.printStackTrace(); >> 
public void run() < while(true) < int numRead = -1; try < while(mInputStream.available() < 1) < //spin in circles try < Thread.sleep(10); >catch (Exception e) <> > numRead = mInputStream.read(data); System.out.println("Num Read: "+numRead); > catch (Exception e) < e.printStackTrace(); numRead = -1; >if (numRead == -1) < mListener.OnConnectionClosed(); break; >> > 

This code works as expected, but it constantly has to poll the file to see if it has any new data. Instead of that while loop, I would prefer to have something like:

But when I do that, it sits there waiting forever, presumably because the underlying stream never calls notify() (and there isn’t any reason to suspect that it would, I’m just saying I wish it did). My question is: Is there any way to read from a serial port in a non-polling manner? I’d really hate to have to use a serial library because my research seems to show that every single one of them is absolutely terrible. Any advice is appreciated!

Источник

Serial port in java linux

View on GitHub

Platform-independent serial port access for Java

What is jSerialComm?

jSerialComm is a Java library designed to provide a platform-independent way to access standard serial ports without requiring external libraries, native code, or any other tools. It is meant as an alternative to RxTx and the (deprecated) Java Communications API, with increased ease-of-use, an enhanced support for timeouts, and the ability to open multiple ports simultaneously.

Some of the features of this library include:

  • Platform-independent library deployment (automatically uses correct native library based on current architecture)
  • Very lightweight and efficient implementation
  • Enumerates all available serial ports on a machine
  • Returns both a system port description and a friendly device description
  • User-specifiable port descriptors including symbolic links
  • Configurable ports according to baud rate, data bits, stop bits, and parity
  • Configurable port timeouts (blocking and non-blocking) for both reading and writing
  • Configurable flow control parameters for the serial port (CTS, RTS/CTS, DSR, DTR/DSR, XOn/XOff)
  • Ability to read and write raw data bytes directly to the serial port
  • Ability to read and write byte streams via Java’s InputStream and OutputStream interfaces
  • Event-based reading and writing via callbacks
  • Callback notification when:
    • New data is available for reading
    • All data has been successfully written
    • A complete fixed-length data packet has arrived
    • A delimited string-based message has been received
    • Modem control lines have changed state
    • Communication errors have been encountered

    Additionally, this library can be used in any Java project intended for use on the following platforms:

    • Windows XP and later (32-bit, 64-bit, ARM, and ARM64)
    • Mac OS X Tiger (10.4) and later (32/64-bit Intel and Apple Silicon)
    • All Linux distributions (32/64-bit x86, ARM, and PowerPC)
    • Solaris 10 and later (32/64-bit x86 and SPARC)
    • FreeBSD (32/64-bit x86 and ARM64)
    • OpenBSD (32/64-bit x86)
    • ARM/Intel/AMD Mobile Linux derivatives (e.g. RaspberryPi, Beaglebone, etc.)
    • Android 4.1 (Jelly Bean) and later

    How can use this library in my own project?

    One of the most convenient features of this library is that it allows you to simply include the JAR file in your custom project, and it will automatically select and load the correct native library for your platform and architecture. As such, you can make use of this library by simply copying the jSerialComm.jar file into your project directory and linking to it as you would any other JAR file.

    To access the contents of the library in your project, make sure to import com.fazecast.jSerialComm.* into your java files. You can then generate a list of all available serial ports on your system (real or virtual), by calling the following static method:

    This will return an array of SerialPort objects through which you can iterate. See the Javadoc Library Reference for a complete overview of this library and its methods. Alternately, if you already know the port descriptor of the port you wish to use (e.g., «/dev/ttyS0» or «COM3»), or if you are using this library with pseudo-terminals (e.g., «/dev/pts/14»), you can create a SerialPort object using the following static method:

    SerialPort.getCommPort(String portDescriptor)

    Note for Linux users: Serial port access is limited to certain users and groups in Linux. To enable user access, you must open a terminal and enter the following commands before jSerialComm will be able to access the ports on your system. Don’t worry if some of the commands fail. All of these groups may not exist on every Linux distro. (Note, this process must only be done once for each user):

    sudo usermod -a -G uucp username
    sudo usermod -a -G dialout username
    sudo usermod -a -G lock username
    sudo usermod -a -G tty username

    Replace the username parameter with your current username. (If you are not sure what your username is, type whoami and it will tell you.) If you are using SUSE 11.3 or higher, replace the ‘-a -G’ flags with a single ‘-A’ flag. Log out and you should have access to the serial port after logging back in.

    Additionally, if you are using an automated build system (such as Maven), you can import this library directly into your project as a dependency from the Maven Central Repository instead of copying the .jar file manually. Use one of the following dependency declarations depending on the build system you are using:

     
    com.fazecast
    jSerialComm
    [2.0.0,3.0.0)
    @Grab(group='com.fazecast', module='jSerialComm', version='[2.0.0,3.0.0)')

    Источник

    Java Comm Serial API How-To for Linux

    Special thanks to Trent Jarvi and Kevin Hester for putting together RXTX and JCL. These two gentlemen have done an excellent job of porting the original Sun Java Comm API to the Linux OS. However, with all due respect, and not to be insulting, their installation documentation leaves much to be desired. This is the primary reason I have chosen to put this document together.

    Getting Started

    For the purposes of this paper, it will be assumed that you have installed a JSDK and it is located in:

    And java is then located in:

    If your setup is different, please adjust accordingly.

    Installing RXTX

    First, obtain the RXTX bins package from:

    Decompress and Untar this package:

    /bin/gzip —decompress rxtx-bins.1.tar.gz

    At this point, you’ll have an rxtx-bins.1 directory. Next, you’ll need to copy the shared objects into your java installation:

    cp rxtx-bins.1/1.4/i386-pc-linux/libParallel.so /usr/java/j2sdk1.4.0/jre/lib/i386/

    cp rxtx-bins.1/1.4/i386-pc-linux/libSerial.so /usr/java/j2sdk1.4.0/jre/lib/i386/

    If you are installing on an architecture other than an x86, you’ll need to adjust both the /i386-pc-linux / and the /i386/ accordingly.

    Next, you’ll need to install the jcl.jar file:

    cp rxtx-bins.1/1.4/jcl.jar /usr/java/j2sdk1.4.0/jre/lib/ext/

    At this point, the RXTX installation is complete.

    Installing Comm

    The final step to getting the Java Comm API working under Linux, is to install the Comm API itself. At this point, you have all of the necessary kernel-level drivers installed. Because Linux is a form of Unix, the authors of RXTX and JCL have wisely decided to reuse sun’s solaris (unix) comm library. At this point, you must download and install this library:

    Make sure you choose the Solaris/Sparc TM version. Next, you must Decompress and Untar this package:

    /bin/gzip —decompress javax_comm-2_0_2-solsparc.tar.Z

    /bin/tar xf javax_comm-2_0_2-solsparc.tar

    Next, you’ll need to install the comm.jar file:

    cp commapi/comm.jar /usr/java/j2sdk1.4.0/jre/lib/ext/

    At this point, we are almost finished. We just need to create the properties file that the Comm API will use to load the drivers (.so files). To create this file, type the following command:

    /bin/echo Driver=gnu.io.RXTXCommDriver > /usr/java/j2sdk1.4.0/jre/lib/javax.comm.properties

    Congratulations! You have installed the Linux Comm API.

    Tips

    While windows uses COM and LPT designators for port identifiers, Linux is a bit different. Use the following table to identify your ports:

    Port Windows port identifier What you use in Linux
    Serial Port 1 COM1 /dev/ttyS0
    Serial Port 2 COM2 /dev/ttyS1
    Parallel Port 1 LPT1 /dev/lp0

    Troubleshooting

    Several people have emailed me and reported that they get the following error:

    Exception in thread «main» java.lang.VerifyError: (class:
    gnu/io/RXTXPort$SerialOutputStream, method: write signature: ([BII)V) Illegal
    use of nonvirtual function call
    at gnu.io.RXTXPort.(RXTXPort.java)
    at gnu.io.RXTXCommDriver.getCommPort(RXTXCommDriver.java)
    at javax.comm.CommPortIdentifier.open(CommPortIdentifier.java:547)

    I personally have not experienced this problem, but if you encounter this error, you can work around it by adding -noverify to your command line:

    Also, it has been suggested that recompiling the jcl with the java compiler you have chosen will resolve this issue. As I have never experienced this verification problem, I have no way to test this. It should also be noted that the purpose of this paper is to be a quick and easy way to get serial and parallel port access in Java on Linux. Most of the instructions on this page as well as the VerifyError are irrelevant if you chose to download the RXTX source and do a manual compile and installation.

    Other Resources

    Источник

    How do I configure and communicate with a serial port? [closed]

    Want to improve this question? Update the question so it focuses on one problem only by editing this post.

    I need to send and receive data over serial connections (RS-232 and RS-422). How do I set up and communicate with such a connection? How do I figure out what the configuration settings (e.g. baud rate) should be and how do I set them? In particular I am looking to do this in Java, C/C++, or one of the major Unix shells but I also have some interest in serial programming using Windows/Hyperterminal.

    10 Answers 10

    Build a time machine and go back to 1987? Ho ho.

    Ok, no more snarky comments.

    How do I figure out what the configuration settings (e.g. baud rate) should be.

    Read the datasheet? Ok, ok. Seriously, last one. If you don’t know the baud rate of the device you are trying to communicate with, you have two choices. Start guessing, or possibly bust out an o-scope. If you need a good starting point, let me suggest 9600-8-N-1. My suspicion is you can get there with brute force relatively quickly. There’s a third option of having an old-school ninja who can tell just by the LOOK of the garbled characters at some standard baud rate what actual baud rate is. An impressive party trick to be sure.

    Hopefully though you have access to this information. In unix/linux, you can get ahold of minicom to play with the serial port directly. This should make it fairly quick to get the configuration figured out.

    one of the major Unix shells

    In Unix the serial port(s) is/are file-mapped into the /dev/ subdir. ttyS0, for example. If you setup the correct baud rate and whatnot using minicom, you can even cat stuff to that file to send stuff out there.

    On to the meat of the question, you can access it programmatically through the POSIX headers. termios.h is the big one.

    but I also have some interest in serial programming using Windows/Hyperterminal.

    Hyperterminal and minicom are basically the same program. As for how Windows let’s you get access to the serial port, I’ll leave that question for someone else. I haven’t done that in Windows since the Win95 days.

    Источник

    Читайте также:  Linux mint перенести home
Оцените статью
Adblock
detector