123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650 |
- 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<string, CFDClass> dicReleaseArea = new Dictionary<string, CFDClass>();
- public int CurCFDRoute = -1;
- Dictionary<string, bool> InitOK = new Dictionary<string, bool>();
- List<int> CFDRoutes = new List<int>();
- int index = 0;
- int CFDWaitTimes = 15;
- int CFDCheckTimes = 0;
- Dictionary<string, List<string>> dicCheck = new Dictionary<string, List<string>>();
- DataTable DtTraffic = new DataTable();
- List<string> listTra = new List<string>();
- byte PLCHeartBitCount = 0;
- bool HeartBitFlag = true;
- OperateResult<byte> PLCResult;
- bool IsPLCChangeOff = false;
- DataTable LineDt = new DataTable();
- bool DockingOK = false;
- 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 = 10;
- GlobalPara.s7.ReceiveTimeOut = 10;
-
- 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);
-
- 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>();
- if (lineName == "充放电测试")
- {
- DataView dv = temp2.DefaultView;
- dv.Sort = " 优先级 asc";
- temp2 = dv.ToTable();
- }
- 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);
- }
- }
- if (temp2.Columns.Contains("判断地标"))
- {
- if (temp2.Rows[j - 1]["判断地标"] != null && !string.IsNullOrEmpty(temp2.Rows[j - 1]["判断地标"].ToString()))
- {
- if (!dicCheck.ContainsKey(temp2.Rows[j - 1]["工位地标"].ToString()))
- {
- dicCheck.Add(temp2.Rows[j - 1]["工位地标"].ToString(), temp2.Rows[j - 1]["判断地标"].ToString().Split(',').ToList());
- }
- }
- }
- 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.Click
- += new EventHandler(btn_Click);
- 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);
- if (lineName == "充放电测试")
- {
- if (!CFDRoutes.Contains(int.Parse(temp2.Rows[j - 1]["放行路线"].ToString())))
- {
- CFDRoutes.Add(int.Parse(temp2.Rows[j - 1]["放行路线"].ToString()));
- }
- }
- }
- 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;
- if (lineName == "充放电测试")
- {
- CurCFDRoute = CFDRoutes[index];
- }
- listThread.Add(new Thread(new ParameterizedThreadStart(DockingOpeare0)), obj);//.Start(listBtn);
- // DockingOpeare0(obj);
- // if (lineName == "充放电测试") { tabControl1.SelectedTab = tb; }
- }
- OleDbDataAdapter oleDDA3 = new OleDbDataAdapter("Select * From [管制信息$]", oleDC);
- oleDDA3.Fill(DtTraffic);
- if (File.Exists(@"Exception\管制点放行信息.txt"))
- {
- string[] texts = File.ReadAllLines(@"Exception\管制点放行信息.txt");
- listTra.AddRange(texts.ToList());
- if (listTra.Count < DtTraffic.Rows.Count)
- {
- for (int i = 0; i < DtTraffic.Rows.Count - listTra.Count; i++)
- {
- listTra.Add("0");
- }
- }
- }
- else
- {
- if (DtTraffic.Rows.Count > 0)
- {
- listTra = new List<string>(DtTraffic.Rows.Count);
- for (int i = 0; i < DtTraffic.Rows.Count; i++)
- {
- listTra.Add("0");
- }
- }
- }
- foreach (Thread t in listThread.Keys)
- {
- t.Priority = ThreadPriority.Highest;
- t.Start(listThread[t]);
- }
- // Thread.Sleep(8000);
- //Thread t2 = new Thread(new ThreadStart(checkingOperate));
- //t2.Priority = ThreadPriority.BelowNormal;
- //t2.Start();
- // new Thread(new ThreadStart(CFDCheck)).Start();
- // new Thread(new ThreadStart(checkingRelease2)).Start();
- //Thread t3 = new Thread(new ThreadStart(TrafficByDispatch));
- //t3.Priority = ThreadPriority.AboveNormal;
- //t3.Start();
- Thread t4 = new Thread(new ThreadStart(PLCHeartBit));
- t4.Priority = ThreadPriority.Lowest;
- t4.Start();
- }
- catch (System.Exception ex)
- {
- MessageBox.Show(ex.StackTrace);
- }
- }
- void btn_Click(object sender, EventArgs e)
- {
- //throw new NotImplementedException();
- Button btn = (Button)sender;
- if (btn.BackColor == Color.Blue)
- {
- if (MessageBox.Show("该工位已被分配锁定,是否解除锁定?", "警告", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
- {
- btn.Invoke(new InvokeDelegate(delegate
- {
- if (AGVIDWithPosByCheckPos.ContainsValue(int.Parse(btn.Tag.ToString())))
- {
- int num = AGVIDWithPosByCheckPos.Keys.ToList()[AGVIDWithPosByCheckPos.Values.ToList().IndexOf(int.Parse(btn.Tag.ToString()))];
- if (AGVIDWithPosByCheckPos.ContainsKey(num))
- {
- lock (AGVIDWithPosByCheckPos)
- {
- AGVIDWithPosByCheckPos.Remove(num);
- }
- }
- if (AGVIDWithRouteByCheckPos.ContainsKey(num))
- {
- lock (AGVIDWithRouteByCheckPos)
- {
- AGVIDWithRouteByCheckPos.Remove(num);
- }
- }
- btn.BackColor = Color.FromKnownColor(KnownColor.Control);
- }
- else
- {
- int num = int.Parse(btn.Tag.ToString());
- if (AGVIDWithPosByCheckPos.Values.Contains(num))
- {
- lock (AGVIDWithPosByCheckPos)
- {
- var temp = AGVIDWithPosByCheckPos.First(o => o.Value == num);
- if (AGVIDWithPosByCheckPos.ContainsKey(temp.Key))
- {
- AGVIDWithPosByCheckPos.Remove(temp.Key);
- }
- }
- }
- if (AGVIDWithRouteByCheckPos.Values.Contains(num))
- {
- lock (AGVIDWithRouteByCheckPos)
- {
- var temp = AGVIDWithRouteByCheckPos.First(o => o.Value == num);
- if (AGVIDWithRouteByCheckPos.ContainsKey(temp.Key))
- {
- AGVIDWithRouteByCheckPos.Remove(temp.Key);
- }
- }
- }
- btn.BackColor = Color.FromKnownColor(KnownColor.Control);
- }
- }
- ));
- }
- else if (btn.BackColor == Color.Red)
- {
- if (MessageBox.Show("该工位AGV已故障,是否解除状态,并将AGV移到故障?", "警告", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
- {
- List<AGVInfoModel> listModel = GlobalPara.AgvInfoDic.Values.ToList();
- IEnumerable<AGVInfoModel> temp = listModel.Where(o => o.MARKNUM.ToString() == btn.Tag.ToString());
- if (temp.Count() > 0)
- {
- AGVInfoModel info = temp.ToList()[0];
- info.MARKNUM = 0;
- GlobalPara.AgvInfoDic[info.AGVNUM] = info;
- }
- btn.Invoke(new InvokeDelegate(delegate
- {
- btn.BackColor = Color.FromKnownColor(KnownColor.Control);
- }));
- }
- }
- }
- }
- /// <summary>
- /// 记录放行后的情况
- /// </summary>
- public void recordReleaseInfo()
- {
- if (AGVIDWithPosByCheckPos.Count > 0)
- {
- string[] textArray = new string[AGVIDWithPosByCheckPos.Count];
- int aryIndex = 0;
- foreach (int num in AGVIDWithPosByCheckPos.Keys)
- {
- if (AGVIDWithPosByCheckPos.ContainsKey(num))
- {
- textArray[aryIndex] = num + "," + AGVIDWithPosByCheckPos[num];
- }
- if (AGVIDWithRouteByCheckPos.ContainsKey(num))
- {
- textArray[aryIndex] += "," + AGVIDWithRouteByCheckPos[num];
- }
- ++aryIndex;
- }
- File.WriteAllLines(@"Exception\判断点放行信息.txt", textArray);
- }
- }
- /// <summary>
- /// 调度管制
- /// </summary>
- public void TrafficByDispatch()
- {
- if (DtTraffic.Rows.Count > 0)
- {
- bool b = true;
- while (b)
- {
- try
- {
- List<AGVInfoModel> listModel = GlobalPara.AgvInfoDic.Values.ToList();
- for (int i = 0; i < DtTraffic.Rows.Count; i++)
- {
- List<string> listIn = DtTraffic.Rows[i][0].ToString().Split(',').ToList();
- List<string> listTraffic = DtTraffic.Rows[i][1].ToString().Split(',').ToList();
- //List<AGVInfoModel> results = listModel.FindAll(o => listTra[i].Equals(o.MARKNUM.ToString()) && o.ConnectStatus == true);
- //if (results != null && results.Count > 0)
- //{
- //}
- //else
- // {
- List<AGVInfoModel> results = listModel.FindAll(o => listIn.Contains(o.MARKNUM.ToString()) && o.ConnectStatus == true);
- // }
- if (results != null && results.Count > 0)
- {
- AGVInfoModel result = results.OrderBy(o => o.LastModifyMarkTime).ToList()[0];
- List<AGVInfoModel> results2 = listModel.FindAll(o => listTraffic.Contains(o.MARKNUM.ToString()) && o.ConnectStatus == true);
- if (listIn.Count == 1 && results.Count > 1)
- {
- continue;
- }
- if (results == null || results2.Count <= 0)
- {
- List<AGVInfoModel> results3 = listModel.FindAll(o => result.MARKNUM == o.MARKNUM && o.RUNSTATUS_Cur != 0x43 && o.ConnectStatus == true);
- if (results3 != null && results3.Count <= 0)
- {
- int route = 0; int targetMark = 0;
- if (AGVIDWithPosByCheckPos.Keys.Contains(result.AGVNUM))
- {
- targetMark = AGVIDWithPosByCheckPos[result.AGVNUM];
- }
- if (AGVIDWithRouteByCheckPos.Keys.Contains(result.AGVNUM))
- {
- route = AGVIDWithRouteByCheckPos[result.AGVNUM];
- }
- DispatcherTool.ReleaseAgvOnStop(result.MARKNUM, route, targetMark, 1);
- if (listTra[i] != result.MARKNUM.ToString())
- {
- listTra[i] = result.MARKNUM.ToString();
- File.WriteAllLines(@"Exception\管制点放行信息.txt", listTra.ToArray());
- }
- WriteFile("管制记录" + DateTime.Now.ToString("yyyy-MM-dd"), result.AGVNUM + "号AGV符合放行条件,地标为:" + result.MARKNUM + ",路线为" + route + ",目的地标为" + targetMark);
- }
- }
- }
- }
- }
- catch (Exception)
- {
- b = false;
- //Thread.Sleep(200);
- //new Thread(new ThreadStart(TrafficByDispatch)).Start();
- }
- finally
- {
- if (!b)
- {
- Thread.Sleep(500);
- Thread t2 = new Thread(new ThreadStart(TrafficByDispatch));
- t2.Priority = ThreadPriority.AboveNormal;
- t2.Start();
- WriteFile("线程重启", "TrafficByDispatch报错,已重启!");
- }
- }
- Thread.Sleep(500);
- }
- }
- }
- /// <summary>
- /// 收到PLC放行信号继续发送放行
- /// </summary>
- public void checkingRelease()
- {
- bool b = true;
- while (b)
- {
- try
- {
- if (!GlobalPara.IsOneKeySleep)
- {
- if (result != null && result.IsSuccess)
- {
- for (int j = 0; j < tabControl1.TabPages.Count; j++)
- {
- if (tabControl1.TabPages[j].Tag != null)
- {
- TabPageTag tt = (TabPageTag)tabControl1.TabPages[j].Tag;
- for (int k = 0; k < tt.Table.Rows.Count; k++)
- {
- DataRow dr = tt.Table.Rows[k];
- string releaseAddress = dr["放行DB"].ToString();
- if (!string.IsNullOrEmpty(releaseAddress))
- {
- OperateResult<byte> resultRead = GlobalPara.s7.ReadByte(releaseAddress);
- if (resultRead != null && result.IsSuccess)
- {
- if (resultRead.Content == (byte)GlobalPara.DBControlValues.OKRelease)
- {
- DispatcherTool.ReleaseAgvOnStop(int.Parse(dr["工位地标"].ToString()), 0, int.Parse(dr["目的地标"].ToString()));
- }
- else if (resultRead.Content == (byte)GlobalPara.DBControlValues.NGRelease)
- {
- DispatcherTool.ReleaseAgvOnStop(int.Parse(dr["工位地标"].ToString()), int.Parse(dr["NG路线"].ToString()));
- }
- }
- }
- Thread.Sleep(10);
- }
- }
- }
- }
- }
- }
- catch (Exception)
- {
- b = false;
- //Thread.Sleep(500);
- //new Thread(new ThreadStart(checkingRelease)).Start();
- }
- finally
- {
- if (!b)
- {
- Thread.Sleep(500);
- Thread t2 = new Thread(new ThreadStart(checkingRelease));
- t2.Priority = ThreadPriority.BelowNormal;
- t2.Start();
- WriteFile("线程重启", "checkingRelease报错,已重启!");
- }
- }
- Thread.Sleep(500);
- }
- }
- /// <summary>
- /// 收到PLC放行信号继续发送放行
- /// </summary>
- public void checkingRelease2()
- {
- bool b = true;
- while (b)
- {
- try
- {
- if (result != null && result.IsSuccess)
- {
- List<string> keys = DBWithByteValue.Keys.ToList();
- for (int i = 0; i < keys.Count; i++)
- {
- if (DBWithByteValue[keys[i]] == (byte)GlobalPara.DBControlValues.OKRelease ||
- DBWithByteValue[keys[i]] == (byte)GlobalPara.DBControlValues.NGRelease)
- {
- for (int j = 0; j < tabControl1.TabPages.Count; j++)
- {
- if (tabControl1.TabPages[j].Tag != null)
- {
- TabPageTag tt = (TabPageTag)tabControl1.TabPages[j].Tag;
- DataRow[] drs = tt.Table.Select("放行DB='" + keys[i] + "'");
- if (drs != null && drs.Length > 0)
- {
- if (DBWithByteValue[keys[i]] == (byte)GlobalPara.DBControlValues.OKRelease)
- {
- DispatcherTool.ReleaseAgvOnStop(int.Parse(drs[0]["工位地标"].ToString()), 0, int.Parse(drs[0]["目的地标"].ToString()));
- break;
- }
- else if (DBWithByteValue[keys[i]] == (byte)GlobalPara.DBControlValues.NGRelease)
- {
- DispatcherTool.ReleaseAgvOnStop(int.Parse(drs[0]["工位地标"].ToString()), int.Parse(drs[0]["NG路线"].ToString()));
- break;
- }
- }
- }
- }
- }
- }
- }
- }
- catch (Exception)
- {
- b = false;
- //Thread.Sleep(500);
- //new Thread(new ThreadStart(checkingRelease2)).Start();
- }
- finally
- {
- if (!b)
- {
- Thread.Sleep(500);
- new Thread(new ThreadStart(checkingRelease2)).Start();
- WriteFile("线程重启", "checkingRelease报错,已重启!");
- }
- }
- Thread.Sleep(500);
- }
- }
- /// <summary>
- /// 判断点事件
- /// </summary>
- public void checkingOperate()
- {
- bool bb = false;
- Stopwatch sw2 = new Stopwatch();
- List<AGVInfoModel> listModel = GlobalPara.AgvInfoDic.Values.ToList();
- ParallelLoopResult result;
- try
- {
-
- result = Parallel.ForEach<int>(checkPosDic.Keys, new ParallelOptions { MaxDegreeOfParallelism = 2 }, pos =>
- {
- if (!GlobalPara.IsOneKeySleep)
- {
- IEnumerable<AGVInfoModel> temp = listModel.Where(o => o.MARKNUM == pos && (o.RUNSTATUS_Cur == 0x43 || o.RUNSTATUS_Cur == 0x47 || o.ALARMCODE == "9") && !AGVIDWithPosByCheckPos.ContainsKey(o.AGVNUM) && o.ConnectStatus == true);
- 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;
- {
- drs = tag.Table.Select("优先级>0", "优先级 asc");
- }
- for (int j = 0; j < drs.Length; j++)
- {
- // 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)
- {
- //找到目的站点,放行路线
- bool b = true;
- if (dicCheck.ContainsKey(drs[j]["工位地标"].ToString()))
- {
- List<string> tempList = dicCheck[drs[j]["工位地标"].ToString()];
- for (int a = 0; a < tempList.Count; a++)
- {
- int iindex = listModel.FindIndex(o => o.MARKNUM.ToString() == tempList[a]);
- if (iindex > -1)
- {
- b = false;
- break;
- }
- }
- }
- if (b)
- {
- AGVIDWithPosByCheckPos.Add(num, int.Parse(drs[j]["工位地标"].ToString()));
- AGVIDWithRouteByCheckPos.Add(num, int.Parse(drs[j]["放行路线"].ToString()));
- recordReleaseInfo();
- DispatcherTool.ReleaseAgvOnStop(pos, int.Parse(drs[j]["放行路线"].ToString()), int.Parse(drs[j]["工位地标"].ToString()));
- WriteFile("判断点记录-" + DateTime.Now.ToString("yyyy-MM-dd"), "(判断点地标:" + pos + ",放行路线:" + drs[j]["放行路线"].ToString() + ",目的地标:" + int.Parse(drs[j]["工位地标"].ToString()) + ",车号:" + num + ") ");
- btn.Invoke(new InvokeDelegate(delegate
- {
- if (btn.BackColor != Color.FromKnownColor(KnownColor.Blue))
- {
- btn.BackColor = Color.Blue;
- if (btn.Text.Contains("("))
- {
- int textIndex = btn.Text.LastIndexOf("(");
- string orignName = btn.Text.Substring(0, textIndex).Replace("\n", "");
- btn.Text = orignName + "\n" + "(" + num + ")";
- }
- else
- {
- btn.Text = btn.Text.Replace("\n", "") + "\n" + "(" + num + ")";
- }
- }
- }));
- break;
- }
- }
- }
- }
- }
- }
- }
- }
- });
-
- if (result.IsCompleted)
- {
- sw2.Stop();
- Console.WriteLine("判断点任务总共花费{0}s.", sw.Elapsed.TotalSeconds);
- Thread.Sleep(500);
- Thread t2 = new Thread(new ThreadStart(checkingOperate));
- t2.Priority = ThreadPriority.BelowNormal;
- t2 .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();
- }
- bb = true;
- //Thread.Sleep(500);
- //new Thread(new ThreadStart(checkingOperate)).Start();
- }
- finally
- {
- if (bb)
- {
- Thread.Sleep(500);
- Thread t2 = new Thread(new ThreadStart(checkingOperate));
- t2.Priority = ThreadPriority.BelowNormal;
- t2.Start();
- WriteFile("线程重启", "checkingOperate报错,已重启!");
- }
- }
- }
- public void CFDCheck()
- {
- ParallelLoopResult result2;
- try
- {
- List<string> list = dicReleaseArea.Keys.ToList();
- result2 = Parallel.ForEach<string>(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;
- dicReleaseArea.Remove(key);
- }
- WriteFile("充放电记录", "(" + cfd.number + "," + cfd.numberInner + ") 组放行完成,已解锁");
- }
- else
- {
- for (int i = 0; i < listBtn.Count(); i++)
- {
- if (listBtn[i].BackColor == Color.Yellow)
- {
- DispatcherTool.ReleaseAgvOnStop(int.Parse(listBtn[i].Tag.ToString()), 0);
- }
- }
- }
- }
- }
- });
- if (result2.IsCompleted)
- {
- Thread.Sleep(200);
- 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();
- }
- Thread.Sleep(200);
- 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;
- bool bb = false;
- 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.MARKFUN == 1 && o.ALARMINFO == "低电压报警"))
- && o.ConnectStatus == true && o.AGVNUM != 0));
- if (temp2.Count() > 0)
- {
- List<AGVInfoModel> infos = temp2.ToList();
- AGVInfoModel info = infos[0];
- btn.Invoke(new InvokeDelegate(delegate
- {
- if (btn.BackColor != Color.FromKnownColor(KnownColor.Yellow))
- {
- if (AGVIDWithPosByCheckPos.ContainsKey(info.AGVNUM))
- {
- AGVIDWithPosByCheckPos.Remove(info.AGVNUM);
- }
- if (AGVIDWithPosByCheckPos.ContainsKey(info.AGVNUM))
- {
- int mark = AGVIDWithPosByCheckPos[info.AGVNUM];
- AGVIDWithPosByCheckPos.Remove(info.AGVNUM);
- if (AGVIDWithPosByCheckPos.ContainsValue(mark))
- {
- for (int ab = AGVIDWithPosByCheckPos.Keys.Count - 1; ab >= 0; ab--)
- {
- if (AGVIDWithPosByCheckPos[AGVIDWithPosByCheckPos.Keys.ToList()[ab]] == mark)
- {
- AGVIDWithPosByCheckPos.Remove(AGVIDWithPosByCheckPos.Keys.ToList()[ab]);
- }
- }
- }
- recordReleaseInfo();
- }
- 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 (btn.Text.Contains("("))
- {
- int textIndex = btn.Text.LastIndexOf("(");
- string orignName = btn.Text.Substring(0, textIndex).Replace("\n", "");
- btn.Text = orignName + "\n" + "(" + info.AGVNUM + ")";
- }
- else
- {
- btn.Text = btn.Text.Replace("\n", "") + "\n" + "(" + info.AGVNUM + ")";
- }
- }
- }
-
- }
- else
- {
- //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 (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)
- {
- {
- DispatcherTool.ReleaseAgvOnStop(int.Parse(btn.Tag.ToString()),
- 0, int.Parse(query.ToList()[0]["目的地标"].ToString()),5);
- lock (portLock)
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- WriteFile("工位点记录-" + DateTime.Now.ToString("yyyy-MM-dd"), "(放行地标:" + btn.Tag.ToString() + ",放行路线:0" + ",目的地标:" + (query.ToList()[0]["目的地标"].ToString()) + ",车号:" + info.AGVNUM + ") ");
- }
- //走OK放行路线
- }
- else if (resultRead.Content == (byte)GlobalPara.DBControlValues.NGRelease)
- {
- {
- DispatcherTool.ReleaseAgvOnStop(int.Parse(btn.Tag.ToString()),
- int.Parse(query.ToList()[0]["NG路线"].ToString()),0,5);
- lock (portLock)
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- WriteFile("工位点记录-" + DateTime.Now.ToString("yyyy-MM-dd"), "(放行地标:" + btn.Tag.ToString() + ",放行路线:" + query.ToList()[0]["NG路线"].ToString() + ",车号:" + info.AGVNUM + ") ");
- }
- }
- else
- {
- if (resultRead.Content != (byte)GlobalPara.DBControlValues.StopImmediate)
- {
- DBWithByteValue[releaseAddress] = resultRead.Content;
- }
- }
- }
- }
- }
- else
- {
- IEnumerable<AGVInfoModel> temp3 = temp.Where(o => (o.RUNSTATUS_Cur == 0x41 || o.RUNSTATUS_Cur == 0x47 || (o.MARKFUN == 1 && o.ALARMINFO == "低电压停机")) && 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 && info.ALARMCODE != "")
- {
- OperateResult rs = GlobalPara.s7.Write(query.ToList()[0]["AGVDB"].ToString(), (byte)info.AGVNUM);
- OperateResult rs2 = null;
- if (info.ALARMCODE != "5" && info.ALARMCODE != "0" && info.ALARMCODE != "9")
- {
- 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 (btn.Text.Contains("("))
- {
- int textIndex = btn.Text.LastIndexOf("(");
- string orignName = btn.Text.Substring(0, textIndex).Replace("\n", "");
- btn.Text = orignName + "\n" + "(" + info.AGVNUM + ")";
- }
- else
- {
- btn.Text = btn.Text.Replace("\n", "") + "\n" + "(" + info.AGVNUM + ")";
- }
- }
- }
- }
- }
- else
- {
- //OperateResult rs = GlobalPara.s7.Write(query.ToList()[0]["AGVDB"].ToString(), (byte)info.AGVNUM);
- //OperateResult rs2 = null;
- //if (info.ALARMCODE != "5" && info.ALARMCODE != "0" && info.ALARMCODE != "9")
- //{
- // 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 (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("工位点记录" + DateTime.Now.ToString("yyyy-MM-dd"), 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 (btn.Text.Contains("("))
- {
- int textIndex = btn.Text.LastIndexOf("(");
- string orignName = btn.Text.Substring(0, textIndex).Replace("\n", "");
- btn.Text = orignName + "\n" + "(" + info.AGVNUM + ")";
- }
- else
- {
- btn.Text = btn.Text.Replace("\n", "") + "\n" + "(" + info.AGVNUM + ")";
- }
- }
- }
- }
- }
- else
- {
- //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 (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
- {
- lock (portLock)
- {
- DBWithByteValue[releaseAddress] = (byte)resultRead.Content;
- }
- }
- }
- }
- }
- }
- else
- {
- btn.Invoke(new InvokeDelegate(delegate
- {
- if (tag >= 1)
- {
- if (AGVIDWithPosByCheckPos.ContainsValue(int.Parse(query.ToList()[0]["工位地标"].ToString())))
- {
- List<int> keys = AGVIDWithPosByCheckPos.Keys.ToList();
- for (int a = 0; a < keys.Count; a++)
- {
- if (AGVIDWithPosByCheckPos[keys[a]] == int.Parse(query.ToList()[0]["工位地标"].ToString()))
- {
- btn.Text = query.ToList()[0]["工位名称"].ToString() + "\n(" + keys[a] + ")";
- btn.BackColor = Color.Blue;
- break;
- }
- }
- }
- else
- {
- 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);
- if (btn.Text.Contains("("))
- {
- int textIndex = btn.Text.LastIndexOf("(");
- string orignName = btn.Text.Substring(0, textIndex).Replace("\n", "");
- btn.Text = orignName;
- }
- }
- }
- }
- }
- }
- 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 (AGVIDWithPosByCheckPos.ContainsValue(int.Parse(query.ToList()[0]["工位地标"].ToString())))
- {
- List<int> keys = AGVIDWithPosByCheckPos.Keys.ToList();
- for (int a = 0; a < keys.Count; a++)
- {
- if (AGVIDWithPosByCheckPos[keys[a]] == int.Parse(query.ToList()[0]["工位地标"].ToString()))
- {
- btn.Text = query.ToList()[0]["工位名称"].ToString() + "\n(" + keys[a] + ")";
- btn.BackColor = Color.Blue;
- break;
- }
- }
- }
- }
- }));
- 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);
- if (btn.Text.Contains("("))
- {
- int textIndex = btn.Text.LastIndexOf("(");
- string orignName = btn.Text.Substring(0, textIndex).Replace("\n", "");
- btn.Text = orignName;
- }
- }
- }
- }
- 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 (AGVIDWithPosByCheckPos.ContainsValue(int.Parse(query.ToList()[0]["工位地标"].ToString())))
- {
- List<int> keys = AGVIDWithPosByCheckPos.Keys.ToList();
- for (int a = 0; a < keys.Count; a++)
- {
- if (AGVIDWithPosByCheckPos[keys[a]] == int.Parse(query.ToList()[0]["工位地标"].ToString()))
- {
- btn.Text = query.ToList()[0]["工位名称"].ToString() + "\n(" + keys[a] + ")";
- btn.BackColor = Color.Blue;
- break;
- }
- }
- }
- }
- }));
- 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 == 10)
- {
- if (!InitOK.ContainsKey(lineName))
- {
- InitOK.Add(lineName, true);
- // tag = 1;
- }
- }
- if (tag > 10)
- {
- tag = 11;
- }
- Thread.Sleep(100);
- Thread t2 = new Thread(new ParameterizedThreadStart(DockingOpeare0));
- t2.Priority = ThreadPriority.Highest;
- t2.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();
- }
- bb = true;
- //object[] obj = new object[3];
- //obj[0] = listBtn; obj[1] = 0; obj[2] = lineName;
- //Thread.Sleep(500);
- //new Thread(new ParameterizedThreadStart(DockingOpeare0)).Start(obj);
- }
- finally
- {
- if (bb)
- {
- object[] obj = new object[3];
- obj[0] = listBtn; obj[1] = 0; obj[2] = lineName;
- Thread.Sleep(500);
- Thread t2 = new Thread(new ParameterizedThreadStart(DockingOpeare0));
- t2.Priority = ThreadPriority.Highest;
- t2.Start(obj);
- WriteFile("线程重启", "DockingOpeare0报错,已重启!");
- }
- if (!DockingOK && InitOK.Count == LineDt.Rows.Count)
- {
- DockingOK = true;
- Thread t2 = new Thread(new ThreadStart(checkingOperate));
- t2.Priority = ThreadPriority.BelowNormal;
- t2.Start();
- Thread t3 = new Thread(new ThreadStart(TrafficByDispatch));
- t3.Priority = ThreadPriority.AboveNormal;
- t3.Start();
- }
- }
- }
- 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 PLCHeartBit()
- {
- while (true)
- {
- PLCResult = GlobalPara.s7.ReadByte(dtConfig.Rows[4][1].ToString()); //PLC心跳记录
- if (PLCResult != null && PLCResult.IsSuccess)
- {
- // OperateResult<byte> tempResult = GlobalPara.s7.ReadByte(dtConfig.Rows[1][4].ToString());
- if (PLCResult != null && PLCResult.IsSuccess)
- {
- if (PLCResult.Content != PLCHeartBitCount)
- {
- result = GlobalPara.s7.ConnectServer();
- PLCHeartBitCount = PLCResult.Content;
- HeartBitFlag = true;
- IsPLCChangeOff = false;
- }
- else
- {
- result = null;
- GlobalPara.s7.ConnectServer();
- HeartBitFlag = false;
- IsPLCChangeOff = true;
- }
- }
- }
- else
- {
- result = null;
- GlobalPara.s7.ConnectServer();
- HeartBitFlag = false;
- IsPLCChangeOff = true;
- }
- Thread.Sleep(2000);
- }
- }
- /// <summary>
- /// 发送心跳包
- /// </summary>
- private void HeartBit()
- {
- while (true)
- {
- if (HeartBitFlag)
- {
- //更新心跳包
- 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
- {
- if (result != null && result.IsSuccess)
- {
- 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连接失败";
- }
- ));
- }
- }
- }
- }
- Thread.Sleep(500);
- }
- }
- /// <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);
- }
- }
- }
- }
|