using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using Mesnac.Controls.Base; using System; using Mesnac.Controls.Default; using System.Drawing.Design; using System.Collections; using System.Windows.Forms; using System.ComponentModel.Design; using System.Globalization; using Mesnac.Basic; using Mesnac.Codd.Session; using System.Data; using System.Text; using Mesnac.Compressor.Entity; using System.Threading; using System.Reflection; using Mesnac.Compressor.Station; using PLCManager; using System.IO; using Mesnac.Controls.Feeding; using System.Windows.Forms.Design; using Mesnac.Gui.Edit.Dialog; namespace Mesnac.Controls.Compressor { [ToolboxBitmap(typeof(Mixer2), "ICONS.mixer.bmp")]//新添加的代码 public partial class StationButton : FeedingControl { private List _clickActionList = new List(); private List _keyDownActionList = new List(); private List _keyUpActionList = new List(); private bool _mcVisible = true; //保存可见性 private bool _mcEnabled = true; //保存可用性 private bool _isValid = true; //保存有效性 private object _mcvalue; DbHelper dbHelper = DataSourceFactory.Instance.GetDbHelper("DataSource1"); private const int dataStateIndex = 1; private const int MaxData = 6000; private const int dataLength = 90;//读取数据长度,字 public event EventHandler ReshreshStationData; private int dataIndex = -1; private bool FirstRead = true; public StationButton() { InitializeComponent(); this.textBox1.ReadOnly = true; this.textBox1.Multiline = true; //this.textBox1.Size = new Size(150,150); this.textBox1.BackColor = Color.LightCyan; this.textBox2.BackColor = Color.LightCyan; this.textBox3.BackColor = Color.LightCyan; this.pressureSwitch1.Status = Mesnac.Controls.Feeding.PressureSwitch.Statuses.ylNormal; panel5.Parent = this.pictureBox1; this.panel5.BackColor = Color.Transparent; SetDefautText(); } public StationButton(IContainer container) { //container.Add(this); InitializeComponent(); } public List ClickActionList { get { return this._clickActionList; } set { this._clickActionList = value; } } public List KeyDownActionList { get { return _keyDownActionList; } set { _keyDownActionList = value; } } public List KeyUpActionList { get { return _keyUpActionList; } set { _keyUpActionList = value; } } [Description("工位"), Category("工位信息")] public Image picture { get { return this.pictureBox1.Image; } set { this.pictureBox1.Image = value; } } private Station _station { get { Station st = new Station(); if (!string.IsNullOrEmpty(MCStationName)) { string name = MCStationName; string[] arry = name.Split(':'); if (arry.Length > 1) { st.StationID = arry[0]; st.StationName = arry[1]; } } else { st.StationID = ""; st.StationName = ""; } return st; } } [Editor(typeof(PropertyGridFileItem), typeof(System.Drawing.Design.UITypeEditor))] [Description("工位"), Category("工位信息")] /// /// 工位名称 /// public string MCStationName { get; set; } private StationInfo _stationInfo; public StationInfo StationInfo { get { if (_stationInfo == null) { InitStationInfo(); } return _stationInfo; } } private void InitStationInfo() { if (string.IsNullOrEmpty(_station.StationID)) { return; } try { if (dbHelper == null) { return ; } dbHelper.ClearParameter(); dbHelper.CommandType = CommandType.Text; dbHelper.CommandText = ""; string sql = "Exec SP_Pro_getStationInfo @StationID"; dbHelper.AddParameter("@StationID", _station.StationID); dbHelper.CommandText = sql; DataTable ds = (DataTable)dbHelper.ToDataTable(); GetInfoName(ds); } catch (Exception e) { ICSharpCode.Core.LoggingService.Error("网络服务器请求失败"+e.ToString()); return ; } } private void GetInfoName(DataTable dt) { //工位表 DataTable dt2 = dt; try { _stationInfo = new StationInfo(); if (dt2 != null && dt2.Rows.Count > 0) { ///工位一参数 _stationInfo.stationID = dt2.Rows[0]["StationID"].ToString(); _stationInfo.StationCode = dt2.Rows[0]["StationCode"].ToString(); _stationInfo.StationName = dt2.Rows[0]["StationName"].ToString(); _stationInfo.TableName = dt2.Rows[0]["TableName"].ToString(); _stationInfo.ParaCount = Convert.ToInt32(dt2.Rows[0]["paraCount"]); _stationInfo.StationType = dt2.Rows[0]["Type_Class"].ToString(); _stationInfo.lineID= dt2.Rows[0]["LineID"].ToString(); _stationInfo.barcodeHead = dt2.Rows[0]["barcodeHead"].ToString(); _stationInfo.IfMainline = Convert.ToInt32(dt2.Rows[0]["LineTypeFlag"]) == 1; ICSharpCode.Core.LoggingService.Error("前缀:"+_stationInfo.barcodeHead); } } catch(Exception e) { ICSharpCode.Core.LoggingService.Error("参数获取错误:"+ e.ToString()); } } public object read = new object(); public void OnRerefreshData() { lock (read) { //if () //{ StationInfo.Data.NewFlag = false; //plc复位 //ResetPLCState(TextName); ThreadPool.QueueUserWorkItem(new WaitCallback(SaveStationdata), StationInfo); //} //if (ReshreshStationData != null) //{ // ReshreshStationData(StationInfo, null); //} } } private void ResetPLCState(string EquipKey) { object[] data=new object[1]; data[0] = 0; PlcData.Instance.PlcWriteByEquipKey(EquipKey, dataStateIndex, data); } public void SaveStationdata(object o) { var station = o as StationInfo; if (station == null) { return; } #region 生成动态处理类 string stationType = station.StationType; //根据类型,动态生成业务类 Assembly assembly = Assembly.GetExecutingAssembly(); // 获取当前程序集 string AssemName = "Mesnac.Compressor.Station." + stationType; var obj = assembly.CreateInstance(AssemName, true); var stationManager = obj as IStation; #endregion stationManager = ReflectClass(stationType); if (stationManager == null) { ICSharpCode.Core.LoggingService.Debug("工位类型不存在" + stationType + " 工位:" + station.StationCode); return; } //ICSharpCode.Core.LoggingService.Debug("工位:" + station.StationCode + " 开始上传数据。托盘号:" + station.Data.RFIDNo); stationManager.HandleData(station); //if (stationManager.CheckNewData(station)) //{ // stationManager.HandleData(station); //} //else //{ // ICSharpCode.Core.LoggingService.Debug("工位:" + station.StationCode + "的RFID:" + station.Data.RFIDNo + "数据已上传。条码号:" + station.Data.ProductBarcode + " 任务号:" + station.Data.MaskID.ToString()); //} } private object _stationone; private int time = 0; private object _mcValue; public object MCValue { get { return _mcValue; } set { try { if (value == null) { ClearText(); return; } if(value==_mcValue) { return; } time++; object[] objectarray; if (!TryObject(value, out objectarray)) { return; } _mcValue = value; StationInfo.Data = ParaFormart(objectarray, StationInfo.ParaCount); SetText(); //过滤第一次标签 if (FirstRead) { FirstRead = false; return; } ///询问信息 ////有新数据 if (isConnect && StationInfo.Data.NewFlag) { ICSharpCode.Core.LoggingService.Debug("工位:" + StationInfo.StationCode + " 收到作业完成信号,开始上传数据。托盘号:" + StationInfo.Data.RFIDNo); OnRerefreshData(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } } private string _textName = null; public string TextName { get { return _textName; } set { _textName = value; } } public bool isConnect { get; set; } private string _state = ""; public string State { get { return _state; } set { _state = value; } } public string NewMachineID = ""; public string OldMachineID { get; set; } public string MachineName = ""; private string _productCount = ""; public string productCount { get { return _productCount; } set { _productCount = value; } } #region 数据解析 /// /// 单工位数据解析 /// /// /// public stationPara ParaFormart(object [] obj,int paraCount) { stationPara sinfo = new stationPara(); int index = 0; ArrayList array = ConvertToBit(obj, index); Array(array); sinfo.Restart = Convert.ToInt32(array[2]) == 1; if (sinfo.Restart) { ICSharpCode.Core.LoggingService.Info("重投数据"); } sinfo.BarcodeUpdate = Convert.ToInt32(array[3]) == 1; sinfo.MaterialBarcodeUpdate = Convert.ToInt32(array[4]) == 1; index++; sinfo.MaskID = SingleConvertToInt(obj, index);//0为新数据 sinfo.NewFlag = newData(sinfo.MaskID); //数据保存区 index ++; sinfo.ProductOkNg = SingleConvertToInt(obj, index); index++; sinfo.machineID = SingleConvertToInt(obj, index); NewMachineID = sinfo.machineID.ToString(); index++ ; //sinfo.RFIDNo = int intNum=SingleConvertToInt(obj, index); //十进制转16进制 try { sinfo.RFIDNo = string.Format("{0:X}", intNum); } catch { sinfo.RFIDNo = "8888"; } index += 2; //sinfo.productDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//这里不用日期了 if (sinfo.BarcodeUpdate) { GetBarcodeList(obj, index, ref sinfo); } if (sinfo.MaterialBarcodeUpdate) { int barcodeLegth = 30;//设置单个条码长度 sinfo.MaterialBarcode = Getbarcode(obj, index + 4, barcodeLegth); //ICSharpCode.Core.LoggingService.Debug("物料条码更新为True:" + sinfo.MaterialBarcode); } else { //ICSharpCode.Core.LoggingService.Debug("物料条码更新为false"); } index += 4; //sinfo.ProductBarcode = Getbarcode(obj, index, dataLength); index += 90; for (int i = 0; i < paraCount; i++) { dataUnite du = new dataUnite(); du.actValue = ConvertToString(obj, index); du.MaxValue = ConvertToString(obj, index+2); du.MinValue = ConvertToString(obj, index + 4); du.result = ConvertToInt(obj, index+6); du.Remark = ConvertToString(obj, index + 8); index += 10; sinfo.SavedataList.Add(du); } return sinfo; } private void GetBarcodeList(object[] buffer, int index, ref stationPara sinfo) { try { //条码个数 int count = Convert.ToInt32(buffer[index]); if (count <= 0) { return; } //支线条码个数 int subcount = count - 1; //获取条码支线信息 for (int i = 1; i <= subcount; i++) { subLine sl = new subLine(); sl.lineID = buffer[index + i].ToString(); sl.barcode = ""; sinfo.subLineList.Add(sl); } int barcodeLegth = 30;//设置单个条码长度 //获取主条码 sinfo.ProductBarcode = Getbarcode(buffer, index + 4, barcodeLegth); for (int i = 1; i <= subcount; i++) { sinfo.subLineList[i - 1].barcode = Getbarcode(buffer, index + 4 + i * barcodeLegth, barcodeLegth); } } catch (Exception ex) { ICSharpCode.Core.LoggingService.Debug("条码信息获取失败:" + ex.ToString()); } } /// /// 判断是否是新数据 /// /// /// private bool newData2(int num) { if (num > dataIndex) { //if (dataIndex == -1 && num == MaxData)//第一次也上传 if (dataIndex == -1 && num!=1)//开机第一次不上传 { return false; } dataIndex = num; if (dataIndex == MaxData) { dataIndex = 0; } return true; } else { return false; } } private bool newData(int num) { if (num != dataIndex) { //if (dataIndex == 0 && num == MaxData)//第一次也上传 if (dataIndex == -1)//开机第一次不上传 { dataIndex = num; return false; } dataIndex = num; return true; } else { return false; } } /// /// 获取条码号 /// /// 数组 /// 起始 /// 长度 /// //private string Getbarcode(object[] obj, int index, int length) //{ // StringBuilder sb=new StringBuilder(); // for (int i = 0; i < length; i++) // { // string code = SingleConvertToInt(obj , index+i).ToString(); // code = "0000"+code; // code = code.Substring(code.Length-4, 4); // sb.Append(code); // } // return sb.ToString(); //} //南京方法 private string Getbarcode(object[] buffer, int index, int len) { string messge = ""; try { //int len = Convert.ToInt32(buffer[index]) / 2 - 1; int[] orgdata = new int[len]; for (int i = 0; i < len; i++) { orgdata[i] = Convert.ToInt32(buffer[index + i]); } byte[] newdata = new byte[len * 2]; for (int i = 0; i < len; i++) { newdata[i * 2] = (byte)(orgdata[i] % 256); newdata[i * 2 + 1] = (byte)(orgdata[i] / 256); } messge = ASCIIEncoding.ASCII.GetString(newdata).Replace("\0", "").Replace("\n", "").Replace("\r", "").Replace("\t", ""); } catch (Exception ex) { ICSharpCode.Core.LoggingService.Debug("条码信息获取失败:" + ex.ToString()); } return messge; } /// /// 杭州方法 /// /// /// /// /// //private string Getbarcode(object[] obj, int index, int length) //{ // StringBuilder builder = new StringBuilder(); // for (int i = 0; i < length; i++) // { // string str = this.SingleConvertToInt(obj, index + i).ToString(); // str = "0000" + str; // str = str.Substring(str.Length - 4, 4); // builder.Append(str); // } // return builder.ToString(); //} /// /// 将数据里的数据解析出来 /// /// private void Array(ArrayList array) { try { isConnect = Convert.ToInt32(array[0]) == 1; State = stateString(Convert.ToInt32(array[1])); } catch { } } private string ConvertToString(object[] obj, int index) { float data = convertTofloat(obj, index); return data.ToString("F4"); } private int ConvertToInt(object[] obj, int index) { float fstate = convertTofloat(obj, index); return Convert.ToInt32(fstate); } /// /// 单字转Int /// /// /// private int SingleConvertToInt(object[] obj, int index) { try { return Convert.ToInt32(obj[index]); } catch { return 0; } } public ArrayList ConvertToBit(object[] obj, int index) { ArrayList al = new ArrayList(); int IntValue = SingleConvertToInt(obj,index); for (int i = 0; i < 16; i++) { int value = IntValue & 1; al.Add(value); IntValue=IntValue >> 1; } return al; } private string stateString(int state) { switch (state) { case 0: return "非自动"; case 1: return "自动"; case 2: return "未知"; default: return "未知"; } } /// /// 如果是数组获取第一个字的值,如果是object获取Int值 /// /// /// private int GetValue(object ob) { //bool isArry = false; int IntValue = 0; try { var value = ob as object[]; object convertValue; if (value == null) { convertValue = ob; } else { convertValue = value[0]; } IntValue = Convert.ToInt32(convertValue); } catch { IntValue = Convert.ToInt32(ob); } return IntValue; } private float convertTofloat(object[] buff, int startIndex) { try { int b = Convert.ToInt32(buff[startIndex]); int a = Convert.ToInt32(buff[startIndex + 1]); byte[] low = System.BitConverter.GetBytes(b); byte[] high = System.BitConverter.GetBytes(a); byte[] abc = new byte[4]; for (int i = 0; i < 2; i++) { abc[i] = low[i]; } for (int i = 0; i < 2; i++) { abc[i + 2] = high[i]; } return BitConverter.ToSingle(abc, 0); } catch { return -1; } } public Object[] floatToObject(float ff) { //正负符号,默认为0 byte flag = 0; if (ff < 0) { flag = 128; ff = ff * -1; } byte[] floatByte = BitConverter.GetBytes(ff); byte[] lowhByte = new byte[4]; lowhByte[0] = floatByte[0]; lowhByte[1] = floatByte[1]; lowhByte[2] = 0; lowhByte[3] = 0; byte[] highByte = new byte[4]; highByte[0] = floatByte[2]; highByte[1] = floatByte[3]; highByte[2] = 0; highByte[3] = 0; highByte[1] = (byte)(highByte[1] + flag); UInt32 low = BitConverter.ToUInt32(lowhByte, 0); int high = BitConverter.ToInt16(highByte, 0); object[] buff = new object[2]; buff[0] = low; buff[1] = high; return buff; } private bool TryObject(object value, out object[] arry) { arry = null; try { arry = (object[])value; return true; } catch { return false; } } #endregion public void SetText() { try { if (isConnect) { this.pressureSwitch1.Status = Mesnac.Controls.Feeding.PressureSwitch.Statuses.ylMove; } else { this.pressureSwitch1.Status = Mesnac.Controls.Feeding.PressureSwitch.Statuses.ylNormal; } this.textBox1.Text = "名称:" + StationInfo.StationCode+StationInfo.StationName; this.textBox2.Text = "机种:"+getMachineName(); this.textBox3.Text = "状态:" + State; } catch(Exception ex) { ICSharpCode.Core.LoggingService.Debug("信息设置失败" + ex.ToString()); } } public void ClearText() { try { this.pressureSwitch1.Status = Mesnac.Controls.Feeding.PressureSwitch.Statuses.ylNormal; this.textBox1.Text = "名称:" + StationInfo.StationCode + StationInfo.StationName; this.textBox2.Text = "机种:"; this.textBox3.Text = "状态:"; } catch (Exception ex) { ICSharpCode.Core.LoggingService.Debug("信息清空失败" + ex.ToString()); } } private string getMachineName() { if (string.IsNullOrEmpty(OldMachineID) || OldMachineID != NewMachineID) { try { if (dbHelper == null) { return MachineName; } dbHelper.ClearParameter(); dbHelper.CommandType = CommandType.Text; dbHelper.CommandText = ""; string sql = " SELECT ProductName FROM T_BD_ProductInfo WHERE ProductID='" + NewMachineID + "'"; dbHelper.CommandText = sql; object ob = dbHelper.ToScalar(); if (ob != null) { MachineName=ob.ToString(); } } catch (Exception e) { ICSharpCode.Core.LoggingService.Error("机种获取失败"+e.ToString()); return MachineName; } OldMachineID = NewMachineID; } return MachineName; } private void SetDefautText() { this.pressureSwitch1.Status = Mesnac.Controls.Feeding.PressureSwitch.Statuses.ylNormal; this.textBox1.Text = "名称:\r\n"; this.textBox2.Text = "机种:"; this.textBox3.Text = "状态:"; } #region 属性 public IBaseControl MCRoot { get { return null; } set { ; } } #region 数据库的屏蔽,现在用不着 [TypeConverter(typeof(DataSourceConverter))] [Description("数据连接"), Category("Data")] public string MCDataSourceID { get; set; } public MCDataSource MCDataSource { get; set; } [Description("是否为数据库控件"), Category("Data")] public bool IsDbControl { get; set; } [Description("初始化SQL"), Category("Data")] public string InitDataSource { get; set; } [Description("执行SQL"), Category("Data")] public string ActionDataSource { get; set; } [Description("绑定数据源"), Category("Data")] public object BindDataSource { get; set; } [Description("操作类型"), Category("Data")] public DbOptionTypes DbOptionType { get; set; } #endregion [Description("是否可见"), Category("Behavior")] public bool MCVisible { get { return this._mcVisible; } set { this._mcVisible = value == null ? true : value; //if (this.Site.DesignMode) //{ // this.Visible = true; //} //else //{ // this.Visible = this._mcVisible; //} } } [Description("是否可用"), Category("Behavior")] public bool MCEnabled { get { return this._mcEnabled; } set { this._mcEnabled = value == null ? true : value; //if (this.Site.DesignMode) //{ // this.Enabled = true; //} //else //{ // this.Enabled = this._mcEnabled; //} } } [Description("是否控制权限"), Category("Behavior")] public bool MCPurview { get; set; } public bool IsValid { get { return _isValid; } set { _isValid = value; } } #endregion private IStation ReflectClass(string Name) { string thisPath = this.GetType().Assembly.Location; string assPath = (new FileInfo(thisPath)).Directory + "\\Mesnac.Compressor.Station"; //string dllName = "Mesnac.Compressor.Station"; string path = assPath + ".dll"; string className = "Mesnac.Compressor.Station."+Name; if (!File.Exists(path)) { return null; } Assembly ass = Assembly.LoadFile(path); if (ass == null) { return null; } var classname=ass.CreateInstance(className,true); Type type = ass.GetType(className); if (type == null) { return null; } IStation to = (IStation)Activator.CreateInstance(type); return to; } private void StationButton_Click(object sender, EventArgs e) { FrmStationData frm = new FrmStationData(_station.StationID, _station.StationName); frm.ShowDialog(); } } public class PropertyGridFileItem : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, System.IServiceProvider provider, object value) { IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService)); if (edSvc != null) { // 可以打开任何特定的对话框 FrmStation dialog = new FrmStation(); if (dialog.ShowDialog().Equals(DialogResult.OK)) { Station st = new Station(); st.StationID = dialog.StationID; st.StationName = dialog.StationName; string result = dialog.StationID + ":" + dialog.StationName; return result; } } return value; } } //[TypeConverterAttribute(typeof(StringToHumanTypeConverter))] public class Station { /// /// 工位ID /// public string StationID { get; set; } /// /// 工位名称 /// public string StationName { get; set; } public override string ToString() { if (this.StationName != null) { return this.StationName; } else { return base.ToString(); } } } }