Commit fbedd15c authored by guoyu's avatar guoyu

称重服务

parents
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
</web-app>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.10-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mushiny</groupId>
<artifactId>metage</artifactId>
<version>1</version>
<packaging>war</packaging>
<name>metage</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<tomcat.version>8.5.42</tomcat.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!--<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
</project>
package com.mushiny.metage;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class BackendInTomcatApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MetageApplication.class);
}
}
package com.mushiny.metage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MetageApplication {
public static void main(String[] args) {
SpringApplication.run(MetageApplication.class, args);
}
}
package com.mushiny.metage.api;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Map;
/**
* @version 1.0
* @author: Gy
* @date: 2023-02-31 13:53
*/
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/mushiny")
public class MetageController {
@RequestMapping("/getWeight")
public void getWeight(@RequestBody(required = false) Map<String, String> map) throws Exception{
/*cRead.outputStream.write(st.getBytes("gbk"), 0, st.getBytes("gbk").length);*/
/*return RxtxUtils.weightings;*/
//服务端获取客户端发送数据
receiveData();
}
private void receiveData() throws IOException{
//于服务端而言,首先需要定义DatagramSocket对象,指定接受端口。
DatagramSocket server = new DatagramSocket(10086);
//定义接受数据的packet包,这算是一个存储接收的容器
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes,bytes.length);
//用定义的pakcet接受客户端传送过来的数据
server.receive(packet);
//接收完成之后,数据在容器里面,需要调用容器的getData()方法获取之前定义好的数据类型的数据
//比如说之前定义packet接收包的时候,定义的是字节数据,所以获取的也是字节数组。
byte[] receiveData = packet.getData();
//拿到数据之后,我们可以把它转化为字符串输出打印到控制台上。
String receiveString = new String(receiveData,0,receiveData.length);
System.out.println(receiveString);
//关闭资源
server.close();
}
}
package com.mushiny.metage.util;
/**
* 进制转换
* */
public class HexadecimalUtil {
/**
* 十六进制转十进制
*
* @param num
* @return
*/
public static Integer get10HexNum(String num) {
if (num.contains("0X")) {
num = num.replace("0X", "");
}
return Integer.parseInt(num.substring(0), 16);
}
/**
* 十进制转十六进制
*
* @param num
* @return
*/
public static String get16Num(Object num) {
return Integer.toHexString(Integer.parseInt(num + ""));
}
/**
* 十进制转十六进制,设置长度,不足补0
*
* @param num
* @return
*/
public static String get16NumAdd0(String num, int len) {
String str = Integer.toHexString(Integer.parseInt(num)).toUpperCase();
String res = "";
if (len >= str.length()) {
// res = HexadecimalUtil.repeat("0", (len - str.length())) + str;
} else {
return str;
}
return res;
}
//num & 0xff
public static int low8(Object num) {
return Integer.parseInt(num + "") & 0xff;
}
//获取高四位
public static int getHeight4(byte data) {
int height;
height = ((data & 0xf0) >> 4);
return height;
}
/**
* 16进制表示的字符串转换为字节数组
*
* @param hexString 16进制表示的字符串
* @return byte[] 字节数组
*/
public static byte[] hexStringToByteArray(String hexString) {
hexString = hexString.replaceAll(" ", "");
int len = hexString.length();
byte[] bytes = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
// 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个字节
bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
.digit(hexString.charAt(i + 1), 16));
}
return bytes;
}
}
package com.mushiny.metage.util;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import gnu.io.*;
/**
* @version 1.0
* @author: Gy
* @date: 2023-02-31 13:54
*/
public class RxtxUtils extends Thread implements SerialPortEventListener {
// 监听器,我的理解是独立开辟一个线程监听串口数据
static CommPortIdentifier portId; // 串口通信管理类
static Enumeration<?> portList; // 有效连接上的端口的枚举
InputStream inputStream; // 从串口来的输入流
public static OutputStream outputStream;// 向串口输出的流
SerialPort serialPort; // 串口的引用
// 堵塞队列用来存放读到的数据
private BlockingQueue<String> msgQueue = new LinkedBlockingQueue<String>();
//当前接收到的重量信息
public static Double weightings;
/**
* SerialPort EventListene 的方法,持续监听端口上是否有数据流
*/
@Override
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:// 当有可用数据时读取数据
byte[] readBuffer = new byte[1024];
try {
int numBytes = -1;
while (inputStream.available() > 0) {
numBytes = inputStream.read(readBuffer);
if (numBytes > 0) {
msgQueue.add(new String(readBuffer,"gbk"));
readBuffer = new byte[1024];// 重新构造缓冲对象,否则有可能会影响接下来接收的数据
} else {
msgQueue.add("额------没有读到数据");
}
}
} catch (IOException e) {
}
break;
}
} // SerialPortEventListener {
/**
*
* 通过程序打开COM4串口,设置监听器以及相关的参数
*
* @return 返回1 表示端口打开成功,返回 0表示端口打开失败
*/
public int startComPort(String portName) {
// 通过串口通信管理类获得当前连接上的串口列表
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
// 获取相应串口对象
portId = (CommPortIdentifier) portList.nextElement();
System.out.println("设备类型:--->" + portId.getPortType());
System.out.println("设备名称:---->" + portId.getName());
// 判断端口类型是否为串口
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
// 判断如果COM7串口存在,就打开该串口
if (portId.getName().equals(portName)) {
try {
// 打开串口名字为COM_7(名字任意),延迟为2毫秒
serialPort = (SerialPort) portId.open(portName, 2000);
} catch (PortInUseException e) {
e.printStackTrace();
return 0;
}
// 设置当前串口的输入输出流
try {
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
return 0;
}
// 给当前串口添加一个监听器
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
e.printStackTrace();
return 0;
}
// 设置监听器生效,即:当有数据时通知
serialPort.notifyOnDataAvailable(true);
// 设置串口的一些读写参数
try {
// 比特率、数据位、停止位、奇偶校验位
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
e.printStackTrace();
return 0;
}
return 1;
}
}
}
return 0;
}
//处理返回后的消息
@Override
public void run() {
try {
while (true) {
// 如果堵塞队列中存在数据就将其输出
if (msgQueue.size() > 0) {
weightings = Double.parseDouble(msgQueue.take());
System.out.println(weightings);
sendDate(weightings);
}
}
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
private void sendDate(Double weightings) throws IOException{
//客户端发送数据,首先用无参构造方法获得DatagramSocket对象。
DatagramSocket send = new DatagramSocket();
//首先需要明确发送的数据类型和格式,比如字节数组
byte[] sendData = weightings.toString().getBytes();
//我们创建DatagramPacket打包对象对其进行打包
//四个参数分别为:数据,数据长度,主机地址,端口
DatagramPacket dataPacket = new DatagramPacket(
sendData,sendData.length, InetAddress.getByName("192.168.1.15"),10086);
//调用DatagramSocket对象的send()方法进行数据发送
send.send(dataPacket);
//关闭资源
send.close();
}
}
package com.mushiny.metage.util;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
/**
* @version 1.0
* @author: Gy
* @date: 2023-02-31 13:53
*/
@Component
public class ServerStart implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
RxtxUtils cRead = new RxtxUtils();
int i = cRead.startComPort("COM2");
if (i == 1) {
cRead.start();
System.out.println("打开端口");
} else {
System.out.println("端口打开失败!");
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment