using Gs.WeightIqc.ToolBox;
|
using Microsoft.Win32;
|
using Newtonsoft.Json;
|
using NModbus;
|
using NModbus.Serial;
|
using System;
|
using System.Collections.Generic;
|
using System.ComponentModel;
|
using System.Configuration;
|
using System.Data;
|
using System.Drawing;
|
using System.IO.Ports;
|
using System.Linq;
|
using System.Text;
|
using System.Threading;
|
using System.Threading.Tasks;
|
using System.Windows.Forms;
|
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
|
|
namespace Gs.WeightLine
|
{
|
public partial class Form1 : DevExpress.XtraEditors.XtraForm
|
{
|
string _webServiceName = "WorkWeight/";
|
public System.IO.Ports.SerialPort Sp = new System.IO.Ports.SerialPort();
|
public delegate void HandleInterfaceUpdataDelegate(string text);
|
private Form1.HandleInterfaceUpdataDelegate interfaceUpdataHandle;
|
private Dictionary<string, Thread> dicThread = new Dictionary<string, Thread>();
|
private System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
|
|
System.Timers.Timer timerGridview = new System.Timers.Timer(10000);
|
public Form1()
|
{
|
InitializeComponent();
|
GetComList();
|
comLine.getSuppler("");
|
#region MyRegion
|
int int32 = 10000;
|
string _vanishingSeconds = ConfigurationManager.AppSettings["TimingMailInterval"];
|
if (!string.IsNullOrEmpty(_vanishingSeconds))
|
int32 = int.Parse(_vanishingSeconds);
|
this.timer1.Interval = int32;
|
this.button1.Enabled = true;
|
this.button2.Enabled = false;
|
this.comLine.IsReadly = false;
|
this.cmbSerialPortNum.Enabled = true;
|
this.cmbBaudRate.Enabled = true;
|
this.cmbBaudRate.SelectedIndex = 1;
|
#endregion
|
this.timer1.Tick += (s, e) =>
|
{
|
if (this.dicThread.Keys.Contains<string>("GetWeight"))
|
return;
|
Thread thread1 = new Thread(new ThreadStart(this.GetWeight));
|
thread1.Start();
|
this.dicThread.Add("GetWeight", thread1);
|
};
|
this.button1.Click += (s, e) =>
|
{
|
string _comLine = comLine.GetId();
|
if (string.IsNullOrEmpty(_comLine))
|
{
|
MessageBox.Show("请选择线体");
|
this.comLine.Focus();
|
return;
|
}
|
try
|
{
|
LogHelper.Debug(this.ToString(), " 开始采集");
|
if (this.cmbBaudRate.Text.Trim() != "" && this.cmbSerialPortNum.Text != "")
|
{
|
LogHelper.Debug(this.ToString(), "配置串口通信");
|
this.interfaceUpdataHandle = new Form1.HandleInterfaceUpdataDelegate(this.UpdateTextBox);
|
this.Sp.PortName = this.cmbSerialPortNum.Text.Trim();
|
this.Sp.BaudRate = Convert.ToInt32(this.cmbBaudRate.Text.Trim());
|
this.Sp.Parity = Parity.None;
|
this.Sp.StopBits = StopBits.One;
|
LogHelper.Debug(this.ToString(), "打开串口同通信");
|
this.Sp.Open();
|
this.button1.Enabled = false;
|
this.button2.Enabled = true;
|
this.timer1.Enabled = false;
|
this.comLine.IsReadly = true;
|
this.cmbSerialPortNum.Enabled = false;
|
this.cmbBaudRate.Enabled = false;
|
LogHelper.Debug(this.ToString(), "启动刷新数据定时器");
|
this.timer1.Start();
|
}
|
else
|
{
|
LogHelper.Debug(this.ToString(), "请输入正确的串口号和波特率");
|
int num = (int)MessageBox.Show("请输入正确的串口号和波特率!");
|
this.cmbSerialPortNum.Focus();
|
}
|
}
|
catch (Exception ex)
|
{
|
LogHelper.Debug(this.ToString(), ex.Message);
|
int num = (int)MessageBox.Show($"串口{this.cmbSerialPortNum.Text.Trim()}打开失败!{ex.Message}");
|
}
|
};
|
this.button2.Click += (s, e) =>
|
{
|
try
|
{
|
if (this.dicThread.Keys.Contains<string>("GetWeight"))
|
{
|
Thread thread = this.dicThread["GetWeight"];
|
if (thread.IsAlive)
|
thread.Abort();
|
this.dicThread.Remove("GetWeight");
|
}
|
this.button1.Enabled = true;
|
this.button2.Enabled = false;
|
this.comLine.IsReadly = false;
|
this.cmbSerialPortNum.Enabled = true;
|
this.cmbBaudRate.Enabled = true;
|
this.timer1.Stop();
|
this.Sp.Close();
|
}
|
catch (Exception ex)
|
{
|
//int num = (int)MessageBox.Show(ex.Message);
|
//Application.Exit();
|
MessageBox.Show(ex.Message);
|
LogHelper.Debug(this.ToString(), ex.Message);
|
}
|
};
|
this.FormClosing += (s, e) =>
|
{
|
if (Sp.IsOpen)
|
Sp.Close();
|
if (timer1 != null)
|
{
|
timer1.Stop();
|
timer1.Dispose();
|
}
|
if (timerGridview != null)
|
{
|
timerGridview.Stop();
|
timerGridview.Dispose();
|
}
|
try
|
{
|
if (this.dicThread.Keys.Contains<string>("GetWeight"))
|
{
|
Thread thread = this.dicThread["GetWeight"];
|
if (thread.IsAlive)
|
thread.Abort();
|
this.dicThread.Remove("GetWeight");
|
}
|
this.timer1.Stop();
|
this.Sp.Close();
|
}
|
catch (Exception ex)
|
{
|
//int num = (int)MessageBox.Show(ex.Message);
|
//Application.Exit();
|
MessageBox.Show(ex.Message);
|
}
|
};
|
#region gridview设置
|
timerGridview.Elapsed += (s, e) =>
|
{
|
string _lineId = comLine.GetId();
|
if (string.IsNullOrEmpty(_lineId))
|
return;
|
var _obj = new
|
{
|
lineId = _lineId,
|
};
|
try
|
{
|
var strReturn = UtilityHelper.HttpPost("", _webServiceName + "GetModelList", JsonConvert.SerializeObject(_obj), false);
|
var dd = UtilityHelper.ReturnToList(strReturn);
|
var dt = dd.rtnData;
|
BeginInvoke(new Action(() =>
|
{
|
gcMx1.BindingContext = new BindingContext();
|
gcMx1.DataSource = dt;
|
gcMx1.ForceInitialize();
|
gvMx1.BestFitColumns();
|
}));
|
BeginInvoke(new Action(() =>
|
{
|
this.txtMsg.Text = "最近刷新列表时间:" + DateTime.Now.ToString();
|
}));
|
}
|
catch (Exception ex)
|
{
|
MessageBox.Show("gvMx1:" + ex.Message);
|
}
|
};
|
timerGridview.AutoReset = true; // 设置为true表示重复执行,false表示执行一次后停止
|
timerGridview.Enabled = true; // 开始计时
|
gvMx1.OptionsFind.ShowSearchNavButtons = false;
|
gvMx1.OptionsView.ShowAutoFilterRow = false;
|
gvMx1.OptionsView.ShowGroupPanel = false;
|
gvMx1.RowStyle += (s, e) =>
|
{
|
//默认选中行不变色
|
gvMx1.OptionsSelection.EnableAppearanceFocusedRow = false;
|
//默认选中单元格不变色
|
gvMx1.OptionsSelection.EnableAppearanceFocusedCell = false;
|
if (e.RowHandle >= 0)
|
{
|
DataRow row = gvMx1.GetDataRow(e.RowHandle);
|
if (row == null)
|
return;
|
string colorString = row["bgColor"].ToString(); // 使用十六进制表示颜色的ARGB值
|
Color color = ColorTranslator.FromHtml(colorString);
|
e.Appearance.BackColor = color;
|
}
|
};
|
gvMx1.IndicatorWidth = 60;
|
gvMx1.CustomDrawRowIndicator += (s, e) =>
|
{
|
if (e.Info.IsRowIndicator && e.RowHandle >= 0)
|
e.Info.DisplayText = (e.RowHandle + 1).ToString();
|
};
|
#endregion
|
}
|
|
/// <summary>
|
/// 获取重量
|
/// </summary>
|
public void GetWeight()
|
{
|
ModbusFactory factory = new ModbusFactory();
|
LogHelper.Debug(this.ToString(), "GetWeight创建modbus对象");
|
IModbusMaster rtuMaster = (IModbusMaster)factory.CreateRtuMaster(this.Sp);
|
bool flag = true;
|
while (true)
|
{
|
//addModel("1", "2");
|
//ToolBox.LogHelper.Debug(this.ToString(), "GetWeight创建modbus对象");
|
try
|
{
|
if (!this.Sp.IsOpen)
|
{
|
LogHelper.Debug(this.ToString(), "GetWeight 重新打开串口连接");
|
this.Sp.Open();
|
rtuMaster = (IModbusMaster)factory.CreateRtuMaster(this.Sp);
|
}
|
if (rtuMaster == null)
|
{
|
LogHelper.Debug(this.ToString(), "GetWeight 重新创建modbus对象2");
|
rtuMaster = (IModbusMaster)factory.CreateRtuMaster(this.Sp);
|
}
|
byte slaveAddress3 = byte.Parse("1");
|
ushort startAddress3 = ushort.Parse("0002");
|
ushort numberOfPoints1 = ushort.Parse("2");
|
ushort[] numArray = rtuMaster.ReadHoldingRegisters(slaveAddress3, startAddress3, numberOfPoints1);
|
float single = BitConverter.ToSingle(this.CombomBinaryArray(BitConverter.GetBytes(numArray[1]), BitConverter.GetBytes(numArray[0])), 0);
|
this.Invoke((Delegate)this.interfaceUpdataHandle, (object)single.ToString());
|
byte slaveAddress4 = byte.Parse("1");
|
ushort startAddress4 = ushort.Parse("0001");
|
ushort numberOfPoints2 = ushort.Parse("1");
|
int int32 = Convert.ToInt32(rtuMaster.ReadHoldingRegisters(slaveAddress4, startAddress4, numberOfPoints2)[0].ToString());
|
string str = Convert.ToString(int32, 2).PadLeft(16 /*0x10*/, '0');
|
char ch1 = str[1];
|
char ch2 = str[6];
|
if (ch1 == '0' && ch2 == '0')
|
{
|
flag = true;
|
}
|
else if (flag)
|
{
|
flag = false;
|
}
|
addModel(single.ToString(), int32.ToString());
|
LogHelper.Debug(this.ToString(), "single:" + single.ToString() + ",flag:" + flag.ToString() + ",int32:" + int32.ToString());
|
Thread.Sleep(2000);
|
}
|
catch (Exception ex)
|
{
|
Thread.Sleep(2000);
|
}
|
}
|
}
|
/// <summary>
|
/// 上传称重数据
|
/// </summary>
|
/// <param name="_realWeight">截取后的数量</param>
|
/// <param name="_realWeightTxt">原子串</param>
|
private void addModel(string _realWeight, string _realWeightTxt)
|
{
|
string _lineId = comLine.GetId();
|
var _obj = new
|
{
|
lineId = _lineId,
|
realWeight = _realWeight.Trim(),
|
realWeightTxt = _realWeightTxt.Trim(),
|
};
|
try
|
{
|
string strJson = UtilityHelper.HttpPost("", "WorkWeight/EditModel", JsonConvert.SerializeObject(_obj));
|
ReturnModel<dynamic> _rtn = UtilityHelper.ReturnToDynamic(strJson);
|
if (_rtn.rtnCode <= 0)
|
{
|
LogHelper.Debug(this.ToString(), "WorkWeight/EditModel:" + strJson);
|
}
|
}
|
catch (Exception ex)
|
{
|
LogHelper.Debug(this.ToString(), ex.Message);
|
}
|
}
|
|
|
/// <summary>
|
/// 更新UI
|
/// </summary>
|
/// <param name="text"></param>
|
|
private void UpdateTextBox(string text)
|
{
|
try
|
{
|
this.txtMsg.Text = "最近获取称重时间:" + DateTime.Now.ToString();
|
if (this.txtNum.Text == text)
|
return;
|
this.txtNum.Text = text;
|
}
|
catch (Exception ex)
|
{
|
LogHelper.Debug(this.ToString(), ex.Message);
|
}
|
}
|
|
private void GetComList()
|
{
|
this.cmbSerialPortNum.Clear();
|
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
|
if (registryKey == null)
|
return;
|
foreach (string valueName in registryKey.GetValueNames())
|
{
|
string description = (string)registryKey.GetValue(valueName);
|
cmbSerialPortNum.Properties.Items.Add(description);
|
}
|
if (this.cmbSerialPortNum.Properties.Items.Count > 0)
|
this.cmbSerialPortNum.SelectedIndex = 0;
|
}
|
|
private byte[] CombomBinaryArray(byte[] srcArray1, byte[] srcArray2)
|
{
|
byte[] destinationArray = new byte[srcArray1.Length + srcArray2.Length];
|
Array.Copy((Array)srcArray1, 0, (Array)destinationArray, 0, srcArray1.Length);
|
Array.Copy((Array)srcArray2, 0, (Array)destinationArray, srcArray1.Length, srcArray2.Length);
|
return destinationArray;
|
}
|
|
|
}
|
}
|