using System;
using HPSocket;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using csharp_networkprotocol_hpsocket;
namespace MainForm
{
///
/// Form_Home类 - 操作TCP操作
/// 简单拆分Form_Home类
///
public partial class Form_Home
{
///
/// 包数据结束符
///
private readonly string _endsWith = "\r";
///
/// 初始化TCP连接
///
private void HpTCPClientInit()
{
// 扫码枪_载具下线装备(弹夹上线)- 弹夹扫码
// 扫码枪_载具下线装备(弹夹上线)- 载具扫码
// 扫码枪_桁架 - 查询弹夹的状态
// 扫码枪_载具上线装备(弹夹下线)- 弹夹扫码
// 扫码枪_载具上线装备(弹夹下线)- 载具扫码
#region 连接 扫码枪_载具下线装备(弹夹上线)- 弹夹扫码
try
{
//初始化TCP
_HPSocket_TcpClients[1].Address = GlobalContext.QrCodeTCPAddress1; // IP
_HPSocket_TcpClients[1].Port = (ushort)GlobalContext.QrCodeTCPPort1; // 端口
_HPSocket_TcpClients[1].SocketBufferSize = 4096; // 缓存4K
_HPSocket_TcpClients[1]._client.OnPrepareConnect += OnPrepareConnect; // 准备连接了事件
_HPSocket_TcpClients[1]._client.OnConnect += OnConnect; // 连接事件
_HPSocket_TcpClients[1]._client.OnSend += OnSend; // 数据包发送事件
_HPSocket_TcpClients[1]._client.OnReceive += OnReceive; // 数据包到达事件
_HPSocket_TcpClients[1]._client.OnClose += OnClose; // TCP连接关闭事件
//打开TCP
bool connResult = _HPSocket_TcpClients[1].Connect(); // 连接
if (connResult)
AddMessage(LogType.Info, $"TCPClient[To载具下线装备_弹夹扫码:{_HPSocket_TcpClients[1].Address}:{_HPSocket_TcpClients[1].Port}]连接完成");
else
AddMessage(LogType.Error, $"TCPClient[To载具下线装备_弹夹扫码:{_HPSocket_TcpClients[1].Address}:{_HPSocket_TcpClients[1].Port}]连接失败");
}
catch (Exception ex)
{
string str = ex.StackTrace;
AddMessage(LogType.Error, $"TCPClient[To载具下线装备_弹夹扫码:{_HPSocket_TcpClients[1].Address}:{_HPSocket_TcpClients[1].Port}]失败!异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message.ToString());
}
#endregion 连接 扫码枪_载具下线装备(弹夹上线)- 弹夹扫码
#region 连接 扫码枪_载具下线装备(弹夹上线)- 载具扫码
try
{
//初始化TCP
_HPSocket_TcpClients[2].Address = GlobalContext.QrCodeTCPAddress2; // IP
_HPSocket_TcpClients[2].Port = (ushort)GlobalContext.QrCodeTCPPort2; // 端口
_HPSocket_TcpClients[2].SocketBufferSize = 4096; // 缓存4K
_HPSocket_TcpClients[2]._client.OnPrepareConnect += OnPrepareConnect; // 准备连接了事件
_HPSocket_TcpClients[2]._client.OnConnect += OnConnect; // 连接事件
_HPSocket_TcpClients[2]._client.OnSend += OnSend; // 数据包发送事件
_HPSocket_TcpClients[2]._client.OnReceive += OnReceive; // 数据包到达事件
_HPSocket_TcpClients[2]._client.OnClose += OnClose; // TCP连接关闭事件
//打开TCP
bool connResult = _HPSocket_TcpClients[2].Connect(); // 连接
if (connResult)
AddMessage(LogType.Info, $"TCPClient[To载具下线装备_载具扫码:{_HPSocket_TcpClients[2].Address}:{_HPSocket_TcpClients[2].Port}]连接完成");
else
AddMessage(LogType.Error, $"TCPClient[To载具下线装备_载具扫码:{_HPSocket_TcpClients[2].Address}:{_HPSocket_TcpClients[2].Port}]连接失败");
}
catch (Exception ex)
{
string str = ex.StackTrace;
AddMessage(LogType.Error, $"TCPClient[To载具下线装备_载具扫码:{_HPSocket_TcpClients[2].Address}:{_HPSocket_TcpClients[2].Port}]失败!异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message.ToString());
}
#endregion 连接 扫码枪_载具下线装备(弹夹上线)- 载具扫码
#region 连接 扫码枪_桁架 - 查询弹夹的状态
try
{
//初始化TCP
_HPSocket_TcpClients[3].Address = GlobalContext.QrCodeTCPAddress3; // IP
_HPSocket_TcpClients[3].Port = (ushort)GlobalContext.QrCodeTCPPort3; // 端口
_HPSocket_TcpClients[3].SocketBufferSize = 4096; // 缓存4K
_HPSocket_TcpClients[3]._client.OnPrepareConnect += OnPrepareConnect; // 准备连接了事件
_HPSocket_TcpClients[3]._client.OnConnect += OnConnect; // 连接事件
_HPSocket_TcpClients[3]._client.OnSend += OnSend; // 数据包发送事件
_HPSocket_TcpClients[3]._client.OnReceive += OnReceive; // 数据包到达事件
_HPSocket_TcpClients[3]._client.OnClose += OnClose; // TCP连接关闭事件
//打开TCP
bool connResult = _HPSocket_TcpClients[3].Connect(); // 连接
if (connResult)
AddMessage(LogType.Info, $"TCPClient[To桁架_查询弹夹的状态:{_HPSocket_TcpClients[3].Address}:{_HPSocket_TcpClients[3].Port}]连接完成");
else
AddMessage(LogType.Error, $"TCPClient[To桁架_查询弹夹的状态:{_HPSocket_TcpClients[3].Address}:{_HPSocket_TcpClients[3].Port}]连接失败");
}
catch (Exception ex)
{
string str = ex.StackTrace;
AddMessage(LogType.Error, $"TCPClient[To桁架_查询弹夹的状态:{_HPSocket_TcpClients[3].Address}:{_HPSocket_TcpClients[3].Port}]失败!异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message.ToString());
}
#endregion 连接 扫码枪_桁架 - 查询弹夹的状态
#region 连接 扫码枪_载具上线装备(弹夹下线)- 弹夹扫码
try
{
//初始化TCP
_HPSocket_TcpClients[4].Address = GlobalContext.QrCodeTCPAddress4; // IP
_HPSocket_TcpClients[4].Port = (ushort)GlobalContext.QrCodeTCPPort4; // 端口
_HPSocket_TcpClients[4].SocketBufferSize = 4096; // 缓存4K
_HPSocket_TcpClients[4]._client.OnPrepareConnect += OnPrepareConnect; // 准备连接了事件
_HPSocket_TcpClients[4]._client.OnConnect += OnConnect; // 连接事件
_HPSocket_TcpClients[4]._client.OnSend += OnSend; // 数据包发送事件
_HPSocket_TcpClients[4]._client.OnReceive += OnReceive; // 数据包到达事件
_HPSocket_TcpClients[4]._client.OnClose += OnClose; // TCP连接关闭事件
//打开TCP
bool connResult = _HPSocket_TcpClients[4].Connect(); // 连接
if (connResult)
AddMessage(LogType.Info, $"TCPClient[To载具上线装备_弹夹扫码:{_HPSocket_TcpClients[4].Address}:{_HPSocket_TcpClients[4].Port}]连接完成");
else
AddMessage(LogType.Error, $"TCPClient[To载具上线装备_弹夹扫码:{_HPSocket_TcpClients[4].Address}:{_HPSocket_TcpClients[4].Port}]连接失败");
}
catch (Exception ex)
{
string str = ex.StackTrace;
AddMessage(LogType.Error, $"TCPClient[To载具上线装备_弹夹扫码:{_HPSocket_TcpClients[4].Address}:{_HPSocket_TcpClients[4].Port}]失败!异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message.ToString());
}
#endregion 连接 扫码枪_载具上线装备(弹夹下线)- 弹夹扫码
#region 连接 扫码枪_载具上线装备(弹夹下线)- 载具扫码
try
{
//初始化TCP
_HPSocket_TcpClients[5].Address = GlobalContext.QrCodeTCPAddress5; // IP
_HPSocket_TcpClients[5].Port = (ushort)GlobalContext.QrCodeTCPPort5; // 端口
_HPSocket_TcpClients[5].SocketBufferSize = 4096; // 缓存4K
_HPSocket_TcpClients[5]._client.OnPrepareConnect += OnPrepareConnect; // 准备连接了事件
_HPSocket_TcpClients[5]._client.OnConnect += OnConnect; // 连接事件
_HPSocket_TcpClients[5]._client.OnSend += OnSend; // 数据包发送事件
_HPSocket_TcpClients[5]._client.OnReceive += OnReceive; // 数据包到达事件
_HPSocket_TcpClients[5]._client.OnClose += OnClose; // TCP连接关闭事件
//打开TCP
bool connResult = _HPSocket_TcpClients[5].Connect(); // 连接
if (connResult)
AddMessage(LogType.Info, $"TCPClient[To载具上线装备_载具扫码:{_HPSocket_TcpClients[5].Address}:{_HPSocket_TcpClients[5].Port}]连接完成");
else
AddMessage(LogType.Error, $"TCPClient[To载具上线装备_载具扫码:{_HPSocket_TcpClients[5].Address}:{_HPSocket_TcpClients[5].Port}]连接失败");
}
catch (Exception ex)
{
string str = ex.StackTrace;
AddMessage(LogType.Error, $"TCPClient[To载具上线装备_载具扫码:{_HPSocket_TcpClients[5].Address}:{_HPSocket_TcpClients[5].Port}]失败!异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message.ToString());
}
#endregion 连接 扫码枪_载具上线装备(弹夹下线)- 载具扫码
}
#region 扫码数据解析
///
/// 发送TCP数据-TCP1
///
///
public bool TCP_Send(HPSocket_TcpClientHelper hPSocket_TcpClientHelper, string sendMsg)
{
if (!hPSocket_TcpClientHelper._client.IsConnected || hPSocket_TcpClientHelper._client.State != ServiceState.Started)
{
hPSocket_TcpClientHelper.Connect();
AddMessage(LogType.Info, "正在尝试连接仪器TCPServer...");
Thread.Sleep(100);
}
if (string.IsNullOrEmpty(sendMsg))
{
AddMessage(LogType.Error, "TCP发送失败,发送信息不可为空!");
return false;
}
byte[] bytes = Encoding.UTF8.GetBytes(sendMsg);
#region
//bytes = Encoding.UTF8.GetBytes("BR,0");
//string[] strings2 = new string[bytes.Length];
//for (int i = 0; i < bytes.Length; i++)
//{
// strings2[i] = bytes[i].ToString("X2");
//}
#endregion
int length = bytes.Length;
return hPSocket_TcpClientHelper.Send(bytes, length); // 发送
}
///
/// 发送TCP数据
///
///
public bool TCP_Send(HPSocket_TcpClientHelper hPSocket_TcpClientHelper, byte[] bytes)
{
if (!hPSocket_TcpClientHelper._client.IsConnected || hPSocket_TcpClientHelper._client.State != ServiceState.Started)
{
hPSocket_TcpClientHelper.Connect();
AddMessage(LogType.Info, "正在尝试连接仪器TCPServer...");
Thread.Sleep(100);
}
if (bytes == null || bytes.Length < 1)
{
AddMessage(LogType.Error, "TCP发送失败,发送信息不可为空!");
return false;
}
return hPSocket_TcpClientHelper.Send(bytes, bytes.Length); // 发送
}
///
/// 接收串口数据
///
/// 接收到的数据
/// IP
/// 端口
private void ReceivedMsg(string receiveString, string address, ushort port)
{
try
{
//if (address == GlobalContext.MachineTCPAddress1) // 校验说明书1
//{
// int index = 1;
// string itemName = "校验说明书1";
// ReceivedMsg_Do(index, itemName, receiveString);
//}
//else if (address == GlobalContext.MachineTCPAddress2) // 校验说明书2
//{
// int index = 2;
// string itemName = "校验说明书2";
// ReceivedMsg_Do(index, itemName, receiveString);
//}
//else if (address == GlobalContext.MachineTCPAddress3) // 校验说明书3
//{
// int index = 3;
// string itemName = "校验说明书3";
// ReceivedMsg_Do(index, itemName, receiveString);
//}
//else if (address == GlobalContext.MachineTCPAddress4) // 校验纸袋料号
//{
// int index = 4;
// string itemName = "校验纸袋料号";
// ReceivedMsg_Do(index, itemName, receiveString);
//}
//else if (address == GlobalContext.MachineTCPAddress5) // 校验鼠标反正、颜色(上相机)
//{
// int index = 5;
// string itemName = "上IV4相机校验";
// ReceivedMsg_Do(index, itemName, receiveString);
//}
//else if (address == GlobalContext.MachineTCPAddress6) // 校验鼠标背盖颜色(下相机)
//{
// int index = 6;
// string itemName = "下IV4相机校验";
// ReceivedMsg_Do(index, itemName, receiveString);
//}
//else
//{
// AddMessage(LogType.Error, $"#获取仪器数据异常!未知IP{address}:{port}");
//}
}
catch (Exception ex)
{
string str = ex.StackTrace;
//用于运行日志记录
AddMessage(LogType.Warning, "#获取仪器数据异常!异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message.ToString());
}
}
///
/// 按照工位解析指令
///
/// 序列
/// 工位名
/// 接收到的数据
private void ReceivedMsg_Do(int index, string itemName, string receiveString)
{
try
{
//// 切换程序编号指令 = "PW,{0}\r"; // PW,程序号\r切换(如:PW,000);返回 PW
//if (receiveString.Contains("PW"))
//{
// switch (index)
// {
// case 1:
// Parsing_PW_ModProgramNum(index, itemName, receiveString, MreReceive_ModProgramNum1[0]);
// break;
// case 2:
// Parsing_PW_ModProgramNum(index, itemName, receiveString, MreReceive_ModProgramNum2[0]);
// break;
// case 3:
// Parsing_PW_ModProgramNum(index, itemName, receiveString, MreReceive_ModProgramNum3[0]);
// break;
// case 4:
// Parsing_PW_ModProgramNum(index, itemName, receiveString, MreReceive_ModProgramNum4[0]);
// break;
// case 5:
// Parsing_PW_ModProgramNum(index, itemName, receiveString, MreReceive_ModProgramNum5[0]);
// break;
// case 6:
// Parsing_PW_ModProgramNum(index, itemName, receiveString, MreReceive_ModProgramNum6[0]);
// break;
// }
//}
//// 更改主控字符指令 = "CW,{0},{1}\r"; // CW,序列号,校验字符串\r更改(如:CW,01,变量字符串);返回 CW,nn\r
//else if (receiveString.Contains("CW"))
//{
// switch (index)
// {
// case 1:
// Parsing_CW_ModMainCharacter(index, itemName, receiveString, MreReceive_ModMainCharacter1[0]);
// break;
// case 2:
// Parsing_CW_ModMainCharacter(index, itemName, receiveString, MreReceive_ModMainCharacter2[0]);
// break;
// case 3:
// Parsing_CW_ModMainCharacter(index, itemName, receiveString, MreReceive_ModMainCharacter3[0]);
// break;
// case 4:
// Parsing_CW_ModMainCharacter(index, itemName, receiveString, MreReceive_ModMainCharacter4[0]);
// break;
// }
//}
//// 触发加读取判断结果指令 = "T2\r"; // T2\r启动;返回 RT,aaaaa\r;aa为工具结果,可以为OK或NG 或者 00 ~ 07
//else if (receiveString.Contains("RT,"))
//{
// switch (index)
// {
// case 1:
// Parsing_T2_Do(index, itemName, receiveString, MreReceive_Do1[0]);
// break;
// case 2:
// Parsing_T2_Do(index, itemName, receiveString, MreReceive_Do2[0]);
// break;
// case 3:
// Parsing_T2_Do(index, itemName, receiveString, MreReceive_Do3[0]);
// break;
// case 4:
// Parsing_T2_Do(index, itemName, receiveString, MreReceive_Do4[0]);
// break;
// case 5:
// Parsing_T2_Do(index, itemName, receiveString, MreReceive_Do5[0]);
// break;
// case 6:
// Parsing_T2_Do(index, itemName, receiveString, MreReceive_Do6[0]);
// break;
// }
//}
//else
//{
// // 未知指令结果
// AddMessage(LogType.Warning, $"获取'{itemName}'仪器数据异常!未知报文:{receiveString}");
//}
}
catch (Exception ex)
{
string str = ex.StackTrace;
//用于运行日志记录
AddMessage(LogType.Warning, $"获取'{itemName}'仪器数据异常!异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message.ToString());
}
}
#region TCP事件
///
/// 数据包到达事件
///
/// 客户端
/// 数据
///
private HandleResult OnReceive(IClient sender, byte[] data)
{
// <1> 获取附加数据对象
if (!(sender.ExtraData is string))
{
return HandleResult.Error;
}
string extraDataStr = (string)sender.ExtraData;
// <2> 将接收数据转换成字符串
string msg = Encoding.UTF8.GetString(data);
extraDataStr += msg; // 添加数据到缓存_不合格的数据添加到缓存区(用于粘包、拆包)
// <3> 显示信息
OnMessage(LogType.Info, string.Format("TCP客户端接收到TCP服务器[ID:{0},IP:‘{1}:{2}’]的信息;数据:[长度{3}]: {4}", sender.ConnectionId, sender.Address, sender.Port, data.Length, msg));
// <4> 处理数据
HandleResult result = HandleResult.Ignore;
int index = extraDataStr.IndexOf(_endsWith);
if (index == -1 || extraDataStr.Equals(_endsWith)) // 数据接收不完整,忽略后等待下一次接收
{
sender.ExtraData += extraDataStr;
result = HandleResult.Ignore;
return result;
}
else
{
sender.ExtraData = string.Empty;
string dataStr = extraDataStr.Remove(index, _endsWith.Length);
ReceivedMsg(dataStr, sender.Address, sender.Port);
}
return result;
}
///
/// 准备连接了事件
///
/// 客户端
/// 客户端Id
///
private HandleResult OnPrepareConnect(IClient sender, IntPtr socket)
{
sender.ExtraData = string.Empty; // 设置附加数据(用来做粘包处理)
return HandleResult.Ok;
}
///
/// 连接事件
///
/// 客户端
///
private HandleResult OnConnect(IClient sender)
{
OnMessage(LogType.Info, string.Format("TCP客户端([{0}]{1}:{2})接入TCP服务器{3}:{4}", sender.ConnectionId, sender.BindAddress, sender.BindPort, sender.Address, sender.Port));
return HandleResult.Ok;
}
///
/// 数据包发送事件
///
/// 客户端
/// 数据
///
private HandleResult OnSend(IClient sender, byte[] data)
{
OnMessage(LogType.Debug, string.Format("TCP客户端发送数据到TCP服务器[{0}]{1}:{2};数据内容[长度{3}]:{4}", sender.ConnectionId, sender.Address, sender.Port, data.Length, Encoding.UTF8.GetString(data)));
return HandleResult.Ok;
}
///
/// TCP连接关闭事件
///
/// 客户端
/// 关闭类型
/// 错误代码
///
private HandleResult OnClose(IClient sender, SocketOperation socketOperation, int errorCode)
{
sender.ExtraData = null; // 删除附加数据
OnMessage(LogType.Info, string.Format("TCP客户端断开与TCP服务器[{0}] {1}:{2}的连接, 断开类型: {3},错误代码: {4}", sender.ConnectionId, sender.Address, sender.Port, socketOperation.ToString(), errorCode));
return HandleResult.Ok;
}
#endregion TCP事件
#endregion 扫码数据解析
}
}