Location>code7788 >text

Three Hardcore Ways Revealed: How Java Easily Communicates with Underlying Hardware and Industrial Devices!

Popularity:646 ℃/2024-09-26 12:07:26

Hello, I'm V, programmers chat is really less than three sentences can not leave the technology ah, this is not two days ago with a buddy dinner, he is my students years ago, have kept in touch, and now are Li total, doing industrial Internet-related projects, really as long as the Java learn well, can do a lifetime, the volume of death is the half-dozen.

Thank you, Mr. Li, for sharing with me about the Industrial Internet project, which has yielded a lot of benefits, and today's content to talk about how Java can easily communicate with the underlying hardware and industrial equipment.

Java reading register data usually involves communication with a hardware device. This operation is usually accomplished in several ways:

Read device register data using the Modbus protocol (using thejLibModbus

Modbus It is a communication protocol used for industrial automation devices. Common Modbus communication methods include:Modbus RTU(based on serial communication) andModbus TCP(web-based communication). In this example, we will use Java and thejLibModbus library viaModbus TCP The protocol reads the device's register data.

Implementation steps

  1. Add jLibModbus dependency.
  2. Set up the Modbus Master client.
  3. Read the register data of the device via Modbus Master.

1. Add jLibModbus dependency

When using Maven to manage a project, you can add the AddjLibModbus Dependency:

<dependency>
    <groupId> </groupId>
    <artifactId>jlibmodbus</artifactId>
    <version>1.2.8.1</version> <! -- Versioning for specific needs -->
</dependency>

Or just download the jar and add it to your project's classpath.

2. Example code: Reading registers via Modbus TCP

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

public class ModbusTcpClient {
    public static void main(String[] args) {
        try {
            // configure Modbus TCP parameters
            TcpParameters tcpParameters = new TcpParameters();
            InetAddress address = ("192.168.1.100"); // equipmentIPaddress
            (address);
            (Modbus.TCP_PORT); // Modbus default (setting)TCPports 502

            // establish ModbusMaster an actual example
            ModbusMaster master = (tcpParameters);
            ();

            // equipment Slave ID(通常是从站address)
            int slaveId = 1;
            // Read Holding Register(Holding Registers),从address 0 commencement,retrieve 10 registers
            int startAddress = 0;
            int quantity = 10;

            try {
                // Read Holding Register数据
                int[] registerValues = (slaveId, startAddress, quantity);
                ("register data:");
                for (int i = 0; i < ; i++) {
                    ("processor register[" + (startAddress + i) + "] = " + registerValues[i]);
                }
            } catch (ModbusProtocolException | ModbusNumberException | ModbusIOException e) {
                ("Modbus retrieve失败: " + ());
            }

            // Disconnect
            ();
        } catch (Exception e) {
            ();
        }
    }
}

Let me explain the code.

  1. Modbus TCP Parameters

    • TcpParameters The host and port used to configure Modbus TCP. The default Modbus TCP port is502
    • utilization("192.168.1.100") Set the IP address of the device.
  2. Modbus Master Example

    • ModbusMaster master = (tcpParameters); Creates a Modbus master (Master) for communicating with slave devices.
    • (); Connects to a Modbus device.
  3. Read Holding Register

    • int[] registerValues = (slaveId, startAddress, quantity); Reads the Holding Registers of the slave device from thestartAddress Start, readquantity registers.
    • Output register value.
  4. error handling

    • capturesModbusProtocolExceptionModbusNumberException cap (a poem)ModbusIOException to handle errors that may occur during communication.
  5. Disconnect

    • utilization(); Disconnect from the Modbus device after completing data reading.

3. How it is used

  1. Equipment Configuration: Make sure you have a Modbus TCP enabled device and that the device's IP address is properly configured with the port. Typically, Modbus TCP devices listen on port 502.
  2. running program: To run this Java program, the program will connect to the device and read the data in the specified registers.
  3. Examples of results
   Register data:
   Register[0] = 1234
   Register[1] = 5678
   Register[2] = 910
   ...

Things to keep in mind when using

  1. Device communication parameters: Ensure that the device supports the Modbus TCP protocol and that the IP address, port, and slave address (Slave ID) are properly configured.
  2. Reading different types of registers: In Modbus, it is possible to read different types of registers, such as Input Registers or Coils. The corresponding methods are called according to the requirements:
    • readInputRegisters(...): Reads the input register.
    • readCoils(...): Read coil status.
  3. Modbus Address Offset: Some Modbus devices use a 1-based address system, while 0-based addresses may be used in the program, so be aware of this to prevent reading the wrong address.

To summarize.

We do this byjLibModbus The library uses Java to read register data from devices that support the Modbus TCP protocol.Modbus is a widely used communication protocol in industrial control, and the use of Java to implement device communication can be used in a variety of automation systems. If your device uses the Modbus RTU protocol, you can configure serial communication to achieve similar operations.

JNI(Java Native Interface)

The Java Native Interface (JNI) allows Java code to interact with code written in native languages such as C/C++, and can be used to implement high-performance, direct hardware access such as register reads.

JNI Basic Flow

  1. Declaring native methods in Java.
  2. utilizationjavacCompile Java classes.
  3. utilizationjavahGenerate C/C++ header files.
  4. Write C/C++ code to implement Java methods.
  5. Compile to generate dynamic libraries.
  6. Java code loads dynamic libraries and calls native methods.

Let's take a look at a case study: using JNI to read register data

1. Java code

First, define a Java class that declares a local method for reading register data.

public class RegisterReader {
    // Declaring Local Methods,This method will be added to theC/C++Implemented in code
    public native int readRegister(int address);

    static {
        // Loading Local Libraries,Assuming the library is named "register_reader"
        ("register_reader");
    }

    public static void main(String[] args) {
        RegisterReader reader = new RegisterReader();
        int registerAddress = 0x1000; // Assuming the register address
        int value = (registerAddress);
        ("Register Value: " + value);
    }
}

Compile Java files:

javac 

Generate C/C++ header files:

javah -jni RegisterReader

This command will generate afile containing method declarations to be implemented in C/C++.

2. Header files generated (

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <>
/* Header for class RegisterReader */

#ifndef _Included_RegisterReader
#define _Included_RegisterReader
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     RegisterReader
 * Method:    readRegister
 * Signature: (I)I
 */
JNIEXPORT jint JNICALL Java_RegisterReader_readRegister
  (JNIEnv *, jobject, jint);

#ifdef __cplusplus
}
#endif
#endif

3. C-code implementation

Next, implement it in CreadRegisterMethods. Here, we assume that the registers are accessed by means of a memory map.

#include ""
#include <>
#include <>

// Memory-mapped address of analog registers
#define REGISTER_BASE_ADDRESS 0x1000

JNIEXPORT jint JNICALL Java_RegisterReader_readRegister(JNIEnv *env, jobject obj, jint address) {
    // Simulate reading a register, the actual implementation should access the real hardware.
    int registerValue = (address - REGISTER_BASE_ADDRESS) * 2; // Pseudo-code to simulate this.
    printf("Reading register at address: 0x%x\n", address); return registerValue; return registerValue; return registerValue; return registerValue; return registerValue
    return registerValue; }
}

4. Compiling dynamic libraries

Compile C code and generate dynamic libraries on Linux or macOS:

gcc -shared -o libregister_reader.so -I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux 

On Windows:

gcc -shared -o register_reader.dll -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" 

5. Running the Java program

Make sure that the dynamic libraries generated by compilation are located in Java's library path, and then run the Java program:

java -=. RegisterReader

in the end

The Java program will call the native C code to read the value of the register, outputting a result similar to the following:

Reading register at address: 0x1000
Register Value: 0

Explain.

  1. readRegistermethodologies: When called in Java, it will call the C code via JNI to theJava_RegisterReader_readRegisterfunction.
  2. Dynamic library loading("register_reader")Load a file namedregister_readerdynamic libraries to ensure that C functions can be called by Java programs.

vantage

  • Direct access to hardware: Through JNI you can directly access registers or other hardware devices without the limitations of the JVM.
  • high performance: The C/C++ language can provide more efficient underlying operations.

caveat

  • JNI involves native code and therefore requires attention to platform compatibility and security issues.
  • Dealing with JNI usually requires an understanding of the device's driver interface and communication mechanisms.

Libraries such as JSerialComm or RXTX

utilizationJSerialComm Read device register data via serial communication.
In some embedded or industrial devices, it is very common to use serial ports (e.g. RS232 or RS485) for data communication.Java provides several libraries to implement serial port communication, among themJSerialCommcap (a poem)RXTXare two commonly used libraries.JSerialCommIt is relatively new and well-maintained, and has better compatibility, so we will use it as an example to introduce how to use it for serial communication.

Implementation steps

  1. increaseJSerialComm Dependency.
  2. Configure the serial port connection.
  3. Sends and receives data through the serial port.

1. AddJSerialComm dependencies

When using Maven to manage a project, you can add theAddJSerialCommof dependence:

<dependency>
    <groupId> </groupId>
    <artifactId>jSerialComm</artifactId>
    <version>2.9.2</version> <! -- Select version as needed -->
</dependency>

Alternatively, download the jar package and add it to your project's classpath.

2. Sample code: usingJSerialComm Read register data

import ;

public class SerialCommExample {
    public static void main(String[] args) {
        // Get all the serial devices on the system
        SerialPort[] ports = (); ("List of available serial port devices:"); // Get all serial port devices on the system.
        ("List of available serial port devices:");
        for (int i = 0; i < ; i++) {
            (i + ": " + " + ports[i].getSystemPortName());
        }

        // Select the first serial device and turn it on
        SerialPort serialPort = ports[0]; }
        (9600); // Set the baud rate
        (8); // Data bits
        (SerialPort.ONE_STOP_BIT); // Stop bit
        (SerialPort.NO_PARITY); // Checksum bit

        if (()) {
            ("Serial port opened successfully: " + ()); // Checksum bit if (()) { ("Serial port opened successfully: " + ()); } else {
        } else {
            ("Unable to open serial port"); } else {
            return; } else { ("Unable to open serial port"); }
        }

        // Wait for the serial device to be ready
        try {
            (2000); // wait 2 seconds
        } catch (InterruptedException e) {
            (); // wait 2 seconds } catch (InterruptedException e) {
        }

        // Send a command to the device to read the registers.
        String command = "READ_REGISTER"; // Construct the read command based on the device protocol
        byte[] commandBytes = ().
        (commandBytes, );

        // Receive the device response
        byte[] readBuffer = new byte[1024]; // Receive device response.
        int numRead = (readBuffer, ); // Receive device response.

        ("Length of data read: " + numRead);
        ("Data content:");
        for (int i = 0; i < numRead; i++) {
            ((char) readBuffer[i]);
        }

        // Close the serial port
        ();
        ("\n serial port closed"); }
    }
}

Explain the code.

  1. Get available serial devices

    • () Gets all available serial devices on the system and prints their names, making it easy to select which port to use.
  2. Serial Port Configuration

    • Set the serial port'sbauddata bitstop bitcap (a poem)check digit. These parameters must be set according to your device documentation.
    • For example, the baud rate is set to 9600, the data bits are 8, the stop bit is 1, and there are no parity bits.
  3. Open the serial port

    • () Open the serial port, if successful, the program will continue to execute, otherwise it outputs an error and terminates.
  4. Send command

    • (commandBytes, ) Sends a command to the serial device, which is usually determined by the device's communication protocol. Here is the commandREAD_REGISTER is a hypothetical example; the actual command needs to be determined from the device's manual.
  5. Retrieve response

    • (readBuffer, ) Receives response data from the serial device. The received data is stored in thereadBuffer in it and print it out byte by byte.
  6. Close the serial port

    • After completing the operation, use the() Turn off the serial device.

Example of runtime results

List of available serial devices.
0: COM3
Serial port opened successfully: COM3
Length of data read: 6
Data content: 123456
123456
Serial port closed

What to look for

  1. serial port communication protocol: Communication between serial devices usually follows some kind of protocol, e.g. Modbus RTU, customized protocols etc. You need to implement specific commands to send and data to parse according to the device manual.

  2. Baud rate and other parameter settings: Ensure that the baud rate, data bits, stop bits, and parity bits are set to match the device. Incorrect settings may result in communication failure or garbled data.

  3. error handling: Various errors may be encountered in serial communications, such as communication timeout, loss of data frames, and so on. Errors need to be handled on a case-by-case basis.

RXTX Example

RXTXis another library for serial port communication, but is not as well maintained as theJSerialCommPositive, V suggests the use ofJSerialComm. If you still want to use theRXTXWhat should I do? That V brother can only ... A simple serial port communication example:

import ;
import ;
import ;
import ;

public class RXTXExample {
    public static void main(String[] args) throws Exception {
        // Get Serial Port
        CommPortIdentifier portIdentifier = ("COM3");
        SerialPort serialPort = (SerialPort) ("SerialComm", 2000);

        // Setting Serial Port Parameters
        (9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

        // Getting Input and Output Streams
        InputStream inputStream = ();
        OutputStream outputStream = ();

        // Send command
        String command = "READ_REGISTER";
        (());

        // receive a response
        byte[] buffer = new byte[1024];
        int length = (buffer);
        ("Length of data read: " + length);

        // Print received data
        for (int i = 0; i < length; i++) {
            ((char) buffer[i]);
        }

        // Close the serial port
        ();
    }
}

To summarize.

pass (a bill or inspection etc)JSerialComm library, we can easily implement the serial port communication in Java. This library simplifies the configuration and operation of serial ports and has good cross-platform compatibility, making it ideal for projects that need to communicate with hardware devices via serial ports. It is a good choice if you need to use serial communication in industrial equipment, embedded systems or IoT applications.

To summarize the usage scenarios of the three ways

The following is a summary of the use of theJNIModbus protocol cap (a poem)Serial communication library (JSerialComm or RXTX) Scenario summaries for all three approaches:

1. JNI(Java Native Interface)

  • take

    • Using JNI is great when you need direct access to the hardware layer or underlying system APIs.
    • For hardware operations that Java can't handle directly, such as interacting directly with a device's registers, memory maps, and drivers.
    • Ideal for scenarios that require extremely high performance or complex communication with devices using C/C++ libraries.
    • If the device's driver provides only a C/C++ API, you can integrate it into a Java project via JNI.
  • typical application

    • Development and use of device drivers.
    • High-performance, low-latency hardware communication.
    • OS-specific API calls to access system resources (e.g., registers, hardware interfaces).
  • advantages and disadvantages

    • vantage: Allows Java to communicate with native system code; suitable for complex hardware control.
    • drawbacks: Development is complex and involves C/C++ code, adding cross-platform complexity.

2. Modbus protocol

  • take

    • The Modbus protocol is a common standard used for communication between industrial devices, and is suitable for use via theRS485/RS232 serial portmaybeEthernet TCPCommunicates with devices that support the Modbus protocol.
    • It is mainly used for data exchange in automation control systems, such as PLC, sensors, inverters, HMI and other industrial equipment.
    • Ideal for scenarios that require monitoring and data collection with multiple devices via standard industrial protocols.
  • typical application

    • Industrial automation: reading device status, controlling outputs, acquiring sensor data.
    • Monitoring and management of IoT devices.
    • Remote control and device management: e.g. reading remote device data via Modbus TCP.
  • advantages and disadvantages

    • vantage: Standardized protocols, compatible with a large number of industrial devices, easy to use.
    • drawbacks: Relatively slow communication rates, suitable for monitoring and control rather than real-time complex computations.

3. Serial communication library (JSerialComm or RXTX)

  • take

    • When the device is passed through theSerial port (RS232, RS485)When communicating, you can use the serial communication library to read device data directly.
    • Suitable for communication with industrial equipment, embedded systems, sensors, meters and other scenarios that require communication based on the serial port.
    • If the device is using a custom protocol and does not support the standard Modbus protocol, communication with the device can be achieved in this way.
    • Ideal for devices that require simple, straightforward communication, especially in traditional embedded devices and industrial scenarios.
  • typical application

    • Communicate with the embedded device through the serial port to get the sensor data.
    • Communicate with PLCs, industrial control systems, microcontrollers, and other devices.
    • IoT device data transfer, especially low-speed devices that need to be transferred over serial ports.
  • advantages and disadvantages

    • vantage: Lightweight, extensive cross-platform support, easy to configure, and suitable for direct communication with serial devices.
    • drawbacks: Applies only to serial communications and lacks support for complex protocols.

Summarize the comparison:

  • JNI pertainunderlying hardware accesscap (a poem)High-performance applications, such as direct interaction with the operating system or driver.
  • Modbus protocol beindustry standard protocolIt is suitable for applications that require a serial or Ethernet connection with theIndustrial equipment communicationsThe scene.
  • JSerialComm/RXTX Suitable for use withserial devicecommunications, especially inembeddedmaybeInternet of Things (IoT) devicesfor simple device interactions in the

The choice depends on the communication protocol of the device and the complexity of the project required, in the case of standard industrial equipment, theModbus protocol is preferred. In the case of custom devices or embedded devices, use theJSerialComm maybeRXTX. If efficient underlying hardware access is required:JNI It may be the only option. Well, today's content will be here, welcome to pay attention to Wei brother love programming, praise attention plus collection, let us together in the Java road farther and farther.