灯光调整
This commit is contained in:
@@ -23,6 +23,12 @@ public class LightService {
|
||||
*/
|
||||
public boolean connect() {
|
||||
try {
|
||||
// 先关闭旧的连接(如果存在)
|
||||
if (serialHandler != null) {
|
||||
log.info("关闭旧的串口连接");
|
||||
serialHandler.close();
|
||||
serialHandler = null;
|
||||
}
|
||||
// 使用COM1串口
|
||||
String portName = "COM1";
|
||||
// 默认波特率9600
|
||||
@@ -62,6 +68,30 @@ public class LightService {
|
||||
return serialHandler != null && serialHandler.isOpen();
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查连接状态并尝试重连
|
||||
* @return 重连成功返回true,否则返回false
|
||||
*/
|
||||
public boolean checkAndReconnect() {
|
||||
if (isConnected()) {
|
||||
return true;
|
||||
}
|
||||
log.warn("串口连接异常,尝试重新连接");
|
||||
return connect();
|
||||
}
|
||||
|
||||
/**
|
||||
* 重新连接控制器
|
||||
* @return 重连成功返回true,否则返回false
|
||||
*/
|
||||
public boolean reconnect() {
|
||||
if (serialHandler != null) {
|
||||
serialHandler.close();
|
||||
serialHandler = null;
|
||||
}
|
||||
return connect();
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开指定通道
|
||||
* @param channel 通道号 (1-2)
|
||||
@@ -109,7 +139,7 @@ public class LightService {
|
||||
* 发送命令到控制器
|
||||
*/
|
||||
private boolean sendCommand(CommandTypeEnum type, int channel, int brightness) {
|
||||
if (serialHandler == null || !serialHandler.isOpen()) {
|
||||
if (!checkAndReconnect()) {
|
||||
log.error("控制器未连接");
|
||||
return false;
|
||||
}
|
||||
@@ -138,15 +168,12 @@ public class LightService {
|
||||
* 发送读取命令并获取返回值
|
||||
*/
|
||||
private int sendReadCommand(int channel) {
|
||||
if (serialHandler == null || !serialHandler.isOpen()) {
|
||||
if (!checkAndReconnect()) {
|
||||
log.error("控制器未连接");
|
||||
return -1;
|
||||
}
|
||||
|
||||
byte[] command = buildCommand(CommandTypeEnum.READ, channel, 0);
|
||||
if (command == null) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 发送命令
|
||||
serialHandler.sendData(command);
|
||||
|
||||
@@ -264,9 +264,11 @@ public class SerialPortHandler {
|
||||
try {
|
||||
if (inputStream != null) {
|
||||
inputStream.close();
|
||||
inputStream = null;
|
||||
}
|
||||
if (outputStream != null) {
|
||||
outputStream.close();
|
||||
outputStream = null;
|
||||
}
|
||||
if (serialPort != null && serialPort.isOpen()) {
|
||||
serialPort.closePort();
|
||||
@@ -274,6 +276,8 @@ public class SerialPortHandler {
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("关闭串口失败: {}", e.getMessage());
|
||||
}finally {
|
||||
serialPort = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user