102 lines
3.7 KiB
C#
102 lines
3.7 KiB
C#
using System;
|
||
using System.Net.Sockets;
|
||
using System.Text;
|
||
using System.Windows;
|
||
|
||
namespace OneClick
|
||
{
|
||
class LightSourceService
|
||
{
|
||
private static TcpClient? OpenSocket()
|
||
{
|
||
try
|
||
{
|
||
TcpClient tcpclient = new TcpClient();
|
||
tcpclient.Connect("192.168.0.7", 1234);
|
||
return tcpclient;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
MessageBox.Show("光源连接失败: " + ex.Message, "连接错误", MessageBoxButton.OK, MessageBoxImage.Error);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
public int TestSourceService()
|
||
{
|
||
// 使用通用发送方法测试固定命令
|
||
var response = SendCommand("SA0000#");
|
||
if (!string.IsNullOrEmpty(response) && response.StartsWith("A", StringComparison.Ordinal))
|
||
{
|
||
//MessageBox.Show("光源通信成功!收到响应: " + response, "提示", MessageBoxButton.OK, MessageBoxImage.Information);
|
||
return 0;
|
||
}
|
||
else if (response != null)
|
||
{
|
||
MessageBox.Show("光源响应异常,收到: " + response, "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||
return 1;
|
||
}
|
||
return 1;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 发送指定的原始指令到光源控制器,并尝试读取响应。
|
||
/// 调用者根据返回值判断是否通信成功;方法内部会在连接失败时弹窗提示错误。
|
||
/// </summary>
|
||
/// <param name="command">要发送的命令(请包含必要的结束符,例如 #)</param>
|
||
/// <param name="timeoutMs">发送/接收超时(毫秒)</param>
|
||
/// <returns>收到的响应字符串(可能为空),连接失败或异常时返回 null</returns>
|
||
public string? SendCommand(string command, int timeoutMs = 2000)
|
||
{
|
||
if (string.IsNullOrEmpty(command))
|
||
throw new ArgumentException("command 不能为空", nameof(command));
|
||
|
||
var tcpclient = OpenSocket();
|
||
if (tcpclient == null)
|
||
return null;
|
||
|
||
NetworkStream? networkstream = null;
|
||
try
|
||
{
|
||
tcpclient.ReceiveTimeout = timeoutMs;
|
||
tcpclient.SendTimeout = timeoutMs;
|
||
|
||
networkstream = tcpclient.GetStream();
|
||
|
||
byte[] sendbytes = Encoding.ASCII.GetBytes(command);
|
||
networkstream.Write(sendbytes, 0, sendbytes.Length);
|
||
networkstream.Flush();
|
||
|
||
// 读取响应(阻塞,受 ReceiveTimeout 控制)
|
||
byte[] buffer = new byte[1024];
|
||
int bytesRead = networkstream.Read(buffer, 0, buffer.Length); // 受 tcpclient.ReceiveTimeout 控制
|
||
|
||
if (bytesRead > 0)
|
||
{
|
||
string response = Encoding.ASCII.GetString(buffer, 0, bytesRead).Trim();
|
||
return response;
|
||
}
|
||
else
|
||
{
|
||
return string.Empty;
|
||
}
|
||
}
|
||
catch (SocketException se)
|
||
{
|
||
MessageBox.Show("光源通信超时或套接字错误: " + se.Message, "通信错误", MessageBoxButton.OK, MessageBoxImage.Error);
|
||
return null;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
MessageBox.Show("光源通信错误: " + ex.Message, "通信错误", MessageBoxButton.OK, MessageBoxImage.Error);
|
||
return null;
|
||
}
|
||
finally
|
||
{
|
||
try { networkstream?.Close(); } catch { }
|
||
try { tcpclient.Close(); } catch { }
|
||
}
|
||
}
|
||
}
|
||
}
|