以面向对面的思想控制仪器
目的:代码调用简单,复用性强
1、创建仪器类(以信号发生器为例,TCP通讯)
public class WaveGenerator
{
#region 单例模式
private static WaveGenerator intance = null;
public static WaveGenerator Intance
{
get
{
if (intance == null)
intance = new WaveGenerator();
return intance;
}
}
private WaveGenerator() { }
#endregion
TcpClientHelper objWaveGenerator = new TcpClientHelper("192.168.0.50", 5025);
public string Freq
{
get { return GetProperty("FREQ?"); }
set { SetProperty($"FREQ {value}"); }
}
public string Volt
{
get { return GetProperty("VOLTage?"); }
set { SetProperty($"VOLTage {value}"); }
}
private string GetProperty(string order)
{
string rstStr = objWaveGenerator.Query(order);
if (!rstStr.Contains("失败"))
return Convert.ToDouble(rstStr).ToString();
else
return "XXX";
}
private void SetProperty(string order)
{
objWaveGenerator.Write(order);
}
}
2、调用仪器
WaveGenerator.Intance.Volt = "5";
avr srt = WaveGenerator.Intance.Volt;
3、TCP客户端
public class TcpClientHelper
{
private Socket socket = null;
private string ip;
private int port;
public TcpClientHelper(string ip, int port)
{
this.ip = ip;
this.port = port;
}
private bool Connect()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
EndPoint point = new IPEndPoint(IPAddress.Parse(ip), port);
IAsyncResult connResult = socket.BeginConnect(point, null, null);
connResult.AsyncWaitHandle.WaitOne(500, true);
return connResult.IsCompleted && socket.Connected;
}
public bool Write(string order)
{
if (socket == null || !socket.Connected)
{
if (!Connect())
return false;
}
byte[] data = Encoding.ASCII.GetBytes(order + Environment.NewLine);
if (socket.Send(data) != data.Length)
{
return false;
}
return true;
}
public string Query(string order)
{
if (socket == null || !socket.Connected)
{
if (!Connect())
return "网络链接失败";
}
byte[] data = Encoding.ASCII.GetBytes(order + Environment.NewLine);
try
{
int a= socket.Send(data);
}
catch (Exception e)
{
return $"数据发送失败:{e.Message}";
}
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);
int length;
byte[] recData = new byte[1024 * 1024];
try
{
length = socket.Receive(recData);
}
catch (Exception e)
{
return $"接收失败:{e.Message}";
}
if (length == 0)
return "失败:数据接收为空";
return Encoding.ASCII.GetString(recData, 0, length).Trim();
}
}