pom
< ! -- 串口连接需要的依赖 -- > < dependency> < groupId> com. fazecast< / groupId> < artifactId> jSerialComm< / artifactId> < version> 2.9 .2 < / version> < / dependency>
Controller
import com. example. tcpclient. seralport. SerialPortInstructions ;
import com. example. tcpclient. seralport. SerialPortManager ;
import com. example. tcpclient. seralport. SerialPortResult ;
import com. example. tcpclient. utils. ConvertHexStrAndStrUtils ;
import org. springframework. stereotype. Controller ;
import org. springframework. util. CollectionUtils ;
import org. springframework. web. bind. annotation. * ;
import java. util. List ;
@Controller
@RequestMapping ( "/serialPort" )
public class SerialPortController { @GetMapping ( "/connect" ) @ResponseBody public Boolean connectPorts ( ) { List < String > portList = SerialPortManager . getSerialPortList ( ) ; if ( ! CollectionUtils . isEmpty ( portList) ) { for ( String port : portList) { SerialPortManager . connectSerialPort ( port) ; if ( SerialPortResult . SERIAL_PORT_STATE ) { return true ; } } } return false ; } @GetMapping ( "/disconnect" ) @ResponseBody public Boolean disconnectPorts ( ) { SerialPortManager . closeSerialPort ( ) ; return ! SerialPortResult . SERIAL_PORT_STATE ; } @GetMapping ( "/sendPortsByLength" ) @ResponseBody public String sendPortsByLength ( ) { if ( SerialPortResult . SERIAL_PORT_STATE ) { SerialPortManager . sendSerialPortData ( ConvertHexStrAndStrUtils . hexStrToBytes ( SerialPortInstructions . READ_NUMBER_ABOVE ) ) ; return SerialPortResult . SERIAL_PORT_LENGTH ; } return "fail" ; } @GetMapping ( "/sendPortsByOther" ) @ResponseBody public String sendPortsByOther ( @RequestParam ( "hexData" ) String hexData) { if ( SerialPortResult . SERIAL_PORT_STATE ) { SerialPortManager . sendSerialPortData ( ConvertHexStrAndStrUtils . hexStrToBytes ( hexData) ) ; return SerialPortResult . SERIAL_PORT_RESULT ; } return "fail" ; }
}
SerialPortManager
import com. fazecast. jSerialComm. SerialPort ; import java. util. ArrayList ;
import java. util. List ;
import java. util. concurrent. TimeUnit ;
import java. util. stream. Collectors ;
public class SerialPortManager { public static List < String > getSerialPortList ( ) { SerialPort [ ] serialPorts = SerialPort . getCommPorts ( ) ; List < String > portNameList = new ArrayList < String > ( ) ; for ( SerialPort serialPort: serialPorts) { portNameList. add ( serialPort. getSystemPortName ( ) ) ; } portNameList = portNameList. stream ( ) . distinct ( ) . collect ( Collectors . toList ( ) ) ; return portNameList; } public static void connectSerialPort ( String portName) { try { SerialPort serialPort = SerialPortManager . openSerialPort ( portName, SerialPortInstructions . SERIAL_BAUD_RATE ) ; TimeUnit . MILLISECONDS . sleep ( 200 ) ; serialPort. addDataListener ( new SerialPortListener ( new SerialPortCallback ( ) ) ) ; if ( serialPort. isOpen ( ) ) { SerialPortResult . SERIAL_PORT_OBJECT = serialPort; SerialPortResult . SERIAL_PORT_STATE = true ; } } catch ( InterruptedException ex) { ex. printStackTrace ( ) ; } } public static SerialPort openSerialPort ( String portName, Integer baudRate) { SerialPort serialPort = SerialPort . getCommPort ( portName) ; if ( baudRate != null ) { serialPort. setBaudRate ( baudRate) ; } if ( ! serialPort. isOpen ( ) ) { serialPort. openPort ( 1000 ) ; } else { return serialPort; } serialPort. setFlowControl ( SerialPort . FLOW_CONTROL_DISABLED ) ; serialPort. setComPortParameters ( baudRate, 8 , SerialPort . ONE_STOP_BIT , SerialPort . NO_PARITY ) ; serialPort. setComPortTimeouts ( SerialPort . TIMEOUT_READ_BLOCKING | SerialPort . TIMEOUT_WRITE_BLOCKING , 1000 , 1000 ) ; return serialPort; } public static void closeSerialPort ( ) { if ( SerialPortResult . SERIAL_PORT_OBJECT != null && SerialPortResult . SERIAL_PORT_OBJECT . isOpen ( ) ) { SerialPortResult . SERIAL_PORT_OBJECT . closePort ( ) ; SerialPortResult . SERIAL_PORT_STATE = false ; SerialPortResult . SERIAL_PORT_OBJECT = null ; } } public static void sendSerialPortData ( byte [ ] content) { if ( SerialPortResult . SERIAL_PORT_OBJECT != null && SerialPortResult . SERIAL_PORT_OBJECT . isOpen ( ) ) { SerialPortResult . SERIAL_PORT_OBJECT . writeBytes ( content, content. length) ; } } public static byte [ ] readSerialPortData ( ) { if ( SerialPortResult . SERIAL_PORT_OBJECT != null && SerialPortResult . SERIAL_PORT_OBJECT . isOpen ( ) ) { byte [ ] reslutData = null ; try { if ( ! SerialPortResult . SERIAL_PORT_OBJECT . isOpen ( ) ) { return null ; } ; int i= 0 ; while ( SerialPortResult . SERIAL_PORT_OBJECT . bytesAvailable ( ) > 0 && i++ < 5 ) Thread . sleep ( 20 ) ; byte [ ] readBuffer = new byte [ SerialPortResult . SERIAL_PORT_OBJECT . bytesAvailable ( ) ] ; int numRead = SerialPortResult . SERIAL_PORT_OBJECT . readBytes ( readBuffer, readBuffer. length) ; if ( numRead > 0 ) { reslutData = readBuffer; } } catch ( InterruptedException e) { e. printStackTrace ( ) ; } return reslutData; } return null ; }
}
SerialPortCallback
import com. example. tcpclient. utils. ConvertHexStrAndStrUtils ; import java. text. SimpleDateFormat ;
import java. util. Date ;
public class SerialPortCallback { public static void dataAvailable ( ) { try { byte [ ] back = SerialPortManager . readSerialPortData ( ) ; System . out. println ( "back-" + ( new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ) . format ( new Date ( ) ) ) + "--" + ConvertHexStrAndStrUtils . bytesToHexStr ( back) ) ; String result = ConvertHexStrAndStrUtils . bytesToHexStr ( back) ; SerialPortResult . SERIAL_PORT_RESULT = result; SerialPortResult . SERIAL_PORT_LENGTH = ConvertHexStrAndStrUtils . hexToDecimal ( result. substring ( 6 , 14 ) ) . toString ( ) ; } catch ( Exception e) { System . out. println ( e. toString ( ) ) ; } }
}
SerialPortInstructions
public class SerialPortInstructions { public static final int SERIAL_BAUD_RATE = 9600 ; public static final String READ_ALARM_STATUS = "010300000001840A" ; public static final String READ_NUMBER_ABOVE = "0103002100029401" ; public static final String READ_NUMBER_BELOW = "01030023000235C1" ; public static final String CLEAR_NUMBER_ABOVE = "010600000002080B" ; public static final String AL1_10_AL2_20 = "0110000F00040800000010000000206275" ;
}
SerialPortListener
import com. fazecast. jSerialComm. SerialPort ;
import com. fazecast. jSerialComm. SerialPortDataListener ;
import com. fazecast. jSerialComm. SerialPortEvent ;
public class SerialPortListener implements SerialPortDataListener { private final SerialPortCallback serialPortCallback; public SerialPortListener ( SerialPortCallback serialPortCallback) { this . serialPortCallback = serialPortCallback; } @Override public int getListeningEvents ( ) { return SerialPort . LISTENING_EVENT_DATA_AVAILABLE ; } @Override public void serialEvent ( SerialPortEvent serialPortEvent) { if ( serialPortCallback != null ) { serialPortCallback. dataAvailable ( ) ; } }
}
SerialPortResult
import com. fazecast. jSerialComm. SerialPort ;
public class SerialPortResult { public static volatile boolean SERIAL_PORT_STATE = false ; public static volatile SerialPort SERIAL_PORT_OBJECT = null ; public static volatile String SERIAL_PORT_RESULT = null ; public static volatile String SERIAL_PORT_LENGTH = null ; }
ConvertHexStrAndStrUtils
import java. nio. charset. StandardCharsets ; public class ConvertHexStrAndStrUtils { private static final char [ ] HEXES = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f' } ; public static String bytesToHexStr ( byte [ ] bytes) { if ( bytes == null || bytes. length == 0 ) { return null ; } StringBuilder hex = new StringBuilder ( bytes. length * 2 ) ; for ( byte b : bytes) { hex. append ( HEXES [ ( b >> 4 ) & 0x0F ] ) ; hex. append ( HEXES [ b & 0x0F ] ) ; } return hex. toString ( ) . toUpperCase ( ) ; } public static byte [ ] hexStrToBytes ( String hex) { if ( hex == null || hex. length ( ) == 0 ) { return null ; } char [ ] hexChars = hex. toCharArray ( ) ; byte [ ] bytes = new byte [ hexChars. length / 2 ] ; for ( int i = 0 ; i < bytes. length; i++ ) { bytes[ i] = ( byte ) Integer . parseInt ( "" + hexChars[ i * 2 ] + hexChars[ i * 2 + 1 ] , 16 ) ; } return bytes; } public static String strToHexStr ( String str) { StringBuilder sb = new StringBuilder ( ) ; byte [ ] bs = str. getBytes ( ) ; int bit; for ( int i = 0 ; i < bs. length; i++ ) { bit = ( bs[ i] & 0x0f0 ) >> 4 ; sb. append ( HEXES [ bit] ) ; bit = bs[ i] & 0x0f ; sb. append ( HEXES [ bit] ) ; } return sb. toString ( ) . trim ( ) ; } public static String hexStrToStr ( String hexStr) { byte [ ] array = new byte [ hexStr. length ( ) / 2 ] ; try { for ( int i = 0 ; i < array. length; i++ ) { array[ i] = ( byte ) ( 0xff & Integer . parseInt ( hexStr. substring ( i * 2 , i * 2 + 2 ) , 16 ) ) ; } hexStr = new String ( array, StandardCharsets . UTF_8 ) ; } catch ( Exception e) { e. printStackTrace ( ) ; return "" ; } return hexStr; } public static Integer hexToDecimal ( String hexString) throws NumberFormatException { if ( hexString. startsWith ( "0x" ) || hexString. startsWith ( "0X" ) ) { hexString = hexString. substring ( 2 ) ; } Integer decimalValue = Integer . parseInt ( hexString, 16 ) ; return decimalValue; } public static long hexToLong ( String hexString) throws NumberFormatException { if ( hexString. startsWith ( "0x" ) || hexString. startsWith ( "0X" ) ) { hexString = hexString. substring ( 2 ) ; } long decimalValue = Long . parseLong ( hexString, 16 ) ; return decimalValue; }
}