using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Data; using System.Collections; using NPOIReport; using System.Diagnostics; using System.Runtime.InteropServices; using Estsh.Client.Base; using System.Windows.Forms; using Com.Estsh.MES.App; using ApServerProvider; using MainProgram; using MainProgram.BLL; using System.Threading; using Esi.Mes.LabelPrinter; using ZPLPrinter; using System.Net.NetworkInformation; namespace Estsh.Client.StepLibrary { public class PrintSN : StepBase { //计数器数量 private string _PrdCount = string.Empty; private RouteHelper _routeHelper = null; private string _ProcessID; private string _CheckRouteNecessary; private static CodesoftPrinter m_csPrinter = new CodesoftPrinter(); private static string BarTenderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"App_Data\Bartend\bartend.exe"); private static string LabelPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"App_Data\LabelFile"); private static object _lock_print_object = new object(); private const char TAB = '\t'; private const string NEW_LINE = "\r\n"; private List dtLabel = null; public static bool PrintSerialNumber(List snData, string templateFile, string txtDataFile) { if (!CommonListData.CheckDataValid(snData)) return false; string LabelTemplatePath = Path.Combine(LabelPath, templateFile); string partLation = snData[0]["part_location"].ToString(); //string LabelTextPath = Path .Combine (LabelPath , "BS" + ".txt"); //string LabelFilePath = Path .Combine (LabelPath , "BS" + ".BTW"); string LabelTextPath = Path.Combine(LabelPath, "BS" + ".txt"); string LabelFilePath = string.Empty; if (partLation == "03") { LabelFilePath = Path.Combine(LabelPath, "MaxBS.Lab"); } else { LabelFilePath = Path.Combine(LabelPath, "BS.Lab"); } StringBuilder PrintContent = new StringBuilder(); foreach (DataRow dr in snData) { string partLocation = dr["part_location"].ToString(); if (partLocation == "0D" || partLocation == "0E") { PrintContent.Append(dr["f10"].ToString()); PrintContent.Append(TAB);//1 serial_number } else { PrintContent.Append(dr["f1"].ToString()); PrintContent.Append(TAB);//1 serial_number } PrintContent.Append(dr["f2"].ToString()); PrintContent.Append(TAB); //2 type_name PrintContent.Append(dr["f3"].ToString()); PrintContent.Append(TAB); //3 model_name PrintContent.Append(dr["f4"].ToString()); PrintContent.Append(TAB); //4 part_spec PrintContent.Append(dr["f5"].ToString()); PrintContent.Append(TAB); //5 part_no_3c PrintContent.Append(dr["f6"].ToString()); PrintContent.Append(TAB); //6 enum_desc PrintContent.Append(dr["f7"].ToString()); PrintContent.Append(TAB); //7 car_no PrintContent.Append(dr["f8"].ToString()); PrintContent.Append(TAB); //8 简码+颜色代码 cust_part_no + part_class PrintContent.Append(dr["part_no"].ToString()); PrintContent.Append(TAB); PrintContent.Append(dr["number_T"].ToString()); PrintContent.Append(TAB); //9流水号 PrintContent.Append(dr["part_T"].ToString()); PrintContent.Append(TAB); //10 PrintContent.Append(dr["ymd"].ToString()); PrintContent.Append(TAB); //11 ymd PrintContent.Append(dr["hms"].ToString()); PrintContent.Append(TAB); //12 hms PrintContent.Append(dr["part_class"].ToString()); PrintContent.Append(TAB); //11 part_class PrintContent.Append(Environment.NewLine); lock (_lock_print_object) { WritePrintLog(PrintContent.ToString()); //BarTenderPrinter .WriteFile (LabelTextPath , PrintContent .ToString () , Encoding .UTF8 , false); //BarTenderPrinter .Print (BarTenderPath , LabelFilePath); PrintCodeSoftSN(dr, LabelFilePath, m_csPrinter); } return true; } return true; } public static bool PrintCodeSoftSN(DataRow snData, string LabelTextPath, CodesoftPrinter csPrinter) { Dictionary printData = new Dictionary(); printData.Add("serial_number", snData["f1"].ToString()); printData.Add("cust_part_no", snData["cust_part_no"].ToString()); printData.Add("part_spec", snData["f4"].ToString()); printData.Add("part_no", snData["part_no"].ToString()); printData.Add("part_T", snData["part_T"].ToString()); printData.Add("number_T", snData["number_T"].ToString()); printData.Add("model_alias", snData["model_alias"].ToString()); printData.Add("create_time", snData["create_time"].ToString()); csPrinter.DoPrint(LabelTextPath, printData, 1); return true; } private static void WritePrintLog(string msgText) { string logPath = AppDomain.CurrentDomain.BaseDirectory + @"\\PrintLog"; try { if (!System.IO.Directory.Exists(logPath)) { System.IO.Directory.CreateDirectory(logPath); } string txtMsgPath = logPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log"; string timeStamp = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss-->"); using (StreamWriter sw = new StreamWriter(txtMsgPath, true)) { sw.WriteLine(timeStamp + msgText.ToString()); sw.Flush(); sw.Close(); } } catch (System.Exception ex) { } } /// /// 输入到打印机 /// /// BarTender.exe 的路径 /// *.btw 文件的路径 public static void Print(string bartendPath, string labelPath) { Process process = new Process(); process.StartInfo = new ProcessStartInfo(ToShortPathName(bartendPath), @" /F=" + ToShortPathName(labelPath) + " /p /x"); process.StartInfo.CreateNoWindow = true; process.StartInfo.UseShellExecute = false; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.RedirectStandardOutput = true; try { process.Start(); process.WaitForExit(100 * 1000); //等待上述进程执行完毕 if (process.HasExited == false) //程序停止响应处理 { process.Kill(); process.Dispose(); } } catch { process.Kill(); process.Dispose(); } } /// /// 获取短路径 /// /// 长路径 /// 短路径 /// 短路径的长度 /// 执行结果 [DllImport("kernel32.dll ", CharSet = CharSet.Auto)] public static extern int GetShortPathName([MarshalAs(UnmanagedType.LPTStr)] string path, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder shortPath, int shortPathLength); /// /// 把长路径转化为短路径(兼容 WIN 98 格式) /// /// 长路径 /// 短路径 public static string ToShortPathName(string longName) { StringBuilder shortNameBuffer = new StringBuilder(256); int bufferSize = shortNameBuffer.Capacity; int result = GetShortPathName(longName, shortNameBuffer, bufferSize); return shortNameBuffer.ToString(); } /// /// Ping 打印机,看是否连通 /// /// private bool IsActive() { Ping ping = new Ping(); PingReply reply = ping.Send(printIP); return reply.Status == IPStatus.Success; } private string printIP = string.Empty; /// /// 执行工步操作 /// /// 执行结果 public override bool Do() { try { //本地计数器 CountRead(); MESPrintSN _app = new MESPrintSN(App); Action(this, new EventArgs()); //bool useJupStep = Context.Contains("useJupStep"); //if (!useJupStep) //{ dtLabel = _app.GetPrintSN2(Context["serial_number"].ToString()); ShowMessage(this, "green|条码正在打印中,条码: " + Context["serial_number"].ToString()); PrintSerialNumber(dtLabel, LabelPath, ""); #region 无用代码 //try //{ // printIP = _app.GetPrintIP(Context["terminal_id"].ToString()); // if (string.IsNullOrEmpty(printIP)) // { // ShowMessage(this, "red|工位参数中没有正确配置打印机IP地址,请联系系统管理员处理!"); // return false; // } // if (!IsActive()) // { // ShowMessage(this, "red|打印机 " + printIP + " 无法连通,请确认网线连接!"); // } // else // { // PrintSNByZPL zplPrinter = new PrintSNByZPL(); // string partLocation = dtLabel[0]["part_location"].ToString(); // if (partLocation == "0D" || partLocation == "0E") // { // zplPrinter.PrintSerialNumber(dtLabel, Context["StepLibrary.PrintSN1.BTWFileName.BTW"].ToString(), printIP, 9100, 1); // } // else // { // zplPrinter.PrintSerialNumber(dtLabel, Context["StepLibrary.PrintSN.BTWFileName.BTW"].ToString(), printIP, 9100, 1); // } // } //} //catch //{ // ShowMessage(this, "red|打印机连接失败,请确认打印机网络!"); // return false; //} #endregion _app.UpdatePrintCount(Context["serial_number"].ToString()); // 修改上线时间 _app.UpdateBarcodeInPdlineTime(Context["serial_number"].ToString()); string stationType = _app.stationType(Context["terminal_id"].ToString()); string pdlineID = _app.pdLineID(Context["terminal_id"].ToString()); if (stationType == "B") { _app.updateOnLineStatus(Context["serial_number"].ToString(), pdlineID); } //} //Context.Remove("useJupStep"); //本地计数器 CountAdd(); Complate(this, new EventArgs()); return base.Do(); } catch (Exception ex) { // 记录日志 using (StreamWriter sw = new StreamWriter("Error_Log_" + DateTime.Now.ToString("yyyyMM") + ".txt", true)) { sw.WriteLine(string.Format("{0} {1}", "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] ", ex.ToString())); sw.Flush(); sw.Close(); } return false; } } void routeGO() { MESPrintSN _app = new MESPrintSN(App); _routeHelper = new RouteHelper(App); _ProcessID = _app.GetProcessID(Convert.ToInt32(Context["terminal_id"].ToString()))[0]["process_id"].ToString(); _CheckRouteNecessary = _app.GetRouteNecessary(_ProcessID)[0]["necessary"].ToString(); if (_CheckRouteNecessary == "Y") { // 流程卡站功能 if (!_routeHelper.RouteGO(Context["serial_number"].ToString(), Convert.ToInt32(Context["terminal_id"].ToString()))) { ShowMessage(this, _routeHelper.ErrorMessage); return; } } } private void InitializeComponent() { this.SuspendLayout(); // // PrintSN // this.Name = "PrintSN"; this.Size = new System.Drawing.Size(467, 186); this.Load += new System.EventHandler(this.PrintSN_Load); this.ResumeLayout(false); } private void CountAdd() { string value = _PrdCount; int count = 0; try { count = Convert.ToInt32(value); count++; _PrdCount = count.ToString(); } catch { _PrdCount = "1"; } try { StreamWriter sw = new StreamWriter("InPdlineCount.txt"); sw.Write(count.ToString()); sw.Flush(); sw.Close(); } catch { ShowMessage(this, "计数器更新错误,未知!"); } } private void CountRead() { try { if (File.Exists("InPdlineCount.txt")) { FileStream fs = new FileStream(@"InPdlineCount.txt", FileMode.Open); StreamReader sr = new StreamReader(fs); string content = sr.ReadToEnd(); //一次性读取全部数据 _PrdCount = content; fs.Close(); sr.Close(); } else { _PrdCount = "0"; } } catch { _PrdCount = "0"; ShowMessage(this, "计数器更新错误,未知!"); } } private void PrintSN_Load(object sender, EventArgs e) { } } }