123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209 |
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Threading;
- using AGV_WPF_Global;
- using System.Data.OleDb;
- using System.Xml.Serialization;
- using System.IO;
- using System.Threading.Tasks;
- using AGV_WPF.Models;
- using HslCommunication;
- using AGV_WPF.Tools;
- using System.Diagnostics;
- namespace AGV_WPF
- {
- public partial class DispatchSystem : Form
- {
- DataTable dtConfig = new DataTable();
- HslCommunication.OperateResult result;
- int HeartBitCount = 1;
- private delegate void InvokeDelegate();
- Dictionary<int, string> checkPosDic = new Dictionary<int, string>();
- Dictionary<int, int> AGVIDWithPosByCheckPos = new Dictionary<int, int>();
- Dictionary<int, int> AGVIDWithRouteByCheckPos = new Dictionary<int, int>();
- Dictionary<string, byte> DBWithByteValue = new Dictionary<string, byte>();
- private static object portLock = new object();
- Stopwatch sw = new Stopwatch();
- Dictionary<int, CFDClass> dicReleaseArea = new Dictionary<int, CFDClass>();
- public int CurCFDRoute = -1;
- Dictionary<string, bool> InitOK = new Dictionary<string, bool>();
- public DispatchSystem()
- {
- InitializeComponent();
- }
- private void DispatchSystem_Load(object sender, EventArgs e)
- {
- LoadConfig();
- this.FormClosing += new FormClosingEventHandler(DispatchSystem_FormClosing);
- Thread thread2 = new Thread(HeartBit);
- thread2.Start();
- Thread thread = new Thread(Analzye);
- thread.Start();
- }
- void DispatchSystem_FormClosing(object sender, FormClosingEventArgs e)
- {
- e.Cancel = true;
- }
- /// <summary>
- /// 加载配置
- /// </summary>
- public void LoadConfig()
- {
- sw.Restart();
- tabControl1.TabPages.Clear();
- 物料设置ToolStripMenuItem.DropDownItems.Clear();
- checkPosDic.Clear();
- AGVIDWithPosByCheckPos.Clear();
- DBWithByteValue.Clear();
- HeartBitCount = 1;
- XmlSerializer deserializer1 = new XmlSerializer(GlobalPara.gs_configInfo.GetType());
- try
- {
- using (TextReader tr = new StreamReader("CConfig.xml"))
- {
- GlobalPara.gs_configInfo = (AGV_WPF.Tools.CConfigData)deserializer1.Deserialize(tr);
- }
- }
- catch (Exception ex)
- { }
- string currPath = System.AppDomain.CurrentDomain.BaseDirectory;
- string dataPath = currPath + @"data";
- string dataFile = dataPath + @"\基础配置表.xls";
- try
- {
- string confStr1 = @"Provider=Microsoft.ACE.OLEDB.12.0;";
- string confStr2 = @"Persist Security Info=false;";
- string confStr3 = @"Data Source=" + dataFile + ";";
- string confStr4 = @"Extended Properties=" + "'Excel 12.0;HDR=YES;IMEX=1'";
- string connStr = confStr1 + confStr2 + confStr3 + confStr4;
- OleDbConnection oleDC = new OleDbConnection(connStr);
- OleDbDataAdapter oleDDA1 = new OleDbDataAdapter("Select * From [参数配置$]", oleDC);
- oleDDA1.Fill(dtConfig);
- OleDbDataAdapter oleDDA2 = new OleDbDataAdapter("Select * From [物料类型$]", oleDC);
- DataTable temp = new DataTable();
- oleDDA2.Fill(temp);
- if (temp.Rows.Count > 0)
- {
- for (int i = 0; i < temp.Rows.Count; i++)
- {
- ToolStripMenuItem tsm = new ToolStripMenuItem(temp.Rows[i][1].ToString());
- 物料设置ToolStripMenuItem.DropDownItems.Add(tsm);
- tsm.Font = new Font("黑体", 15);
- if (GlobalPara.gs_configInfo.CurrentMatName == temp.Rows[i][1].ToString())
- {
- tsm.CheckState = CheckState.Checked;
- }
- tsm.Click += new EventHandler(tsm_Click);
- }
- }
- tabControl1.DrawMode = TabDrawMode.Normal;
- tabControl1.SizeMode = TabSizeMode.Fixed;
- tabControl1.DrawItem += new DrawItemEventHandler(tabControl1_DrawItem);
- GlobalPara.s7 = new HslCommunication.Profinet.Siemens.SiemensS7Net(HslCommunication.Profinet.Siemens.SiemensPLCS.S1500,
- dtConfig.Rows[0][1].ToString());
- GlobalPara.s7.Rack = (byte)Convert.ToInt16(dtConfig.Rows[2][1].ToString());
- GlobalPara.s7.Slot = (byte)Convert.ToInt16(dtConfig.Rows[3][1].ToString());
- GlobalPara.s7.ConnectTimeOut = 200;
- GlobalPara.s7.ReceiveTimeOut = 200;
- result = GlobalPara.s7.ConnectServer();
- sw.Stop();
- Console.WriteLine("配置初始化总共花费{0}s.", sw.Elapsed.TotalSeconds);
- sw.Restart();
- InitView();
- sw.Stop();
- Console.WriteLine("界面初始化总共花费{0}s.", sw.Elapsed.TotalSeconds);
- }
- catch (System.Exception ex)
- {
- MessageBox.Show(ex.StackTrace);
- }
- }
- void tsm_Click(object sender, EventArgs e)
- {
- for (int i = 0; i < 物料设置ToolStripMenuItem.DropDownItems.Count; i++)
- {
- if (((ToolStripMenuItem)物料设置ToolStripMenuItem.DropDownItems[i]).Text == ((ToolStripMenuItem)sender).Text
- && ((ToolStripMenuItem)sender).CheckState == CheckState.Checked)
- {
- return;
- }
- ((ToolStripMenuItem)物料设置ToolStripMenuItem.DropDownItems[i]).CheckState = CheckState.Unchecked;
- }
- ((ToolStripMenuItem)sender).Checked = true;
- GlobalPara.gs_configInfo.CurrentMatName = ((ToolStripMenuItem)sender).Text;
- XmlSerializer serializer2 = new XmlSerializer(GlobalPara.gs_configInfo.GetType());
- using (TextWriter tw = new StreamWriter("CConfig.xml"))
- {
- serializer2.Serialize(tw, GlobalPara.gs_configInfo);
- }
- this.DispatchSystem_Load(null, null);
- }
- void tsm_CheckedChanged(object sender, EventArgs e)
- {
- //throw new NotImplementedException();
- }
- void tsm_CheckStateChanged(object sender, EventArgs e)
- {
- //throw new NotImplementedException();
- }
- /// <summary>
- /// 界面初始化
- /// </summary>
- /// <param name="temp"></param>
- public void InitView()
- {
- string currPath = System.AppDomain.CurrentDomain.BaseDirectory;
- string dataPath = currPath + @"data\";
- string dataFile = dataPath + GlobalPara.gs_configInfo.CurrentMatName + ".xls";
- if (false == File.Exists(dataFile))
- {
- DirectoryInfo di = new DirectoryInfo(dataPath);
- foreach (FileInfo f in di.GetFiles())
- {
- if (f.Name != "基础配置表" && f.Extension.Contains(".xls"))
- {
- GlobalPara.gs_configInfo.CurrentMatName = f.Name.Replace(".xls", "");
- for (int i = 0; i < 物料设置ToolStripMenuItem.DropDownItems.Count; i++)
- {
- if (物料设置ToolStripMenuItem.DropDownItems[i].Text == GlobalPara.gs_configInfo.CurrentMatName)
- {
- ((ToolStripMenuItem)物料设置ToolStripMenuItem.DropDownItems[i]).CheckState = CheckState.Checked;
- }
- }
- dataFile = f.FullName;
- break;
- }
- }
- }
- try
- {
- string confStr1 = @"Provider=Microsoft.ACE.OLEDB.12.0;";
- string confStr2 = @"Persist Security Info=false;";
- string confStr3 = @"Data Source=" + dataFile + ";";
- string confStr4 = @"Extended Properties=" + "'Excel 12.0;HDR=YES;IMEX=1'";
- string connStr = confStr1 + confStr2 + confStr3 + confStr4;
- OleDbConnection oleDC = new OleDbConnection(connStr);
- OleDbDataAdapter oleDDA2 = new OleDbDataAdapter("Select * From [线体信息$]", oleDC);
- DataTable LineDt = new DataTable();
- oleDDA2.Fill(LineDt);
- Dictionary<Thread, object[]> listThread = new Dictionary<Thread, object[]>();
- for (int i = 0; i < LineDt.Rows.Count; i++)
- {
- string lineName = LineDt.Rows[i]["线体名称"].ToString();
- TabPage tb = new TabPage(lineName);
- tb.Font = new System.Drawing.Font("楷体", tb.Font.Size + 5);
- oleDDA2 = new OleDbDataAdapter("Select * From [" + lineName + "$]", oleDC);
- DataTable temp2 = new DataTable();
- temp2.TableName = lineName;
- oleDDA2.Fill(temp2);
- if (LineDt.Rows[i]["判断点"] != null && !string.IsNullOrEmpty(LineDt.Rows[i]["判断点"].ToString()) && LineDt.Rows[i]["判断点"].ToString() != "0")
- {
- if (!checkPosDic.ContainsKey(int.Parse(LineDt.Rows[i]["判断点"].ToString())))
- {
- checkPosDic.Add(int.Parse(LineDt.Rows[i]["判断点"].ToString()), lineName);
- }
- }
- int X = 10, Y = 10;
- List<Button> listBtn = new List<Button>();
- for (int j = 1; j <= temp2.Rows.Count; j++)
- {
- if (temp2.Columns.Contains("组号") && !dicReleaseArea.ContainsKey(int.Parse(temp2.Rows[j - 1]["组号"].ToString())))
- {
- dicReleaseArea.Add(int.Parse(temp2.Rows[j - 1]["组号"].ToString()), null);
- }
- if (temp2.Rows[j - 1]["放行DB"] != null && !string.IsNullOrEmpty(temp2.Rows[j - 1]["放行DB"].ToString()) && temp2.Rows[j - 1]["放行DB"].ToString() != "0")
- {
- if (!DBWithByteValue.ContainsKey((temp2.Rows[j - 1]["放行DB"].ToString())))
- {
- DBWithByteValue.Add((temp2.Rows[j - 1]["放行DB"].ToString()), (byte)255);
- }
- }
- Button btn = new Button();
- btn.Text = temp2.Rows[j - 1][1].ToString();
- btn.Location = new Point(X, Y);
- btn.Font = new Font("宋体", 15);
- btn.Size = new Size(100, 80);
- btn.BackColor = Color.FromKnownColor(KnownColor.Control);
- X += btn.Size.Width + 20;
- if (j % 6 == 0)
- {
- X = 10; Y += btn.Height + 20;
- }
- btn.Tag = temp2.Rows[j - 1][2].ToString();
- tb.Controls.Add(btn);
- listBtn.Add(btn);
- }
- Tools.TabPageTag tt = new Tools.TabPageTag();
- tt.Table = temp2.Copy();
- tt.ListBtn = new List<Button>();
- tt.ListBtn.AddRange(listBtn);
- tb.Tag = tt;
- tabControl1.TabPages.Add(tb);
- object[] obj = new object[3];
- obj[0] = listBtn; obj[1] = 0; obj[2] = lineName;
- listThread.Add(new Thread(new ParameterizedThreadStart(DockingOpeare0)), obj);//.Start(listBtn);
- // DockingOpeare0(obj);
- // if (lineName == "充放电测试") { tabControl1.SelectedTab = tb; }
- }
- foreach (Thread t in listThread.Keys)
- {
- t.Start(listThread[t]);
- }
- // Thread.Sleep(8000);
- new Thread(new ThreadStart(checkingOperate)).Start();
- new Thread(new ThreadStart(CFDCheck)).Start();
- // new Thread(new ThreadStart(checkingRelease)).Start();
- }
- catch (System.Exception ex)
- {
- MessageBox.Show(ex.StackTrace);
- }
- }
- /// <summary>
- /// 判断点发送5次仍未放行的问题
- /// </summary>
- public void checkingRelease()
- {
- while (true)
- {
- if (AGVIDWithRouteByCheckPos.Count > 0)
- {
- List<AGVInfoModel> listModel = GlobalPara.AgvInfoDic.Values.ToList();
- ParallelLoopResult result = Parallel.ForEach<int>(AGVIDWithRouteByCheckPos.Keys, new ParallelOptions { MaxDegreeOfParallelism = 2 }, pos =>
- {
- IEnumerable<AGVInfoModel> temp = listModel.Where(o => o.AGVNUM == pos && (o.RUNSTATUS_Cur == 0x40)
- && AGVIDWithRouteByCheckPos.ContainsKey(o.AGVNUM) && AGVIDWithPosByCheckPos.ContainsKey(o.AGVNUM));
- if (temp.Count() > 0)
- {
- lock (AGVIDWithRouteByCheckPos)
- {
- if (AGVIDWithRouteByCheckPos.ContainsKey(pos))
- {
- AGVIDWithRouteByCheckPos.Remove(pos);
- }
- }
- }
- else
- {
- temp = listModel.Where(o => o.AGVNUM == pos && (o.RUNSTATUS_Cur == 0x43 || o.ALARMCODE == "9")
- && AGVIDWithRouteByCheckPos.ContainsKey(o.AGVNUM) && AGVIDWithPosByCheckPos.ContainsKey(o.AGVNUM));
- if (temp.Count() > 0)
- {
- int agvNum = temp.ToList()[0].AGVNUM;
- int mark = temp.ToList()[0].MARKNUM;
- DispatcherTool.ReleaseAgvOnStop(mark, AGVIDWithRouteByCheckPos[agvNum], AGVIDWithPosByCheckPos[agvNum]);
- }
- }
- });
- if (result.IsCompleted)
- {
- Console.WriteLine("判断点放行任务总共花费{0}s.", sw.Elapsed.TotalSeconds);
- // new Thread(new ThreadStart(checkingRelease)).Start();
- }
- }
- else
- {
- // new Thread(new ThreadStart(checkingRelease)).Start();
- }
- Thread.Sleep(200);
- }
- }
- /// <summary>
- /// 判断点事件
- /// </summary>
- public void checkingOperate()
- {
- Stopwatch sw2 = new Stopwatch();
- List<AGVInfoModel> listModel = GlobalPara.AgvInfoDic.Values.ToList();
- ParallelLoopResult result = Parallel.ForEach<int>(checkPosDic.Keys, new ParallelOptions { MaxDegreeOfParallelism = 2 }, pos =>
- {
- IEnumerable<AGVInfoModel> temp = listModel.Where(o => o.MARKNUM == pos && (o.RUNSTATUS_Cur == 0x43 || o.ALARMCODE == "9") && !AGVIDWithPosByCheckPos.ContainsKey(o.AGVNUM));
- if (temp.Count() > 0)
- {
- int num = temp.ToList()[0].AGVNUM;
- if (!AGVIDWithPosByCheckPos.ContainsKey(num))
- {
- string lineName = checkPosDic[pos];
- for (int i = 0; i < this.tabControl1.TabPages.Count; i++)
- {
- if (this.tabControl1.TabPages[i].Text == lineName && InitOK.ContainsKey(lineName)&&InitOK[lineName])
- {
- TabPageTag tag = this.tabControl1.TabPages[i].Tag as TabPageTag;
- DataRow[] drs = null;
- if (lineName != "充放电测试")
- {
- drs = tag.Table.Select("优先级>0", "优先级 asc");
- }
- else
- {
- if (CurCFDRoute < 0)
- {
- drs = tag.Table.Select("优先级>0", "优先级 asc");
- }
- else
- {
- drs = tag.Table.Select("优先级>0 and 放行路线='" + CurCFDRoute + "'", "优先级 asc");
- }
- }
- List<string> ChannelDB = new List<string>();
- bool b = false;
- bool b3 = false;
- for (int j = 0; j < drs.Length; j++)
- {
- if (tag.Table.Columns.Contains("通道DB"))
- {
- string releaseAddress = drs[j]["通道DB"].ToString();
- if (releaseAddress != "0")
- {
- if (!ChannelDB.Contains(releaseAddress))
- {
- OperateResult<byte> resultRead = GlobalPara.s7.ReadByte(releaseAddress);
- if (resultRead.IsSuccess)
- {
- if (resultRead.Content == (byte)0)
- {
- b = true;
- }
- else
- {
- ChannelDB.Add(releaseAddress);
- continue;
- }
- }
- }
- else
- {
- continue;
- }
- }
- else { b = true; }
- }
- else
- {
- b = true;
- }
- if (b)
- {
- // IEnumerable<DataRow> query =
- //from data in tag.Table.AsEnumerable()
- //group data by data["路线"] into g
- //select g.First();
- Button btn = tag.ListBtn.Find(o => o.Tag.ToString() == drs[j]["工位地标"].ToString() && !AGVIDWithPosByCheckPos.ContainsValue(int.Parse(o.Tag.ToString()))
- && (o.BackColor == Color.FromKnownColor(KnownColor.Control)
- || o.BackColor == Color.FromKnownColor(KnownColor.Green)) && o.BackColor != Color.FromKnownColor(KnownColor.Blue));
- if (btn != null)
- {
- if (lineName == "充放电测试")
- {
- DataRow[] temp2 = tag.Table.Select("放行路线='" + drs[j]["放行路线"].ToString() + "'", "ID asc");
- if (temp2.Count() > 1)
- {
- int indexFirst = tag.Table.Rows.IndexOf(temp2[0]);
- if (indexFirst >= 0 && indexFirst != j)
- {
- Button btn2 = tag.ListBtn.Find(o => o.Tag.ToString() == tag.Table.Rows[indexFirst]["工位地标"].ToString() &&
- (o.BackColor == Color.Yellow || o.BackColor == Color.Blue));
- if (btn2 == null)
- {
- continue;
- }
- }
- else if (indexFirst >= 0 && indexFirst == j)
- {
- bool b2 = true;
- for (int a = 1; a < temp2.Length; a++)
- {
- Button btn2 = tag.ListBtn.Find(o => o.Tag.ToString() == temp2[a]["工位地标"].ToString()
- && o.BackColor == Color.FromKnownColor(KnownColor.Control));
- if (btn2 == null) { b2 = false; break; }
- }
- if (!b2)
- {
- continue;
- }
- }
- }
- }
- //找到目的站点,放行路线
- AGVIDWithPosByCheckPos.Add(num, int.Parse(drs[j]["工位地标"].ToString()));
- AGVIDWithRouteByCheckPos.Add(num, int.Parse(drs[j]["放行路线"].ToString()));
- DispatcherTool.ReleaseAgvOnStop(pos, int.Parse(drs[j]["放行路线"].ToString()), int.Parse(drs[j]["工位地标"].ToString()));
- if (btn.BackColor != Color.FromKnownColor(KnownColor.Blue))
- {
- btn.BackColor = Color.Blue;
- }
- if (lineName == "充放电测试")
- {
- CurCFDRoute = int.Parse(drs[j]["放行路线"].ToString());
- }
- b3 = true;
- break;
- }
- }
- else
- {
- if (lineName == "充放电测试")
- {
- CurCFDRoute = -1;
- }
- }
- }
- if (!b3)
- {
- if (lineName == "充放电测试")
- {
- CurCFDRoute = -1;
- }
- }
- }
- }
- }
- }
- });
- if (result.IsCompleted)
- {
- sw2.Stop();
- Console.WriteLine("判断点任务总共花费{0}s.", sw.Elapsed.TotalSeconds);
-
- new Thread(new ThreadStart(checkingOperate)).Start();
- }
- }
- public void CFDCheck()
- {
- ParallelLoopResult result2;
- try
- {
- List<int> list = dicReleaseArea.Keys.ToList();
- result2 = Parallel.ForEach<int>(list, new ParallelOptions { MaxDegreeOfParallelism = 2 }, key =>
- {
- if (dicReleaseArea[key] != null)
- {
- List<Button> listBtn = dicReleaseArea[key].btns;
- if (listBtn != null && listBtn.Count > 0)
- {
- var result = listBtn.AsParallel().Where(o => o.BackColor == Color.FromKnownColor(KnownColor.Control));
- if (result != null && result.Count() == listBtn.Count)
- {
- CFDClass cfd = dicReleaseArea[key];
- lock (dicReleaseArea)
- {
- dicReleaseArea[key] = null;
- }
- WriteFile("充放电记录", "(" + cfd.number + "," + cfd.numberInner + ") 组放行完成,已解锁");
- }
- }
- }
- });
- if (result2.IsCompleted)
- {
- new Thread(new ThreadStart(CFDCheck)).Start();
- }
- }
- catch (Exception ex)
- {
- DateTime time = DateTime.Now;
- //MessageBox.Show("线程异常:"+e.ExceptionObject);
- FileStream stream = File.Open(@"Exception\调度程序异常.txt", FileMode.Append, FileAccess.Write);
- StreamWriter writer = new StreamWriter(stream);
- if (ex != null)
- {
- string msg = string.Format("[{0}]Test:\r\nMessage:{1}\r\nStackTrace:\r\n{2}", time.ToString("yyyy-MM-dd HH:mm:ss"), ex.Message, ex.StackTrace);
- writer.WriteLine(msg);
- writer.Close();
- stream.Close();
- }
-
- new Thread(new ThreadStart(CFDCheck)).Start();
- }
- }
- public void DockingOpeare0(object o)
- {
- object[] obj = (object[])o;
- DockingOpeare((List<Button>)obj[0], (int)obj[1],(string)obj[2]);
- }
- /// <summary>
- /// 工位事件
- /// </summary>
- /// <param name="listBtn"></param>
- public void DockingOpeare(List<Button> listBtn, int tag,string lineName)
- {
- ParallelLoopResult result2;
- try
- {
- Stopwatch sw2 = new Stopwatch();
- List<Button> list = (List<Button>)listBtn;
- // TabPageTag tag = this.tabControl1.TabPages[i].Tag as TabPageTag;
- DataTable dt = (list[0].Parent.Tag as TabPageTag).Table;
- List<AGVInfoModel> listModel = GlobalPara.AgvInfoDic.Values.ToList();
- List<int> list2 = AGVIDWithPosByCheckPos.Values.ToList();
- // while (true)
- {
- // for (int i = 0; i < list.Count; i++)
- result2 = Parallel.ForEach<Button>(list, new ParallelOptions { MaxDegreeOfParallelism = 2 }, btn =>
- {
- //if (list2.Contains((int)btn.Tag))
- //{
- // IEnumerable<AGVInfoModel> temp = listModel.Where(o => o.MARKNUM.ToString() == btn.Tag.ToString() && o.ConnectStatus == true);
- // btn.Invoke(new InvokeDelegate(delegate
- // {
- // if (btn.BackColor != Color.FromKnownColor(KnownColor.Blue))
- // {
- // btn.BackColor = Color.Blue;
- // }
- // }));
- //}
- //else
- {
- // Button btn = list[i];
- // if (btn.Tag != null)
- {
- IEnumerable<AGVInfoModel> temp = listModel.Where(o => o.MARKNUM.ToString() == btn.Tag.ToString() && o.ConnectStatus == true);
- IEnumerable<DataRow> query =
- from order in dt.AsEnumerable()
- where order["工位地标"].ToString() == btn.Tag.ToString()
- select order;
- if (temp.Count() > 0)
- {
-
- IEnumerable<AGVInfoModel> temp2 = temp.Where(o => ((o.RUNSTATUS_Cur == 0x43 || o.RUNSTATUS_Cur == 0x44)
- && o.ConnectStatus == true && o.AGVNUM != 0));
- if (temp2.Count() > 0)
- {
- List<AGVInfoModel> infos = temp2.ToList();
- btn.Invoke(new InvokeDelegate(delegate
- {
- if (btn.BackColor != Color.FromKnownColor(KnownColor.Yellow))
- {
- AGVInfoModel info = infos[0];
- if (AGVIDWithPosByCheckPos.ContainsKey(info.AGVNUM))
- {
- AGVIDWithPosByCheckPos.Remove(info.AGVNUM);
- }
- if (AGVIDWithRouteByCheckPos.ContainsKey(info.AGVNUM))
- {
- AGVIDWithRouteByCheckPos.Remove(info.AGVNUM);
- }
- if (result != null && result.IsSuccess)
- {
- OperateResult rs = GlobalPara.s7.Write(query.ToList()[0]["AGVDB"].ToString(), (byte)info.AGVNUM);
- OperateResult rs2 = null;
- if (info.ALARMCODE != "5")
- {
- rs2 = GlobalPara.s7.Write(query.ToList()[0]["行驶状态DB"].ToString(), (byte)GlobalPara.DBRunValues.StopOnStation);
- }
- else //在工位上时 障碍物的状态也给停站状态
- {
- rs2 = GlobalPara.s7.Write(query.ToList()[0]["行驶状态DB"].ToString(), (byte)GlobalPara.DBRunValues.StopOnStation);
- }
- GlobalPara.s7.Write(query.ToList()[0]["故障DB"].ToString(), (byte)(int.Parse(info.ALARMCODE) - 1));
- if (rs.IsSuccess && rs2.IsSuccess)
- {
- btn.BackColor = Color.Yellow;
- }
- }
- }
- }));
- if (result != null && result.IsSuccess)
- {
- string releaseAddress = query.ToList()[0]["放行DB"].ToString();
- OperateResult<byte> resultRead = GlobalPara.s7.ReadByte(releaseAddress);
- if (resultRead.IsSuccess && DBWithByteValue.Keys.Contains(releaseAddress) &&
- DBWithByteValue[releaseAddress] != resultRead.Content)
- {
- if (resultRead.Content == (byte)GlobalPara.DBControlValues.OKRelease)
- {
- if (dt.TableName != "充放电测试")
- {
- DispatcherTool.ReleaseAgvOnStop(int.Parse(btn.Tag.ToString()),
- 0, int.Parse(query.ToList()[0]["目的地标"].ToString()));
- lock (portLock)
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- }
- else
- {
- WriteFile("充放电记录-信号切换", btn.Text + " 放行信号改变,原值为 " + DBWithByteValue[releaseAddress] + " ,新值为 " +
- resultRead.Content.ToString() + ",放行地址为 " + releaseAddress + ",地标为:" + btn.Tag.ToString());
- int number = int.Parse(query.ToList()[0]["组号"].ToString());
- int numberInner = int.Parse(query.ToList()[0]["组内号"].ToString());
- if (dicReleaseArea.ContainsKey(number))
- {
- if (dicReleaseArea[number] == null)
- {
- CFDClass cfd = new CFDClass();
- cfd.number = number;
- IEnumerable<int> query2 =
- from order in dt.AsEnumerable()
- where order["组内号"].ToString() == numberInner.ToString() && order["组号"].ToString() == number.ToString()
- select int.Parse(order["工位地标"].ToString());
- if (query2 != null && query2.Count() > 0)
- {
- cfd.btns = new List<Button>();
- foreach (int mark in query2.ToList())
- {
- cfd.btns.Add(list.AsParallel().First(o => o.Tag.ToString() == mark.ToString()));
- }
- }
- cfd.number = number;
- cfd.numberInner = int.Parse(query.ToList()[0]["组内号"].ToString());
- DispatcherTool.ReleaseAgvOnStop(int.Parse(btn.Tag.ToString()),
- 0, int.Parse(query.ToList()[0]["目的地标"].ToString()));
- lock (dicReleaseArea)
- {
- dicReleaseArea[number] = cfd;
- WriteFile("充放电记录", "(" + cfd.number + "," + cfd.numberInner + ") 组开始放行,已上锁,当前放行地标:" + btn.Tag.ToString());
- }
- lock (portLock)
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- }
- else
- {
- CFDClass cfd = dicReleaseArea[number];
- if (cfd.numberInner == numberInner && cfd.number == number)
- {
- DispatcherTool.ReleaseAgvOnStop(int.Parse(btn.Tag.ToString()),
- 0, int.Parse(query.ToList()[0]["目的地标"].ToString()));
- lock (portLock)
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- WriteFile("充放电记录", "(" + cfd.number + "," + cfd.numberInner + ") 组继续放行,已上锁,当前放行地标:" + btn.Tag.ToString());
- }
- }
- }
- }
- //走OK放行路线
- }
- else if (resultRead.Content == (byte)GlobalPara.DBControlValues.NGRelease)
- {
- if (dt.TableName != "充放电测试")
- {
- DispatcherTool.ReleaseAgvOnStop(int.Parse(btn.Tag.ToString()),
- int.Parse(query.ToList()[0]["NG路线"].ToString()));
- lock (portLock)
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- }
- else
- {
- int number = int.Parse(query.ToList()[0]["组号"].ToString());
- int numberInner = int.Parse(query.ToList()[0]["组内号"].ToString());
- if (dicReleaseArea.ContainsKey(number))
- {
- if (dicReleaseArea[number] == null)
- {
- CFDClass cfd = new CFDClass();
- cfd.number = number;
- IEnumerable<int> query2 =
- from order in dt.AsEnumerable()
- where order["组内号"].ToString() == numberInner.ToString() && order["组号"].ToString() == number.ToString()
- select int.Parse(order["工位地标"].ToString());
- if (query2 != null && query2.Count() > 0)
- {
- cfd.btns = new List<Button>();
- foreach (int mark in query2.ToList())
- {
- cfd.btns.Add(list.Find(o => o.Tag.ToString() == mark.ToString()));
- }
- }
- cfd.numberInner = int.Parse(query.ToList()[0]["组内号"].ToString());
- DispatcherTool.ReleaseAgvOnStop(int.Parse(btn.Tag.ToString()),
- int.Parse(query.ToList()[0]["NG路线"].ToString()));
- lock (dicReleaseArea)
- {
- dicReleaseArea[number] = cfd;
- }
- lock (portLock)
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- }
- else
- {
- CFDClass cfd = dicReleaseArea[number];
- if (cfd.numberInner == numberInner && cfd.number == number)
- {
- DispatcherTool.ReleaseAgvOnStop(int.Parse(btn.Tag.ToString()),
- int.Parse(query.ToList()[0]["NG路线"].ToString()));
- lock (portLock)
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- }
- }
- }
- }
- //走NG放行路线
- }
- else
- {
- if (resultRead.Content != (byte)GlobalPara.DBControlValues.StopImmediate)
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- }
- }
- }
- }
- else
- {
- IEnumerable<AGVInfoModel> temp3 = temp.Where(o => o.RUNSTATUS_Cur == 0x41 && o.ConnectStatus == true && o.AGVNUM != 0);
- if (temp3.Count() > 0)
- {
- AGVInfoModel info = temp3.ToList()[0];
- btn.Invoke(new InvokeDelegate(delegate
- {
- if (btn.BackColor != Color.FromKnownColor(KnownColor.Red))
- {
- if (AGVIDWithPosByCheckPos.ContainsKey(info.AGVNUM))
- {
- AGVIDWithPosByCheckPos.Remove(info.AGVNUM);
- }
- if (AGVIDWithRouteByCheckPos.ContainsKey(info.AGVNUM))
- {
- AGVIDWithRouteByCheckPos.Remove(info.AGVNUM);
- }
- if (result != null && result.IsSuccess)
- {
- OperateResult rs = GlobalPara.s7.Write(query.ToList()[0]["AGVDB"].ToString(), (byte)info.AGVNUM);
- OperateResult rs2 = null;
- if (info.ALARMCODE != "5")
- {
- rs2 = GlobalPara.s7.Write(query.ToList()[0]["行驶状态DB"].ToString(), (byte)GlobalPara.DBRunValues.Pause);
- }
- else
- {
- rs2 = GlobalPara.s7.Write(query.ToList()[0]["行驶状态DB"].ToString(), (byte)GlobalPara.DBRunValues.Running);
- }
- GlobalPara.s7.Write(query.ToList()[0]["故障DB"].ToString(), (byte)(int.Parse(info.ALARMCODE) - 1));
- if (btn.BackColor != Color.FromKnownColor(KnownColor.Blue))
- {
- if (rs.IsSuccess && rs2.IsSuccess)
- {
- btn.BackColor = Color.Red;
- }
- }
- }
- }
- }));
- if (info.ALARMCODE == "1")
- {
- if (result != null && result.IsSuccess)
- {
- string releaseAddress = query.ToList()[0]["放行DB"].ToString();
- OperateResult<byte> resultRead = GlobalPara.s7.ReadByte(releaseAddress);
- if (resultRead.IsSuccess && DBWithByteValue.Keys.Contains(releaseAddress) &&
- DBWithByteValue[releaseAddress] != resultRead.Content)
- {
- if (resultRead.Content == (byte)GlobalPara.DBControlValues.StopRelease)
- {
- lock (portLock)
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- DispatcherTool.ControlAGVBy1071(info.AGVNUM, 0);
- //放行被暂停的车
- WriteFile("急停记录", btn.Text + "工位被放行,已生成消息,当前放行地标:" + btn.Tag.ToString() + ",车号为:" + info.AGVNUM);
- }
- else if (resultRead.Content == (byte)GlobalPara.DBControlValues.OKRelease)
- {
- lock (portLock)
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- DispatcherTool.ReleaseAgvOnStop(int.Parse(btn.Tag.ToString()),
- int.Parse(query.ToList()[0]["放行路线"].ToString()));
- //放行被暂停的车
- WriteFile("充电点记录", btn.Text + "工位被放行,已生成消息,当前放行地标:" + btn.Tag.ToString() + ",车号为:" + info.AGVNUM);
- }
- else
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- }
- }
- }
- }
- else
- {
- IEnumerable<AGVInfoModel> temp4 = temp.Where(o => o.RUNSTATUS_Cur == 0x40 && o.ConnectStatus == true && o.AGVNUM != 0);
- if (temp4.Count() > 0)
- {
- AGVInfoModel info = temp4.ToList()[0];
- btn.Invoke(new InvokeDelegate(delegate
- {
- if (btn.BackColor != Color.FromKnownColor(KnownColor.Green))
- {
- if (AGVIDWithPosByCheckPos.ContainsKey(info.AGVNUM))
- {
- AGVIDWithPosByCheckPos.Remove(info.AGVNUM);
- }
- if (AGVIDWithRouteByCheckPos.ContainsKey(info.AGVNUM))
- {
- AGVIDWithRouteByCheckPos.Remove(info.AGVNUM);
- }
- // if (info.AGVNUM != 0)
- //{
- if (result != null && result.IsSuccess)
- {
- OperateResult rs = GlobalPara.s7.Write(query.ToList()[0]["AGVDB"].ToString(), (byte)info.AGVNUM);
- OperateResult rs2 = null;
- rs2 = GlobalPara.s7.Write(query.ToList()[0]["行驶状态DB"].ToString(), (byte)GlobalPara.DBRunValues.Running);
- GlobalPara.s7.Write(query.ToList()[0]["故障DB"].ToString(), (byte)(int.Parse(info.ALARMCODE) - 1));
- //}
- if (btn.BackColor != Color.FromKnownColor(KnownColor.Blue))
- {
- if (rs.IsSuccess && rs2.IsSuccess)
- {
- btn.BackColor = Color.Green;
- }
- }
- }
- }
- }));
- if (query.ToList()[0]["放行DB"].ToString() == "DB200.2")
- {
- // MessageBox.Show(info.AGVNUM.ToString() + ":" + info.RUNSTATUS_Cur.ToString());
- }
- if (info.RUNSTATUS_Cur == 0x40 && info.ALARMCODE == "1")
- {
- if (result != null && result.IsSuccess)
- {
- string releaseAddress = query.ToList()[0]["放行DB"].ToString();
- OperateResult<byte> resultRead = GlobalPara.s7.ReadByte(releaseAddress);
- if (resultRead.IsSuccess && DBWithByteValue.Keys.Contains(releaseAddress) &&
- DBWithByteValue[releaseAddress] != resultRead.Content)
- {
- if (resultRead.Content == (byte)GlobalPara.DBControlValues.StopImmediate)
- {
- lock (portLock)
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- DispatcherTool.ControlAGVBy1071(info.AGVNUM, 1);
- //立刻暂停行驶中的车
- WriteFile("急停记录", btn.Text + "工位被暂停,已生成消息,当前急停地标:" + btn.Tag.ToString() + ",车号为:" + info.AGVNUM);
- }
- else
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- }
- }
- }
- }
- else
- {
- btn.Invoke(new InvokeDelegate(delegate
- {
- if (tag == 1)
- {
- if (btn.BackColor != Color.FromKnownColor(KnownColor.Control))
- {
- OperateResult rs = GlobalPara.s7.Write(query.ToList()[0]["AGVDB"].ToString(), (byte)0);
- OperateResult rs2 =
- GlobalPara.s7.Write(query.ToList()[0]["行驶状态DB"].ToString(), (byte)GlobalPara.DBRunValues.Unknow);
- GlobalPara.s7.Write(query.ToList()[0]["故障DB"].ToString(), (byte)0);
- if (btn.BackColor != Color.FromKnownColor(KnownColor.Blue))
- {
- if (rs.IsSuccess && rs2.IsSuccess)
- {
- btn.BackColor = Color.FromKnownColor(KnownColor.Control);
- }
- }
- }
- }
- else if (tag == 0)
- {
- btn.BackColor = Color.FromKnownColor(KnownColor.Control);
- if (result != null && result.IsSuccess)
- {
- GlobalPara.s7.Write(query.ToList()[0]["AGVDB"].ToString(), (byte)0);
- GlobalPara.s7.Write(query.ToList()[0]["行驶状态DB"].ToString(), (byte)GlobalPara.DBRunValues.Unknow);
- GlobalPara.s7.Write(query.ToList()[0]["故障DB"].ToString(), (byte)0);
- }
- }
- }));
- if (result != null && result.IsSuccess)
- {
- string releaseAddress = query.ToList()[0]["放行DB"].ToString();
- OperateResult<byte> resultRead = GlobalPara.s7.ReadByte(releaseAddress);
- if (resultRead.IsSuccess && DBWithByteValue.Keys.Contains(releaseAddress) &&
- DBWithByteValue[releaseAddress] != resultRead.Content)
- {
- {
- if (resultRead.Content != (byte)GlobalPara.DBControlValues.StopImmediate)
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- }
- }
- }
- }
- }
- }
- }
- else
- {
- btn.Invoke(new InvokeDelegate(delegate
- {
- if (tag == 1)
- {
- if (btn.BackColor != Color.FromKnownColor(KnownColor.Control) &&
- btn.BackColor != Color.FromKnownColor(KnownColor.Blue))
- {
- OperateResult rs = GlobalPara.s7.Write(query.ToList()[0]["AGVDB"].ToString(), (byte)0);
- OperateResult rs2 =
- GlobalPara.s7.Write(query.ToList()[0]["行驶状态DB"].ToString(), (byte)GlobalPara.DBRunValues.Unknow);
- GlobalPara.s7.Write(query.ToList()[0]["故障DB"].ToString(), (byte)0);
- if (rs.IsSuccess && rs2.IsSuccess)
- {
- btn.BackColor = Color.FromKnownColor(KnownColor.Control);
- }
- }
- }
- else if (tag == 0)
- {
- btn.BackColor = Color.FromKnownColor(KnownColor.Control);
- if (result != null && result.IsSuccess)
- {
- GlobalPara.s7.Write(query.ToList()[0]["AGVDB"].ToString(), (byte)0);
- GlobalPara.s7.Write(query.ToList()[0]["行驶状态DB"].ToString(), (byte)GlobalPara.DBRunValues.Unknow);
- GlobalPara.s7.Write(query.ToList()[0]["故障DB"].ToString(), (byte)0);
- }
- }
- }));
- if (result != null && result.IsSuccess)
- {
- string releaseAddress = query.ToList()[0]["放行DB"].ToString();
- OperateResult<byte> resultRead = GlobalPara.s7.ReadByte(releaseAddress);
- if (resultRead.IsSuccess && DBWithByteValue.Keys.Contains(releaseAddress) &&
- DBWithByteValue[releaseAddress] != resultRead.Content)
- {
- if (resultRead.Content != (byte)GlobalPara.DBControlValues.StopImmediate)
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- }
- }
- }
- }
- }
- });
- if (result2.IsCompleted)
- {
- sw2.Stop();
- Console.WriteLine(dt.TableName + "任务总共花费{0}s.", sw.Elapsed.TotalSeconds);
- object[] obj = new object[3];
- obj[0] = listBtn; obj[1] = ++tag; obj[2] = lineName;
- if (tag == 5)
- {
- if (!InitOK.ContainsKey(lineName))
- {
- InitOK.Add(lineName, true);
-
- }
- }
- if (tag > 10)
- {
- tag = 11;
- }
-
- new Thread(new ParameterizedThreadStart(DockingOpeare0)).Start(obj);
- // DockingOpeare(list);
- }
-
- }
- }
- catch (Exception ex)
- {
- DateTime time = DateTime.Now;
- //MessageBox.Show("线程异常:"+e.ExceptionObject);
- FileStream stream = File.Open(@"Exception\调度程序异常.txt", FileMode.Append, FileAccess.Write);
- StreamWriter writer = new StreamWriter(stream);
- if (ex != null)
- {
- string msg = string.Format("[{0}]Test:\r\nMessage:{1}\r\nStackTrace:\r\n{2}", time.ToString("yyyy-MM-dd HH:mm:ss"), ex.Message, ex.StackTrace);
- writer.WriteLine(msg);
- writer.Close();
- stream.Close();
- }
- object[] obj = new object[3];
- obj[0] = listBtn; obj[1] = 0; obj[2] = lineName;
- new Thread(new ParameterizedThreadStart(DockingOpeare0)).Start(obj);
- }
- }
- void WriteFile(string fileName, string context)
- {
- DateTime time = DateTime.Now;
- //MessageBox.Show("线程异常:"+e.ExceptionObject);
- FileStream stream = File.Open(@"Exception\" + fileName + ".txt", FileMode.Append, FileAccess.Write);
- StreamWriter writer = new StreamWriter(stream);
- {
- string msg = string.Format("[{0}]Test:\r\nMessage:{1}\r\n", time.ToString("yyyy-MM-dd HH:mm:ss"), context);
- writer.WriteLine(msg);
- writer.Close();
- stream.Close();
- }
- }
- void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
- {
- Graphics g = e.Graphics;
- Font font = new Font("微软雅黑", 16f, System.Drawing.GraphicsUnit.Pixel);
- SolidBrush brush = new SolidBrush(Color.Black);
- if (e.Index == this.tabControl1.SelectedIndex)
- {
- brush = new SolidBrush(Color.Blue);
- }
- RectangleF rectangle = (RectangleF)(tabControl1.GetTabRect(e.Index));
- RectangleF rectangle2 = new RectangleF(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);
- g.FillRectangle(new SolidBrush(SystemColors.ButtonHighlight), rectangle2);
- StringFormat sformat = new StringFormat();
- sformat.LineAlignment = StringAlignment.Center;
- sformat.Alignment = StringAlignment.Center;
- g.DrawString(((TabControl)sender).TabPages[e.Index].Text, font, brush, rectangle2, sformat);
- }
- /// <summary>
- /// 发送心跳包
- /// </summary>
- private void HeartBit()
- {
- while (true)
- {
- //更新心跳包
- if (result == null || !result.IsSuccess)
- {
- if (GlobalPara.s7 != null)
- {
- result = GlobalPara.s7.ConnectServer();
- }
- statusStrip1.Invoke(new InvokeDelegate(delegate
- {
- toolStripStatusLabel1.Text = GlobalPara.s7.IpAddress + ", " + "PLC连接失败";
- }));
- }
- else
- {
- var tempResult = GlobalPara.s7.Write(dtConfig.Rows[1][1].ToString(), (byte)HeartBitCount);
- if (tempResult.IsSuccess)
- {
- HeartBitCount++;
- if (HeartBitCount > 0xFF)
- {
- HeartBitCount = 1;
- }
- statusStrip1.Invoke(new InvokeDelegate(delegate
- {
- toolStripStatusLabel1.Text = GlobalPara.s7.IpAddress + "," + " " + "PLC连接成功";
- }
- ));
- }
- else
- {
- this.Invoke(new InvokeDelegate(delegate
- {
- toolStripStatusLabel1.Text = GlobalPara.s7.IpAddress + "," + " " + "PLC连接失败";
- }
- ));
- }
- }
-
- }
- }
- /// <summary>
- /// 处理调度的协议
- /// </summary>
- private void Analzye()
- {
- while (true)
- {
- if (GlobalPara.dispatchList.Count > 0)
- {
- byte[] bytes = GlobalPara.dispatchList[0];
- Console.WriteLine("调度模块收到数据:" + GlobalPara.ByteToHexString(bytes));
- GlobalPara.dispatchList.Remove(bytes);
- }
- Thread.Sleep(20);
- }
- }
- }
- }
|