using System; using System.Collections.Generic; using System.Data; using System.Text; using System.Timers; //using System.Windows.Forms; using Curtain.DataAccess; using Curtain.Framework.Utils; using Curtain.Framework.Windows; using Curtain.WCF.Proxy; using Dongke.IBOSS.PRD.Basics.Library; using PLCCommunication.Proxy; namespace PCLCommunication { public class ConnSetting { private ConnSetting() { } public static Dictionary PLC_Timers = new Dictionary(); //public static Dictionary PLC_Do = new Dictionary(); public static Dictionary PLC_Conn = new Dictionary(); public static Dictionary PLC_ConnServer = new Dictionary(); public static DataTable T_Setting = null; public static DataTable T_PLC = null; public static string _sqlitString = null; public static string _oracleString = null; public static string INI_NAME = "DBSetting.ini"; public static string INI_PATH = ApplicationInformation.GetAbsolutePath(INI_NAME); public static string[] PLCServiceSettings = new string[2]; public static MESInfo MESInfo = null; public static void SetMESInfo() { INIUtil ini = INIUtil.IniFile(INI_PATH); MESInfo = new MESInfo(); MESInfo.IP = ini.Read("iBOSS.MES", "IP"); MESInfo.Port = ini.Read("iBOSS.MES", "Port"); MESInfo.ServiceName = ini.Read("iBOSS.MES", "ServiceName"); MESInfo.AccountCode = ini.Read("iBOSS.MES", "AccountCode"); MESInfo.UserCode = ini.Read("iBOSS.MES", "UserCode"); MESInfo.Password = ini.Read("iBOSS.MES", "Password"); MESInfo.Procedures.Add(ini.Read("Procedures", "ProcedureID")); if (!string.IsNullOrWhiteSpace(MESInfo.IP)) { WCFProxySetting.DefaultSetting.ResetRemoteAddress(MESInfo.IP, MESInfo.Port, MESInfo.ServiceName); } } public static void SavePLCServicePort() { INIUtil ini = INIUtil.IniFile(INI_PATH); ini.Write("PLCService", "Port", PLCServiceSettings[1]); } public static void SetOracleConnStr() { INIUtil ini = INIUtil.IniFile(INI_PATH); PLCServiceSettings[0] = ini.Read("PLCService", "AutoStart"); PLCServiceSettings[1] = ini.Read("PLCService", "Port"); string p = ini.Read("Oracle", "Password"); try { p = Encryption.DecryptDES(p, "DongkeIbossprd"); } catch { } _oracleString = DataAccessFactory.GetConnectionString(DataBaseType.Oracle, ini.Read("Oracle", "Server"), ini.Read("Oracle", "Port"), ini.Read("Oracle", "Database"), ini.Read("Oracle", "UserName"), p ); } /// /// 初始化 /// public static void Init() { _sqlitString = DataAccessFactory.GetConnectionString(DataBaseType.SQLite, ApplicationInformation.GetAbsolutePath("PLCSetting.db")); SetOracleConnStr(); SetMESInfo(); IDataAccess dataAccess = null; try { dataAccess = DataAccessFactory.CreateDataAccess(_sqlitString, DataBaseType.SQLite); T_Setting = dataAccess.ExecuteDatatable("select * from T_Setting"); string sqlString = "SELECT t.*\n" + " , CASE\n" + " WHEN t.ConnType = '1' THEN\n" + " '长连接'\n" + " ELSE\n" + " '短连接'\n" + " END ConnTypeName\n" + " , CASE\n" + " WHEN t.Enable = -1 THEN\n" + " '禁用'\n" + " WHEN t.Enable = 0 THEN\n" + " '手动'\n" + " ELSE\n" + " '自动'\n" + " END EnableName\n" + " ,0 status \n" + " ,'未启动' statusname\n" + " ,'启用' ss\n" + " FROM T_PLC t"; T_PLC = dataAccess.ExecuteDatatable(sqlString); AutoRun(); } catch (Exception ex) { // TODO log LogOut.Error(null, ex); throw ex; } finally { dataAccess?.Close(); } } /// /// 自动启动 /// public static void AutoRun() { try { string autoRun = T_Setting.Rows[0]["AutoRun"].ToString(); foreach (DataRow item in T_PLC.Rows) { string key = item["GUID"].ToString(); //PLC_Do.Add(key, false); /* Timer t = new Timer(); PLC_Timers.Add(key, t); //t.Tag = key; t.AutoReset = true; t.Interval = Convert.ToInt32(item["Interval"]); //t.Tick += Timer_Tick; t.Elapsed += T_Elapsed; */ /* MelsecA1EAscii m = new MelsecA1EAscii(item["IP"].ToString(), Convert.ToInt32(item["Port"])); m.Always = (item["ConnType"].ToString() == "1" ? true : false); //PLC_Conn.Add(key, m); PLC_Conn.Add(t, m); */ MelsecA1EAscii m1 = new MelsecA1EAscii(item["IP"].ToString(), Convert.ToInt32(item["Port"])); m1.Always = (item["ConnType"].ToString() == "1" ? true : false); PLC_ConnServer.Add(key, m1); /* //if (autoRun == "1") if (autoRun == "0") { if (item["Enable"].ToString() == "1") { item["Status"] = "1"; item["StatusName"] = "已启动"; item["ss"] = "停止"; t.Start(); //T_Elapsed(t, null); } //else //{ // item["Status"] = "0"; // item["StatusName"] = "停用"; //} } */ } } catch (Exception ex) { // TODO log LogOut.Error(null, ex); throw ex; } } /// /// PLC通信 /// /// /// //private static void Timer_Tick(object sender, EventArgs e) private static void T_Elapsed(object sender, ElapsedEventArgs e) { Timer t = sender as Timer; MelsecA1EAscii m = null; if (t == null) { return; } //string key = t.Tag + ""; bool hasLog = true; StringBuilder lbl = new StringBuilder(); string d501 = null; string code = null; try { lock (t) { //MelsecA1EAscii m = PLC_Conn[key]; m = PLC_Conn[t]; try { m.Always = true; //m.ConnectSocket(); } catch( Exception ex) { //string j = JsonUtil.FromObject(t) // + JsonUtil.FromObject(m) // + "\r\n" + lbl; //LogOut.Error(null, ex, j); lbl.Append("PLC连接失败 : " + ex.Message); return; } lbl.Append("读取 D330 标识 : "); // 读取 D330 标识 string d330 = m.GetHexData("D", 330, 1); lbl.AppendLine(d330); lbl.AppendLine(JsonUtil.FromObject(m)); if (d330 != "81000001") { // TODO 调试 //hasLog = false; return; } lbl.Append("读取 D341 条码 : "); // 读取 D341 条码 byte[] b501 = m.GetByteData("D", 341, 6); if (b501 == null || b501.Length == 0) { SetPLCError(m, lbl, "条码为空"); return; } d501 = Encoding.ASCII.GetString(b501); d501 = d501.Substring(0, 11); lbl.AppendLine(d501); lbl.AppendLine(JsonUtil.FromObject(m)); lbl.Append("查询 产品编码 : "); // 查询 产品编码 code = GetGoodscode(d501); lbl.AppendLine(code); bool r = false; if (string.IsNullOrEmpty(code)) { lbl.AppendLine("写入 D332 产品型号长度"); // 写入 D332 产品型号长度 r = m.SetData("D", 332, 1, "0000"); lbl.AppendLine(JsonUtil.FromObject(m)); lbl.AppendLine("写入 D351 产品型号"); r = m.SetData("D", 351, 10, "0000000000000000000000000000000000000000"); lbl.AppendLine(JsonUtil.FromObject(m)); lbl.AppendLine("写入 D330 标识"); // 写入 D330 标识 r = m.SetData("D", 330, 1, "0000"); lbl.AppendLine(JsonUtil.FromObject(m)); } else { int l = code.Length; lbl.AppendLine("写入 D332 产品型号长度"); // 写入 D332 产品型号长度 r = m.SetData("D", 332, 1, l.ToString("0000")); lbl.AppendLine(JsonUtil.FromObject(m)); lbl.AppendLine("写入 D351 产品型号"); // 写入 D351 产品编码 byte[] d521 = Encoding.ASCII.GetBytes(code); r = m.SetData("D", 351, 10, d521); lbl.AppendLine(JsonUtil.FromObject(m)); lbl.AppendLine("写入 D330 标识"); // 写入 D330 标识 //r = m.SetData("D", 330, 1, "0002"); r = m.SetData("D", 330, 1, "0000"); lbl.AppendLine(JsonUtil.FromObject(m)); } } // TODO 正常读取不记录日志 //hasLog = false; } catch (Exception ex) { SetPLCError(m, lbl, "系统异常:"+ ex.Message); string j = JsonUtil.FromObject(t) + JsonUtil.FromObject(m) + "\r\n" + lbl; LogOut.Error(null, ex, j); //throw ex; } finally { m.CloseSocket(); if (hasLog) { string j = JsonUtil.FromObject(t) + JsonUtil.FromObject(m) + "\r\n" + lbl; LogOut.Debug(null, j); } } } public static void SetPLCError(MelsecA1EAscii m, StringBuilder lbl, string message) { //try //{ // lbl.AppendLine("写入 D541 错误标识 : " + message); // // 写入 D541 错误标识 // m.SetData("D", 541, 1, "0001"); // lbl.AppendLine(JsonUtil.FromObject(m)); //} //catch(Exception ex) //{ // string j = JsonUtil.FromObject(m) // + "\r\n" + lbl; // LogOut.Error(null, ex, j); //} if (m == null) { return; } lbl.AppendLine("写入 D331 错误标识 : " + message); // 写入 D331 错误标识 bool result = m.SetData("D", FrmMelsecA1EAscii.PLC_Error_Flag, 1, "0001"); lbl.AppendLine(JsonUtil.FromObject(m)); if (!result) { lbl.AppendLine("PLC操作失败"); } } public static void SetPLCError2(MelsecA1EAscii m, StringBuilder lbl, string message) { //try //{ // lbl.AppendLine("写入 D541 错误标识 : " + message); // // 写入 D541 错误标识 // m.SetData("D", 541, 1, "0001"); // lbl.AppendLine(JsonUtil.FromObject(m)); //} //catch(Exception ex) //{ // string j = JsonUtil.FromObject(m) // + "\r\n" + lbl; // LogOut.Error(null, ex, j); //} if (m == null) { return; } lbl.AppendLine("写入 D511 错误标识 : " + message); // 写入 D331 错误标识 bool result = m.SetData("D", FrmMelsecA1EAscii.PLC_Error_Flag2, 1, "0001"); lbl.AppendLine(JsonUtil.FromObject(m)); if (!result) { lbl.AppendLine("PLC操作失败"); } } /// /// 查询 产品编码 /// /// /// public static string GetGoodscode(string barcode) { IDataAccess dataAccess = null; try { dataAccess = DataAccessFactory.CreateDataAccess(_oracleString, DataBaseType.Oracle); string goodscode = dataAccess.ExecuteScalar( "select g.goodscode from tp_pm_groutingdailydetail g where g.barcode = '" + barcode + "'"); if (goodscode == null) { goodscode = ""; } return goodscode; } catch (Exception ex) { // todo log LogOut.Error(null, ex, barcode + " :: " + _oracleString); //return "H0126L-N"; return ""; } finally { dataAccess?.Close(); } } public static bool DeletePLC(string guid) { IDataAccess dataAccess = null; try { dataAccess = DataAccessFactory.CreateDataAccess(_sqlitString, DataBaseType.SQLite); dataAccess.ExecuteNonQuery("delete from t_plc where guid = '" + guid + "'"); /* if (PLC_Timers.ContainsKey(guid)) { Timer t = PLC_Timers[guid]; if (t != null) { if (PLC_Conn.ContainsKey(t)) { MelsecA1EAscii m = PLC_Conn[t]; if (m != null) { m.Dispose(); m = null; } PLC_Conn.Remove(t); } t.Stop(); t.Dispose(); t = null; } PLC_Timers.Remove(guid); //PLC_ConnServer.Remove(guid); } */ if (PLC_ConnServer.ContainsKey(guid)) { PLC_ConnServer.Remove(guid); } //if (PLC_Conn.ContainsKey(guid)) //{ // MelsecA1EAscii m = PLC_Conn[guid]; // if (m != null) // { // m.Dispose(); // m = null; // } // PLC_Conn.Remove(guid); //} return true; } catch (Exception ex) { LogOut.Error(null, ex); throw ex; } finally { dataAccess?.Close(); } } public static bool StopPLC(string guid) { try { if (PLC_Timers.ContainsKey(guid)) { Timer t = PLC_Timers[guid]; if (t != null) { t.Stop(); } } return true; } catch (Exception ex) { LogOut.Error(null, ex); throw ex; } } public static bool StartPLC(string guid) { try { if (PLC_Timers.ContainsKey(guid)) { Timer t = PLC_Timers[guid]; if (t != null) { t.Start(); T_Elapsed(t, null); } } return true; } catch (Exception ex) { LogOut.Error(null, ex); throw ex; } } public static void Dispose() { try { foreach (string guid in PLC_Timers.Keys) { Timer t = PLC_Timers[guid]; if (t != null) { if (PLC_Conn.ContainsKey(t)) { MelsecA1EAscii m = PLC_Conn[t]; if (m != null) { m.Dispose(); m = null; } PLC_Conn.Remove(t); } t.Stop(); t.Dispose(); t = null; } //PLC_Timers.Remove(guid); } PLC_Timers.Clear(); PLC_ConnServer.Clear(); } catch { } } public static void EditPLC(DataRow item) { IDataAccess dataAccess = null; try { dataAccess = DataAccessFactory.CreateDataAccess(_sqlitString, DataBaseType.SQLite); string sql = "update t_plc set ip = '" + item["ip"] + "'" + ", port = " + item["port"] + "" + ", Interval = " + item["Interval"] + "" + " where guid = '" + item["guid"] + "'"; dataAccess.ExecuteNonQuery(sql); string guid = item["guid"].ToString(); if (PLC_ConnServer.ContainsKey(guid)) { MelsecA1EAscii m = PLC_ConnServer[guid]; if (m != null) { m.IP = item["ip"].ToString(); m.Port = Convert.ToInt32(item["port"]); //m.CloseSocket(); } } if (PLC_Timers.ContainsKey(guid)) { Timer t = PLC_Timers[guid]; if (t != null) { if (PLC_Conn.ContainsKey(t)) { MelsecA1EAscii m = PLC_Conn[t]; if (m != null) { m.IP = item["ip"].ToString(); m.Port = Convert.ToInt32(item["port"]); m.CloseSocket(); } } int inter = Convert.ToInt32(t.Interval); int newInter = Convert.ToInt32(item["Interval"]); if (inter != newInter) { t.Interval = newInter; if (t.Enabled) { t.Stop(); t.Start(); T_Elapsed(t, null); } } } } } catch (Exception ex) { LogOut.Error(null, ex); throw ex; } finally { dataAccess?.Close(); } } /// /// 自动工序计件 /// /// public static void AddWorkPiece(string barcode, string text) { if (MESInfo == null|| string.IsNullOrWhiteSpace(MESInfo.IP) || string.IsNullOrWhiteSpace(MESInfo.Port) || string.IsNullOrWhiteSpace(MESInfo.AccountCode) || string.IsNullOrWhiteSpace(MESInfo.UserCode) ) { return; } try { string userPassword = (string.IsNullOrWhiteSpace(ConnSetting.MESInfo.Password) ? text : ConnSetting.MESInfo.Password); int procedureID = Convert.ToInt32(ConnSetting.MESInfo.Procedures[0]); SmartDeviceProxy.Instance.Invoke(p => p.AddWorkPiece(ConnSetting.MESInfo.AccountCode, ConnSetting.MESInfo.UserCode, userPassword, procedureID, barcode)); } catch (Exception ex) { LogOut.Error(SmartDeviceProxy.Instance.ServiceName, ex, "AddWorkPiece"); } } } }