using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using UAS_AutoPass.ToolClass;
namespace UAS_XmlAnalysor
{
public partial class Form1 : Form
{
DataHelper dh;
DataTable dt;
Tip tipform;
///
/// 用户编号
///
string iusercode;
///
/// 岗位资源
///
string isource;
///
/// 线别
///
string ilinecode;
///
/// 不良代码组
///
string ibadgroup;
///
/// 当前工序
///
string istepcode;
StringBuilder sql = new StringBuilder();
DataTable DB;
Thread InitDB;
///
/// 缓存的文件
///
public static string CachePath = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/Cache.xml";
///
/// 缓存的文件夹
///
public static string CachePathFolder = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/";
public Form1()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
tipform = new Tip();
}
public Form1(string iUserName, string iSource)
{
tipform = new Tip();
InitializeComponent();
iusercode = iUserName;
isource = iSource.ToUpper();
StartPosition = FormStartPosition.CenterScreen;
}
private void Form1_Load(object sender, EventArgs e)
{
tipform.Show();
CheckForIllegalCrossThreadCalls = false;
FormBorderStyle = FormBorderStyle.FixedSingle;
InitDB = new Thread(ConnectDB);
//添加监控事件
XmlWatcher.Created += new FileSystemEventHandler(XmlWatcher_Created);
SetLoadingWindow stw = new SetLoadingWindow(InitDB, "正在启动程序");
stw.StartPosition = FormStartPosition.CenterScreen;
stw.ShowDialog();
List CacheInf = new List();
DB = (DataTable)dh.ExecuteSql("select ms_pwd,ma_user,ma_address,ma_inneraddress from master", "select");
Master.DataSource = DB;
Master.DisplayMember = "ma_user";
Master.ValueMember = "ma_user";
//获取缓存信息
try
{
FolderPath.Text = BaseUtil.GetCacheData("FolderPath").ToString();
BackUpFolderPath.Text = BaseUtil.GetCacheData("BackUpFolderPath").ToString();
Master.Text = BaseUtil.GetCacheData("Master").ToString();
AutoStart.Checked = (bool)BaseUtil.GetCacheData("AutoStart");
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
for (int i = 0; i < DB.Rows.Count; i++)
{
if (Master.Text == DB.Rows[i]["ma_user"].ToString())
{
DataHelper.DBConnectionString = "Connection Timeout=0;Pooling=false;Password=select!#%*(;User ID=" + DB.Rows[i]["ma_user"].ToString() + ";Pooling=false;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=" + DB.Rows[i]["ma_inneraddress"].ToString() + ")(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orcl)));";
dh = new DataHelper();
}
}
//获取岗位资源相关信息
dt = (DataTable)dh.ExecuteSql("select sc_linecode,sc_stepcode,st_badgroupcode from source left join step on sc_stepcode=st_code where sc_code='" + isource + "'", "select");
if (dt.Rows.Count > 0)
{
ilinecode = dt.Rows[0]["sc_linecode"].ToString();
istepcode = dt.Rows[0]["sc_stepcode"].ToString();
ibadgroup = dt.Rows[0]["st_badgroupcode"].ToString();
}
}
private void ConnectDB()
{
dh = new DataHelper();
}
private void StartWatch_Click(object sender, EventArgs e)
{
if (FolderPath.Text == "" || BackUpFolderPath.Text == "")
{
OperateResult.AppendText("请选择监控文件夹和备份文件夹\n");
return;
}
else
{
if (!Directory.Exists(FolderPath.Text))
{
OperateResult.AppendText("监控文件夹不存在\n");
return;
}
if (!Directory.Exists(BackUpFolderPath.Text))
{
OperateResult.AppendText("备份文件夹不存在\n");
return;
}
}
if (FolderPath.Text == BackUpFolderPath.Text)
{
OperateResult.AppendText("监控文件夹和备份文件夹不能相同\n");
return;
}
for (int i = 0; i < DB.Rows.Count; i++)
{
if (Master.Text == DB.Rows[i]["ma_user"].ToString())
{
DataHelper.DBConnectionString = "Connection Timeout=0;Pooling=false;Password=select!#%*(;User ID=" + DB.Rows[i]["ma_user"].ToString() + ";Pooling=false;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=" + DB.Rows[i]["ma_inneraddress"].ToString() + ")(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orcl)));";
dh = new DataHelper();
}
}
if (!dh.CheckExist("source", "sc_code='" + isource + "' and sc_statuscode='AUDITED'"))
{
OperateResult.AppendText("岗位资源错误或者未审核\n");
return;
}
XmlWatcher.Path = FolderPath.Text;
XmlWatcher.Filter = "*.xml";
XmlWatcher.EnableRaisingEvents = true;
BaseUtil.SetCacheData("FolderPath", FolderPath.Text);
BaseUtil.SetCacheData("BackUpFolderPath", BackUpFolderPath.Text);
BaseUtil.SetCacheData("Source", isource);
BaseUtil.SetCacheData("Master", Master.Text);
BaseUtil.SetCacheData("AutoStart", AutoStart.Checked);
StartWatch.Enabled = false;
ChooseFolder.Enabled = false;
ChooseBackUpFolder.Enabled = false;
StopWatch.Enabled = true;
OperateResult.AppendText("开始执行监控\n");
}
public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
{
XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
node.InnerText = value;
parentNode.AppendChild(node);
}
public void SetAutoRun()
{
if (AutoStart.Checked) //设置开机自启动
{
string path = Application.ExecutablePath;
RegistryKey rk = Registry.LocalMachine;
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
rk2.SetValue("UAS_XML解析器.exe", path);
rk2.Close();
rk.Close();
}
else //取消开机自启动
{
string path = Application.ExecutablePath;
RegistryKey rk = Registry.LocalMachine;
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
rk2.DeleteValue("UAS_XML解析器.exe", false);
rk2.Close();
rk.Close();
}
}
private void XmlWatcher_Created(object sender, FileSystemEventArgs e)
{
while (true)
{
try
{
using (Stream stream = File.Open(e.FullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
if (stream != null)
break;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
string test_result = "";
string oErrMessage = "";
string testDate = "";
string testTime = "";
XmlReader myReader = XmlReader.Create(FolderPath.Text + @"\" + e.Name);
//获取文件名的序列号,如SA123456.xml
string sncode = e.Name.Split('.')[0];
string makecode = "";
//获取序列号ID最大的工单号
OperateResult.AppendText("读取文件" + e.Name + "\n");
//获取采集的项目名称
List name = new List();
//获取采集项目的结果
List result = new List();
string class2name = "";
string class3name = "";
List class2 = new List();
//获取采集项目的结果
List class3 = new List();
while (myReader.Read())
{
if (myReader.NodeType == XmlNodeType.Element && myReader.Name == "test" && myReader.IsStartElement())
{
test_result = myReader.GetAttribute("test_result");
testDate = myReader.GetAttribute("test_date");
testTime = myReader.GetAttribute("test_time");
class2name = "";
class3name = "";
}
if (myReader.NodeType == XmlNodeType.Element && myReader.Name == "OperatorInput" && myReader.IsStartElement())
{
class2name = "OperatorInput";
class3name = "";
}
if (myReader.NodeType == XmlNodeType.Element && myReader.Name == "SelfTest" && myReader.IsStartElement())
{
class2name = "SelfTest";
class3name = "";
}
if (myReader.NodeType == XmlNodeType.Element && myReader.Name == "BlueTooth" && myReader.IsStartElement())
{
class2name = "SelfTest";
class3name = "BlueTooth";
}
if (myReader.NodeType == XmlNodeType.Element && myReader.Name == "wifi" && myReader.IsStartElement())
{
class2name = "SelfTest";
class3name = "wifi";
}
if (myReader.NodeType == XmlNodeType.Element && myReader.Name == "temperature" && myReader.IsStartElement())
{
class2name = "SelfTest";
class3name = "temperature";
}
if (myReader.NodeType == XmlNodeType.Element && myReader.Name == "nightvision" && myReader.IsStartElement())
{
class2name = "SelfTest";
class3name = "nightvision";
}
//if (myReader.NodeType == XmlNodeType.Text)
//{
// if (name_or_result % 2 == 0)
// {
// name.Add(myReader.Value+" ");
// name_or_result++;
// }
// else
// {
// result.Add(myReader.Value+" ");
// name_or_result++;
// class2.Add(class2name);
// class3.Add(class3name);
// }
//}
if (myReader.NodeType == XmlNodeType.Element && myReader.Name == "command_name" && myReader.IsStartElement())
{
name.Add(myReader.ReadInnerXml() + " ");
}
if (myReader.NodeType == XmlNodeType.Element && myReader.Name == "command_result" && myReader.IsStartElement())
{
result.Add(myReader.ReadInnerXml() + " ");
class2.Add(class2name);
class3.Add(class3name);
}
}
myReader.Close();
string test_date = testDate + " " + testTime;
string status = "";
string errmessage = "";
bool NoteAlready = false;
LogicHandler.GetMakeInfo(sncode, out makecode, out status, out errmessage);
if (ma_code.Text != makecode && makecode != "" && ma_code.Text != "" && status != "2")
{
string ChangeMakeCode = MessageBox.Show(this.ParentForm, "序列号" + sncode + "所属工单不同,是否切换?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
//如果选择不切换赋值当前界面工单
if (ChangeMakeCode != "Yes")
{
makecode = ma_code.Text;
}
else
{
NoteAlready = true;
}
}
if (CheckRoutePassed(sncode,isource, makecode,out oErrMessage))
{
if (!NoteAlready)
{
if (makecode != ma_code.Text && ma_code.Text != "" && status != "")
{
string ChangeMakeCode = MessageBox.Show(this.ParentForm, "序列号所属工单不同,是否切换?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
//如果选择不切换赋值当前界面工单
if (ChangeMakeCode == "Yes")
{
ma_code.Text = makecode;
}
else
{
OperateResult.AppendText(">>请重新采集序列号\n");
tipform.startthread("请重新采集序列号", test_result);
return;
}
}
}
//获取序列号ID最大的工单
dt = (DataTable)dh.ExecuteSql("select ms_status,ms_makecode,ms_id,ms_craftcode,ms_prodcode from makeserial where ms_sncode='" + sncode + "' order by ms_id desc", "select");
if (dt.Rows.Count > 0)
{
string ms_status = dt.Rows[0]["ms_status"].ToString();
string ms_craftcode = dt.Rows[0]["ms_craftcode"].ToString();
string ms_prodcode = dt.Rows[0]["ms_prodcode"].ToString();
ma_code.Text = dt.Rows[0]["ms_makecode"].ToString();
makecode = dt.Rows[0]["ms_makecode"].ToString();
switch (test_result)
{
case "OK":
if(BaseUtil.GetCacheData("Status").ToString() != "offline")
{
if (ms_status == "3")
{
string nextstepcode = dh.getFieldDataByCondition("craft left join craftdetail on cr_id=cd_crid ", "cd_nextstepcode", "cr_code='" + ms_craftcode + "' and cr_prodcode='" + ms_prodcode + "' and cd_stepcode='" + istepcode + "'").ToString();
dh.UpdateByCondition("makeserial", "ms_status=1,ms_nextstepcode='" + nextstepcode + "'", "ms_sncode='" + sncode + "' and ms_makecode='" + makecode + "'");
dh.UpdateByCondition("makebad", "mb_status=-1", "mb_sncode='" + sncode + "' and mb_makecode='" + makecode + "'");
}
if (!LogicHandler.SetStepResult(makecode, isource, sncode, "自动过站采集", test_result, iusercode, out oErrMessage))
{
OperateResult.AppendText(oErrMessage + "\n");
tipform.startthread(oErrMessage, test_result);
return;
}
}
tipform.startthread("序列号 " + sncode + "通过检测,OK", test_result);
break;
case "NG":
if (BaseUtil.GetCacheData("Status").ToString() != "offline")
{
RecordBadInfo(sncode, makecode, e.Name, "");
//所有的序列号均采集为良品
if (!LogicHandler.SetTestNGDetail(sncode, makecode, iusercode, isource, test_result, out oErrMessage))
{
OperateResult.AppendText(oErrMessage + "\n");
tipform.startthread(oErrMessage, test_result);
return;
}
}
tipform.startthread("序列号 " + sncode + "未通过检测,NG", test_result);
break;
default:
break;
}
LogicHandler.AutoPassLog(sncode, isource, makecode, test_date, istepcode, ilinecode, e.Name, test_result == "NG" ? "1" : "0", "0");
}
}
else
{
OperateResult.AppendText(oErrMessage + "\n");
tipform.startthread(oErrMessage, "NG");
return;
}
if (BaseUtil.GetCacheData("Mode").ToString() != "SPI")
{
string sql = "insert into STEPTESTDETAIL(std_id,std_makecode,std_sn,std_subclass1,std_subclass2,std_subclass3,std_testresult,std_indate,";
sql += "std_rescode,std_testdate,std_testtime,std_date) values(STEPTESTDETAIL_seq.nextval, '" + makecode + "', ";
sql += "'" + sncode + "',:std_subclass1,:std_subclass2,:std_subclass3,:std_testresult, sysdate,'" + isource + "',to_char(to_date('" + testDate + "','YYYY/MM/DD'), 'YYYYMMDD'),";
sql += "to_char(to_date('" + testTime + "','hh24:mi:ss'), 'hh24miss'),to_date('" + test_date + "','YYYY/MM/DD hh24:mi:ss'))";
dh.BatchInsert(sql, new string[] { "std_subclass1", "std_subclass2", "std_subclass3", "std_testresult" }, name.ToArray(), class2.ToArray(), class3.ToArray(), result.ToArray());
}
else {
string sql = "insert into SPIDATA(SPI_ID,SPI_SNCODE,SPI_ITEM,SPI_RESULT,SPI_DATE,SPI_TESTDATE) values(SPIDATA_SEQ.nextval, ";
sql += "'" + sncode + "',:std_subclass1,:std_testresult, sysdate,";
sql += "to_date('" + test_date + "','YYYY/MM/DD hh24:mi:ss'))";
dh.BatchInsert(sql, new string[] { "std_subclass1", "std_testresult" }, name.ToArray(), result.ToArray());
}
FileInfo file = new FileInfo(FolderPath.Text + @"\" + e.Name);
if (file.Exists)
{
try
{
for (int i = 1; i <= 20; i++)
{
if (!File.Exists(BackUpFolderPath.Text + @"\" + e.Name))
{
file.MoveTo(BackUpFolderPath.Text + @"\" + e.Name);
OperateResult.AppendText("成功解析文件" + e.Name + "\n");
//tipform.startthread(e.Name);
break;
}
else if (!File.Exists(BackUpFolderPath.Text + @"\" + e.Name.Split('.')[0] + "(" + i + ")" + "." + e.Name.Split('.')[1]))
{
file.MoveTo(BackUpFolderPath.Text + @"\" + e.Name.Split('.')[0] + "(" + i + ")" + "." + e.Name.Split('.')[1]);
OperateResult.AppendText("成功解析文件" + e.Name + "\n");
//tipform.startthread(e.Name);
break;
}
}
}
catch (Exception ex)
{
OperateResult.AppendText(e.Name + ex.Message + "\n");
}
}
}
private void StopWatch_Click(object sender, EventArgs e)
{
XmlWatcher.EnableRaisingEvents = false;
StartWatch.Enabled = true;
ChooseFolder.Enabled = true;
ChooseBackUpFolder.Enabled = true;
StopWatch.Enabled = false;
OperateResult.AppendText("停止执行监控\n");
}
private void Clean_Click(object sender, EventArgs e)
{
OperateResult.Clear();
}
private void ChooseFolder_Click(object sender, EventArgs e)
{
FolderBrowserDialog folder = new FolderBrowserDialog();
folder.Description = "选择监控文件夹";
DialogResult result = folder.ShowDialog();
if (result == DialogResult.OK)
{
FolderPath.Text = folder.SelectedPath;
}
}
private void ReadNodeFromXML(string FileName)
{
}
private void RecordBadInfo(string sncode, string makecode, string filename, string combine)
{
string ID = dh.GetSEQ("makebad_seq");
sql.Clear();
sql.Append("insert into makebad(mb_id,mb_makecode,mb_mscode,mb_sncode,mb_inman,mb_indate,mb_stepcode");
sql.Append(",mb_sourcecode,mb_badcode,mb_bgcode,mb_badtable,mb_status,mb_badremark) select "+ ID + "");
sql.Append(",ma_code,ms_code,ms_sncode,'" + iusercode + "',sysdate,'" + istepcode + "','" + isource + "',");
sql.Append("'','" + ibadgroup + "','','0','' from make left join makeSerial on ms_makecode=ma_code ");
sql.Append("where ms_sncode='" + sncode + "' and ms_makecode='" + makecode + "'");
dh.ExecuteSql(sql.ToString(),"insert");
sql.Clear();
sql.Append("update makebad set mb_badname=(select DISTINCT bc_name from badcode where bc_code=mb_badcode),mb_bgname=(select DISTINCT bg_name from badgroup where bg_code=mb_bgcode) ");
sql.Append("where mb_id="+ ID + "");
dh.ExecuteSql(sql.ToString(), "insert");
//记录判断日志
if (dh.getFieldDataByCondition("source", "sc_scantype", "sc_code='" + isource + "'").ToString() == "REJUCE")
{
LogicHandler.AutoPassJudge(sncode, makecode, isource, filename, ilinecode, combine);
}
}
private void ChooseBackUpFolder_Click(object sender, EventArgs e)
{
FolderBrowserDialog folder = new FolderBrowserDialog();
folder.Description = "选择备份文件夹";
DialogResult result = folder.ShowDialog();
if (result == DialogResult.OK)
{
BackUpFolderPath.Text = folder.SelectedPath;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
string ExitConfirm = MessageBox.Show(this, "确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
if (ExitConfirm != "Yes")
{
WindowState = FormWindowState.Minimized;
e.Cancel = true;
}
}
private void AutoStart_CheckedChanged(object sender, EventArgs e)
{
SetAutoRun();
}
public bool CheckRoutePassed(string iSN, string iResCode,string makecode, out string oErrMessage)
{
if (iSN == "")
{
oErrMessage = "SN不能为空";
return false;
}
oErrMessage = "";
string[] param = new string[] { ma_code.Text == "" ? makecode : ma_code.Text, iResCode, iSN, iusercode, "", "", oErrMessage };
string[] ParamName = new string[] { "v_i_macode", "v_i_sourcecode", "v_i_sncode", "v_i_usercode", "v_o_macode", "v_o_msid", "v_o_errmsg" };
dh.CallProcedure("CS_CHECKSTEPSNANDMACODE", ParamName, ref param);
oErrMessage = param[6];
DataTable dt = (DataTable)dh.ExecuteSql("select ms_status,ms_stepcode,ms_nextstepcode from makeserial where ms_id=( select max(ms_id) from makeserial where ms_sncode in ( select '" + iSN + "' from dual union select sn from makesnrelation where beforesn='" + iSN + "' and sn<>' ' union select beforesn from makesnrelation where sn='" + iSN + "' and beforesn<>' '))", "select");
string ms_status = "";
string ms_stepcode = "";
string ms_nextstepcode = "";
if (dt.Rows.Count > 0)
{
ms_status = dt.Rows[0]["ms_status"].ToString();
ms_stepcode = dt.Rows[0]["ms_stepcode"].ToString();
ms_nextstepcode = dt.Rows[0]["ms_nextstepcode"].ToString();
}
string stepcode = GetStepCodeBySource(iResCode);
if (ms_nextstepcode != "" && ms_nextstepcode != stepcode)
{
oErrMessage = "当前序列号下一工序" + ms_nextstepcode;
return false;
}
if (oErrMessage == "" || oErrMessage == null || oErrMessage == "null" || (ms_status == "3" && stepcode == ms_stepcode))
{
if (ms_status == "3")
{
oErrMessage = "";
}
return true;
}
else
return false;
}
private string GetStepCodeBySource(string Source)
{
return dh.getFieldDataByCondition("source", "sc_stepcode", "sc_code='" + Source + "'").ToString();
}
}
}