jsp代码:
<%@ page import="com.cn.hnust.util.serialport.manager.SerialCommunication" %>
<%@page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8"/>
<title>串口工具</title>
<meta name="Keywords" content="串口工具">
<meta name="Description" content="串口工具">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<script src="js/jquery-1.8.3.min.js"></script>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.divcss {
margin-left: 20px;
margin-top: 5px;
}
.Menubutton {
width: 60px;
height: 25px;
}
button {
height: 25px;
}
</style>
</head>
<body>
<div style="width: 800px;height: 600px;border: 1px solid;margin: auto auto;margin-top: 40px;background-color: #eff1f0">
<div style="width: 100%;height: 300px">
<div style="width: 450px;height: 100%;float: left">
<div style="height: 30px;">
<span>握手连接</span>
<select id="COM_NAME">
<option value=""></option>
</select>
<button id="openSerialPortButton" onclick="openSerialPort()">打开串口</button>
<input style="">
</div>
<div style="height: 160px;">
<div style="float: left;width: 400px;height: 550px">
<textarea id="textarea" style="height: 100%;width: 100%"></textarea>
</div>
</div>
</div>
<div style="width: 350px;height: 100%;float: right">
<div style="width: 100%">
<div>
<input id="poll" type="checkbox" checked>poll
<input id="pollTime" value="50" style="width: 50px">ms
<input id="poll_cishu" value="100" style="width: 50px">次(心跳周期统计)
</div>
<div style="margin-top: 10px">
<button onclick="handshake()">握手</button>
<button onclick="autoTest()">自动测试</button>
</div>
<div style="margin: 10px;">
<button onclick="sendData('State?text=true')">STATUS=TRUE</button>
<button onclick="sendData('State?text=12345678')">STATUS=FALSE</button>
</div>
</div>
<div style="height: 30px;width: 100%">
<span>PN:</span>
<input id="type" style="width: 100px">
<button onclick="sendData('GetType','didi')">读</button>
</div>
<div style="height: 30px;width: 100%">
<span>SN:</span>
<input id="SN_prefix" style="width: 105px">
<input id="SN_suffix" style="width: 60px">
<input checked type="checkbox">后5位自动滚码
</div>
<div style="height: 120px;width: 100%">
<div style="float:left;width: 200px;height: 100px">
<div style="height: 30px;padding-left: 30px;">
<button onclick="sendData('GetSN','didi')">读</button>
<button disabled onclick="sendData('ipt?value=')">写</button>
<button onclick="autoGetSN()">自动获取SN</button>
</div>
<div style="height: 30px">
<span>Ver</span>
<input id="version" style="width: 120px">
</div>
<div style="height: 30px;padding-left: 30px;">
<button onclick="sendData('GetVersion','didi')">读</button>
</div>
</div>
<div style="float:right;width: 140px;height: 100px;border: 1px solid #000000">00001~99999测试通过自动写入</div>
</div>
</div>
</div>
<div style="height: 300px;width: 100%">
<div style="width: 450px;height: 100%;float: left">
<%--<div>--%>
<%--<input id="cycleTimes" placeholder="循环次数" value="2">--%>
<%--<button onclick="cyclicTest();">开始测试</button>--%>
<%--</div>--%>
<%--<div>--%>
<%--<span>请将测试文件设置为D:/tools/test.txt</span>--%>
<%--</div>--%>
<%--<div>--%>
<%--<span>结果请在D:/tools/result.txt中查看</span>--%>
<%--</div>--%>
</div>
<div style="width: 350px;height: 100%;float: right">
<div>
<input id="Beep_cmd" placeholder="喇叭发声指令">
<button onclick="sendData('BeepSound?duration=')">发送</button>
</div>
<div>
<button onclick="sendData('SetBeepVolume?level=0')">静音</button>
<button onclick="sendData('SetBeepVolume?level=1')">小音量</button>
<button onclick="sendData('SetBeepVolume?level=2')">中音量</button>
<button onclick="sendData('SetBeepVolume?level=3')">大音量</button>
</div>
<div>
<input id="SetBrightness" style="display: none" placeholder="请输入亮度值">
亮度测试:
<button onclick="slow_brighten()">逐渐变量</button>
<button onclick="slow_darken()">逐渐变暗</button>
</div>
<div style="padding-top: 10px">
<button onclick="sendData('EnableButton?Enabled=true')">Enable Button</button>
<button onclick="sendData('EnableButton?Enabled=false')">Disable Button</button>
</div>
<div style="padding-top: 10px">
<button id="plus" class="Menubutton">+</button>
<button id="Menu" class="Menubutton">Menu</button>
<button id="Mines" class="Menubutton">-</button>
</div>
<div style="margin: 10px;">
<input id="cycleTimes" placeholder="循环次数" value="2">
<button onclick="cyclicTest();">开始测试</button>
</div>
<div>
<span>请将测试文件设置为D:/tools/test.txt</span>
</div>
<div>
<span>结果请在D:/tools/result.txt中查看</span>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
function autoGetSN(){
if (openSerialPort_action == "open") {
alert("请打开串口");
return;
}
$.ajax({
type: "post",
async: false, //同步请求
url: "${pageContext.request.contextPath }/autoGetSN",
data: {
"commName": $("#COM_NAME").val()
},
success: function (dates) {
// var json = JSON.parse(dates);
var json = dates;
if (json.length == 10) {
var SN = json;
var SN_prefix = SN.substr(0, 5);
var SN_suffix = SN.substr(5);
$("#SN_prefix").val(SN_prefix);
$("#SN_suffix").val(SN_suffix);
didi();
} else {
alert(json);
}
},
error: function () {
alert("串口操作失败!");
}
});
}
function cyclicTest() {
if (openSerialPort_action == "open") {
alert("请打开串口");
return;
}
var cycleTimes = $("#cycleTimes").val();
var commName = $("#COM_NAME").val();
if (cycleTimes.length == 0) {
alert("请设置循环次数");
return;
}
$.ajax({
type: "post",
async: false, //同步请求
url: "${pageContext.request.contextPath }/cyclicTest",
data: {
"cycleTimes": cycleTimes,
"commName": commName
},
success: function (dates) {
var json = JSON.parse(dates);
if (json.result == "success") {
$("#textarea").val($("#textarea").val() + json.result1 + "\n");
didi();
} else {
alert(json.result);
}
},
error: function () {
alert("测试失败");
}
});
}
function handshake() {
$("#textarea").val($("#textarea").val() + "握手中。。。\n");
if (openSerialPort_action == "open") {
alert("请打开串口");
return;
}
sendData('handshake');
$("#textarea").val($("#textarea").val() + "握手成功!\n");
}
var mCommList = <%=SerialCommunication.initData()%>;
var html = "";
for (var i = 0; i < mCommList.length; i++) {
html += '<option value="' + mCommList[i] + '">' + mCommList[i] + '</option>';
}
$("#COM_NAME").html(html);
var openSerialPort_action = "open";
function openSerialPort() {
var commName = $("#COM_NAME").val();
var baudrate = "115200";
$.ajax({
type: "post",
async: false, //同步请求
url: "${pageContext.request.contextPath }/openSerialPort",
data: {
"commName": commName,
"action": openSerialPort_action,
"baudrate": baudrate
},
success: function (dates) {
var json = JSON.parse(dates);
if (json.result == "success") {
if (openSerialPort_action == "open") {
$("#textarea").val($("#textarea").val() + "串口打开成功!\n");
$("#COM_NAME").attr("disabled", "disabled");
$("#openSerialPortButton").html("关闭串口");
openSerialPort_action = "close";
} else {
$("#textarea").val("关闭串口成功!\n");
$("#COM_NAME").removeAttr("disabled");
$("#openSerialPortButton").html("打开串口");
openSerialPort_action = "open";
}
} else {
alert(json.result);
}
},
error: function () {
alert("串口操作失败!");
}
});
}
function didi() {
sendData('SetBeepVolume?level=1');
$("#Beep_cmd").val("150,150,150,150");
sendData('BeepSound?duration=');
}
function slow_brighten() {
if (openSerialPort_action == "open") {
alert("请打开串口");
return;
}
$("#SetBrightness").val("0");
sendData('SetBrightness?level=');
$("#SetBrightness").val("10");
sendData('SetBrightness?level=');
$("#SetBrightness").val("20");
sendData('SetBrightness?level=');
$("#SetBrightness").val("30");
sendData('SetBrightness?level=');
$("#SetBrightness").val("40");
sendData('SetBrightness?level=');
$("#SetBrightness").val("50");
sendData('SetBrightness?level=');
$("#SetBrightness").val("60");
sendData('SetBrightness?level=');
$("#SetBrightness").val("70");
sendData('SetBrightness?level=');
$("#SetBrightness").val("80");
sendData('SetBrightness?level=');
$("#SetBrightness").val("90");
sendData('SetBrightness?level=');
$("#SetBrightness").val("100");
sendData('SetBrightness?level=');
didi();
}
function slow_darken() {
if (openSerialPort_action == "open") {
alert("请打开串口");
return;
}
$("#SetBrightness").val("100");
sendData('SetBrightness?level=');
$("#SetBrightness").val("90");
sendData('SetBrightness?level=');
$("#SetBrightness").val("80");
sendData('SetBrightness?level=');
$("#SetBrightness").val("70");
sendData('SetBrightness?level=');
$("#SetBrightness").val("60");
sendData('SetBrightness?level=');
$("#SetBrightness").val("50");
sendData('SetBrightness?level=');
$("#SetBrightness").val("40");
sendData('SetBrightness?level=');
$("#SetBrightness").val("30");
sendData('SetBrightness?level=');
$("#SetBrightness").val("20");
sendData('SetBrightness?level=');
$("#SetBrightness").val("10");
sendData('SetBrightness?level=');
$("#SetBrightness").val("0");
sendData('SetBrightness?level=');
didi();
}
function sendData(cmd, param1) {
if (openSerialPort_action == "open") {
alert("请打开串口");
return;
}
var commName = $("#COM_NAME").val();
var baudrate = "115200";
if ((typeof param1) == "undefined") {
param1 = "";
}
if (cmd == 'SetSN?value=') {
cmd = cmd + $("#SN_prefix").val() + $("#SN_suffix").val();
}
if (cmd == 'ipt?value=') {
var SN_prefix = $("#SN_prefix").val();
var SN_suffix = $("#SN_suffix").val();
if (SN_prefix.length != 5 || SN_suffix.length != 5) {
alert("请设置5位长度的sn前缀和后缀!");
return;
}
cmd = cmd + SN_prefix + SN_suffix;
}
if (cmd == 'BeepSound?duration=') {
cmd = cmd + $("#Beep_cmd").val();
}
if (cmd == 'SetBrightness?level=') {
var tmp = $("#SetBrightness").val();
// if(tmp)
cmd = cmd + $("#SetBrightness").val();
}
$.ajax({
type: "post",
async: false, //同步请求
url: "${pageContext.request.contextPath }/sendData",
data: {
"commName": commName,
"cmd": cmd,
"param1": param1,
"baudrate": baudrate
},
success: function (dates) {
var json = JSON.parse(dates);
switch (json.cmd) {
case "success":
break;
case "timeout":
alert(json.result);
break;
case "GetType":
var type = json.result.split("value=")[1];
$("#type").val(type);
if (param1 == "didi") {
didi();
}
break;
case "SetBeepVolume?level=0":
case "SetBeepVolume?level=1":
case "SetBeepVolume?level=2":
case "SetBeepVolume?level=3":
$("#Beep_cmd").val("150,150,150,150");
sendData('BeepSound?duration=');
break;
case "GetVersion":
var version = json.result.split("value=")[1];
$("#version").val(version);
if (param1 == "didi") {
didi();
}
break;
case "GetSN":
var SN = json.result.split("value=")[1];
var SN_prefix = SN.substr(0, 5);
var SN_suffix = SN.substr(5);
$("#SN_prefix").val(SN_prefix);
$("#SN_suffix").val(SN_suffix);
if (param1 == "didi") {
didi();
}
break;
case "handshake":
if (json.result == "fail") {
alert("握手失败");
return;
}
if (json.result == "success") {
if ($("#poll").attr("checked")) {
sendData("Poll", $("#pollTime").val() + "|" + $("#poll_cishu").val());
}
sendData('GetType');
sendData('GetVersion');
sendData('GetSN');
didi();
return;
}
break;
case "State?text=true":
case "State?text=12345678":
didi();
break;
case "EnableButton?Enabled=true":
$("#textarea").val($("#textarea").val() + "EnableButton?Enabled=true成功!\n");
break;
case "EnableButton?Enabled=false":
$("#textarea").val($("#textarea").val() + "EnableButton?Enabled=false成功!\n");
break;
}
if (cmd.indexOf("ipt?value=") > -1) {
didi();
}
},
error: function () {
alert("指令发送失败!");
}
});
}
window.setInterval("listenMenu()", 500);
function listenMenu() {
$.ajax({
type: "post",
async: true, //同步请求
url: "${pageContext.request.contextPath }/listenMenu",
data: {
},
success: function (dates) {
var json = JSON.parse(dates);
if (json.result == "success") {
$("#plus").css("background-color", "#eff1f0");
$("#Mines").css("background-color", "#eff1f0");
$("#Menu").css("background-color", "#eff1f0");
switch (json.menu) {
case "+":
$("#plus").css("background-color", "yellow");
break;
case "-":
$("#Mines").css("background-color", "yellow");
break;
case "Menu":
$("#Menu").css("background-color", "yellow");
break;
}
} else {
alert(json.result);
}
},
error: function () {
}
});
}
function autoTest() {
handshake();
setTimeout(autoTest1(), 1000);
// sendData('SetBeepVolume?level=1');
// $("#textarea").val($("#textarea").val()+ "小音量测试成功\n");
// setTimeout(after(),1000);
// sendData('SetBeepVolume?level=2');
// $("#textarea").val($("#textarea").val()+ "中音量测试成功\n");
// setTimeout(after(),1000);
// sendData('SetBeepVolume?level=3')
// $("#textarea").val($("#textarea").val()+ "大音量测试成功\n");
// setTimeout(after(),1000);
//
//
// slow_darken()
// $("#textarea").val($("#textarea").val()+ "逐渐变暗测试成功\n");
// setTimeout(after(),1000);
// slow_brighten();
// $("#textarea").val($("#textarea").val()+ "逐渐变量测试成功\n");
// setTimeout(after(),1000);
//
// $("#textarea").val($("#textarea").val()+ "循环指令测试中。。。\n");
// cyclicTest();
// $("#textarea").val($("#textarea").val()+ "循环指令测试成功!\n");
}
function autoTest1() {
sendData('SetBeepVolume?level=1');
$("#textarea").val($("#textarea").val() + "小音量测试成功\n");
setTimeout("autoTest2()", 1000);
}
function autoTest2() {
sendData('SetBeepVolume?level=2');
$("#textarea").val($("#textarea").val() + "中音量测试成功\n");
setTimeout("autoTest3()", 1000);
}
function autoTest3() {
sendData('SetBeepVolume?level=3')
$("#textarea").val($("#textarea").val() + "大音量测试成功\n");
setTimeout("autoTest4()", 1000);
}
function autoTest4() {
slow_darken()
$("#textarea").val($("#textarea").val() + "逐渐变暗测试成功\n");
setTimeout("autoTest5()", 1000);
}
function autoTest5() {
slow_brighten();
$("#textarea").val($("#textarea").val() + "逐渐变量测试成功\n");
setTimeout("autoTest6()", 1000);
}
function autoTest6() {
$("#textarea").val($("#textarea").val() + "循环指令测试中。。。\n");
cyclicTest();
$("#textarea").val($("#textarea").val() + "循环指令测试成功!\n");
}
</script>
</html>
IndexController:
package com.cn.hnust.controller;
import com.cn.hnust.pojo.Equipment;
import com.cn.hnust.pojo.Order;
import com.cn.hnust.service.EquipmentService;
import com.cn.hnust.service.OrderService;
import com.cn.hnust.thread.PollThread;
import com.cn.hnust.util.serialport.manager.SerialCommunication;
import gnu.io.SerialPort;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Controller
public class IndexController {
@Autowired
private EquipmentService equipmentService;
@Autowired
private OrderService orderService;
public static String staticCommName = "";
public static volatile String staticMenu = "";
@ResponseBody
@RequestMapping(value = "/openSerialPort", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public String openSerialPort(@RequestParam("commName") String commName,
@RequestParam("action") String action,
@RequestParam("baudrate") String baudrate) {
staticCommName = commName;
JSONObject jsonObject = new JSONObject();
if (action.equals("open")) {
SerialPort serialPort = SerialCommunication.openSerialPort(commName, Integer.valueOf(baudrate));
if (serialPort == null) {
jsonObject.put("result", "串口已被占用");
} else {
jsonObject.put("result", "success");
}
}
if (action.equals("close")) {
String result = SerialCommunication.closeSerialPort(commName, Integer.valueOf(baudrate));
if (result.equals("success")) {
jsonObject.put("result", "success");
} else {
jsonObject.put("result", "关闭串口失败");
}
}
return jsonObject.toString();
}
@ResponseBody
@RequestMapping(value = "/sendData", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public static String sendData(@RequestParam("commName") String commName,
@RequestParam("cmd") String cmd,
@RequestParam("param1") String param1,
@RequestParam("baudrate") String baudrate) {
switch (cmd) {
case "handshake":
JSONObject jsonObject = new JSONObject();
if (!SerialCommunication.handshake(commName, Integer.valueOf(baudrate))) {
jsonObject.put("cmd", "handshake");
jsonObject.put("result", "fail");
return jsonObject.toString();
} else {
jsonObject.put("cmd", "handshake");
jsonObject.put("result", "success");
return jsonObject.toString();
}
case "Poll":
SerialCommunication.cishu = Integer.valueOf(param1.split("\\|")[1]);
PollThread.startPoll(commName, Integer.valueOf(baudrate), Integer.valueOf(param1.split("\\|")[0]));
break;
case "GetSN":
case "GetVersion":
case "GetType":
default:
SerialCommunication.sendData(cmd, "Hex", commName, Integer.valueOf(baudrate));
while (true) {
if ((SerialCommunication.current_result_time < SerialCommunication.send_time) && (new Date().getTime() - SerialCommunication.send_time > 500)) {
System.out.println(SerialCommunication.request_cmd + " time out,current time=" + new Date().getTime() + ",send_time=" + SerialCommunication.send_time);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
SerialCommunication.isNewResult = false;
SerialCommunication.isChannelOccupancy = false;
JSONObject obj = new JSONObject();
obj.put("cmd", "timeout");
obj.put("result", cmd + "超时");
return obj.toString();
}
if (SerialCommunication.isNewResult) {
String result = SerialCommunication.getResultFrom_result_hex(SerialCommunication.result_hex);
JSONObject obj = new JSONObject();
obj.put("cmd", SerialCommunication.request_cmd);
obj.put("result", result);
if (SerialCommunication.request_cmd.contains("Alert?pic")) {
Long usetime = SerialCommunication.current_result_time - SerialCommunication.send_time;
String str = (Long.valueOf(arry.get(index % arry.size())[1]) - usetime >= 0) ? "合格" : "不合格";
String[] strarry = new String[]{arry.get(index % arry.size())[0], arry.get(index % arry.size())[1], usetime.toString(), str};
result_arry.add(strarry);
}
SerialCommunication.isNewResult = false;
SerialCommunication.isChannelOccupancy = false;
return obj.toString();
}
}
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("cmd", "success");
jsonObject.put("result", "success");
return jsonObject.toString();
}
@ResponseBody
@RequestMapping(value = "/getData", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public String getData(@RequestParam("cmd") String cmd) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("cmd", cmd);
switch (cmd) {
case "GetType":
jsonObject.put("result", SerialCommunication.PN);
break;
case "GetVersion":
jsonObject.put("result", SerialCommunication.Ver);
break;
case "GetSN":
jsonObject.put("result", SerialCommunication.SN);
break;
}
return jsonObject.toString();
}
public static List<String[]> txt2String(File file) {
List<String[]> result = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
String s = null;
while ((s = br.readLine()) != null) {//使用readLine方法,一次读一行
if (s.trim().length() > 0) {
String[] arry = s.split("\\|");
result.add(arry);
}
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
//
//
public static List<String[]> arry = new ArrayList<>();
public static volatile List<String[]> result_arry = new ArrayList<>();
public static volatile int index;
@ResponseBody
@RequestMapping(value = "/cyclicTest", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public String cyclicTest(@RequestParam("cycleTimes") String cycleTimes,
@RequestParam("commName") String commName) throws IOException {
int t = Integer.valueOf(cycleTimes);
String dir = "D:/tools/test.txt";
File file = new File(dir);
arry = txt2String(file);
result_arry = new ArrayList<>();
index = 0;
for (int i = 0; i < t; i++) {
for (String[] s : arry) {
sendData(commName, s[0], "", "115200");
index++;
}
}
String dir1 = "D:/tools/test_result.txt";
File myFile = new File(dir1);
if (!myFile.exists()) {
myFile.createNewFile();
}
String content = "";
String result1 = "";
for (String[] sa : result_arry) {
String line = sa[0] + "|" + sa[1] + "|" + sa[2] + "|" + sa[3] + "\r\n";
content += line;
if (sa[3].equals("不合格")) {
result1 += line;
}
}
FileOutputStream fop = new FileOutputStream(myFile);
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
JSONObject jsonObject = new JSONObject();
jsonObject.put("result", "success");
jsonObject.put("result1", result1);
return jsonObject.toString();
}
@ResponseBody
@RequestMapping(value = "/listenMenu", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public String listenMenu() throws IOException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("result", "success");
jsonObject.put("menu", staticMenu);
return jsonObject.toString();
}
@ResponseBody
@RequestMapping(value = "/autoGetSN", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public String autoGetSN(@RequestParam("commName") String commName) {
String sn = JSONObject.fromObject(sendData(commName, "GetSN", "", "115200")).get("result").toString().split("=")[1].trim();
String getNewSN_result = "";
if (sn.length() == 10) {
String SN_prefix = sn.substring(0, 5);
String SN_suffix = sn.substring(5);
Equipment equipment = equipmentService.selectEquipmentBySN(SN_prefix, SN_suffix);
if (equipment != null) {
return sn;
} else {
return getNewSN( commName);
}
} else {
return getNewSN( commName);
}
}
public String getNewSN(String commName){
List<Order> orderList = orderService.selectOrderByisUsing("true");
if(orderList.size()==0){
return "没有可用的订单";
}
if(orderList.size()>1){
return "当前使用的订单数大于1";
}
String SN_prefix = orderList.get(0).getName();
String SN_suffix = String.format("%5d", Integer.valueOf(orderList.get(0).getCurrent_num())+1).replace(" ", "0");
sendData(commName, "ipt?value="+SN_prefix+SN_suffix, "", "115200");
orderService.updateOrder(SN_prefix,SN_suffix);
Equipment equipment = new Equipment();
equipment.setPN(JSONObject.fromObject(sendData(commName, "GetType", "", "115200")).get("result").toString().split("=")[1]);
equipment.setVer(JSONObject.fromObject(sendData(commName, "GetVersion", "", "115200")).get("result").toString().split("=")[1]);
equipment.setSN_prefix(SN_prefix);
equipment.setSN_suffix(SN_suffix);
equipmentService.addEquipment(equipment);
return SN_prefix+SN_suffix;
}
public static void main(String args[]) {
int a = "Alert?pic=008.jpg&text=yyy|10".split("\\|").length;
System.out.println("没有可用的订单".length());
System.out.println("当前使用的订单数大于1".length());
}
}
SerialCommunication:
package com.cn.hnust.util.serialport.manager;
import com.cn.hnust.controller.IndexController;
import com.cn.hnust.util.DateUtil;
import com.cn.hnust.util.serialport.utils.ByteUtils;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SerialCommunication {
// 串口对象
public static Map<String, SerialPort> SerialPortMap = new HashMap<String, SerialPort>();
public static String request_cmd = "";
public static String result_hex = "";
public static String PN = "";
public static String SN = "";
public static String Ver = "";
public static volatile long current_result_time = 0;
// public static volatile long last_result_time = 0;
public static volatile long send_time = 0;
public static volatile boolean isChannelOccupancy = false;
public static volatile boolean isNewResult = false;
private static byte[] lock = new byte[0];
public static String initData() {
current_result_time = new Date().getTime();
// last_result_time = current_result_time;
send_time = 0;
for (Map.Entry<String, SerialPort> entry : SerialPortMap.entrySet()) {
closeSerialPort(entry.getValue());
}
SerialPortMap.clear();
List<String> mCommList = SerialPortManager.findPorts();
// 检查是否有可用串口,有则加入选项中
String result = "[";
if (mCommList == null || mCommList.size() < 1) {
System.out.println("没有搜索到有效串口!");
} else {
System.out.println("搜索到如下串口:");
for (String s : mCommList) {
System.out.println(s);
result += ("'" + s + "',");
}
if (result.length() > 1) {
result = result.substring(0, result.length() - 1);
}
}
result += "]";
return result;
}
public static SerialPort openSerialPort(String commName, int baudrate) {
// 检查串口名称是否获取正确
SerialPort serialPort = null;
String key = commName + "_" + baudrate;
if (SerialPortMap.get(key) == null) {
try {
serialPort = SerialPortManager.openPort(commName, baudrate);
if (serialPort != null) {
System.out.println("COM open success:" + key);
SerialPortMap.put(key, serialPort);
}
} catch (PortInUseException e) {
System.out.println("COM has been used:" + key);
return null;
}
}
SerialPortManager.addListener(commName, baudrate, serialPort, new SerialPortManager.DataAvailableListener() {
@Override
public void dataAvailable(String commName, int baudrate) {
current_result_time = new Date().getTime();
byte[] data = null;
String key = commName + "_" + baudrate;
data = SerialPortManager.readFromPort(SerialPortMap.get(key));
result_hex = ByteUtils.byteArrayToHexString(data);
isNewResult = true;
System.out.println("current_result_time=" + current_result_time);
System.out.println("receive string:" + new String(data) + "\r\n");
System.out.println("receive hex:" + result_hex + "\r\n");
}
});
return serialPort;
}
public static String getResultFrom_result_hex(String result_hex) {
String hex_str = result_hex.substring(2, result_hex.length() - 4);
String str = hexStringToString(hex_str);
String result = str.substring(str.indexOf("$") + 1, str.indexOf("*"));
return result;
}
private static void closeSerialPort(SerialPort mSerialport) {
System.out.println("close COM:" + mSerialport.getName());
SerialPortManager.closePort(mSerialport);
System.out.println("COM closed,Serialport=" + mSerialport.getName() + "\r\n");
mSerialport = null;
}
public static String closeSerialPort(String commName, int baudrate) {
String key = commName + "_" + baudrate;
if (SerialPortMap.get(key) != null) {
closeSerialPort(SerialPortMap.get(key));
SerialPortMap.remove(key);
return "success";
}
return "fail";
}
//将cmd命令转化成十六进制发送指令,并加上头尾
public static String paramDataToHexData(String cmd) {
String cmd_hex = SerialCommunication.strTo16(cmd);
String yihuo = SerialCommunication.yihuo(cmd_hex);
String middleStr = SerialCommunication.strTo16("$" + cmd + "*" + yihuo);
String hex = "aa" + middleStr + "0d0a";
return hex;
}
public static void sendData(String cmd, String sendType, String commName, int baudrate) {
String key = commName + "_" + baudrate;
SerialPort mSerialport = SerialPortMap.get(key);
String data = SerialCommunication.paramDataToHexData(cmd);
while (true) {
if (!isChannelOccupancy) {
synchronized (lock) {
isChannelOccupancy = true;
request_cmd = cmd;
sendData(data, sendType, mSerialport);
break;
}
}
// }
}
}
public static void sendData(String data, String sendType, SerialPort mSerialport) {
// 待发送数据
System.out.println("sendData:" + data);
if (mSerialport == null) {
System.out.println("please open COM");
return;
}
// if ("".equals(data) || data == null) {
// System.out.println("请输入要发送的数据!");
// return;
// }
switch (sendType) {
case "ASCII":
SerialPortManager.sendToPort(mSerialport, data.getBytes());
break;
case "Hex":
SerialPortManager.sendToPort(mSerialport, ByteUtils.hexStr2Byte(data));
break;
}
}
public static void main(String args[]) {
new Date().getTime();
System.out.println(yihuo(strTo16("GetSN")));
System.out.println(strTo16("GetSN"));
System.out.println(hexStringToString("2453746172742a3430"));
}
public static String yihuo(String content) {
content = change(content);
String[] b = content.split(" ");
int a = 0;
for (int i = 0; i < b.length; i++) {
a = a ^ Integer.parseInt(b[i], 16);
}
if (a < 10) {
StringBuffer sb = new StringBuffer();
sb.append("0");
sb.append(a);
return sb.toString();
}
String result = Integer.toHexString(a).toUpperCase();
if (result.length() == 1) {
result = "0" + result;
}
return result;
}
public static String change(String content) {
String str = "";
for (int i = 0; i < content.length(); i++) {
if (i % 2 == 0) {
str += " " + content.substring(i, i + 1);
} else {
str += content.substring(i, i + 1);
}
}
return str.trim();
}
public static String strTo16(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
public static String hexStringToString(String s) {
if (s == null || s.equals("")) {
return null;
}
s = s.replace(" ", "");
byte[] baKeyword = new byte[s.length() / 2];
for (int i = 0; i < baKeyword.length; i++) {
try {
baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
s = new String(baKeyword, "UTF-8");
new String();
} catch (Exception e1) {
e1.printStackTrace();
}
return s;
}
public static final String[] handshake_cmd = new String[]{
"Start",
"Configure?Setting=1,xx,004.jpg;",
"Configure?Setting=2,xx,003.jpg;",
"Configure?Setting=3,xx,002.jpg;",
"Configure?Setting=0,xx,005.jpg;",
"ConfigureFinished"
};
public static boolean handshake(String commName, int baudrate) {
for (String s : handshake_cmd) {
sendData(s, "Hex", commName, baudrate);
if (waitForDataResult().equals("fail")) {
return false;
}
}
return true;
}
public static volatile int pollIndex = 0;
public static volatile int pollTotalTime = 0;
public static Date start = null;
public static Date end = null;
public static int cishu = 100;
static File errfile = new File("D:/tools/poll_err.txt");
static FileOutputStream errfop = null;
public static void poll(String commName, int baudrate, int pollTime) throws IOException {
String dir1 = "D:/tools/poll_result.txt";
File myFile = new File(dir1);
if (myFile.exists()) {
myFile.delete();
}
if (!myFile.exists()) {
myFile.createNewFile();
}
if (errfile.exists()) {
errfile.delete();
}
if (!errfile.exists()) {
errfile.createNewFile();
}
start = new Date();
FileOutputStream fop = new FileOutputStream(myFile, true);
errfop = new FileOutputStream(errfile, true);
while (true) {
sendData("Poll", "Hex", commName, baudrate);
if (waitForDataResult().equals("fail")) {
return;
}
pollIndex++;
try {
Thread.sleep(pollTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (pollIndex == cishu) {
end = new Date();
int pinjun_time = pollTotalTime / cishu;
String content = DateUtil.format(start, "yyyy-MM-dd HH:mm:ss") + "-" +
DateUtil.format(end, "HH:mm:ss") + "|" + cishu + "次|" + "平均响应时间" + pinjun_time + "\r\n";
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
// fop.close();
pollIndex = 0;
pollTotalTime = 0;
start = new Date();
}
}
}
public static String waitForDataResult() {
while (true) {
long tmpTime = new Date().getTime();
if ((current_result_time < send_time) && (tmpTime - send_time > 500)) {
System.out.println(request_cmd + " time out!current Time=" + tmpTime);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
isNewResult = false;
isChannelOccupancy = false;
return "fail";
}
if (isNewResult) {
if (result_hex.equals("AA244F4B2A30340D0A")) {
Long time = current_result_time - send_time;
if (time > 100) {
String content = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "响应时间过长" + time + "\r\n";
byte[] contentInBytes = content.getBytes();
try {
errfop.write(contentInBytes);
} catch (IOException e) {
e.printStackTrace();
}
try {
errfop.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
pollTotalTime += time;
isNewResult = false;
isChannelOccupancy = false;
IndexController.staticMenu = "";
return "success";
} else if (result_hex.contains("427574746F6E507265737365643F427574746F6E3D2B")) {
IndexController.staticMenu = "+";
isNewResult = false;
isChannelOccupancy = false;
// IndexController.sendData(IndexController.staticCommName, "State?text=11111111", "", "115200");
return "success";
} else if (result_hex.contains("427574746F6E507265737365643F427574746F6E3D4D656E75")) {
// IndexController.sendData(IndexController.staticCommName,"State?text=22222222","","115200");
IndexController.staticMenu = "Menu";
isNewResult = false;
isChannelOccupancy = false;
return "success";
} else if (result_hex.contains("427574746F6E507265737365643F427574746F6E3D2D")) {
IndexController.staticMenu = "-";
isNewResult = false;
isChannelOccupancy = false;
// IndexController.sendData(IndexController.staticCommName, "State?text=33333333", "", "115200");
return "success";
} else {
System.out.println(request_cmd + " error");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
isNewResult = false;
isChannelOccupancy = false;
IndexController.staticMenu = "";
return "fail";
}
}
}
}
}
SerialPortManager:
package com.cn.hnust.util.serialport.manager;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.TooManyListenersException;
import com.cn.hnust.util.serialport.utils.ArrayUtils;
import com.cn.hnust.util.serialport.utils.ShowUtils;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
/**
* 串口管理
*
* @author yangle
*/
@SuppressWarnings("all")
public class SerialPortManager {
/**
* 查找所有可用端口
*
* @return 可用端口名称列表
*/
public static final ArrayList<String> findPorts() {
// 获得当前所有可用串口
Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
ArrayList<String> portNameList = new ArrayList<String>();
// 将可用串口名添加到List并返回该List
while (portList.hasMoreElements()) {
String portName = portList.nextElement().getName();
portNameList.add(portName);
}
return portNameList;
}
/**
* 打开串口
*
* @param portName
* 端口名称
* @param baudrate
* 波特率
* @return 串口对象
* @throws PortInUseException
* 串口已被占用
*/
public static final SerialPort openPort(String portName, int baudrate) throws PortInUseException {
try {
// 通过端口名识别端口
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
// 打开端口,并给端口名字和一个timeout(打开操作的超时时间)
CommPort commPort = portIdentifier.open(portName, 2000);
// 判断是不是串口
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
try {
// 设置一下串口的波特率等参数
// 数据位:8
// 停止位:1
// 校验位:None
serialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
e.printStackTrace();
}
return serialPort;
}
} catch (NoSuchPortException e1) {
e1.printStackTrace();
}
return null;
}
/**
* 关闭串口
*
* @param serialport
* 待关闭的串口对象
*/
public static void closePort(SerialPort serialPort) {
if (serialPort != null) {
serialPort.close();
}
}
/**
* 往串口发送数据
*
* @param serialPort
* 串口对象
* @param order
* 待发送数据
*/
public static void sendToPort(SerialPort serialPort, byte[] order) {
OutputStream out = null;
try {
out = serialPort.getOutputStream();
out.write(order);
out.flush();
// 发送时间
SerialCommunication.send_time = new Date().getTime();
System.out.println("send_time="+SerialCommunication.send_time);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
out = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 从串口读取数据
*
* @param serialPort
* 当前已建立连接的SerialPort对象
* @return 读取到的数据
*/
public static byte[] readFromPort(SerialPort serialPort) {
InputStream in = null;
byte[] bytes = {};
try {
in = serialPort.getInputStream();
// 缓冲区大小为一个字节
byte[] readBuffer = new byte[1];
int bytesNum = in.read(readBuffer);
while (bytesNum > 0) {
bytes = ArrayUtils.concat(bytes, readBuffer);
bytesNum = in.read(readBuffer);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
in = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return bytes;
}
/**
* 添加监听器
*
* @param port
* 串口对象
* @param listener
* 串口存在有效数据监听
*/
public static void addListener(String commName,int baudrate, SerialPort serialPort, DataAvailableListener listener) {
try {
// 给串口添加监听器
serialPort.addEventListener(new SerialPortListener(listener,commName,baudrate));
// 设置当有数据到达时唤醒监听接收线程
serialPort.notifyOnDataAvailable(true);
// 设置当通信中断时唤醒中断线程
serialPort.notifyOnBreakInterrupt(true);
} catch (TooManyListenersException e) {
e.printStackTrace();
}
}
/**
* 串口监听
*/
public static class SerialPortListener implements SerialPortEventListener {
private DataAvailableListener mDataAvailableListener;
private String commName;
private int baudrate;
public SerialPortListener(DataAvailableListener mDataAvailableListener, String commName,int baudrate) {
this.mDataAvailableListener = mDataAvailableListener;
this.commName = commName;
this.baudrate = baudrate;
}
public void serialEvent(SerialPortEvent serialPortEvent) {
switch (serialPortEvent.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE: // 1.串口存在有效数据
if (mDataAvailableListener != null) {
mDataAvailableListener.dataAvailable(commName,baudrate);
}
break;
case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 2.输出缓冲区已清空
break;
case SerialPortEvent.CTS: // 3.清除待发送数据
break;
case SerialPortEvent.DSR: // 4.待发送数据准备好了
break;
case SerialPortEvent.RI: // 5.振铃指示
break;
case SerialPortEvent.CD: // 6.载波检测
break;
case SerialPortEvent.OE: // 7.溢位(溢出)错误
break;
case SerialPortEvent.PE: // 8.奇偶校验错误
break;
case SerialPortEvent.FE: // 9.帧错误
break;
case SerialPortEvent.BI: // 10.通讯中断
ShowUtils.errorMessage("与串口设备通讯中断");
break;
default:
break;
}
}
}
/**
* 串口存在有效数据监听
*/
public interface DataAvailableListener {
/**
* 串口存在有效数据
*/
void dataAvailable(String commName,int baudrate);
}
}
PollThread:
package com.cn.hnust.thread;
import com.cn.hnust.util.SendHttp;
import com.cn.hnust.util.serialport.manager.SerialCommunication;
import org.apache.commons.lang.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by wangbin on 2019/4/2.
*/
public class PollThread implements Runnable {
private String commName;
private int baudrate;
private int pollTime;
public String getCommName() {
return commName;
}
public void setCommName(String commName) {
this.commName = commName;
}
public int getBaudrate() {
return baudrate;
}
public void setBaudrate(int baudrate) {
this.baudrate = baudrate;
}
public int getPollTime() {
return pollTime;
}
public void setPollTime(int pollTime) {
this.pollTime = pollTime;
}
@Override
public void run() {
try {
SerialCommunication.poll(commName, baudrate, pollTime);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void startPoll(String commName, int baudrate,int pollTime){
PollThread pollThread = new PollThread();
pollThread.setCommName(commName);
pollThread.setBaudrate(baudrate);
pollThread.setPollTime(pollTime);
Thread thread = new Thread(pollThread,"Sender App Module");
thread.start();
}
public static void main(String args[]) {
PollThread pollThread = new PollThread();
pollThread.setCommName("COM6");
pollThread.setBaudrate(115200);
pollThread.setPollTime(50);
Thread thread = new Thread(new PollThread(),"Sender App Module");
thread.start();
}
}