您的位置:首页 > 游戏 > 游戏 > 网络营销推广系统排名推荐系统_广东东莞寮步疫情最新情况_google google_网站推广网络营销

网络营销推广系统排名推荐系统_广东东莞寮步疫情最新情况_google google_网站推广网络营销

2025/1/11 0:21:49 来源:https://blog.csdn.net/liao3399084/article/details/145023461  浏览:    关键词:网络营销推广系统排名推荐系统_广东东莞寮步疫情最新情况_google google_网站推广网络营销
网络营销推广系统排名推荐系统_广东东莞寮步疫情最新情况_google google_网站推广网络营销

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")@ResponseBodypublic Boolean connectPorts() {//1、查询可用串口List<String> portList = SerialPortManager.getSerialPortList();if(!CollectionUtils.isEmpty(portList)){for (String port : portList) {//2、自动连接串口SerialPortManager.connectSerialPort(port);if(SerialPortResult.SERIAL_PORT_STATE){return true;}}}return false;}/*** 断开连接*/@GetMapping("/disconnect")@ResponseBodypublic Boolean disconnectPorts() {SerialPortManager.closeSerialPort();return !SerialPortResult.SERIAL_PORT_STATE;}/*** 查询长度*/@GetMapping("/sendPortsByLength")@ResponseBodypublic String sendPortsByLength() {if (SerialPortResult.SERIAL_PORT_STATE){SerialPortManager.sendSerialPortData(ConvertHexStrAndStrUtils.hexStrToBytes(SerialPortInstructions.READ_NUMBER_ABOVE));return SerialPortResult.SERIAL_PORT_LENGTH;}return "fail";}/*** 查询其他*/@GetMapping("/sendPortsByOther")@ResponseBodypublic 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>();// 将可用串口名添加到List并返回该Listfor(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 {//当前监听器监听到的串口返回数据 backbyte[] 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";//设置AL1和AL2报警值分别设置为10和20(AL1和AL2必须同时修改)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;}@Overridepublic int getListeningEvents() { //必须是return这个才会开启串口工具的监听return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;}@Overridepublic 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];   // 如果 hex 中的字符不是偶数个, 则忽略最后一个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) {//能被16整除,肯定可以被2整除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;}/*** 将16进制字符串转换为10进制整数** @param hexString 16进制字符串,例如 "1A3F"* @return 对应的10进制整数,例如 6719* @throws NumberFormatException 如果输入的字符串不是有效的16进制数*/public static Integer hexToDecimal(String hexString) throws NumberFormatException {// 去掉可能的前导0x或0Xif (hexString.startsWith("0x") || hexString.startsWith("0X")) {hexString = hexString.substring(2);}// 使用Integer类的parseInt方法将16进制字符串转换为10进制整数Integer decimalValue = Integer.parseInt(hexString, 16);return decimalValue;}// 如果需要处理更大的数(比如long类型),可以添加以下方法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;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com