1.初始化项目。保险起见bin目录完整提交 2.基于现场代码为调整过的初始项目(此次提交还未解决代码差异问题)

This commit is contained in:
龚记林
2026-08-19 11:14:30 +08:00
parent b820c71956
commit 2b30644d28
382 changed files with 140652 additions and 1 deletions
@@ -0,0 +1,534 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.Drawing;
using System.Globalization;
namespace AGVSystem
{
class AGVClientCls
{
public string IPAdress;
public bool connected = false;
public Socket clientSocket;
private IPEndPoint hostEndPoint;
private Byte[] SendDataPro;
private Byte[] RecvDataPro;
private Byte[] SendData;
private Byte[] RecvData;
private Byte SendOrRecv;
private AutoResetEvent autoConnectEvent = new AutoResetEvent(false);
private SocketAsyncEventArgs lisnterSocketAsyncEventArgs;
public delegate void StartListeHandler();
public event StartListeHandler StartListen;
public delegate void ReceiveMsgHandler(byte[] info);
public event ReceiveMsgHandler OnMsgReceived;
private List<SocketAsyncEventArgs> s_lst = new List<SocketAsyncEventArgs>();
public AGVClientCls(string hostName, int port)
{
IPAdress = hostName;
IPAddress[] hostAddresses = Dns.GetHostAddresses(hostName);
this.hostEndPoint = new IPEndPoint(hostAddresses[hostAddresses.Length - 1], port);
this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
}
/// <summary>
/// 连接服务端
/// </summary>
/// <returns></returns>
private bool Connect()
{
using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
{
args.UserToken = this.clientSocket;
args.RemoteEndPoint = this.hostEndPoint;
args.Completed += new EventHandler<SocketAsyncEventArgs>(this.OnConnect);
this.clientSocket.ConnectAsync(args);
bool flag = autoConnectEvent.WaitOne(1000);
//SocketError err = args.SocketError;
if (this.connected)
{
this.lisnterSocketAsyncEventArgs = new SocketAsyncEventArgs();
byte[] buffer = new byte[50];
this.lisnterSocketAsyncEventArgs.UserToken = this.clientSocket;
this.lisnterSocketAsyncEventArgs.SetBuffer(buffer, 0, buffer.Length);
this.lisnterSocketAsyncEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(this.OnReceive);
this.StartListen();
return true;
}
return false;
}
}
/// <summary>
/// 判断有没有连接上
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnConnect(object sender, SocketAsyncEventArgs e)
{
this.connected = (e.SocketError == SocketError.Success);
autoConnectEvent.Set();
}
/// <summary>
/// 发送
/// </summary>
/// <param name="mes"></param>
public void Send(Byte[] mes)
{
if (this.connected)
{
EventHandler<SocketAsyncEventArgs> handler = null;
byte[] buffer = mes;
SocketAsyncEventArgs senderSocketAsyncEventArgs = null;
lock (s_lst)
{
if (s_lst.Count > 0)
{
senderSocketAsyncEventArgs = s_lst[s_lst.Count - 1];
s_lst.RemoveAt(s_lst.Count - 1);
}
}
if (senderSocketAsyncEventArgs == null)
{
senderSocketAsyncEventArgs = new SocketAsyncEventArgs();
senderSocketAsyncEventArgs.UserToken = this.clientSocket;
senderSocketAsyncEventArgs.RemoteEndPoint = this.clientSocket.RemoteEndPoint;
if (handler == null)
{
handler = delegate(object sender, SocketAsyncEventArgs _e)
{
lock (s_lst)
{
s_lst.Add(senderSocketAsyncEventArgs);
}
};
}
senderSocketAsyncEventArgs.Completed += handler;
}
senderSocketAsyncEventArgs.SetBuffer(buffer, 0, buffer.Length);
this.clientSocket.SendAsync(senderSocketAsyncEventArgs);
}
else
{
this.connected = false;
}
}
/// <summary>
/// 监听服务端
/// </summary>
public void Listen()
{
if (this.connected && this.clientSocket != null)
{
try
{
(lisnterSocketAsyncEventArgs.UserToken as Socket).ReceiveAsync(lisnterSocketAsyncEventArgs);
}
catch (Exception)
{
}
}
}
/// <summary>
/// 断开连接
/// </summary>
/// <returns></returns>
private int Disconnect()
{
int res = 0;
try
{
this.clientSocket.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
}
try
{
this.clientSocket.Close();
}
catch (Exception)
{
}
this.connected = false;
return res;
}
/// <summary>
/// 数据接受
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnReceive(object sender, SocketAsyncEventArgs e)
{
if (e.BytesTransferred == 0)
{
try
{
this.clientSocket.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
}
finally
{
if (this.clientSocket.Connected)
{
this.clientSocket.Close();
}
}
byte[] info = new Byte[] { 0 };
this.OnMsgReceived(info);
}
else
{
byte[] buffer = new byte[e.BytesTransferred];
for (int i = 0; i < e.BytesTransferred; i++)
{
buffer[i] = e.Buffer[i];
}
this.OnMsgReceived(buffer);
Listen();
}
}
/// <summary>
/// 接受完成
/// </summary>
/// <param name="info"></param>
private void SimaticSocketClient_OnMsgReceived(byte[] info)
{
if (info[0] != 0)
{
if (this.SendOrRecv == 1)
{
this.SendDataPro = info;
this.SendOrRecv = 0;
}
else if (this.SendOrRecv == 2)
{
this.SendData = info;
this.SendOrRecv = 0;
}
else if (this.SendOrRecv == 3)
{
this.RecvDataPro = info;
this.SendOrRecv = 0;
}
else if (this.SendOrRecv == 4)
{
this.RecvData = info;
this.SendOrRecv = 0;
}
}
else
{
if (this.SendOrRecv == 1)
{
this.SendDataPro = new Byte[] { 0 };
this.SendOrRecv = 0;
}
else if (this.SendOrRecv == 2)
{
this.SendData = new Byte[] { 0 };
this.SendOrRecv = 0;
}
else if (this.SendOrRecv == 3)
{
this.RecvDataPro = new Byte[] { 0 };
this.SendOrRecv = 0;
}
else if (this.SendOrRecv == 4)
{
this.RecvData = new Byte[] { 0 };
this.SendOrRecv = 0;
}
}
}
/// <summary>
/// 建立连接的方法
/// </summary>
/// <returns></returns>
public bool OpenLinkPLC()
{
bool flag = false;
this.StartListen += new StartListeHandler(SimaticSocketClient_StartListen);
this.OnMsgReceived += new ReceiveMsgHandler(SimaticSocketClient_OnMsgReceived);
flag = this.Connect();
if (!flag)
{
return flag;
}
return true;
}
/// <summary>
/// 关闭连接的方法
/// </summary>
/// <returns></returns>
public int CloseLinkPLC()
{
return this.Disconnect();
}
/// <summary>
/// 监听的方法
/// </summary>
private void SimaticSocketClient_StartListen()
{
this.Listen();
}
#region PLC数据(VW)
/// <summary>
/// 写一个VW数据
/// </summary>
/// <param name="paddr"></param>
/// <param name="waddr"></param>
/// <param name="value"></param>
/// <returns></returns>
public int WriteVM(int stationNO, int address, int value)
{
int flag = -1;
Byte[] sendValue = new Byte[6];
byte[] data = new byte[39];
data[0] = 0x68;
data[1] = 0x21;
data[2] = 0x21;
data[3] = 0x68;
data[4] = (byte)stationNO;
data[5] = 0x00;
data[6] = 0x6C;
data[7] = 0x32;
data[8] = 0x01;
data[9] = 0x00;
data[10] = 0x00;
data[11] = 0x00;
data[12] = 0x00;
data[13] = 0x00;
data[14] = 0x0E;
data[15] = 0x00;
data[16] = 0x06;
data[17] = 0x05;
data[18] = 0x01;
data[19] = 0x12;
data[20] = 0x0A;
data[21] = 0x10;
data[22] = 0x04;
data[23] = 0x00;
data[24] = 0x01;
data[25] = 0x00;
data[26] = 0x01;
data[27] = 0x84;
data[28] = 0x00;
data[29] = Convert.ToByte(address * 8 / 256);
data[30] = Convert.ToByte(address * 8 % 256);
data[31] = 0x00;
data[32] = 0x04;
data[33] = 0x00;
data[34] = 0x10;
data[35] = Convert.ToByte(value / 256);
data[36] = Convert.ToByte(value % 256);
int j = 0;
for (int i = 4; i <= 36; i++)
{
j = j + data[i];
}
data[37] = Convert.ToByte(j % 256);
data[38] = 0x16;
sendValue[0] = 0x10;
sendValue[1] = 0x02;
sendValue[2] = 0x00;
sendValue[3] = 0x5C;
sendValue[4] = 0x5E;
sendValue[5] = 0x16;
Thread.Sleep(100);
this.SendOrRecv = 1;
int numPro = 0;
this.Send(data);
while (this.SendOrRecv != 0 && numPro < 500)
{
Thread.Sleep(1);
numPro++;
}
if (numPro < 500)
{
if (this.SendDataPro[0] == 0xE5)
{
Thread.Sleep(100);
this.SendOrRecv = 2;
int num = 0;
this.Send(sendValue);
while (this.SendOrRecv != 0 && num < 500)
{
Thread.Sleep(1);
num++;
}
if (num < 500)
{
if (this.SendData.Length == 24 && Check(this.SendData))
{
flag = 0;
}
return flag;
}
}
}
this.SendOrRecv = 0;
return flag;
}
#endregion
#region VW值
/// <summary>
/// 读值
/// </summary>
/// <param name="stationNO"></param>
/// <param name="length"></param>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
public int ReadVM(int stationNO, int length, int address, out int value)
{
int flag = -1;
value = 0;
Byte[] sendValue = new Byte[6];
Byte[] data = new Byte[33];
data[0] = 0x68;
data[1] = 0x1B;
data[2] = 0x1B;
data[3] = 0x68;
data[4] = (Byte)stationNO;
data[5] = 0x00;
data[6] = 0x6C;
data[7] = 0x32;
data[8] = 0x01;
data[9] = 0x00;
data[10] = 0x00;
data[11] = 0x00;
data[12] = 0x00;
data[13] = 0x00;
data[14] = 0x0E;
data[15] = 0x00;
data[16] = 0x00;
data[17] = 0x04;
data[18] = 0x01;
data[19] = 0x12;
data[20] = 0x0A;
data[21] = 0x10;
data[22] = 0x04;
data[23] = 0x00;
data[24] = Convert.ToByte(length);
data[25] = 0x00;
data[26] = 0x01;
data[27] = 0x84;
data[28] = 0x00;
data[29] = Convert.ToByte(address * 8 / 256);
data[30] = Convert.ToByte(address * 8 % 256);
int j = 0;
for (int i = 4; i <= 30; i++)
{
j = j + Convert.ToInt32(data[i]);
}
data[31] = Convert.ToByte(j % 256);
data[32] = 0x16;
sendValue[0] = 0x10;
sendValue[1] = 0x02;
sendValue[2] = 0x00;
sendValue[3] = 0x5C;
sendValue[4] = 0x5E;
sendValue[5] = 0x16;
Thread.Sleep(100);
this.SendOrRecv = 3;
int numPro = 0;
this.Send(data);
while (this.SendOrRecv != 0 && numPro < 500)
{
Thread.Sleep(1);
numPro++;
}
if (numPro < 500)
{
if (this.RecvDataPro[0] == 0xE5)
{
Thread.Sleep(100);
this.SendOrRecv = 4;
int num = 0;
this.Send(sendValue);
while (this.SendOrRecv != 0 && num < 600)
{
Thread.Sleep(1);
num++;
}
if (num < 600)
{
if (this.RecvData.Length == 1)
{
// FileControl.LogFile.SaveLog(this.clientSocket.RemoteEndPoint.ToString() + this.RecvData.Length.ToString());
}
if (this.RecvData.Length == 29)
{
flag = 0;
if (this.RecvData[25] > 0)
{
value = this.RecvData[26] * 256 + this.RecvData[25];
}
else
{
value = this.RecvData[26];
}
}
else
{
// FileControl.LogFile.SaveLog(this.clientSocket.RemoteEndPoint.ToString() + " recv" + this.RecvData.Length.ToString());
if (this.RecvData[0] == 0)
{
flag = -3;
}
}
return flag;
}
}
else
{
// FileControl.LogFile.SaveLog(this.clientSocket.RemoteEndPoint.ToString() + " recvPro" + this.RecvDataPro.Length.ToString());
if (this.RecvDataPro[0] == 0)
{
flag = -3;
}
}
}
this.SendOrRecv = 0;
return flag;
}
#endregion
private bool Check(Byte[] by)
{
Byte[] byt = by;
if (byt[0] == 104 && byt[1] == 18 && byt[2] == 18 && byt[3] == 104 && byt[4] == 0 && byt[5] == 2 && byt[6] == 8 && byt[7] == 50 && byt[8] == 3 && byt[9] == 0 && byt[10] == 0 && byt[11] == 0 && byt[12] == 0 && byt[13] == 0 && byt[14] == 2 && byt[15] == 0 && byt[16] == 1 && byt[17] == 0 && byt[18] == 0 && byt[19] == 5 && byt[20] == 1 && byt[21] == 255 && byt[22] == 71 && byt[23] == 22)
{
return true;
}
else
{
return false;
}
}
#region IDispose member
public void Dispose()
{
if (this.clientSocket.Connected)
{
this.clientSocket.Close();
}
}
#endregion
}
}
@@ -0,0 +1,276 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
namespace AGVSystem.Cls
{
public class AgvInfo
{
public Label agv_id = new Label();
/// <summary>
/// 设备编号
/// </summary>
public int Agv_ID
{
get { return Convert.ToInt16( agv_id.Text); }
set { agv_id.Text = value.ToString(); }
}
/// <summary>
/// 设备序号
/// </summary>
public int Internal_ID;
/// <summary>
/// 设备联网状态
/// </summary>
public bool bPlcLinked = false;
/// <summary>
/// 设备IP
/// </summary>
public string IP;
/// <summary>
/// 联网端口
/// </summary>
public int Port;
/// <summary>
/// AGV类型
/// </summary>
public int Type;
/// <summary>
/// 设备上下线 true:上线,false:下线
/// </summary>
public bool Enable;
/// <summary>
/// 控制PLC型号
/// 1smart200
/// 2:欧姆龙 hostlink
/// 3:欧姆龙 fins
/// 4:单片机
/// </summary>
public int Control_PLC = 1;
/// <summary>
/// 管控线体编号
/// </summary>
public int AssemblyLine;
/// <summary>
/// 设备所属线体名称
/// </summary>
public string AssemblyName;
public Label location_display = new Label();
/// <summary>
/// 设备位置显示标记
/// </summary>
public int Location_Display
{
get {return Convert.ToInt16(location_display.Text); }
set {location_display.Text =value.ToString(); }
}
public int Rfid_Value = 0;
/// <summary>
/// 设备路径显示标记
/// </summary>
public int Path_Display = 0;
/// <summary>
/// 设备放行点标记
/// </summary>
public int Cross_Location_Go = 0;
/// <summary>
/// agv放行信息
/// </summary>
public string go_info = "";
/// <summary>
/// 设备运动目标编号
/// </summary>
public int Cross_Path_Id = 0;
/// <summary>
/// 设备报警代码
/// </summary>
public string Warn_ID = "0";
public Label warn_info = new Label();
/// <summary>
/// 设备报警信息
/// </summary>
public string Warn_info
{
get { return warn_info.Text; }
set { warn_info.Text = value; }
}
/// <summary>
/// 设备报警等级
/// 1:正常
/// 2:报警
/// 3:故障
/// 4:掉网
/// </summary>
public int Warn_Level = 0;
/// <summary>
/// 设备位置显示地图编号
/// </summary>
public int Area;
public Socket Soc;
/// <summary>
/// Agv行驶里程
/// </summary>
public double Mileage = 0;
/// <summary>
/// 读取地标的时间点
/// </summary>
public DateTime Read_dt;
/// <summary>
/// AGV运动状态
/// 定义:1-运动、2-停止、0-未启动
/// </summary>
public byte Run_Status;
/// <summary>
/// 运动方向
/// 定义:1-前进/2-后退
/// </summary>
public byte Run_Direction = 0;
/// <summary>
/// 前进放行
/// 定义:1-直行/2-左转/3-右转
/// </summary>
public byte Go_Direction = 1;
/// <summary>
/// 设备运动速度
/// </summary>
public byte Run_Speed = 0;
/// <summary>
/// 设备电压
/// </summary>
public float Voltage = 0;
/// <summary>
/// 设备电量剩余百分比
/// </summary>
public float Voltage_precent = 0;
/// <summary>
/// 障碍物设置模式
/// </summary>
public byte Bank_Model = 0;
/// <summary>
/// 任务编号
/// </summary>
public int Task_ID = 0;
public int Task_Temp = 0;
public Label task_descrption = new Label();
/// <summary>
/// 任务描述
/// </summary>
public String Task_Descrption
{
get {return task_descrption.Text; }
set
{
task_descrption.Text = value;
}
}
/// <summary>
/// 作业线体编号
/// </summary>
public int WorkType = 0;
public Label have_goods = new Label();
/// <summary>
/// AGV 是否有货
/// </summary>
public bool Have_Goods
{
get { return have_goods.Text=="有货"?true:false; }
set { have_goods.Text = value == false ? "" : "有货"; }
}
public Channel[] Up_Channel ;
public Channel[] Down_Channel ;
////设备绑定的物料ID
//public string Material_ID2 = "";
////上层2料道是否有料
//public byte Up_Loc2 = 0;//是否有料
//public int Task_Up_Loc2 = 0;//目标地址
//public int Machine_Up_ID2 = 0;//对应设备编号
//public byte Up_Loc2_Doing = 0;
////下层1料道是否有料
//public byte Down_Loc1 = 0;
//public int Task_Down_Loc1 = 0;
//public int Machine_Down_ID1 = 0;
//public byte Down_Loc1_Doing = 0;
}
public class Channel
{
//绑定的物料ID
public string Material_ID = "";
//料道是否有料
public byte Goods_Satus = 0;
//物料数量
public int Goods_Qty = 0;
//Channel上的BOX ID1
public int Box_ID1 = 0;
//Channel上的BOX ID2
public int Box_ID2 = 0;
//货物对应的工位ID
public int Channel_Task_ID = 0;
//货物对应的设备ID
public int Machine_ID = 0;
//动作执行状态 1:正在上/下料 0:非上/下料状态
public byte Do_Status = 0;
public byte Do_Up_Status = 0;
public byte Do_Down_Status = 0;
public byte Do_HgQty_Status = 0;//下滑竿标记
public byte Do_Bxg_Status = 0;//上保险杆标记
//mes指令ID
public Int64 Mes_Task_ID = 0;
}
}
@@ -0,0 +1,258 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace AGVSystem
{
/// <summary>
/// 数据库操作
/// </summary>
public class ClsDBConn_sql
{
/// <summary>
/// 获取CPU运行的时间
/// </summary>
/// <returns></returns>
[DllImport("kernel32")]
static extern uint GetTickCount();
private System.Data.DataSet dt = new System.Data.DataSet();
private SqlConnection sqlconn = new SqlConnection(Cls.Param.connectStr);
private SqlDataAdapter sqladapter = null;
private SqlCommandBuilder sqlcommandb = null;
private SqlCommandBuilder sqlcommandb_ds = null;
private BindingSource bindsource = new BindingSource();
private SqlCommand command = null;
/// <summary>
/// 关闭连接
/// </summary>
public void ConnClosed()
{
try
{
if (sqlconn != null)
{
if (sqlconn.State == ConnectionState.Open)
{
sqlconn.Close();
}
}
}
catch
{
}
}
/// <summary>
/// 连接数据库返回dataset
/// </summary>
/// <param name="str"> SQL语句</param>
/// <returns></returns>
public System.Data.DataSet connDt(string str)
{
try
{
if (sqlconn.State != ConnectionState.Open)
sqlconn.Open();
sqladapter = new SqlDataAdapter(str, sqlconn);
sqlcommandb = new SqlCommandBuilder(sqladapter);
if (dt.Tables.Count > 0)
dt.Tables.Clear();
sqladapter.Fill(dt);
return dt;
}
catch (Exception err)
{
MessageBox.Show("SQL" + str + " , \r\n" + err.Message + " \r\n FunctionNameconnDt", "错误!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}
/// <summary>
/// 返回可更新的dataset
/// </summary>
/// <param name="str"> SQL语句</param>
/// <returns></returns>
public System.Data.DataSet dtEdit(string str)
{
try
{
sqladapter = new SqlDataAdapter(str, sqlconn);
sqlcommandb_ds = new SqlCommandBuilder(sqladapter);
if (dt.Tables.Count > 0)
dt.Tables.Clear();
sqladapter.Fill(dt);
return dt;
}
catch (Exception err)
{
MessageBox.Show("SQL" + str + " , \r\n" + err.Message + " \r\n FunctionNamedtEdit", "错误!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}
/// <summary>
/// 更新Dataset数据到数据库
/// </summary>
/// <param name="ds"></param>
/// <param name="adapter"></param>
/// <returns></returns>
public bool dtCommit(System.Data.DataSet ds )
{
try
{
//Int64 t1 = GetTickCount();
int DS = ds.Tables[0].Rows.Count;
sqladapter.Update(ds);
//Int64 t2 = GetTickCount() - t1;
//if (t2 > 2)
// MessageBox.Show("update time:"+t2.ToString());
}
catch
{
//MessageBox.Show(err.Message+"EventNamedtCommit");
return false;
}
return true;
}
/// <summary>
/// 数据库连接到datagridview
/// </summary>
/// <param name="str">sql语句</param>
/// <param name="dataGridView">datagridview控件名称</param>
public bool connDGV(string str, DataGridView dgv)
{
try
{
if (sqlconn.State == ConnectionState.Open) sqlconn.Close();
sqladapter = new SqlDataAdapter(str, sqlconn);
if (dt.Tables.Count > 0)
dt.Tables.Clear();
sqladapter.Fill(dt);
if (dt.Tables.Count > 0)
dgv.DataSource = dt.Tables[0].Copy();
return true;
}
catch (Exception err)
{
MessageBox.Show("SQL" + str + " , \r\n" + err.Message + " \r\n FunctionNameconnDGV", "错误!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
/// <summary>
/// 数据库连接到datagridview,并可通过datagridview修改数据库
/// </summary>
/// <param name="str">sql语句</param>
/// <param name="dataGridView">datagridview控件名称</param>
public bool connDgvEdit(string str, DataGridView dgv)
{
try
{
if (sqlconn.State == ConnectionState.Open) sqlconn.Close();
sqladapter = new SqlDataAdapter(str, sqlconn);
if (dt.Tables.Count > 0)
dt.Tables.Clear();
sqladapter.Fill(dt);
sqlcommandb = new SqlCommandBuilder(sqladapter);
bindsource.DataSource = dt.Tables[0];
dgv.DataSource = dt.Tables[0];
dgv.DataSource = bindsource;
return true;
}
catch (Exception err)
{
MessageBox.Show("SQL" + str + " , \r\n" + err.Message + " \r\n FunctionNameconnDGVEdit", "错误!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
/// <summary>
/// 提交datagridview的数据
/// </summary>
/// <param name="dataGridView">datagridview控件名称</param>
public bool DgvCommit(DataGridView dgv)
{
try
{
dgv.EndEdit();
bindsource.EndEdit();
sqladapter.Update(dt.Tables[0]);
return true;
}
catch (Exception err)
{
MessageBox.Show(err.Message + " \r\n FunctionNameDgvCommit", "错误!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
/// <summary>
/// 直接执行SQL语句
/// </summary>
/// <param name="sqlstr"></param>
/// <returns></returns>
public string Command(string sqlstr)
{
try
{
int count = 0;
if (sqlconn.State != ConnectionState.Open) sqlconn.Open();
command = new SqlCommand(sqlstr, sqlconn);
count = command.ExecuteNonQuery();
//sqlconn.Close();
return count.ToString();
}
catch (Exception err)
{
return "SQL" + sqlstr + " , \r\n" + err.Message + " \r\n FunctionNameCommand";
}
}
public bool DtCommand(string Sqlstr, string[,] insertValue)
{
try
{
if (sqlconn.State == ConnectionState.Open) sqlconn.Close();
sqladapter = new SqlDataAdapter(Sqlstr, sqlconn);
if (dt.Tables.Count > 0)
dt.Tables.Clear();
sqlcommandb = new SqlCommandBuilder(sqladapter);
sqladapter.Fill(dt);
for (int rw = 0; rw < insertValue.GetLength(0); rw++)
{
System.Data.DataRow drow = dt.Tables[0].NewRow();
for (int cl = 0; cl < insertValue.GetLength(1); cl++)
{
drow[cl] = insertValue[rw, cl];
}
dt.Tables[0].Rows.Add(drow);
}
sqladapter.Update(dt);
sqlconn.Close();
return true;
}
catch (Exception err)
{
MessageBox.Show(err.Message, "错误!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
public void gg()
{
bindsource.AddNew();
bindsource.MoveLast();
}
}
}
@@ -0,0 +1,562 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace AGVSystem.Cls
{
class Cls_Mc_Mitsubishi
{
/// <summary>
/// 客户端连接Socket
/// </summary>
public Socket clientSocket;
/// <summary>
/// 连接状态
/// </summary>
public Boolean connected = false;
/// <summary>
/// 发送数据
/// </summary>
private Byte[] SendMess;
/// <summary>
/// 连接点
/// </summary>
private IPEndPoint hostEndPoint;
/// <summary>
/// 连接信号量
/// </summary>
private static AutoResetEvent autoConnectEvent = new AutoResetEvent(false);
/// <summary>
/// 接受到数据时的委托
/// </summary>
/// <param name="info"></param>
public delegate void ReceiveMsgHandler(Byte[] info);
/// <summary>
/// 接收到数据时调用的事件
/// </summary>
public event ReceiveMsgHandler OnMsgReceived;
/// <summary>
/// 开始监听数据的委托
/// </summary>
public delegate void StartListenHandler();
/// <summary>
/// 开始监听数据的事件
/// </summary>
public event StartListenHandler StartListenThread;
/// <summary>
/// 发送信息完成的委托
/// </summary>
/// <param name="successorfalse"></param>
public delegate void SendCompleted(bool successorfalse);
/// <summary>
/// 发送信息完成的事件
/// </summary>
public event SendCompleted OnSended;
/// <summary>
/// 监听接收的SocketAsyncEventArgs
/// </summary>
private SocketAsyncEventArgs listenerSocketAsyncEventArgs;
int Plcport;
public Cls_Mc_Mitsubishi(String hostName, Int32 port, Int32 PLCStaion)
{
//IPHostEntry host = Dns.GetHostEntry(hostName);
//IPAddress[] addressList = host.AddressList;
//this.hostEndPoint = new IPEndPoint(addressList[addressList.Length - 1], port);
Plcport = PLCStaion;
IPAddress[] addressList = Dns.GetHostAddresses(hostName);
this.hostEndPoint = new IPEndPoint(addressList[addressList.Length - 1], port);
this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
}
/// <summary>
/// 连接服务端
/// </summary>
private bool Connect()
{
using (SocketAsyncEventArgs connectArgs = new SocketAsyncEventArgs())
{
connectArgs.UserToken = this.clientSocket;
connectArgs.RemoteEndPoint = this.hostEndPoint;
connectArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnect);
clientSocket.ConnectAsync(connectArgs);
//等待连接结果
bool autores = autoConnectEvent.WaitOne(1000);
//if (autores)
//{
//bool hasres = autoConnectEvent.WaitOne();
//SocketError errorCode = connectArgs.SocketError;
//if (errorCode == SocketError.Success)
if (autores)
{
listenerSocketAsyncEventArgs = new SocketAsyncEventArgs();
//byte[] receiveBuffer = new byte[32768];
byte[] receiveBuffer = new byte[255];//设置接收buffer区大小
listenerSocketAsyncEventArgs.UserToken = clientSocket;
listenerSocketAsyncEventArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
listenerSocketAsyncEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceive);
StartListenThread();
SocketExtensions.SetKeepAlive(clientSocket, 3000, 1000);
return true;
}
else
//throw new SocketException((Int32)errorCode);
return false;
//}
}
//else
// return false;
}
/// <summary>
/// 开始监听线程的入口函数
/// </summary>
private void Listen()
{
(listenerSocketAsyncEventArgs.UserToken as Socket).ReceiveAsync(listenerSocketAsyncEventArgs);
}
public static List<SocketAsyncEventArgs> s_lst = new List<SocketAsyncEventArgs>();
/// <summary>
/// 发送信息
/// </summary>
/// <param name="message"></param>
private void Send(Byte[] message)
{
if (this.connected)
{
//message = String.Format("[length={0}]{1}", message.Length, message);
//Byte[] sendBuffer = new Byte[256];
//sendBuffer = Encoding.Default.GetBytes(message);
Byte[] sendBuffer = message;
SocketAsyncEventArgs senderSocketAsyncEventArgs = null;// new SocketAsyncEventArgs();
lock (s_lst)
{
if (s_lst.Count>0)
{
senderSocketAsyncEventArgs = s_lst[s_lst.Count - 1];
s_lst.RemoveAt(s_lst.Count - 1);
}
}
if (senderSocketAsyncEventArgs==null)
{
senderSocketAsyncEventArgs = new SocketAsyncEventArgs();
senderSocketAsyncEventArgs.UserToken = this.clientSocket;
senderSocketAsyncEventArgs.RemoteEndPoint = this.hostEndPoint;
senderSocketAsyncEventArgs.Completed += (object sender, SocketAsyncEventArgs _e) =>
{
lock (s_lst)
{
s_lst.Add(senderSocketAsyncEventArgs);
}
};
//senderSocketAsyncEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend);
}
senderSocketAsyncEventArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length);
clientSocket.SendAsync(senderSocketAsyncEventArgs);
}
else
{
this.connected = false;
//throw new SocketException((Int32)SocketError.NotConnected);
}
SendMess = message;
}
/// <summary>
/// 断开连接
/// </summary>
private bool Disconnect()
{
bool returnDis = true;
try
{
this.clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
//clientSocket.Disconnect(true);
//clientSocket.Disconnect(false);
}
catch (Exception)
{
returnDis = false;
}
return returnDis;
}
/// <summary>
/// 连接的完成方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnConnect(object sender, SocketAsyncEventArgs e)
{
autoConnectEvent.Set();
this.connected = (e.SocketError == SocketError.Success);
}
/// <summary>
/// 接收的完成方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnReceive(object sender, SocketAsyncEventArgs e)
{
if (e.BytesTransferred == 0)
{
//Console.WriteLine("Socket is closed", Socket.Handle);
if (clientSocket.Connected)
{
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
//client already closed
}
finally
{
if (clientSocket.Connected)
{
clientSocket.Close();
}
}
}
Byte[] rs = new Byte[1];
rs[0] = 0x00;
//try
//{
OnMsgReceived(rs);
//}
//catch (Exception)
//{
//}
this.connected = false;
}
else
{
//byte[] outValue = BitConverter.GetBytes(0);
//string msg = Encoding.Default.GetString(outValue, 0, e.BytesTransferred);
//string msg = Encoding.Default.GetString(e.Buffer, 0, e.BytesTransferred);
Byte[] outValue = e.Buffer;
//try
//{
OnMsgReceived(outValue);
////}
//catch (Exception)
//{
//}
Listen();
}
}
/// <summary>
/// 发送的完成方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnSend(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
OnSended(true);
}
else
{
OnSended(false);
this.ProcessError(e);
}
}
/// <summary>
/// 处理错误
/// </summary>
/// <param name="e"></param>
private void ProcessError(SocketAsyncEventArgs e)
{
Socket s = e.UserToken as Socket;
if (s.Connected)
{
try
{
s.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
//client already closed
}
finally
{
if (s.Connected)
{
s.Close();
}
}
this.connected = false;
}
//throw new SocketException((Int32)e.SocketError);
}
#region IDisposable Members
public void Dispose()
{
autoConnectEvent.Close();
if (this.clientSocket.Connected)
{
this.clientSocket.Close();
}
}
#endregion
/// <summary>
/// 发送命令反馈
/// </summary>
/// <param name="successorfalse"></param>
void OmronFINS_OnSended(bool successorfalse)
{
if (!successorfalse)
{
}
else
{
}
}
Byte PCS;
Byte PLCS;
int SendOrRev;
int SendOrRev2;
Byte[] SendBack;
Byte[] RecvBack;
/// <summary>
/// 接受命令反馈
/// </summary>
/// <param name="info"></param>
void OmronFINS_OnMsgReceived(byte[] info)
{
if (SendmessHas)
{
if (info[0] != 0x00)//PLC连接错误NO
{
if (info.Length > 24)
{
string SM = "";
for (int i = 0; i < 24; i++)
{
SM = SM + info[i].ToString("X").PadLeft(2, '0');
}
if (int.Parse(info[23].ToString("X").Trim(), System.Globalization.NumberStyles.HexNumber) == Plcport)
{
PCS = info[19];
PLCS = info[23];
SendmessHas = false;
}
}
}
}
else
{
if (info[0] != 0x00)//PLC连接错误NO
{
if (SendOrRev2 == 1)//发送命令
{
SendBack = info;
SendOrRev2 = 0;
}
else if (SendOrRev == 2)//接受命令
{
RecvBack = info;
SendOrRev = 0;
}
}
else
{
if (SendOrRev2 == 1)//发送命令
{
SendBack = new Byte[1];
SendBack[0] = 0x00;
SendOrRev2 = 0;
}
else if (SendOrRev == 2)//接受命令
{
RecvBack = new Byte[1];
RecvBack[0] = 0x00;
SendOrRev = 0;
}
}
}
}
void OmronFINS_StartListenThread()
{
this.Listen();
}
bool SendmessHas = false;
/// <summary>
/// 打开连接
/// </summary>
/// <returns></returns>
public bool OpenLinkPLC()
{
bool Ret = false;
this.StartListenThread += new StartListenHandler(OmronFINS_StartListenThread);
this.OnMsgReceived += new ReceiveMsgHandler(OmronFINS_OnMsgReceived);
this.OnSended += new SendCompleted(OmronFINS_OnSended);
Ret = this.Connect();
return Ret;
}
/// <summary>
/// 关闭连接
/// </summary>
/// <returns></returns>
public bool CloseLinkPLC()
{
return this.Disconnect();
}
public bool WritePlcData(int address , int value )
{
Byte[] SendmessAge = new byte[23];
SendmessAge[0] = 0x50;
SendmessAge[1] = 0x00;
SendmessAge[2] = 0x00;
SendmessAge[3] = 0xFF;
SendmessAge[4] = 0xFF;
SendmessAge[5] = 0x03;
SendmessAge[6] = 0x00;
SendmessAge[7] = 0x0E;
SendmessAge[8] = 0x00;
SendmessAge[9] = 0x00;
SendmessAge[10] = 0x00;
SendmessAge[11] = 0x01;
SendmessAge[12] = 0x14;
SendmessAge[13] = 0x00;
SendmessAge[14] = 0x00;
SendmessAge[15] = Convert.ToByte(address % 256);
SendmessAge[16] = Convert.ToByte(address / 256);
SendmessAge[17] = 0x00;
SendmessAge[18] = 0xA8;
SendmessAge[19] = 0x01;
SendmessAge[20] = 0x00;
SendmessAge[21] = Convert.ToByte(value % 256);
SendmessAge[22] = Convert.ToByte(value / 256);
bool sendRerun = false;
SendOrRev2 = 1;
this.Send(SendmessAge);
int Outtime = 0;
while (SendOrRev2 != 0 & this.connected & Outtime < 1000)
{
Thread.Sleep(1);
Outtime++;
}
if (Outtime < 1000)
{
try
{
if (SendBack[0] == 0xD0 && SendBack[5] == 0x03 && SendBack[7] == 0x02 && SendBack[10] == 0x00)
{
sendRerun = true;
}
else
{
sendRerun = false;
}
}
catch (Exception)
{
}
}
else
{
SendOrRev2 = 0;
}
return sendRerun;
}
public bool ReadPlcData(int address , int length, out int[] IntValue)
{
bool GetPlcRet = false;
IntValue = new int[length];
Byte[] getReciveFunc=new byte[21];
getReciveFunc[0] = 0x50;
getReciveFunc[1] = 0x00;
getReciveFunc[2] = 0x00;
getReciveFunc[3] = 0xFF;
getReciveFunc[4] = 0xFF;
getReciveFunc[5] = 0x03;
getReciveFunc[6] = 0x00;
getReciveFunc[7] = 0x0C;
getReciveFunc[8] = 0x00;
getReciveFunc[9] = 0x00;
getReciveFunc[10] = 0x00;
getReciveFunc[11] = 0x01;
getReciveFunc[12] = 0x04;
getReciveFunc[13] = 0x00;
getReciveFunc[14] = 0x00;
getReciveFunc[15] = Convert.ToByte(address % 256);
getReciveFunc[16] = Convert.ToByte(address / 256);
getReciveFunc[17] = 0x00;
getReciveFunc[18] = 0xA8;
getReciveFunc[19] = Convert.ToByte( length % 256 );
getReciveFunc[20] = Convert.ToByte( length / 256 );
this.Send(getReciveFunc);
SendOrRev = 2;
int Outtime = 0;
while (SendOrRev != 0 & this.connected & Outtime < 1000)
{
Thread.Sleep(1);
Outtime++;
}
if (Outtime < 1000)
{
try
{
if (RecvBack[0] == 0xD0 && RecvBack[5] == 0x03 && RecvBack[7] == 0x16 && RecvBack[10] == 0x00)
{
GetPlcRet = true;
for (int i = 0; i < 10; i++)
{
IntValue[i] = RecvBack[11 + 2 * i] + RecvBack[12 + 2 * i]*256;
}
}
else
{
GetPlcRet = false;
}
}
catch (Exception)
{
}
}
else
{
SendOrRev = 0;
}
return GetPlcRet;
}
}
}
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AGVSystem.Cls
{
public class Cls_Plc_Info
{
public enum Op_Info
{
length_read =11,
length_write=1,
addr_read = 600,
addr_write_go =500,
addr_mb=504
}
}
}
@@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using s7api.net;
namespace AGVSystem.Cls
{
/// <summary>
/// profinet 协议
/// 适用于西门子plc S-300 S-1500 S-1200
/// </summary>
class Cls_Profinet_Siemens
{
private S7Client client_profinet = new S7Client();
private int Rack = 0;
private int Slot = 0;
private string IpAddress = "";
public Cls_Profinet_Siemens(string ip , int rack , int slot)
{
Rack = rack;
Slot = slot;
IpAddress = ip;
}
/// <summary>
/// 连接PLC
/// </summary>
/// <returns></returns>
public bool Connect()
{
int result = 0;
result = client_profinet.ConnectTo(IpAddress, Rack, Slot);
if (result == 0)
return true;
else
return false;
}
/// <summary>
/// 断开与PLC的连接
/// </summary>
/// <returns></returns>
public bool Disconnect()
{
int result = 0;
result = client_profinet.Disconnect();
if (result == 0)
return true;
else
return false;
}
/// <summary>
/// 读取DB块的值
/// </summary>
/// <param name="dbNumber">DB块编号</param>
/// <param name="start_address">DB块起始地址</param>
/// <param name="size">读取的字节数</param>
/// <param name="buffer">读取结果</param>
/// <returns>读取成功返回true ,否则返回false</returns>
public bool Read(int dbNumber , int start_address , int size , byte[] buffer)
{
int result = 0;
result = client_profinet.DBRead(dbNumber, start_address, size, buffer);
if (result != 0)
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 向DB块写入值
/// </summary>
/// <param name="dbNumber">DB块编号</param>
/// <param name="start_address">DB块起始地址</param>
/// <param name="size">写入的字节数</param>
/// <param name="buffer">写入值</param>
/// <returns>写入成功返回true ,否则返回false</returns>
public bool Write(int dbNumber, int start_address, int size, byte[] buffer)
{
int result = 0;
result = client_profinet.DBWrite(dbNumber, start_address, size, buffer);
if (result != 0)
{
return false;
}
else
{
return true;
}
}
}
}
@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace AGVSystem.Cls
{
public class FileRW
{
[DllImport("kernel32")]
public static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
/// <summary>
/// 读取INI文档
/// </summary>
/// <param name="Section">区段名</param>
/// <param name="Key">键</param>
/// <param name="file">文件路径</param>
/// <returns>Value</returns>
public static string ReadIniValue(string Section, string Key, string file)
{
StringBuilder _temp = new StringBuilder(1024);
GetPrivateProfileString(Section, Key, "", _temp, 1024, file);
return _temp.ToString();
}
/// <summary>
/// 写入INI文档
/// </summary>
/// <param name="Section">区段名</param>
/// <param name="Key">键</param>
/// <param name="value">Value</param>
/// <param name="file">文件路劲</param>
public static long WriteIniValue(string Section, string Key, string value, string file)
{
long rtu = WritePrivateProfileString(Section, Key, value, file);
return rtu;
}
}
}
@@ -0,0 +1,567 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Net.NetworkInformation;
using System.Data;
using System.Threading;
using Agv_Info;
using Agv_Control;
namespace AGVSystem
{
public class Func
{
/// <summary>
/// 表示每个AGV的btn
/// </summary>
public static AgvCar.Agv[] agvcar;
public static AgvCar.Agv[] agvcar2;//总图使用
public static Cls.AgvInfo[] AgvInfo;
public static Panel[] Map;
public static ClsDBConn_sql db_conn = new ClsDBConn_sql();
/// <summary>
///AGV位置变更时,记录位置信息的Temp
/// </summary>
public static int[] Agv_Location_Temp;
/// <summary>
/// 创建地标容器
/// </summary>
/// <param name="id">地标编号</param>
/// <param name="b">1.左端(后退) 2.右端(前进) 3.顶部(向上) 4.底部(向下)</param>
/// <param name="x">容器放置坐标x</param>
/// <param name="y">容器放置坐标y</param>
///
public static void CreatePanelLocation(string id, int direction, int x, int y, int area, string Assembly_ID)
{
Panel pl = new Panel();
pl.Parent = Map[area];
pl.BackColor = Color.Transparent;
Label lab = new Label();
//Button lab = new Button();
lab.Visible = Cls.Param.Location_ID_Dispaly;
lab.Text = id;
if (Assembly_ID != "0" || Assembly_ID != "")
{
lab.Tag = Assembly_ID + "-" + id;
lab.DoubleClick += new System.EventHandler(Cls.Path_Reset.label12_DoubleClick);
lab.MouseClick += new MouseEventHandler(label_MouseClick);
}
lab.AutoSize = false;
lab.Height = Cls.Param.Icon_Size;
lab.Width = Cls.Param.Icon_Size;
pl.Width = Cls.Param.Icon_Size;
pl.Height = Cls.Param.Icon_Size;
lab.Parent = pl;
lab.BackColor = Color.Transparent;
lab.Font = new Font("宋体", 9, FontStyle.Regular);
lab.TextAlign = ContentAlignment.MiddleCenter;
if (direction==1)
{
pl.Location = new Point(x, y-Cls.Param.Icon_Size/2);
pl.Tag = id + "-" + "1";
lab.Dock = DockStyle.Left;
}
else if (direction == 2)
{
pl.Location = new Point(x, y - Cls.Param.Icon_Size / 2);
pl.Tag = id + "-" + "2";
lab.Dock = DockStyle.Left;
}
else if (direction == 3)
{
pl.Location = new Point(x - Cls.Param.Icon_Size / 2, y);
pl.Tag = id + "-" + "3";
lab.Dock = DockStyle.Top;
}
else if (direction == 4)
{
pl.Location = new Point(x - Cls.Param.Icon_Size / 2, y);
pl.Tag = id + "-" + "4";
lab.Dock = DockStyle.Top;
}
pl.Name = "Contain"+id.ToString();
}
public static int loc_flag = 0;
private static void label_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
loc_flag = Convert.ToInt16(((Label)sender).Text);
}
}
private static object obj_dgvupdate = new object();
public static void DgvUpdate(DataGridView dgv, int row, string columnname, bool value)
{
lock (obj_dgvupdate)
{
dgvUpdate(dgv, row, columnname, value);
}
}
private static void dgvUpdate(DataGridView dgv , int row , string columnname ,bool value)
{
dgv.Rows[row].Cells[columnname].Value = value;
if (columnname == "Status")
{
if (value)
{
dgv.Rows[row].DefaultCellStyle.ForeColor = Color.Red;
}
else
{
dgv.Rows[row].Cells["联网状态"].Value = value;
dgv.Rows[row].DefaultCellStyle.ForeColor = Color.Gray;
}
}
else if (columnname == "联网状态")
{
if (value)
{
dgv.Rows[row].DefaultCellStyle.ForeColor = Color.Black;
}
else
{
dgv.Rows[row].DefaultCellStyle.ForeColor = Color.Red;
}
}
}
private static object obj_AgvIpToId = new object();
public static int AgvIpToId(string IP)
{
lock (obj_AgvIpToId)
{
string ip = IP;
int ID = 0; ;
DataView rowfilter = new DataView(mainfrm.ds_Agvlist.Tables[0]);
rowfilter.RowFilter = "IPAddress='" + ip + "'";
rowfilter.RowStateFilter = DataViewRowState.OriginalRows;
DataTable dt = rowfilter.ToTable();
try
{
ID = Convert.ToInt16(dt.Rows[0]["ID"].ToString());
}
catch
{
}
return ID;
}
}
private static int run_time;
private static int run_model;
private static int next_loc = 0;
/// <summary>
/// 显示AGV位置状态
/// </summary>
/// <param name="agv_id">AGV编号</param>
/// <param name="run_status">运动状态:运行/停止</param>
/// <param name="warn_level">报警等级</param>
/// <param name="current_location">当前位置</param>
/// <param name="map_id">所属地图编号</param>
/// <param name="run_fx">运动方向:直行/左转/右转</param>
public static void Agv_Car_Status(int agv_id ,
bool run_status,
int warn_level ,
int current_location,
int map_id,
int run_fx)
{
Func.agvcar[agv_id - 1].Car_Warn_Level = warn_level;
if (current_location != Agv_Location_Temp[agv_id - 1])
{
Func.agvcar[agv_id - 1].Run_Status = false;
Agv_Location_Temp[agv_id - 1] = current_location;
}
else
{
Func.agvcar[agv_id - 1].Run_Status = run_status;
}
if (current_location == 0) return;
run_time = 0;
run_model = 0;
next_loc = 0;
Panel pl_new_parent = new Panel();//xin panel
Panel pl_old_parent = new Panel();//jiu panel
Panel parent_pnl = new Panel();
parent_pnl = Func.Map[map_id ];
foreach (System.Windows.Forms.Control ctl in parent_pnl.Controls)
{
if (ctl.GetType().Name == "Panel")
{
if (Convert.ToInt16(ctl.Tag.ToString().Split('-')[0]) == current_location)
{
pl_new_parent = (Panel)ctl;
//AGV移动到新的管控停止位
if (pl_new_parent != (Panel)Func.agvcar[agv_id - 1].Parent && !Func.agvcar[agv_id - 1].Run_Status )
{
Func.agvcar[agv_id - 1].Refresh();
pl_old_parent = (Panel)Func.agvcar[agv_id - 1].Parent;
Func.agvcar[agv_id - 1].Parent = pl_new_parent;
Func.agvcar[agv_id - 1].BringToFront();
if (pl_new_parent.Tag.ToString().Split('-')[1] == "1")
{
Func.agvcar[agv_id - 1].Dock = DockStyle.Left;
}
else if (pl_new_parent.Tag.ToString().Split('-')[1] == "2")
{
Func.agvcar[agv_id - 1].Dock = DockStyle.Right;
}
else if (pl_new_parent.Tag.ToString().Split('-')[1] == "3")
{
Func.agvcar[agv_id - 1].Dock = DockStyle.Top;
}
else if (pl_new_parent.Tag.ToString().Split('-')[1] == "4")
{
Func.agvcar[agv_id - 1].Dock = DockStyle.Bottom;
}
}
//AGV从停止位出发
else if (pl_new_parent == (Panel)Func.agvcar[agv_id - 1].Parent &&
Func.agvcar[agv_id - 1].Run_Status )
{
if (Func.agvcar[agv_id - 1].Parent != parent_pnl)
{
pl_old_parent = (Panel)Func.agvcar[agv_id - 1].Parent;
Func.agvcar[agv_id - 1].Dock = DockStyle.None;
Func.agvcar[agv_id - 1].Parent = parent_pnl;
string ss = parent_pnl.Name;
Func.agvcar[agv_id - 1].Location = pl_old_parent.Location;
Func.agvcar[agv_id - 1].BringToFront();
nextStation(Convert.ToInt16((Func.agvcar[agv_id - 1].Tag.ToString().Split('-'))[1]), current_location, run_fx, out run_time, out run_model,out next_loc);
Func.agvcar[agv_id - 1].TimeLong = run_time;
Func.agvcar[agv_id - 1].Run_Model = run_model;
if (next_loc != 0)
{
foreach (System.Windows.Forms.Control c in parent_pnl.Controls)
{
if (c.GetType().Name == "Panel")
{
if (Convert.ToInt16(c.Tag.ToString().Split('-')[0]) == next_loc)
{
Func.agvcar[agv_id - 1].NextLocation = c.Location;
return;
}
}
}
}
}
}
}
}
}
//以下设置新容器大小
int i = 0;
foreach (System.Windows.Forms.Control ctl in pl_new_parent.Controls)
{
i = i + Cls.Param.Icon_Size;
}
try
{
if (pl_new_parent.Tag.ToString().Split('-')[1] == "3" || pl_new_parent.Tag.ToString().Split('-')[1] == "4")
{
pl_new_parent.Height = i;
}
else
{
pl_new_parent.Width = i;
}
}
catch
{
}
}
/// <summary>
/// 获取下一个站点
/// </summary>
/// <param name="Assembly_ID">线体编号</param>
/// <param name="Landmark_ID">位置编号</param>
/// <param name="flag">区分</param>
/// <param name="p">返回下一个站点坐标</param>
/// <param name="run_time">返回到下一个站点的时间</param>
/// <param name="run_model">返回AGV图标运动模式</param>
private static void nextStation(int Assembly_ID, int Landmark_ID, int flag, out int run_time1, out int run_model1, out int next_loc1)
{
run_time1 = 0;
run_model1 = 0;
next_loc1 = 0;
DataView rowfilter = new DataView(mainfrm.ds_linelandmark.Tables[0]);
rowfilter.RowFilter = "Assembly_Line=" + Assembly_ID + " and LOC_ID= " + Landmark_ID;
rowfilter.RowStateFilter = DataViewRowState.OriginalRows;
DataTable dt = rowfilter.ToTable();
try
{
if (dt.Rows.Count == 1)
{
if (flag == 1)
{
next_loc1 = Convert.ToInt16(dt.Rows[0]["Next_Station1"]);
run_time1 = Convert.ToInt16(dt.Rows[0]["LongTime1"]);
run_model1 = Convert.ToInt16(dt.Rows[0]["Drict1"]);
}
else if (flag == 2)
{
next_loc1 = Convert.ToInt16(dt.Rows[0]["Next_Station1"]);
run_time1 = Convert.ToInt16(dt.Rows[0]["LongTime2"]);
run_model1 = Convert.ToInt16(dt.Rows[0]["Drict2"]);
}
else if (flag == 3)
{
next_loc1 = Convert.ToInt16(dt.Rows[0]["Next_Station1"]);
run_time1 = Convert.ToInt16(dt.Rows[0]["LongTime2"]);
run_model1 = Convert.ToInt16(dt.Rows[0]["Drict2"]);
}
}
}
catch
{
}
}
/// <summary>
/// AGV实时故障显示
/// </summary>
/// <param name="del_agv_no"></param>
/// <param name="Assembly_Name"></param>
/// <param name="Assembly_Id"></param>
/// <param name="AGV_Internal_No"></param>
/// <param name="AlarmInfo"></param>
/// <param name="agv_no"></param>
public static void Agv_Alarm_Insert(int del_agv_no, string Assembly_Name, string Assembly_Id, int AGV_Internal_No, string AlarmInfo, int agv_no)
{
lock (obj_agv_alarm_insert)
{
agv_alarm_insert(del_agv_no, Assembly_Name, Assembly_Id, AGV_Internal_No, AlarmInfo, agv_no);
}
}
private static object obj_agv_alarm_insert = new object();
private static void agv_alarm_insert(int del_agv_no, string Assembly_Name, string Assembly_Id, int AGV_Internal_No, string AlarmInfo, int agv_no)
{
if (del_agv_no == 0)
{
bool update_flag = false;
if (mainfrm.ds_AgvWarn.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < mainfrm.ds_AgvWarn.Tables[0].Rows.Count; i++)
{
if (Convert.ToInt16(mainfrm.ds_AgvWarn.Tables[0].Rows[i][3].ToString()) == agv_no &&
mainfrm.ds_AgvWarn.Tables[0].Rows[i][5].ToString().Trim() == AlarmInfo.Trim())
{
//ds_aGVWarn.Tables[0].Rows[i][0] = DateTime.Now.ToString();
//ds_aGVWarn.Tables[0].Rows[i][1] = Assembly_Id;
//ds_aGVWarn.Tables[0].Rows[i][2] = Assembly_Name;
//ds_aGVWarn.Tables[0].Rows[i][3] = agv_no;
//ds_aGVWarn.Tables[0].Rows[i][4] = AGV_Internal_No;
//ds_aGVWarn.Tables[0].Rows[i][5] = AlarmInfo;
//update_flag = true;
return;
}
}
}
if (!update_flag)
{
DataRow dr = mainfrm.ds_AgvWarn.Tables[0].NewRow();
dr[0] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");// 时间
dr[1] = Assembly_Id; // 线体编号
dr[2] = Assembly_Name; // 线体名称
dr[3] = agv_no; // 设备编号
dr[4] = AGV_Internal_No; // 内部编号
dr[5] = AlarmInfo; // 报警信息
mainfrm.ds_AgvWarn.Tables[0].Rows.Add(dr);
}
}
else
{
for (int i = 0; i < mainfrm.ds_AgvWarn.Tables[0].Rows.Count; i++)
{
if (AlarmInfo == "正常")
{
if (Convert.ToInt16(mainfrm.ds_AgvWarn.Tables[0].Rows[i][3]) == del_agv_no)
{
if (!mainfrm.ds_AgvWarn.Tables[0].Rows[i][5].ToString().Contains("障碍物"))
{
//db_conn.Command("INSERT INTO [Warn_Log] ([Dt] ,[Agv_id] ,[Type] ,[Reset]) VALUES ('" +
// mainfrm.ds_AgvWarn.Tables[0].Rows[i][0] + "'," +
// mainfrm.ds_AgvWarn.Tables[0].Rows[i][3] + ",'" +
// mainfrm.ds_AgvWarn.Tables[0].Rows[i][5] + "','" +
// DateTime.Now.ToString() + "')");
db_conn.Command("INSERT INTO [Warn_Log] ([Dt] ,[Agv_id] ,[Type] ,[Reset] ,[Internal_ID] ,[Line_ID] ,[Line_Name]) VALUES ('" +
mainfrm.ds_AgvWarn.Tables[0].Rows[i][0] + "'," +
mainfrm.ds_AgvWarn.Tables[0].Rows[i][3] + ",'" +
mainfrm.ds_AgvWarn.Tables[0].Rows[i][5] + "','" +
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'," +
Func.AgvInfo[Convert.ToInt16(mainfrm.ds_AgvWarn.Tables[0].Rows[i][3]) - 1].Internal_ID + "," +
Func.AgvInfo[Convert.ToInt16(mainfrm.ds_AgvWarn.Tables[0].Rows[i][3]) - 1].AssemblyLine + ",'" +
Func.AgvInfo[Convert.ToInt16(mainfrm.ds_AgvWarn.Tables[0].Rows[i][3]) - 1].AssemblyName + "')");
}
mainfrm.ds_AgvWarn.Tables[0].Rows.RemoveAt(i);
i--;
}
}
else
{
if (Convert.ToInt16(mainfrm.ds_AgvWarn.Tables[0].Rows[i][3]) == del_agv_no &&
mainfrm.ds_AgvWarn.Tables[0].Rows[i][5].ToString() == AlarmInfo)
{
if (!mainfrm.ds_AgvWarn.Tables[0].Rows[i][5].ToString().Contains("障碍物"))
{
db_conn.Command("INSERT INTO [Warn_Log] ([Dt] ,[Agv_id] ,[Type] ,[Reset] ,[Internal_ID] ,[Line_ID] ,[Line_Name]) VALUES ('" +
mainfrm.ds_AgvWarn.Tables[0].Rows[i][0] + "'," +
mainfrm.ds_AgvWarn.Tables[0].Rows[i][3] + ",'" +
mainfrm.ds_AgvWarn.Tables[0].Rows[i][5] + "','" +
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "',"+
Func.AgvInfo[Convert.ToInt16(mainfrm.ds_AgvWarn.Tables[0].Rows[i][3])-1].Internal_ID+","+
Func.AgvInfo[Convert.ToInt16(mainfrm.ds_AgvWarn.Tables[0].Rows[i][3]) - 1].AssemblyLine+",'"+
Func.AgvInfo[Convert.ToInt16(mainfrm.ds_AgvWarn.Tables[0].Rows[i][3]) - 1].AssemblyName+"')");
}
mainfrm.ds_AgvWarn.Tables[0].Rows.RemoveAt(i);
i--;
}
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="Assembly_Name"></param>
/// <param name="Assembly_Id"></param>
/// <param name="AGV_Internal_No"></param>
/// <param name="LandMark"></param>
/// <param name="Info"></param>
/// <param name="agv_no"></param>
public static void CrossInfo_Insert(string Assembly_Name,
string Assembly_Id,
int AGV_Internal_No,
int LandMark,
string Info,
int agv_no,
int plc_value,
int internal_id,
int line_id,
string line_name)
{
lock (obj_crossinfo_insert)
{
crossInfo_Insert(Assembly_Name, Assembly_Id, AGV_Internal_No, LandMark, Info, agv_no, plc_value, internal_id, line_id,line_name);
}
}
private static object obj_crossinfo_insert = new object();
public static void crossInfo_Insert(string Assembly_Name,
string Assembly_Id,
int AGV_Internal_No,
int LandMark,
string Info,
int agv_no,
int plc_value,
int internal_id,
int line_id,
string line_name)
{
string strsql = "";
strsql = "INSERT INTO [Go_Log] ([Dt] ,[Agv_id] ,[Type] ,[Location],[plc_value] ,[Internal_ID],[Line_ID] ,[Line_Name]) VALUES " +
"('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'," +
agv_no + ",'" +
Info + "'," +
LandMark + "," +
plc_value +","+
internal_id+","+
line_id + ",'"+
line_name + "')";
db_conn.Command(strsql);
}
private static object obj_GetLandMarkId = new object();
/// <summary>
/// 根据地标值读取地标编号
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static int GetLandMarkId(int assemblyline_id, int value)
{
lock (obj_GetLandMarkId)
{
int markid = 0;
DataView rowfilter = new DataView(mainfrm.ds_linelandmark.Tables[0]);
rowfilter.RowFilter = "Flag_Value=" + value + " and Assembly_Line= " + assemblyline_id;
rowfilter.RowStateFilter = DataViewRowState.OriginalRows;
DataTable dt = rowfilter.ToTable();
try
{
markid = Convert.ToInt16(dt.Rows[0]["Loc_ID"].ToString());
}
catch
{
}
return markid;
}
}
private static object obj_change = new object();
public static void Change_Rec(int agv_id ,int current_loc,int histroy_loc,DateTime dt,int internal_id,int line_id,string line_name)
{
lock (obj_change)
{
if (mainfrm.ds_Change.Tables[0].Rows.Count == 0) return;
if (histroy_loc == 0) return;
bool current_loc_res = false;
bool histroy_loc_res = false;
if (mainfrm.ds_Change.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in mainfrm.ds_Change.Tables[0].Rows)
{
if (Convert.ToInt16(dr[0].ToString()) == current_loc)
{
current_loc_res = true;
return;
}
if (Convert.ToInt16(dr[0].ToString()) == histroy_loc)
{
histroy_loc_res = true;
}
}
if (current_loc_res == false && histroy_loc_res == true)
{
db_conn.Command("INSERT INTO [Change_Log]([Agv_ID] ,[Start_time],[Finish_time] ,[Location_ID],internal_id, line_id, line_name) VALUES(" +
agv_id + ",'" +
dt + "','" +
DateTime.Now.ToString() + "'," +
histroy_loc + ","+
internal_id +","+
line_id +",'"+
line_name+"')");
}
}
}
}
}
}
@@ -0,0 +1,630 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Net.NetworkInformation;
using System.Data;
using System.Threading;
using Agv_Info;
using BllSql;
using AGVSystem.A17168;
//using Agv_Control;
namespace AGVSystem
{
public class Func
{
/// <summary>
/// 表示每个AGV的btn
/// </summary>
//public static AgvLib.HxAgv[] AgvBtn;
public static AgvCar.Agv[] agvcar;
public static Cls.AgvInfo[] AgvInfo;
public static ClsDBConn_sql db_conn = new ClsDBConn_sql();
public static BllBase bBllBase = new BllBase();
/// <summary>
///AGV位置变更时,记录位置信息的Temp
/// </summary>
public static int[] Agv_Location_Temp;
/// <summary>
/// 创建地标容器
/// </summary>
/// <param name="id">地标编号</param>
/// <param name="b">1.左端(后退) 2.右端(前进) 3.顶部(向上) 4.底部(向下)</param>
/// <param name="x">容器放置坐标x</param>
/// <param name="y">容器放置坐标y</param>
///
public static void CreatePanelLocation(string id, int direction, int x, int y, int area, string Assembly_ID)
{
Panel pl = new Panel();
if (area == 1)
{
pl.Parent = mainfrm.Map1;
}
else if (area == 2)
{
pl.Parent = mainfrm.Map2;
}
else
{
pl.Parent = mainfrm.Map3;
}
pl.BackColor = Color.Transparent;
Label lab = new Label();
//Button lab = new Button();
lab.Visible = Cls.Param.Location_ID_Dispaly;
lab.Text = id;
if (Assembly_ID != "0" || Assembly_ID != "")
{
lab.Tag = Assembly_ID + "-" + id;
lab.DoubleClick += new System.EventHandler(Cls.Path_Reset.label12_DoubleClick);
lab.MouseClick += new MouseEventHandler(label_MouseClick);
}
else if (Cls.Param.Display_CrossID == false)
{
lab.ForeColor = Color.Black;
}
lab.AutoSize = false;
lab.Height = Cls.Param.Icon_Size;
lab.Width = Cls.Param.Icon_Size;
pl.Width = Cls.Param.Icon_Size;
pl.Height = Cls.Param.Icon_Size;
lab.Parent = pl;
lab.BackColor = Color.Transparent;
lab.Font = new Font("宋体", 9, FontStyle.Regular);
lab.TextAlign = ContentAlignment.MiddleCenter;
if (direction == 1)
{
pl.Location = new Point(x, y - Cls.Param.Icon_Size / 2);
pl.Tag = id + "-" + "1";
lab.Dock = DockStyle.Left;
}
else if (direction == 2)
{
pl.Location = new Point(x, y - Cls.Param.Icon_Size / 2);
pl.Tag = id + "-" + "2";
lab.Dock = DockStyle.Left;
}
else if (direction == 3)
{
pl.Location = new Point(x - Cls.Param.Icon_Size / 2, y);
pl.Tag = id + "-" + "3";
lab.Dock = DockStyle.Top;
}
else if (direction == 4)
{
pl.Location = new Point(x - Cls.Param.Icon_Size / 2, y);
pl.Tag = id + "-" + "4";
lab.Dock = DockStyle.Top;
}
}
public static int loc_flag = 0;
private static void label_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
loc_flag = Convert.ToInt16(((Label)sender).Text);
}
}
private static object obj_dgvupdate = new object();
public static void DgvUpdate(DataGridView dgv, int row, string columnname, bool value)
{
lock (obj_dgvupdate)
{
dgvUpdate(dgv, row, columnname, value);
}
}
private static void dgvUpdate(DataGridView dgv, int row, string columnname, bool value)
{
dgv.Rows[row].Cells[columnname].Value = value;
if (columnname == "Status")
{
if (value)
{
dgv.Rows[row].DefaultCellStyle.ForeColor = Color.Red;
}
else
{
dgv.Rows[row].Cells["联网状态"].Value = value;
dgv.Rows[row].DefaultCellStyle.ForeColor = Color.Gray;
}
}
else if (columnname == "联网状态")
{
if (value)
{
dgv.Rows[row].DefaultCellStyle.ForeColor = Color.Black;
}
else
{
dgv.Rows[row].DefaultCellStyle.ForeColor = Color.Red;
}
}
}
private static object obj_AgvIpToId = new object();
public static int AgvIpToId(string IP)
{
lock (obj_AgvIpToId)
{
string ip = IP;
int ID = 0; ;
DataView rowfilter = new DataView(mainfrm.ds_Agvlist.Tables[0]);
rowfilter.RowFilter = "IPAddress='" + ip + "'";
rowfilter.RowStateFilter = DataViewRowState.OriginalRows;
DataTable dt = rowfilter.ToTable();
try
{
ID = Convert.ToInt16(dt.Rows[0]["ID"].ToString());
}
catch
{
}
return ID;
}
}
private static int run_time;
private static int run_model;
private static int next_loc = 0;
/// <summary>
/// 显示AGV位置状态
/// </summary>
/// <param name="agv_id">AGV编号</param>
/// <param name="run_status">运动状态:运行/停止</param>
/// <param name="warn_level">报警等级</param>
/// <param name="current_location">当前位置</param>
/// <param name="map_id">所属地图编号</param>
/// <param name="run_fx">运动方向:直行/左转/右转</param>
public static void Agv_Car_Status(int agv_id,
bool run_status,
int warn_level,
int current_location,
int map_id,
int run_fx)
{
try
{
Func.agvcar[agv_id - 1].Car_Warn_Level = warn_level;
if (current_location != Agv_Location_Temp[agv_id - 1])
{
Func.agvcar[agv_id - 1].Run_Status = false;
Agv_Location_Temp[agv_id - 1] = current_location;
}
else
{
Func.agvcar[agv_id - 1].Run_Status = run_status;
}
if (current_location == 0) return;
run_time = 0;
run_model = 0;
next_loc = 0;
Panel pl_new_parent = new Panel();//xin panel
Panel pl_old_parent = new Panel();//jiu panel
Panel parent_pnl = new Panel();
if (map_id == 1)
{
parent_pnl = mainfrm.Map1;
}
else if (map_id == 2)
{
parent_pnl = mainfrm.Map2;
}
else
{
parent_pnl = mainfrm.Map3;
}
foreach (System.Windows.Forms.Control ctl in parent_pnl.Controls)
{
if (ctl.GetType().Name == "Panel")
{
if (Convert.ToInt16(ctl.Tag.ToString().Split('-')[0]) == current_location)
{
pl_new_parent = (Panel)ctl;
//AGV移动到新的管控停止位
if (pl_new_parent != (Panel)Func.agvcar[agv_id - 1].Parent && !Func.agvcar[agv_id - 1].Run_Status)
{
Func.agvcar[agv_id - 1].Refresh();
pl_old_parent = (Panel)Func.agvcar[agv_id - 1].Parent;
Func.agvcar[agv_id - 1].Parent = pl_new_parent;
Func.agvcar[agv_id - 1].BringToFront();
if (pl_new_parent.Tag.ToString().Split('-')[1] == "1")
{
Func.agvcar[agv_id - 1].Dock = DockStyle.Left;
}
else if (pl_new_parent.Tag.ToString().Split('-')[1] == "2")
{
Func.agvcar[agv_id - 1].Dock = DockStyle.Right;
}
else if (pl_new_parent.Tag.ToString().Split('-')[1] == "3")
{
Func.agvcar[agv_id - 1].Dock = DockStyle.Top;
}
else if (pl_new_parent.Tag.ToString().Split('-')[1] == "4")
{
Func.agvcar[agv_id - 1].Dock = DockStyle.Bottom;
}
}
//AGV从停止位出发
else if (pl_new_parent == (Panel)Func.agvcar[agv_id - 1].Parent &&
Func.agvcar[agv_id - 1].Run_Status)
{
if (Func.agvcar[agv_id - 1].Parent != parent_pnl)
{
pl_old_parent = (Panel)Func.agvcar[agv_id - 1].Parent;
Func.agvcar[agv_id - 1].Dock = DockStyle.None;
Func.agvcar[agv_id - 1].Parent = parent_pnl;
string ss = parent_pnl.Name;
Func.agvcar[agv_id - 1].Location = pl_old_parent.Location;
Func.agvcar[agv_id - 1].BringToFront();
nextStation(Convert.ToInt16((Func.agvcar[agv_id - 1].Tag.ToString().Split('-'))[1]), current_location, run_fx, out run_time, out run_model, out next_loc);
Func.agvcar[agv_id - 1].TimeLong = run_time;
Func.agvcar[agv_id - 1].Run_Model = run_model;
if (next_loc != 0)
{
foreach (System.Windows.Forms.Control c in parent_pnl.Controls)
{
if (c.GetType().Name == "Panel")
{
if (Convert.ToInt16(c.Tag.ToString().Split('-')[0]) == next_loc)
{
Func.agvcar[agv_id - 1].NextLocation = c.Location;
return;
}
}
}
}
}
}
}
}
}
//以下设置新容器大小
int i = 0;
foreach (System.Windows.Forms.Control ctl in pl_new_parent.Controls)
{
i = i + Cls.Param.Icon_Size;
}
if (pl_new_parent.Tag != null && (pl_new_parent.Tag.ToString().Split('-')[1] == "3" || pl_new_parent.Tag.ToString().Split('-')[1] == "4"))
{
pl_new_parent.Height = i;
}
else
{
pl_new_parent.Width = i;
}
}catch(Exception ex)
{
}
}
/// <summary>
/// 获取下一个站点
/// </summary>
/// <param name="Assembly_ID">线体编号</param>
/// <param name="Landmark_ID">位置编号</param>
/// <param name="flag">区分</param>
/// <param name="p">返回下一个站点坐标</param>
/// <param name="run_time">返回到下一个站点的时间</param>
/// <param name="run_model">返回AGV图标运动模式</param>
private static void nextStation(int Assembly_ID, int Landmark_ID, int flag, out int run_time1, out int run_model1, out int next_loc1)
{
run_time1 = 0;
run_model1 = 0;
next_loc1 = 0;
DataView rowfilter = new DataView(mainfrm.ds_linelandmark.Tables[0]);
rowfilter.RowFilter = "Assembly_Line=" + Assembly_ID + " and LOC_ID= " + Landmark_ID;
rowfilter.RowStateFilter = DataViewRowState.OriginalRows;
DataTable dt = rowfilter.ToTable();
try
{
if (dt.Rows.Count == 1)
{
if (flag == 1)
{
next_loc1 = Convert.ToInt16(dt.Rows[0]["Next_Station1"]);
run_time1 = Convert.ToInt16(dt.Rows[0]["LongTime1"]);
run_model1 = Convert.ToInt16(dt.Rows[0]["Drict1"]);
}
else if (flag == 2)
{
next_loc1 = Convert.ToInt16(dt.Rows[0]["Next_Station1"]);
run_time1 = Convert.ToInt16(dt.Rows[0]["LongTime2"]);
run_model1 = Convert.ToInt16(dt.Rows[0]["Drict2"]);
}
else if (flag == 3)
{
next_loc1 = Convert.ToInt16(dt.Rows[0]["Next_Station1"]);
run_time1 = Convert.ToInt16(dt.Rows[0]["LongTime2"]);
run_model1 = Convert.ToInt16(dt.Rows[0]["Drict2"]);
}
}
}
catch
{
}
}
/// <summary>
/// AGV实时故障显示
/// </summary>
/// <param name="del_agv_no"></param>
/// <param name="Assembly_Name"></param>
/// <param name="Assembly_Id"></param>
/// <param name="AGV_Internal_No"></param>
/// <param name="AlarmInfo"></param>
/// <param name="agv_no"></param>
public static void Agv_Alarm_Insert(int del_agv_no, string Assembly_Name, string Assembly_Id, int AGV_Internal_No, string AlarmInfo, int agv_no)
{
lock (obj_agv_alarm_insert)
{
agv_alarm_insert(del_agv_no, Assembly_Name, Assembly_Id, AGV_Internal_No, AlarmInfo, agv_no);
}
}
private static object obj_agv_alarm_insert = new object();
private static void agv_alarm_insert(int del_agv_no, string Assembly_Name, string Assembly_Id, int AGV_Internal_No, string AlarmInfo, int agv_no)
{
if (del_agv_no == 0)
{
bool update_flag = false;
if (mainfrm.ds_AgvWarn.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < mainfrm.ds_AgvWarn.Tables[0].Rows.Count; i++)
{
if (Convert.ToInt16(mainfrm.ds_AgvWarn.Tables[0].Rows[i][3].ToString()) == agv_no &&
mainfrm.ds_AgvWarn.Tables[0].Rows[i][5].ToString().Trim() == AlarmInfo.Trim())
{
//ds_aGVWarn.Tables[0].Rows[i][0] = DateTime.Now.ToString();
//ds_aGVWarn.Tables[0].Rows[i][1] = Assembly_Id;
//ds_aGVWarn.Tables[0].Rows[i][2] = Assembly_Name;
//ds_aGVWarn.Tables[0].Rows[i][3] = agv_no;
//ds_aGVWarn.Tables[0].Rows[i][4] = AGV_Internal_No;
//ds_aGVWarn.Tables[0].Rows[i][5] = AlarmInfo;
//update_flag = true;
return;
}
}
}
if (!update_flag)
{
DataRow dr = mainfrm.ds_AgvWarn.Tables[0].NewRow();
dr[0] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");// 时间
dr[1] = Assembly_Id; // 线体编号
dr[2] = Assembly_Name; // 线体名称
dr[3] = agv_no; // 设备编号
dr[4] = AGV_Internal_No; // 内部编号
dr[5] = AlarmInfo; // 报警信息
mainfrm.ds_AgvWarn.Tables[0].Rows.Add(dr);
}
}
else
{
for (int i = 0; i < mainfrm.ds_AgvWarn.Tables[0].Rows.Count; i++)
{
if (AlarmInfo == "正常")
{
if (Convert.ToInt16(mainfrm.ds_AgvWarn.Tables[0].Rows[i][3]) == del_agv_no)
{
if (!mainfrm.ds_AgvWarn.Tables[0].Rows[i][5].ToString().Contains("障碍物"))
{
Warn_Log warn_Log = new Warn_Log(mainfrm.ds_AgvWarn.Tables[0].Rows[i][0].ToString(), mainfrm.ds_AgvWarn.Tables[0].Rows[i][3].ToString(),
mainfrm.ds_AgvWarn.Tables[0].Rows[i][5].ToString(), DateTime.Now.ToString());
UPDateDBList.upDbList.Add(warn_Log);
}
mainfrm.ds_AgvWarn.Tables[0].Rows.RemoveAt(i);
i--;
}
}
else
{
if (Convert.ToInt16(mainfrm.ds_AgvWarn.Tables[0].Rows[i][3]) == del_agv_no &&
mainfrm.ds_AgvWarn.Tables[0].Rows[i][5].ToString() == AlarmInfo)
{
if (!mainfrm.ds_AgvWarn.Tables[0].Rows[i][5].ToString().Contains("障碍物"))
{
//db_conn.Command("INSERT INTO [Warn_Log] ([Dt] ,[Agv_id] ,[Type] ,[Reset]) VALUES ('" +
// mainfrm.ds_AgvWarn.Tables[0].Rows[i][0] + "'," + mainfrm.ds_AgvWarn.Tables[0].Rows[i][3] + ",'" + mainfrm.ds_AgvWarn.Tables[0].Rows[i][5] + "','" + DateTime.Now.ToString() + "')");
Warn_Log warn_Log = new Warn_Log(mainfrm.ds_AgvWarn.Tables[0].Rows[i][0].ToString(), mainfrm.ds_AgvWarn.Tables[0].Rows[i][3].ToString(),
mainfrm.ds_AgvWarn.Tables[0].Rows[i][5].ToString(), DateTime.Now.ToString());
UPDateDBList.upDbList.Add(warn_Log);
}
mainfrm.ds_AgvWarn.Tables[0].Rows.RemoveAt(i);
i--;
}
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="Assembly_Name"></param>
/// <param name="Assembly_Id"></param>
/// <param name="AGV_Internal_No"></param>
/// <param name="LandMark"></param>
/// <param name="Info"></param>
/// <param name="agv_no"></param>
public static void CrossInfo_Insert(string Assembly_Name,
string Assembly_Id,
int AGV_Internal_No,
int LandMark,
string Info,
int agv_no,
int plc_value,
int internal_id,
int line_id,
string line_name)
{
lock (obj_crossinfo_insert1)
{
crossInfo_Insert(Assembly_Name, Assembly_Id, AGV_Internal_No, LandMark, Info, agv_no, plc_value, internal_id, line_id, line_name);
}
}
private static object obj_crossinfo_insert1 = new object();
public static void crossInfo_Insert(string Assembly_Name,
string Assembly_Id,
int AGV_Internal_No,
int LandMark,
string Info,
int agv_no,
int plc_value,
int internal_id,
int line_id,
string line_name)
{
string strsql = "";
strsql = "INSERT INTO [Go_Log] ([Dt] ,[Agv_id] ,[Type] ,[Location],[plc_value] ,[Internal_ID],[Line_ID] ,[Line_Name]) VALUES " +
"('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'," +
agv_no + ",'" +
Info + "'," +
LandMark + "," +
plc_value + "," +
internal_id + "," +
line_id + ",'" +
line_name + "')";
db_conn.Command(strsql);
}
///// <summary>
/////
///// </summary>
///// <param name="Assembly_Name"></param>
///// <param name="Assembly_Id"></param>
///// <param name="AGV_Internal_No"></param>
///// <param name="LandMark"></param>
///// <param name="Info"></param>
///// <param name="agv_no"></param>
public static void CrossInfo_Insert(string Assembly_Name, string Assembly_Id, int AGV_Internal_No, int LandMark, string Info, int agv_no, int plc_value)
{
UPDateDBList.upDbList.Add(new CrossInfo_Insert(DateTime.Now, Assembly_Name, Assembly_Id, AGV_Internal_No, LandMark, Info, agv_no, plc_value));
}
private static object obj_crossinfo_insert = new object();
private static object obj_GetLandMarkId = new object();
/// <summary>
/// 根据地标值读取地标编号
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static int GetLandMarkId(int assemblyline_id, int value)
{
lock (obj_GetLandMarkId)
{
int markid = 0;
DataView rowfilter = new DataView(mainfrm.ds_linelandmark.Tables[0]);
rowfilter.RowFilter = "Flag_Value=" + value + " and Assembly_Line= " + assemblyline_id;
rowfilter.RowStateFilter = DataViewRowState.OriginalRows;
DataTable dt = rowfilter.ToTable();
try
{
if (dt.Rows.Count > 0)
markid = Convert.ToInt16(dt.Rows[0]["Loc_ID"].ToString());
}
catch
{
}
return markid;
}
}
private static object obj_change = new object();
public static void Change_Rec(int agv_id, int current_loc, int histroy_loc, DateTime dt, int internal_id, int line_id, string line_name)
{
lock (obj_change)
{
if (mainfrm.ds_Change.Tables[0].Rows.Count == 0) return;
if (histroy_loc == 0) return;
bool current_loc_res = false;
bool histroy_loc_res = false;
if (mainfrm.ds_Change.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in mainfrm.ds_Change.Tables[0].Rows)
{
if (Convert.ToInt16(dr[0].ToString()) == current_loc)
{
current_loc_res = true;
return;
}
if (Convert.ToInt16(dr[0].ToString()) == histroy_loc)
{
histroy_loc_res = true;
}
}
if (current_loc_res == false && histroy_loc_res == true)
{
db_conn.Command("INSERT INTO [Change_Log]([Agv_ID] ,[Start_time],[Finish_time] ,[Location_ID],internal_id, line_id, line_name) VALUES(" +
agv_id + ",'" +
dt + "','" +
DateTime.Now.ToString() + "'," +
histroy_loc + "," +
internal_id + "," +
line_id + ",'" +
line_name + "')");
}
}
}
}
private static object obj_change1 = new object();
public static void Change_Rec(int agv_id, int current_loc, int histroy_loc, DateTime dt)
{
lock (obj_change1)
{
if (mainfrm.ds_Change.Tables[0].Rows.Count == 0) return;
if (histroy_loc == 0) return;
bool current_loc_res = false;
bool histroy_loc_res = false;
if (mainfrm.ds_Change.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in mainfrm.ds_Change.Tables[0].Rows)
{
if (Convert.ToInt16(dr[0].ToString()) == current_loc)
{
current_loc_res = true;
return;
}
if (Convert.ToInt16(dr[0].ToString()) == histroy_loc)
{
histroy_loc_res = true;
}
}
if (current_loc_res == false && histroy_loc_res == true)
{
db_conn.Command("INSERT INTO [Change_Log]([Agv_ID] ,[Start_time],[Finish_time] ,[Location_ID]) VALUES(" +
agv_id + ",'" + dt + "','" + DateTime.Now.ToString() + "'," + histroy_loc + ")");
}
}
}
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,478 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Globalization;
namespace AGVSystem.Cls
{
class OmrlonHostlink
{
public string IPAdress;
public bool connected = false;
public Socket clientSocket;
private IPEndPoint hostEndPoint;
private Byte[] SendDataPro;
private Byte[] RecvDataPro;
private Byte[] SendData;
private Byte[] RecvData;
private Byte SendOrRecv;
private AutoResetEvent autoConnectEvent = new AutoResetEvent(false);
private SocketAsyncEventArgs lisnterSocketAsyncEventArgs;
public delegate void StartListeHandler();
public event StartListeHandler StartListen;
public delegate void ReceiveMsgHandler(byte[] info);
public event ReceiveMsgHandler OnMsgReceived;
private List<SocketAsyncEventArgs> s_lst = new List<SocketAsyncEventArgs>();
public OmrlonHostlink(string hostName, int port)
{
IPAdress = hostName;
IPAddress[] hostAddresses = Dns.GetHostAddresses(hostName);
this.hostEndPoint = new IPEndPoint(hostAddresses[hostAddresses.Length - 1], port);
this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
}
/// <summary>
/// 连接服务端
/// </summary>
/// <returns></returns>
private bool Connect()
{
using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
{
args.UserToken = this.clientSocket;
args.RemoteEndPoint = this.hostEndPoint;
args.Completed += new EventHandler<SocketAsyncEventArgs>(this.OnConnect);
this.clientSocket.ConnectAsync(args);
bool flag = autoConnectEvent.WaitOne(1000);
if (flag)
{
this.lisnterSocketAsyncEventArgs = new SocketAsyncEventArgs();
byte[] buffer = new byte[50];
this.lisnterSocketAsyncEventArgs.UserToken = this.clientSocket;
this.lisnterSocketAsyncEventArgs.SetBuffer(buffer, 0, buffer.Length);
this.lisnterSocketAsyncEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(this.OnReceive);
this.StartListen();
return true;
}
return false;
}
}
/// <summary>
/// 判断有没有连接上
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnConnect(object sender, SocketAsyncEventArgs e)
{
this.connected = (e.SocketError == SocketError.Success);
autoConnectEvent.Set();
}
/// <summary>
/// 发送
/// </summary>
/// <param name="mes"></param>
public void Send(string mes)
{
if (this.connected)
{
EventHandler<SocketAsyncEventArgs> handler = null;
byte[] buffer = Encoding.Default.GetBytes(mes);
SocketAsyncEventArgs senderSocketAsyncEventArgs = null;
lock (s_lst)
{
if (s_lst.Count > 0)
{
senderSocketAsyncEventArgs = s_lst[s_lst.Count - 1];
s_lst.RemoveAt(s_lst.Count - 1);
}
}
if (senderSocketAsyncEventArgs == null)
{
senderSocketAsyncEventArgs = new SocketAsyncEventArgs();
senderSocketAsyncEventArgs.UserToken = this.clientSocket;
senderSocketAsyncEventArgs.RemoteEndPoint = this.clientSocket.RemoteEndPoint;
if (handler == null)
{
handler = delegate(object sender, SocketAsyncEventArgs _e)
{
lock (s_lst)
{
s_lst.Add(senderSocketAsyncEventArgs);
}
};
}
senderSocketAsyncEventArgs.Completed += handler;
}
senderSocketAsyncEventArgs.SetBuffer(buffer, 0, buffer.Length);
this.clientSocket.SendAsync(senderSocketAsyncEventArgs);
}
else
{
this.connected = false;
}
}
/// <summary>
/// 监听服务端
/// </summary>
public void Listen()
{
if (this.connected && this.clientSocket != null)
{
try
{
(lisnterSocketAsyncEventArgs.UserToken as Socket).ReceiveAsync(lisnterSocketAsyncEventArgs);
}
catch (Exception)
{
}
}
}
/// <summary>
/// 断开连接
/// </summary>
/// <returns></returns>
private int Disconnect()
{
int res = 0;
try
{
this.clientSocket.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
}
try
{
this.clientSocket.Close();
}
catch (Exception)
{
}
this.connected = false;
return res;
}
/// <summary>
/// 数据接受
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnReceive(object sender, SocketAsyncEventArgs e)
{
if (e.BytesTransferred == 0)
{
try
{
this.clientSocket.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
}
finally
{
if (this.clientSocket.Connected)
{
this.clientSocket.Close();
}
}
byte[] info = new Byte[] { 0 };
this.OnMsgReceived(info);
}
else
{
byte[] buffer = new byte[e.BytesTransferred];
for (int i = 0; i < e.BytesTransferred; i++)
{
buffer[i] = e.Buffer[i];
}
this.OnMsgReceived(buffer);
Listen();
}
}
/// <summary>
/// 接受完成
/// </summary>
/// <param name="info"></param>
private void OmrlonSocketClient_OnMsgReceived(byte[] info)
{
if (info[0] != 0)
{
if (this.SendOrRecv == 1)
{
this.SendDataPro = info;
this.SendOrRecv = 0;
}
else if (this.SendOrRecv == 2)
{
this.SendData = info;
this.SendOrRecv = 0;
}
else if (this.SendOrRecv == 3)
{
this.RecvDataPro = info;
this.SendOrRecv = 0;
}
else if (this.SendOrRecv == 4)
{
this.RecvData = info;
this.SendOrRecv = 0;
}
}
else
{
if (this.SendOrRecv == 1)
{
this.SendDataPro = new Byte[] { 0 };
this.SendOrRecv = 0;
}
else if (this.SendOrRecv == 2)
{
this.SendData = new Byte[] { 0 };
this.SendOrRecv = 0;
}
else if (this.SendOrRecv == 3)
{
this.RecvDataPro = new Byte[] { 0 };
this.SendOrRecv = 0;
}
else if (this.SendOrRecv == 4)
{
this.RecvData = new Byte[] { 0 };
this.SendOrRecv = 0;
}
}
}
/// <summary>
/// 建立连接的方法
/// </summary>
/// <returns></returns>
public bool OpenLinkPLC()
{
bool flag = false;
this.StartListen += new StartListeHandler(OmrlonSocketClient_StartListen);
this.OnMsgReceived += new ReceiveMsgHandler(OmrlonSocketClient_OnMsgReceived);
flag = this.Connect();
if (!flag)
{
return flag;
}
return true;
}
/// <summary>
/// 关闭连接的方法
/// </summary>
/// <returns></returns>
public int CloseLinkPLC()
{
return this.Disconnect();
}
/// <summary>
/// 监听的方法
/// </summary>
private void OmrlonSocketClient_StartListen()
{
this.Listen();
}
/// <summary>
/// 校验
/// </summary>
/// <param name="Value"></param>
/// <returns></returns>
private string FCS(string Value)
{
int num2 = 0;
for (int i = 0; i < Value.Length; i++)
{
byte[] bytes = Encoding.ASCII.GetBytes(Value.Substring(i, 1));
num2 ^= bytes[0];
}
return num2.ToString("X");
}
#region PLC数据
/// <summary>
/// 写一个DM数据
/// </summary>
/// <param name="paddr"></param>
/// <param name="waddr"></param>
/// <param name="value"></param>
/// <returns></returns>
public int WritePlcDMValue(string stationNO, int address, string value)
{
int flag = -1;
string str = "";
string str2 = "";
string str3 = value;
str2 = address.ToString().PadLeft(4, '0');
stationNO = stationNO.PadLeft(2, '0');
str = "@" + stationNO + "WD" + str2 + str3;
str = string.Concat(new object[] { str, this.FCS(str), "*", '\r' });
this.SendOrRecv = 1;
int numPro = 0;
this.Send(str);
while (this.SendOrRecv != 0 && numPro < 500)
{
Thread.Sleep(1);
numPro++;
}
if (numPro < 500)
{
string STR = Encoding.Default.GetString(SendDataPro, 0, SendDataPro.Length);
if (STR.Length > 7)
{
if (STR.Substring(5, 2) == "00" &&STR.Substring(3, 2) == "WD"&& STR.Substring(0, 1) == "@" && STR.Substring(STR.Length - 1, 1) == "\r")
{
flag = 0;
}
//if (this.SendDataPro.Length > 7)
//{
// if (this.SendDataPro[5] == 0x30 && this.SendDataPro[6] == 0x30)
// {
// flag = 0;
// }
// return flag;
//}
}
}
else
{
this.SendOrRecv = 0;
}
return flag;
}
#endregion
#region DM值
/// <summary>
/// 读DM值
/// </summary>
/// <param name="stationNO"></param>
/// <param name="length"></param>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
public int ReadPlcDMValue(string PlcNo, int Addr, out int value)
{
int A = 0;
if (Addr == 3000)
A = 0;
int flag = -1;
value = -1;
string str = "";
string str2 = "";
str2 = Addr.ToString().PadLeft(4, '0');
PlcNo = PlcNo.PadLeft(2, '0');
str = "@" + PlcNo + "RD" + str2 + "0001";
str = string.Concat(new object[] { str, this.FCS(str), "*", '\r' });
this.SendOrRecv = 3;
int numPro = 0;
this.Send(str);
while (this.SendOrRecv != 0 && numPro < 500)
{
Thread.Sleep(1);
numPro++;
}
if (numPro < 500)
{
string STR = Encoding.Default.GetString(RecvDataPro, 0, RecvDataPro.Length);
if (STR.Length > 11)
{
if (STR.Substring(5, 2) == "00" && STR.Substring(3, 2) == "RD" && STR.Substring(0, 1) == "@" && STR.Substring(STR.Length - 1, 1) == "\r")
{
value = int.Parse(STR.Trim().Substring(7, 4), NumberStyles.HexNumber);
flag = 0;
}
}
//if (this.RecvDataPro.Length > 11)
//{
// if (this.RecvDataPro[5] == 0x30 && this.RecvDataPro[6] == 0x30)
// {
// flag = 0;
// value = RecvDataPro[10] + RecvDataPro[9] * 16 + RecvDataPro[8] * 256 + RecvDataPro[7] * 16 * 256;
// }
// return flag;
//}
}
else
{
this.SendOrRecv = 0;
}
return flag;
}
#endregion
#region HR值
/// <summary>
/// 读HR值
/// </summary>
/// <param name="stationNO"></param>
/// <param name="length"></param>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
public int ReadPlcHRValue(string PlcNo, int Addr, out int Value)
{
int flag = -1;
Value = -1;
string str = "";
string str2 = "";
str2 = Addr.ToString().PadLeft(4, '0');
PlcNo = PlcNo.PadLeft(2, '0');
str = "@" + PlcNo + "RH" + str2 + "0001";
str = string.Concat(new object[] { str, this.FCS(str), "*", '\r' });
this.SendOrRecv = 4;
int num = 0;
this.Send(str);
while (this.SendOrRecv != 0 && num < 500)
{
Thread.Sleep(1);
num++;
}
if (num < 500)
{
string STR = Encoding.Default.GetString(RecvData, 0, RecvData.Length);
if (STR.Length > 11)
{
if (STR.Substring(5, 2) == "00" && STR.Substring(3, 2) == "RH" && STR.Substring(0, 1) == "@" && STR.Substring(STR.Length - 1, 1) == "\r")
{
Value = int.Parse(STR.Trim().Substring(7, 4), NumberStyles.HexNumber);
flag = 0;
}
}
//if (this.RecvData.Length > 11)
//{
// if (this.RecvData[5] == 0x30 && this.RecvData[6] == 0x30)
// {
// flag = 0;
// Value = RecvData[10] + RecvData[9] * 16 + RecvData[8] * 256 + RecvData[7] * 16*256;
// }
// return flag;
//}
}
else
{
this.SendOrRecv = 0;
}
return flag;
}
#endregion
#region IDispose member
public void Dispose()
{
if (this.clientSocket.Connected)
{
this.clientSocket.Close();
}
}
#endregion
}
}
@@ -0,0 +1,115 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Threading;
//using Agv_Control;
using IO_Card_1730U;
namespace AGVSystem.Cls
{
public class Param
{
public static bool Exit_Lg_Flag = false;
public static bool StartFlag = false;
public static string UserName="";
public static string Password="";
public static string UserName_temp = "";
public static string Password_temp = "";
public static Color backcolor;
public static int Icon_Size = 32;
//public static bool Traffic1 = false;
//public static bool Traffic2 = false;
//public static bool Traffic3 = false;
//public static bool Traffic4 = false;
public static bool Write_log;
public static bool Display_CrossID = true;
public static bool Hand1_St = false;
public static bool Hand2_St = false;
public static int Hand1_Agv_St = 0;
public static int Hand2_Agv_St = 0;
public static bool HandLoc1_Go = false;
public static bool HandLoc2_Go = false;
//public static bool BY_ST = false;
//public static int BY_Write_Value = 0;
public static bool BY1_GO = false;
public static bool BY1_Leave = false;
public static bool BY2_GO = false;
public static bool BY2_Leave = false;
public static string map1_path = "";
public static string map2_path = "";
public static string map3_path = "";
public static bool map1_status = true;
public static bool map2_status = false;
public static bool map3_status = false;
public static bool Location_ID_Dispaly = true;
public static string connectStr = "";
public static string Pro_id = "";
public static string Pro_factory = "";
public static string Pro_remark = "";
public static int Day_Count = 15;
public static int Card1_Interval = 0;
public static int Card2_Interval = 0;
public static int Card3_Interval = 0;
public static IO_Card_1730U.IO_Card card1;
public static IO_Card_1730U.IO_Card card2;
public static IO_Card_1730U.IO_Card card3;
public static Thread[] th_GetData;
/// <summary>
/// 定义AGV的总数量
/// </summary>
public static byte AGV_Qty = 0;
public static Agv_Info.AgvInfo agvinfocls = new Agv_Info.AgvInfo();
public static Type t;
/// <summary>
/// 启动程序时自动开始管控
/// </summary>
public static bool Auto_Control = false;
public static bool Load_Path_His = false;
public static byte PLC_Type = 0;
//0:Omron Serial Hostlink
//1:Omron Serial Fins
//2:Siemens S7-200 Serial
//3:Siemens S7-200 Net
//4:SCM Net Protocol
public static bool Agv_Location_Auto_Display = false;
public static byte Map_ID = 1;
public static int Thread_Count = -1;
public static Boolean Frm_Ischild = false;
public static string Xj_Time1 = "";
public static string Xj_Time2 = "";
public static bool Exit_Flag = false;
public static int Wait_Time1 = 0;
public static int Wait_Time2 = 0;
}
}
@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace AGVSystem.Cls
{
class Path_Reset
{
public static void label12_DoubleClick(object sender, EventArgs e)
{
if (((System.Windows.Forms.Label)sender).Tag.ToString() == "")
return;
if (MessageBox.Show("是否复位该路口?", "消息", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No) return;
int[] num = new int[2];
num[0] = Convert.ToInt16(((System.Windows.Forms.Label)sender).Tag.ToString().Split('-')[0]);
num[1] = Convert.ToInt16(((System.Windows.Forms.Label)sender).Tag.ToString().Split('-')[1]);
for (int i = 0; i < mainfrm.ds_CrossInfo.Tables[0].Rows.Count; i++)
{
string s = mainfrm.ds_CrossInfo.Tables[0].Rows[i]["当前地标编号"].ToString();
string a = mainfrm.ds_CrossInfo.Tables[0].Rows[i]["AGV编号"].ToString();
if (mainfrm.ds_CrossInfo.Tables[0].Rows[i]["当前产线编号"].ToString() == num[0].ToString() &&
mainfrm.ds_CrossInfo.Tables[0].Rows[i]["当前地标编号"].ToString() == num[1].ToString() &&
mainfrm.ds_CrossInfo.Tables[0].Rows[i]["AGV编号"].ToString() != "0")
{
MessageBox.Show("AGV-" + mainfrm.ds_CrossInfo.Tables[0].Rows[i]["AGV编号"].ToString() + "占用路口信息被清除!");
mainfrm.ds_CrossInfo.Tables[0].Rows[i]["AGV编号"] = 0;
}
}
}
}
}
@@ -0,0 +1,120 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace AGVSystem
{
class Senddataset
{
/// <summary>
/// 将dataSet转换为json
/// </summary>
/// <param name="dataSet"></param>
/// <returns></returns>
public static string DatasetToJson(DataSet dataSet)
{
string jsonString = "{";
foreach (DataTable table in dataSet.Tables)
{
jsonString += "\"" + table.TableName + "\":" + DataTableToJson(table) + ",";
}
jsonString = jsonString.TrimEnd(',');
return jsonString + "}";
}
public static string DataTableToJson(DataTable dt)
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("[");
DataRowCollection drc = dt.Rows;
for (int i = 0; i < drc.Count; i++)
{
jsonString.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
string strKey = dt.Columns[j].ColumnName;
string strValue = drc[i][j].ToString();
Type type = dt.Columns[j].DataType;
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if (j < dt.Columns.Count - 1)
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
jsonString.Remove(jsonString.Length - 1, 1);
jsonString.Append("]");
return jsonString.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="str"></param>
/// <param name="type"></param>
/// <returns></returns>
private static string StringFormat(string str, Type type)
{
if (type == typeof(string))
{
str = StringToJson(str);
str = "\"" + str + "\"";
}
else if (type == typeof(DateTime))
{
str = "\"" + str + "\"";
}
else if (type == typeof(bool))
{
str = str.ToLower();
}
else if (type != typeof(string) && string.IsNullOrEmpty(str))
{
str = "\"" + str + "\"";
}
return str;
}
//#region 私有方法
/// <summary>
/// 过滤特殊字符
/// </summary>
/// <param name="s">字符串</param>
/// <returns>json字符串</returns>
private static string StringToJson(String s)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
char c = s.ToCharArray()[i];
switch (c)
{
case '\"':
sb.Append("\\\""); break;
case '\\':
sb.Append("\\\\"); break;
case '/':
sb.Append("\\/"); break;
case '\b':
sb.Append("\\b"); break;
case '\f':
sb.Append("\\f"); break;
case '\n':
sb.Append("\\n"); break;
case '\r':
sb.Append("\\r"); break;
case '\t':
sb.Append("\\t"); break;
default:
sb.Append(c); break;
}
}
return sb.ToString();
}
}
}
@@ -0,0 +1,505 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.Globalization;
namespace AGVSystem
{
public class Soc_Client
{
public string IPAdress;
public bool connected = false;
public Socket clientSocket;
private IPEndPoint hostEndPoint;
private AutoResetEvent autoConnectEvent = new AutoResetEvent(false);
private SocketAsyncEventArgs lisnterSocketAsyncEventArgs;
public delegate void StartListeHandler();
public event StartListeHandler StartListen;
public delegate void ReceiveMsgHandler(byte[] info);
public event ReceiveMsgHandler OnMsgReceived;
private List<SocketAsyncEventArgs> s_lst = new List<SocketAsyncEventArgs>();
public Soc_Client(string hostName, int port)
{
IPAdress = hostName;
IPAddress[] hostAddresses = Dns.GetHostAddresses(hostName);
this.hostEndPoint = new IPEndPoint(hostAddresses[hostAddresses.Length - 1], port);
this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
}
/// <summary>
/// 连接服务端
/// </summary>
/// <returns></returns>
private bool Connect()
{
using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
{
try
{
args.UserToken = this.clientSocket;
args.RemoteEndPoint = this.hostEndPoint;
args.Completed += new EventHandler<SocketAsyncEventArgs>(this.OnConnect);
this.clientSocket.ConnectAsync(args);
bool flag = autoConnectEvent.WaitOne(1000);
//SocketError err = args.SocketError;
if (this.connected)
{
this.lisnterSocketAsyncEventArgs = new SocketAsyncEventArgs();
byte[] buffer = new byte[50];
this.lisnterSocketAsyncEventArgs.UserToken = this.clientSocket;
this.lisnterSocketAsyncEventArgs.SetBuffer(buffer, 0, buffer.Length);
this.lisnterSocketAsyncEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(this.OnReceive);
this.StartListen();
return true;
}
}
catch
{ }
return false;
}
}
/// <summary>
/// 判断有没有连接上
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnConnect(object sender, SocketAsyncEventArgs e)
{
this.connected = (e.SocketError == SocketError.Success);
autoConnectEvent.Set();
}
/// <summary>
/// 发送
/// </summary>
/// <param name="mes"></param>
public void Send(Byte[] mes)
{
if (this.connected)
{
EventHandler<SocketAsyncEventArgs> handler = null;
byte[] buffer = mes;
SocketAsyncEventArgs senderSocketAsyncEventArgs = null;
lock (s_lst)
{
if (s_lst.Count > 0)
{
senderSocketAsyncEventArgs = s_lst[s_lst.Count - 1];
s_lst.RemoveAt(s_lst.Count - 1);
}
}
if (senderSocketAsyncEventArgs == null)
{
senderSocketAsyncEventArgs = new SocketAsyncEventArgs();
senderSocketAsyncEventArgs.UserToken = this.clientSocket;
senderSocketAsyncEventArgs.RemoteEndPoint = this.clientSocket.RemoteEndPoint;
if (handler == null)
{
handler = delegate (object sender, SocketAsyncEventArgs _e)
{
lock (s_lst)
{
s_lst.Add(senderSocketAsyncEventArgs);
}
};
}
senderSocketAsyncEventArgs.Completed += handler;
}
senderSocketAsyncEventArgs.SetBuffer(buffer, 0, buffer.Length);
this.clientSocket.SendAsync(senderSocketAsyncEventArgs);
}
else
{
this.connected = false;
}
}
/// <summary>
/// 监听服务端
/// </summary>
public void Listen()
{
if (this.connected && this.clientSocket != null)
{
try
{
(lisnterSocketAsyncEventArgs.UserToken as Socket).ReceiveAsync(lisnterSocketAsyncEventArgs);
}
catch (Exception)
{
}
}
}
/// <summary>
/// 断开连接
/// </summary>
/// <returns></returns>
private int Disconnect()
{
int res = 0;
try
{
this.clientSocket.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
}
try
{
this.clientSocket.Close();
}
catch (Exception)
{
}
this.connected = false;
return res;
}
/// <summary>
/// 数据接受
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnReceive(object sender, SocketAsyncEventArgs e)
{
if (e.BytesTransferred == 0)
{
try
{
this.clientSocket.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
}
finally
{
if (this.clientSocket.Connected)
{
this.clientSocket.Close();
}
}
byte[] info = new Byte[] { 0 };
this.OnMsgReceived(info);
}
else
{
byte[] buffer = new byte[e.BytesTransferred];
for (int i = 0; i < e.BytesTransferred; i++)
{
buffer[i] = e.Buffer[i];
}
this.OnMsgReceived(buffer);
Listen();
}
}
/// <summary>
/// 接受完成
/// </summary>
/// <param name="info"></param>
private void SimaticSocketClient_OnMsgReceived(byte[] info)
{
if (info[0] != 0)
{
for (byte len = 0; len < info.Length; len++)
{
if (Offset < 24)
{
RecvData_Temp[Offset] = info[len];
Offset++;
}
}
}
else
{
for (byte i = 0; i < 24; i++)
{
RecvData_Temp[i] = 0;
}
Offset = 0;
}
}
/// <summary>
/// 建立连接的方法
/// </summary>
/// <returns></returns>
public bool OpenLinkPLC()
{
bool flag = false;
this.StartListen += new StartListeHandler(SimaticSocketClient_StartListen);
this.OnMsgReceived += new ReceiveMsgHandler(SimaticSocketClient_OnMsgReceived);
flag = this.Connect();
if (!flag)
{
return flag;
}
return true;
}
/// <summary>
/// 关闭连接的方法
/// </summary>
/// <returns></returns>
public int CloseLinkPLC()
{
return this.Disconnect();
}
/// <summary>
/// 监听的方法
/// </summary>
private void SimaticSocketClient_StartListen()
{
this.Listen();
}
#region STM数据
private object write_obj = new object();
/// <summary>
/// 写一个数据
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public int WriteInfo(int value_fx, int value_mb, int value_control)
{
lock (write_obj)
{
int flag = -1;
byte[] data = new byte[15];
data[0] = 0xF3;
data[1] = 0x01;
data[2] = Convert.ToByte(value_fx);
data[3] = 0x00;
data[4] = Convert.ToByte(value_mb % 256);
data[5] = Convert.ToByte(value_mb / 256);
data[6] = 0x00;
data[7] = 0x00;
data[8] = Convert.ToByte(value_control);
data[9] = 0x00;
data[10] = 0x00;
data[11] = 0x00;
data[12] = 0x00;
data[13] = 0x00;
data[14] = 0xCF;
data[13] = (FCS(data))[0];
int numPro = 0;
Offset = 0;
RecvData_Temp[0] = 0;
RecvData_Temp[1] = 0;
RecvData_Temp[22] = 0;
RecvData_Temp[23] = 0;
this.Send(data);
while ((RecvData_Temp[0] == 0 || RecvData_Temp[23] == 0) && numPro < 350)
{
Thread.Sleep(2);
numPro++;
}
if (numPro < 350)
{
if (RecvData_Temp[0] == 0xF3 && RecvData_Temp[1] == 0x02 && RecvData_Temp[23] == 0xCF)
{
flag = 0;//成功
}
}
Offset = 0;
RecvData_Temp[0] = 0;
RecvData_Temp[1] = 0;
RecvData_Temp[22] = 0;
RecvData_Temp[23] = 0;
return flag;
}
}
#endregion
/************************************************************************/
/* Description: 写入数据(向AGV写入状态)
/* Time:2018/04/10 13时50分20秒
/* Author:WANGZHEN
/************************************************************************/
/// <summary>
/// 写入数据(向AGV写入状态)
/// 目标地址+放行+取料/放料状态
/// value_mb:目标地址,isDrop 1是放料,2是取料
/// </summary>
/// <param name="results"></param>
/// <returns></returns>
public int WriteInfo(int value_mb, int isDrop, out byte[] results)
{
lock (write_obj)
{
int flag = -1;
byte[] data = new byte[15];
data[0] = 0xF3;
data[1] = 0x01;
data[2] = 0x01;
data[3] = 0x00;
data[4] = Convert.ToByte(value_mb % 256);
data[5] = Convert.ToByte(value_mb / 256);
data[6] = 0x00;
data[7] = 0x00;
data[8] = 0x00;
data[9] = Convert.ToByte(isDrop);
data[10] = 0x00;
data[11] = 0x00;
data[12] = 0x00;
data[13] = 0x00;
data[14] = 0xCF;
data[13] = (FCS(data))[0];
results = new byte[24];
for (byte i = 0; i < 24; i++)
results[i] = 0;
int numPro = 0;
Offset = 0;
RecvData_Temp[0] = 0;
RecvData_Temp[1] = 0;
RecvData_Temp[22] = 0;
RecvData_Temp[23] = 0;
this.Send(data);
while ((RecvData_Temp[0] == 0 || RecvData_Temp[23] == 0) && numPro < 350)
{
Thread.Sleep(2);
numPro++;
}
if (numPro < 350)
{
if (RecvData_Temp[0] == 0xF3 && RecvData_Temp[1] == 0x02 && RecvData_Temp[23] == 0xCF)
{
flag = 0;//成功
for (byte i = 0; i < 23; i++)
{
results[i] = RecvData_Temp[i];
}
}
}
Offset = 0;
RecvData_Temp[0] = 0;
RecvData_Temp[1] = 0;
RecvData_Temp[22] = 0;
RecvData_Temp[23] = 0;
return flag;
}
}
private byte[] FCS(byte[] b)
{
int num2 = 0;
byte[] recValue = new byte[2];
//byte[]b=new byte[30] {0x46, 0x39, 0x30, 0x30, 0x30, 0x30, 0x46, 0x46, 0x30, 0x30, 0x30, 0x34, 0x30, 0x31, 0x30, 0x30, 0x30, 0x30, 0x44, 0x2A , 0x30 , 0x30 , 0x31 , 0x36, 0x31 , 0x36 , 0x30 , 0x30 , 0x30 , 0x31};
for (int i = 0; i < b.Length - 1; i++)
{
num2 += b[i];
}
string s = num2.ToString("X2").Substring(num2.ToString("X2").Length - 2, 2);
//recValue = Encoding.ASCII.GetBytes(s);
recValue = strToToHexByte(s);
return recValue;
}
private static byte[] strToToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
int Offset = 0;
private byte[] RecvData_Temp = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
#region STM值
private object read_obj = new object();
/// <summary>
/// 读值
/// </summary>
/// <param name="alarmvalue"></param>
/// <param name="posvalue"></param>
/// <returns></returns>
public int ReadInfo(out int[] results)
{
lock (read_obj)
{
int flag = -1;
Byte[] data = new Byte[15];
results = new int[24];
for (byte i = 0; i < results.Length; i++)
{
results[i] = 0;
}
data[0] = 0xF3;
data[1] = 0x0A;
data[2] = 0x00;
data[3] = 0x00;
data[4] = 0x00;
data[5] = 0x00;
data[6] = 0x00;
data[7] = 0x00;
data[8] = 0x00;
data[9] = 0x00;
data[10] = 0x00;
data[11] = 0x00;
data[12] = 0x00;
data[13] = 0x00;
data[14] = 0xCF;
data[13] = (FCS(data))[0];
int numPro = 0;
Offset = 0;
RecvData_Temp[0] = 0;
RecvData_Temp[1] = 0;
RecvData_Temp[23] = 0;
this.Send(data);
while ((RecvData_Temp[0] == 0 || RecvData_Temp[23] == 0) && numPro < 350)
{
Thread.Sleep(2);
numPro++;
}
if (numPro < 350)
{
if (RecvData_Temp[0] == 0xF3 && RecvData_Temp[1] == 0x0B && RecvData_Temp[23] == 0xCF)
{
flag = 0;
for (byte i = 0; i < 23; i++)
{
results[i] = RecvData_Temp[i];
}
}
else
{
if (RecvData_Temp[23] == 0)
{
flag = -3;
}
}
}
Offset = 0;
RecvData_Temp[0] = 0;
RecvData_Temp[1] = 0;
RecvData_Temp[22] = 0;
RecvData_Temp[23] = 0;
return flag;
}
}
#endregion
#region IDispose member
public void Dispose()
{
if (this.clientSocket.Connected)
{
this.clientSocket.Close();
}
}
#endregion
}
}
@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace AGVSystem.Cls
{
public static class SocketExtensions
{
private const int BytesPerLong = 4; // 32 / 8
private const int BitsPerByte = 8;
/// <summary>
/// Sets the keep-alive interval for the socket.
/// </summary>
/// <param name="socket">The socket.</param>
/// <param name="time">Time between two keep alive "pings".</param>
/// <param name="interval">Time between two keep alive "pings" when first one fails.</param>
/// <returns>If the keep alive infos were succefully modified.</returns>
public static bool SetKeepAlive(this Socket socket, ulong time, ulong interval)
{
try
{
// Array to hold input values.
var input = new[]
{
(time == 0 || interval == 0) ? 0UL : 1UL, // on or off
time,
interval
};
// Pack input into byte struct.
byte[] inValue = new byte[3 * BytesPerLong];
for (int i = 0; i < input.Length; i++)
{
inValue[i * BytesPerLong + 3] = (byte)(input[i] >> ((BytesPerLong - 1) * BitsPerByte) & 0xff);
inValue[i * BytesPerLong + 2] = (byte)(input[i] >> ((BytesPerLong - 2) * BitsPerByte) & 0xff);
inValue[i * BytesPerLong + 1] = (byte)(input[i] >> ((BytesPerLong - 3) * BitsPerByte) & 0xff);
inValue[i * BytesPerLong + 0] = (byte)(input[i] >> ((BytesPerLong - 4) * BitsPerByte) & 0xff);
}
// Create bytestruct for result (bytes pending on server socket).
byte[] outValue = BitConverter.GetBytes(0);
// Write SIO_VALS to Socket IOControl.
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);
socket.IOControl(IOControlCode.KeepAliveValues, inValue, outValue);
}
catch (SocketException e)
{
Console.WriteLine("Failed to set keep-alive: {0} {1}", e.ErrorCode, e);
return false;
}
return true;
}
}
}
@@ -0,0 +1,145 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace AGVSystem
{
public class WriteTxt
{
//private static object obj = new object();
//public static void writeTxt(string info)
//{
// lock (obj)
// {
// string path = Application.StartupPath + "\\log\\" + DateTime.Now.ToLongDateString() + ".txt";
// string str = DateTime.Now.ToLongTimeString() + info;
// if (!File.Exists(path))
// {
// FileStream fs1 = new FileStream(path, FileMode.Append, FileAccess.Write);
// StreamWriter sw = new StreamWriter(fs1);
// sw.WriteLine(str);
// sw.Close();
// fs1.Close();
// }
// else
// {
// FileStream fs1 = new FileStream(path, FileMode.Append, FileAccess.Write);
// StreamWriter sw = new StreamWriter(fs1);
// sw.Write(str + "\r\n");
// sw.Close();
// fs1.Close();
// }
// }
//}
private static object obj_saveLog1 = new object();
/// <summary>
/// AGV读取的地标值记录
/// </summary>
/// <param name="fileMsg">日志文件路径</param>
/// <param name="filename">文件名称</param>
/// <param name="Assembly_name">线体名称</param>
public static void SaveLog1(string fileMsg, string filename, string Assembly_name )
{
lock (obj_saveLog1)
{
try
{
using (FileStream _fStream = new FileStream(GetFilePath1(filename, Assembly_name) , FileMode.Append, FileAccess.Write))
{
using (StreamWriter _sWrite = new StreamWriter(_fStream))
{
_sWrite.WriteLine(GetCurrentTimeString() + fileMsg);
_sWrite.Close();
_fStream.Close();
}
}
}
catch (Exception)
{
SaveLog1(fileMsg, filename, Assembly_name);
}
}
}
private static string GetCurrentTimeString()
{
return "[" + DateTime.Now.ToLongTimeString() + "]";//+ "." + DateTime.Now.Millisecond.ToString("000")
}
private static string GetFilePath1(string str, string Assembly_Name)
{
string path = Application.StartupPath + @"\log\" + DateTime.Now.ToString("yyyyMMdd")+@"\"+ Assembly_Name;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string pa = Application.StartupPath + @"\log\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + Assembly_Name;
if (!Directory.Exists(pa))
{
Directory.CreateDirectory(pa);
}
return pa + @"\" + str + "_.log";
}
private static object obj_saveLog2 = new object();
public static void SaveLog2(string fileMsg)
{
lock (obj_saveLog2)
{
try
{
if (!Directory.Exists(@"c:\pathlog\"))
{
Directory.CreateDirectory(@"c:\pathlog\");
}
using (FileStream _fStream = new FileStream(@"c:\pathlog\" + DateTime.Now.ToString("yyyyMMdd") + "_.log", FileMode.Append, FileAccess.Write))
{
using (StreamWriter _sWrite = new StreamWriter(_fStream))
{
_sWrite.WriteLine(GetCurrentTimeString() + fileMsg);
_sWrite.Close();
_fStream.Close();
}
}
}
catch (Exception)
{
SaveLog2(fileMsg);
}
}
}
private static object obj_saveLog3 = new object();
public static void SaveLog3(string fileMsg,string id)
{
lock (obj_saveLog3)
{
try
{
if (!Directory.Exists(@"c:\neclog\" + DateTime.Now.ToString("yyyyMMdd")))
{
Directory.CreateDirectory(@"c:\neclog\" + DateTime.Now.ToString("yyyyMMdd"));
}
using (FileStream _fStream = new FileStream(@"c:\neclog\" + DateTime.Now.ToString("yyyyMMdd") +@"\"+id+ "_.log", FileMode.Append, FileAccess.Write))
{
using (StreamWriter _sWrite = new StreamWriter(_fStream))
{
_sWrite.WriteLine(GetCurrentTimeString() + fileMsg);
_sWrite.Close();
_fStream.Close();
}
}
}
catch (Exception)
{
SaveLog3(fileMsg,id);
}
}
}
}
}