using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.IO.Ports; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Windows.Forms; using BO; using BO.BarCodeScan; using BO.BO.Dtos; using BO.Utils; using BO.Utils.BillRpc; using BWP.WinFormControl.WeightDataFormat; using Forks.JsonRpc.Client; using Newtonsoft.Json; using TrunksIousOutInStore.LocalSyncBO; namespace TrunksIousOutInStore { public partial class TrunksIousOutInStoreForm : Form, IAfterLogin { private readonly string mDropDownSetsFileName = "TrunksIousOutInStore_DropDownSets.xml"; private DropDownSets mDropDownSets; private Thread tdSyncUnSubmit, tdSyncSubmited; private readonly Thread _tcCheckNetStatus; private readonly string BaseRpcUrl = "/MainSystem/B3ClientService/Rpcs/BillRpc/TrunksIousOutInStoreRecord_/TrunksIousOutInStoreRecordRpc/"; #region weightNeed SerialPort weightPort; private IDataFormat _dataFormat; private Thread _inQueryThread; private bool _mainProcessIsRun; readonly StringBuilder _dataStrBuilder = new StringBuilder(); #endregion public TrunksIousOutInStoreForm() { InitializeComponent(); gridUnCheck.AutoGenerateColumns = false; gridChecked.AutoGenerateColumns = false; InitCombox(); weightPort = new SerialPort(); this.FormClosing += delegate { if (_inQueryThread != null && _inQueryThread.IsAlive) DisableWeight(); if (tdSyncUnSubmit != null && tdSyncUnSubmit.IsAlive) tdSyncUnSubmit.Abort(); if (tdSyncSubmited != null && tdSyncSubmited.IsAlive) tdSyncSubmited.Abort(); if (_tcCheckNetStatus != null && _tcCheckNetStatus.IsAlive) { _tcCheckNetStatus.Abort(); } }; tdSyncUnSubmit = new Thread(SyncUnSubmit); tdSyncSubmited = new Thread(SyncSubmited); tdSyncUnSubmit.Start(); tdSyncSubmited.Start(); _tcCheckNetStatus = new Thread(CheckNetStatus); _tcCheckNetStatus.Start(); } private bool laseConnection = false; private void CheckNetStatus() { while (true) { try { var newConnection = LoginRpcUtil.TestConnection(500); if (newConnection && laseConnection) { Thread.Sleep(1000); continue; } var png = "stop.png"; if (newConnection) png = "working.png"; var imgPath = Path.Combine(Application.StartupPath, "BWP.WinFormControl.dll"); var s = Assembly.LoadFile(imgPath).GetManifestResourceStream("BWP.WinFormControl.Images." + png); if (this.InvokeRequired) { this.BeginInvoke(new Action(() => { picNetStatus.Image = Image.FromStream(s); picNetStatus.Refresh(); })); } else { picNetStatus.Image = Image.FromStream(s); picNetStatus.Refresh(); } laseConnection = newConnection; } catch (Exception e) { //LogUtil.Error(e.ToString()); } Thread.Sleep(1000); } } #region weightNeed void OpenSerialPort() { if (!_enableWeight) return; if (TrunksIousOutInStoreContext.Config.RateSet == null) throw new Exception("请先配置称相关信息"); weightPort.PortName = TrunksIousOutInStoreContext.Config.ComSet; weightPort.BaudRate = TrunksIousOutInStoreContext.Config.RateSet.Value; weightPort.DataBits = TrunksIousOutInStoreContext.Config.BitSet.Value; weightPort.ReadBufferSize = 4096 * 100; if (!string.IsNullOrEmpty(TrunksIousOutInStoreContext.Config.Format)) format = "{0:{format}}".Replace("{format}", TrunksIousOutInStoreContext.Config.Format); switch (TrunksIousOutInStoreContext.Config.WeightSet) { case "IND560": _dataFormat = new IND560DataFormat(); break; case "Xk3124": _dataFormat = new Xk3124DataFormat(); break; case "Xk3190A9": _dataFormat = new Xk3190A9DataFormat(); break; default: _dataFormat = new Xk3190D10DataFormat(); break; } if (!weightPort.IsOpen) { try { weightPort.Open(); } catch (InvalidOperationException) { MessageBox.Show(@"指定的端口已打开"); } catch (UnauthorizedAccessException) { MessageBox.Show(@"对端口的访问被拒绝"); } } } void ReadData() { _inQueryThread = new Thread(InQuery); _inQueryThread.Start(); } string format = "{0:0.00}"; private void InQuery() { while (_mainProcessIsRun) { int availableCount = weightPort.BytesToRead; if (availableCount == 0) { Thread.Sleep(1); } char[] buffer = new char[availableCount]; if (!weightPort.IsOpen) { continue; } weightPort.Read(buffer, 0, availableCount); foreach (var c in buffer) { if (c == _dataFormat.Beginchar) { _dataStrBuilder.Clear(); _dataStrBuilder.Append(c); } else if (c == _dataFormat.Endchar && _dataStrBuilder.Length == _dataFormat.DataLength - 1) { _dataStrBuilder.Append(c); bool isStatic; string str; if (_dataFormat.ParseAscii(_dataStrBuilder.ToString(), out str, out isStatic)) { if (TrunksIousOutInStoreContext.Config.WeightType == 0) { if (string.IsNullOrEmpty(str)) str = "0"; this.Invoke(new Action(delegate() { lblChengZhong.Text = string.Format(format, decimal.Parse(str)); if (str != "0") { //AddWeightDetail(decimal.Parse(lblChengZhong.Text)); doInsertUnSubmit(decimal.Parse(lblChengZhong.Text)); } })); } else { decimal num = 0; if (decimal.TryParse(str, out num)) { this.Invoke(new Action(delegate() { lblChengZhong.Text = string.Format(format, num); })); // LocalGradeAndWeightBL.SaveWeightData(num); WeighAvgControl.Add(num, isStatic); } if (WeighAvgControl.TryGetValue(out num)) { this.Invoke(new Action(delegate() { //lblChengZhong.Text = string.Format(format, num); if (str != "0") { doInsertUnSubmit(decimal.Parse(string.Format(format, num))); //AddWeightDetail(decimal.Parse(string.Format(format, num))); } })); } } } _dataStrBuilder.Clear(); } else if (_dataStrBuilder.Length != 0) { _dataStrBuilder.Append(c); } } } } private class WeighAvgControl { public static bool TryGetValue(out decimal result) { List> list; if (mWeighList.TryDequeue(out list)) { var r = list.Where(x => x.Item2).Select(x => x.Item1).GroupBy(x => x); var firstOrDefault = r.OrderByDescending(x => x.Count()).FirstOrDefault(); if (firstOrDefault != null) { result = firstOrDefault.Key; return true; } result = 0; return false; } result = 0; return false; } static ConcurrentQueue>> mWeighList = new ConcurrentQueue>>(); static List> _list = new List>(); public static void Add(decimal value, bool isStatic) { if (value >= TrunksIousOutInStoreContext.Config.MinWeight && value <= TrunksIousOutInStoreContext.Config.MaxWeight) { _list.Add(new Tuple(value, isStatic)); } else { if (_list.Count > 0) { mWeighList.Enqueue(_list); _list = new List>(); } } } } void DisableWeight() { _mainProcessIsRun = false; lblChengZhong.Text = string.Format(format, 0); format = "{0:0.00}"; Thread.Sleep(10); if (_inQueryThread.IsAlive) { _inQueryThread.Abort(); } if (weightPort.IsOpen) weightPort.Close(); } #endregion private void InitCombox() { if (LoginRpcUtil.TestConnection(500)) { mDropDownSets = GetmDropDownSets(); XmlUtil.SerializerObjToFile(mDropDownSets, mDropDownSetsFileName); } else { mDropDownSets = XmlUtil.DeserializeFromFile(mDropDownSetsFileName); } var shop = mDropDownSets.Details.FirstOrDefault(x => x.Name == DropDownSets.车间); if (shop != null) { cbxWorkShop.DataSource = shop.Details; cbxWorkShop.DisplayMember = "Name"; cbxWorkShop.ValueMember = "ID"; } var unit = mDropDownSets.Details.FirstOrDefault(x => x.Name == DropDownSets.单元); if (unit != null) { cbxWorkUnit.DataSource = unit.Details; cbxWorkUnit.DisplayMember = "Name"; cbxWorkUnit.ValueMember = "ID"; } var store = mDropDownSets.Details.FirstOrDefault(x => x.Name == DropDownSets.仓库); if (store != null) { cbxStore.DataSource = store.Details; cbxStore.DisplayMember = "Name"; cbxStore.ValueMember = "ID"; } var batch = mDropDownSets.Details.FirstOrDefault(x => x.Name == DropDownSets.批次); if (batch != null) { cbxBatch.DataSource = batch.Details; cbxBatch.DisplayMember = "Name"; cbxBatch.ValueMember = "ID"; } } private DropDownSets GetmDropDownSets() { var sets = new DropDownSets(); var wrokUnitSet = GetWrokUnitSet(); var wrokShopSet = GetWrokShopSet(); var storeSet = GetStoreSet(); var batchSet = GetBatchSet(); sets.Details.Add(wrokUnitSet); sets.Details.Add(wrokShopSet); sets.Details.Add(storeSet); sets.Details.Add(batchSet); return sets; } private DropDownSet GetStoreSet() { var json = RpcFacade.Call("/MainSystem/B3ClientService/Rpcs/BaseInfoRpc/GetStoreList"); var set = new DropDownSet(); set.Name = DropDownSets.仓库; foreach (var detail in JsonConvert.DeserializeObject>(json)) { set.Details.Add(detail); } return set; } private DropDownSet GetWrokShopSet() { var json = RpcFacade.Call("/MainSystem/B3ClientService/Rpcs/BaseInfoRpc/GetWorkShopList"); var set = new DropDownSet(); set.Name = DropDownSets.车间; foreach (var detail in JsonConvert.DeserializeObject>(json)) { set.Details.Add(detail); } return set; } private DropDownSet GetWrokUnitSet() { var json = RpcFacade.Call("/MainSystem/B3ClientService/Rpcs/BaseInfoRpc/GetWorkUnitList"); var set = new DropDownSet(); set.Name = DropDownSets.单元; foreach (var detail in JsonConvert.DeserializeObject>(json)) { set.Details.Add(detail); } return set; } private DropDownSet GetBatchSet() { var json = RpcFacade.Call("/MainSystem/B3ClientService/Rpcs/BaseInfoRpc/GetProductBatchList"); var set = new DropDownSet(); set.Name = DropDownSets.批次; foreach (var detail in JsonConvert.DeserializeObject>(json)) { set.Details.Add(detail); } return set; } static object _obj = new object(); private void doInsertUnSubmit(decimal weight) { lock (_obj) { //称重 //找到称重为空条码不为空的 var fd = unSubmitList.LastOrDefault(x => !string.IsNullOrWhiteSpace(x.BarCode) && x.Weight == null); if (fd == null) { //todo 记录一个异常 // record.ID = unSumbitList.Max(x => x.ID) + 1; // unSumbitList.Add(record); } else { var record = new TrunksIousOutInStoreRecordExt(); record.ID = fd.ID; record.Creator = ButcherAppContext.Context.UserConfig.UserName; record.Weight = weight; this.Invoke(new Action(() => { if (cbxWorkShop.SelectedValue != null) record.WorkShop_ID = Convert.ToInt64(cbxWorkShop.SelectedValue); if (cbxWorkUnit.SelectedValue != null) record.WorkUnit_ID = Convert.ToInt64(cbxWorkUnit.SelectedValue); if (cbxStore.SelectedValue != null) record.Store_ID = Convert.ToInt64(cbxStore.SelectedValue); if (cbxBatch.SelectedValue != null) { record.ProductBatch_ID = Convert.ToInt64(cbxBatch.SelectedValue); record.ProductBatch = cbxBatch.SelectedText; } unSubmitList.Remove(fd); BindUnSubmitGrid(); })); RpcFacade.Call(BaseRpcUrl + "SetWeight", JsonConvert.SerializeObject(record)); } } } public string RoleName { get { return "白条入库"; } } public Form Generate() { return this; } private void TrunksIousOutInStoreForm_FormClosing(object sender, FormClosingEventArgs e) { if (unSubmitList.Count > 0) { if (MessageBox.Show("待提交区域不为空,确定关闭?", "确定关闭", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK) { e.Cancel = false; } else { e.Cancel = true; } } } BindingList unSubmitList = new BindingList(); BindingList submitedList = new BindingList(); void SyncUnSubmit() { while (true) { var json = RpcFacade.Call(BaseRpcUrl + "GetUnSubmitList"); var list = JsonConvert.DeserializeObject>(json); if (this.IsHandleCreated) { this.Invoke(new Action(() => { unSubmitList.Clear(); foreach (TrunksIousOutInStoreRecord record in list) { unSubmitList.Add(record); } BindUnSubmitGrid(); })); } Thread.Sleep(2000); } } void SyncSubmited() { while (true) { var json = RpcFacade.Call(BaseRpcUrl + "GetSubmitedList"); var list = JsonConvert.DeserializeObject>(json); if (this.IsHandleCreated) { this.Invoke(new Action(() => { if (list.Count > 0) { submitedList.Clear(); foreach (TrunksIousOutInStoreRecord record in list) { submitedList.Add(record); } } BindSubmitedGrid(); })); } Thread.Sleep(2000); } } void BindUnSubmitGrid() { if (gridUnCheck.DataSource == null) { gridUnCheck.DataSource = unSubmitList; } else { gridUnCheck.Refresh(); } } void BindSubmitedGrid() { if (gridChecked.DataSource == null) { gridChecked.DataSource = submitedList; } else { gridChecked.Refresh(); } } private void btnWeightSet_Click(object sender, EventArgs e) { var f = new WeightSettingFrom(); if (f.ShowDialog() == DialogResult.OK) { // enableWeight_Click(sender, e); // GridUnCheckFocus(); } } private bool _enableWeight = false; private void btnEnableWeight_Click(object sender, EventArgs e) { _enableWeight = !_enableWeight; if (_enableWeight) { btnEnableWeight.Text = "停止称重"; btnEnableWeight.BackColor = Color.ForestGreen; OpenSerialPort(); _mainProcessIsRun = true; ReadData(); } else { btnEnableWeight.Text = "开始称重"; btnEnableWeight.BackColor = SystemColors.Control; btnEnableWeight.UseVisualStyleBackColor = true; DisableWeight(); } } } }