天津投入产出系统后端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

934 lines
33 KiB

using System;
using System.Text;
using System.Collections.Generic;
using System.Windows.Forms;
using QM.Common;
using QMAPP.FJC.Entity;
using QMAPP.FJC.Entity.Basic;
using QMAPP.FJC.Entity.Operation;
using QMAPP.ServicesAgent;
using QMAPP.WinForm.Common;
using QMAPP.Entity;
using QMAPP.FJC.BLL.Basic;
using QMFrameWork.Data;
using QMFrameWork.Common.Serialization;
using System.Linq;
using QMAPP.WinForm.Forms.Operation;
using System.IO.Ports;
using System.Management;
using System.Threading;
using QMAPP.MD.Entity.Bucket;
namespace QMAPP.WinForm.Forms.Injection
{
/// <summary>
/// 模块编号:M11-2
/// 作 用:搪塑条码打印
/// 作 者:王庆男
/// 编写日期:2015年05月28日
///</summary>
public partial class SlushMoldingPrintForOldNewForm : Form
{
/// <summary>
/// 车型,A:B9车型,B:Q5车型
/// </summary>
public string CarType { set; get; }
List<MoldConfig> moldConfigList;
QMAPP.ServicesAgent.ServiceAgent agent = ClientContext.GetServiceAgent();
/// <summary>
/// 称重记录
/// </summary>
public List<TSWeighRecore> List_tSWeighRecores = new List<TSWeighRecore>();
/// <summary>
/// 新建
/// </summary>
public SlushMoldingPrintForOldNewForm()
{
InitializeComponent();
btnCommSend.Enabled = true;
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
frmMain_Load();
moldConfigList = new List<MoldConfig>();
}
/// <summary>
/// 窗体初始化
/// </summary>
private void InitForm()
{
//预留方法,用于B9\Q5功能差异
}
/// <summary>
/// 窗体加载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form_Load(object sender, EventArgs e)
{
InitForm();
DataPage dataPage = new DataPage();
//获取前台分页设置信息
dataPage.PageIndex = 1;
dataPage.PageSize = 100;
//获取可用的配置信息
MoldConfig searchModel = new MoldConfig() { STATUS = 1 };
dataPage = agent.InvokeServiceFunction<DataPage>(B9BasicService.MoldConfigBLL_GetList.ToString(), searchModel);
List<MoldConfig> recorders = null;
recorders = JsonConvertHelper.GetDeserialize<List<MoldConfig>>(dataPage.Result.ToString());
recorders = recorders.OrderBy(o => o.INDEXVALUE).ToList<MoldConfig>();
moldConfigList = recorders;
#region 绑定下拉列表
BasicData basicData = new BasicData();
//加载搪塑设备列表
//this.comMachineCode.DataSource = basicData.GetMachineInfoList(new string[] { EnumGeter.ProcessType.tangsu.GetHashCode().ToString() }, true);
//this.comMachineCode.DisplayMember = "MACHINENAME";
//this.comMachineCode.ValueMember = "MACHINECODDE";
//this.comMachineCode.SelectedIndex = 1;
//this.comMachineCode.Enabled = false;
var machinelist = basicData.GetMachineInfoAndModelList(new string[] { }, true);
this.comMachineCode.DataSource = machinelist;
this.comMachineCode.DisplayMember = "MACHINENAME";
this.comMachineCode.ValueMember = "MACHINECODDE";
if (ClientContext.MachineInfo != null && !string.IsNullOrEmpty(ClientContext.MachineInfo.PID))
{
this.comMachineCode.SelectedValue = ClientContext.MachineInfo.MACHINECODDE;
//this.lblLock.Visible = false;
this.LockType(false);
}
else
{
//this.lblLock.Visible = false;
this.LockType(false);
}
//颜色
this.comColor.DataSource = basicData.GetDictionaryList(EnumGeter.DictKind.COLOR.ToString());
this.comColor.DisplayMember = "VALUE";
this.comColor.ValueMember = "KEY";
this.comColor.SelectedValue = "1";
//this.comColor.Enabled = false;
////AB腔
this.comPosition.DataSource = basicData.GetDictionaryList(EnumGeter.DictKind.CAVITYTYPE.ToString());
this.comPosition.DisplayMember = "VALUE";
this.comPosition.ValueMember = "KEY";
//this.comPosition.SelectedIndex = 0;
//this.comPosition.Enabled = false;
#endregion
//加工日期
if (string.IsNullOrEmpty(this.dtpDate.Text))
{
this.dtpDate.Text = DateTime.Now.ToString();
}
SetMouldStation();
#region 打印模板拷贝
PrintTempleCopyClass printClass = new PrintTempleCopyClass();
printClass.CopyPrintTemple("SlushMoldingPrintForOldForm");
#endregion
}
#region 设置模架号
/// <summary>
///
/// </summary>
private void SetMouldStation()
{
this.cBoxModelCode.DisplayMember = "VALUE";
this.cBoxModelCode.ValueMember = "KEY";
List<object> cBoxModelCodeList = new List<object>();
foreach (var m in moldConfigList)
{
cBoxModelCodeList.Add(new { VALUE = m.MOLDVALUE, KEY = m.MOLDVALUE });
}
this.cBoxModelCode.DataSource = cBoxModelCodeList;
this.cBoxModelCode.SelectedIndex = 0;
cBoxModelCode.Enabled = false;
this.comMouldNumber.DisplayMember = "VALUE";
this.comMouldNumber.ValueMember = "KEY";
List<object> comMouldNumberList = new List<object>();
foreach (var m in moldConfigList)
{
comMouldNumberList.Add(new { VALUE = m.MOLDSTATION, KEY = m.MOLDSTATION });
}
this.comMouldNumber.DataSource = comMouldNumberList;
this.comMouldNumber.SelectedIndex = 0;
//判断是否有正在使用的模腔配置信息
if (moldConfigList.Count(o => o.USED == 1) > 0)
{
//获取该对象
MoldConfig m = moldConfigList.First(o => o.USED == 1);
//设置模架选择项
comMouldNumber.SelectedValue = m.MOLDSTATION;
//设置模腔选择项
cBoxModelCode.SelectedValue = m.MOLDVALUE;
}
}
#endregion
#region 窗体保存事件
/// <summary>
/// 窗体保存事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tsbSave_Click(object sender, EventArgs e)
{
string message = this.ErrorCheck();
if (!string.IsNullOrEmpty(message))
{
this.ErrorMessage.Text = message;
return;
}
List<Product> listRecorder = new List<Product>();
//窗体数据校验
//老搪塑只出黑色表皮,模腔号2 为高配B腔 模腔号3 为低配A腔,老搪塑只有一套模具,固定即可
//搪塑机
MachineInfo machineInfo = this.comMachineCode.SelectedItem as MachineInfo;
#region 加载保存信息
//for (int i = 0; i < 2; i++)//一次出2个码
//{
//零件属性
Product recorder = new Product();
ProductAttribute productAttribute = new ProductAttribute();
//搪塑机编号
productAttribute.VAL1 = machineInfo.MACHINENUM;
//产品类型(车型)成都固定
productAttribute.VAL2 = "V";
//高低配 成都无,且固定
productAttribute.VAL3 = "B";
//颜色
productAttribute.VAL4 = this.comColor.SelectedValue.ToString();
string[] cb = new string[] { };
if (!string.IsNullOrEmpty(this.cBoxModelCode.Text))
{
cb = this.cBoxModelCode.Text.Split('+');
}
if (cb.Length <= 0)
{
MessageBox.Show("模腔出错!");
return;
}
//腔
if (this.comPosition.Text == "搪塑B腔")//第一个为模腔号2
{
//腔
productAttribute.VAL5 = "B";
//模腔
productAttribute.VAL6 = cb[0].PadLeft(2, '0');
}
else if (this.comPosition.Text == "搪塑A腔")
{
//腔
productAttribute.VAL5 = "A";
//模腔
productAttribute.VAL6 = cb[1].PadLeft(2, '0');
}
//加工日期
if (string.IsNullOrEmpty(this.dtpDate.Text.Trim()))
{
productAttribute.VAL7 = Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM-dd HH:mm:ss");
}
else
{
productAttribute.VAL7 = Convert.ToDateTime(this.dtpDate.Text.Trim()).ToString("yyyy-MM-dd HH:mm:ss");
}
recorder.MACHINECODDE = machineInfo.MACHINECODDE;
recorder.MACHINENAME = machineInfo.MACHINENAME;
recorder.PRODUCTSOURCE = EnumGeter.PRODUCTSOURCE.SELFMADE.GetHashCode().ToString();
recorder.PRODUCTTYPE = EnumGeter.ProductType.biaopi.GetHashCode().ToString();
////添加加物料号
//QMAPP.ServicesAgent.ServiceAgent agents = ClientContext.GetServiceAgent();
//DataResult<string> materialcode = agents.InvokeServiceFunction<DataResult<string>>(B9BasicService.MaterialCodeBLL_GetMaterialCode.ToString(), productAttribute.VAL2);
//recorder.MATERIAL_CODE = materialcode.Result.ToString();
recorder.STATUS = EnumGeter.PRODUCTSTAUTS.QUALIFIED.GetHashCode().ToString();
recorder.CURRENTPROCESS = EnumGeter.ProcessType.lengdaoruohua.GetHashCode().ToString();
//ToDo:选择生产线
//成都固定生产线
recorder.PRODUCELINE = "IPVW371";
recorder.OUTFLAG = EnumGeter.PRODUCTOUTFLAG.INLIBRARY.GetHashCode().ToString();
recorder.USINGSTATE = EnumGeter.PRODUCTUSESTATE.UNUSED.GetHashCode().ToString();
recorder.PRODUCESHIFTTCODE = ClientContext.produceShift.PRODUCESHIFTTCODE;
recorder.PRODUCESHIFTNAME = ClientContext.produceShift.PRODUCESHIFTNAME;
recorder.CAPACITY = 1;
recorder.USINGCOUNT = 0;
recorder.PRODUCTATTRIBUTE = productAttribute;
recorder.AddM = this.cbM.Checked;
listRecorder.Add(recorder);
//}
#region 保存
QMAPP.ServicesAgent.ServiceAgent agent = ClientContext.GetServiceAgent();
DataResult<List<PrintCode>> result = agent.InvokeServiceFunction<DataResult<List<PrintCode>>>(B9BasicService.ProductBLL_InsertListEpidermis.ToString(), listRecorder);
//保存成功
if (result.IsSuccess)
{
#region 打印条码
this.DialogResult = System.Windows.Forms.DialogResult.OK;
string barCode = result.Result.ToString();
foreach (PrintCode item in result.Result)
{
QM.Assist.LabelInfo ll = new QM.Assist.LabelInfo();
ll.BarCode = item.MAINCODE + ",*" + item.PRODUCTCODE + "*" + "," + item.COLOR_CODE;
QM.Assist.PrintUtil.LabelList2.Add(ll);
//创建新行
var row = new DataGridViewRow();
if (DGView.Rows.Count == 0)
{
var index = this.DGView.Rows.Add();
row = DGView.Rows[index];
}
else
{
this.DGView.Rows.InsertCopy(0, 0);
row = DGView.Rows[0];
}
//对datagridview赋值
row.Cells["MAINCODE"].Value = item.MAINCODE;
row.Cells["PRODUCTCODE"].Value = item.PRODUCTCODE;
row.Cells["COLOR"].Value = item.COLOR_CODE;
row.Cells["COLOR"].Value = item.COLOR_CODE;
row.Cells["CREATETIME"].Value = DateTime.Now;
if (DGView.Rows.Count > 200)
{
DGView.Rows.RemoveAt(200);
}
#region 保存称重记录
btnCommSend_Click(sender, e); //发送信号
var Entity = new TSWeighRecore();
Entity.ProductCode = item.PRODUCTCODE;
Entity.PColour = item.COLOR_CODE;
Entity.MATERIAL_CODE = item.MAINCODE;
List_tSWeighRecores.Add(Entity);
#endregion
}
QM.Assist.PrintUtil pu = new QM.Assist.PrintUtil();
pu.PrintLabel2(System.Configuration.ConfigurationManager.AppSettings["proPath"].ToString
(), System.Configuration.ConfigurationManager.AppSettings[EnumGeter.ProductType.biaopi.GetHashCode().ToString() + "temPath"].ToString
(), System.Configuration.ConfigurationManager.AppSettings[EnumGeter.ProductType.biaopi.GetHashCode().ToString() + "dataPath"].ToString
());
#endregion
#region 重新设置当前使用和列表信息
var Station = comMouldNumber.SelectedItem;
string moldStation = GetPropertyValue(Station, "KEY").ToString();
#region 重新设置当前使用
DataResult updateresult = agent.InvokeServiceFunction<DataResult>(B9BasicService.MoldConfigBLL_UpdateNextUsed.ToString(), new MoldConfig() { MOLDSTATION = moldStation });
#endregion
#region 绑定下拉列表
DataPage dataPage = new DataPage();
//获取前台分页设置信息
dataPage.PageIndex = 1;
dataPage.PageSize = 100;
//获取可用的配置信息
MoldConfig searchModel = new MoldConfig() { STATUS = 1 };
dataPage = agent.InvokeServiceFunction<DataPage>(B9BasicService.MoldConfigBLL_GetList.ToString(), searchModel);
moldConfigList = JsonConvertHelper.GetDeserialize<List<MoldConfig>>(dataPage.Result.ToString());
moldConfigList = moldConfigList.OrderBy(o => o.INDEXVALUE).ToList<MoldConfig>();
SetMouldStation();
#endregion
#endregion
//MessageBox.Show("打印成功!");
this.ErrorMessage.Text = "";
}
else
{
MessageBox.Show(result.Msg);
}
#endregion
#endregion
}
#endregion
#region 窗体关闭
/// <summary>
/// 窗体关闭
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tsbClose_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion
#region 错误检测
///<summary>
///错误检测
///</summary>
///<returns></returns>
private string ErrorCheck()
{
#region
string strMessage = "";
//判断条码是否为空
////搪塑设备
if (this.comMachineCode.SelectedValue == null || this.comMachineCode.SelectedValue == string.Empty)
{
strMessage += Resource1.SlushMachineNullValidate + "\r\n";
}
////产品类别
//if (this.comProType.SelectedValue == null || this.comProType.SelectedValue == string.Empty)
//{
// strMessage += Resource1.ProductTypeNullValidate + "\r\n";
//}
//颜色
if (this.comColor.SelectedValue == null || this.comColor.SelectedValue == string.Empty)
{
strMessage += Resource1.ColorNullValidate + "\r\n";
}
////高低配
//if (this.comHOrL.SelectedValue == null || this.comHOrL.SelectedValue == string.Empty)
//{
// strMessage += Resource1.HLNullValidate + "\r\n";
//}
//腔
if (this.comPosition.SelectedValue == null || this.comPosition.SelectedValue == string.Empty)
{
strMessage += Resource1.PositionNullValidate + "\r\n";
}
////模腔号
//if (this.cBoxModelCode.Text == null || this.cBoxModelCode.Text == string.Empty)
//{
// strMessage += Resource1.ModelCodeNullValidate + "\r\n";
//}
return strMessage;
#endregion
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void comMouldNumber_SelectedIndexChanged(object sender, EventArgs e)
{
var Station = comMouldNumber.SelectedItem;
string moldStation = GetPropertyValue(Station, "KEY").ToString();
MoldConfig m = moldConfigList.First(o => o.MOLDSTATION == moldStation);
//设置模腔选择项
cBoxModelCode.SelectedValue = m.MOLDVALUE;
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="field"></param>
/// <returns></returns>
public object GetPropertyValue(object info, string field)
{
if (info == null) return null;
Type t = info.GetType();
IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi;
return property.First().GetValue(info, null);
}
#region 锁定解锁
/// <summary>
/// 锁定解锁
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lblLock_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (this.lblLock.Tag.ToString().Equals("0"))
{
LockType(false);
}
else
{
LockType(true);
}
}
#endregion
#region 设备和类别锁定
/// <summary>
/// 设备和类别锁定
/// </summary>
/// <param name="lockFlag"></param>
private void LockType(bool lockFlag)
{
this.comMachineCode.Enabled = lockFlag;
//this.comProductType.Enabled = lockFlag;
if (lockFlag)
{
this.lblLock.Text = "锁定工位";
this.lblLock.Tag = "0";
}
else
{
string locationfile = System.Configuration.ConfigurationManager.AppSettings["loactionfile"];
System.IO.File.WriteAllText(locationfile, this.comMachineCode.SelectedValue.ToString());
this.lblLock.Text = "解锁工位";
this.lblLock.Tag = "1";
}
}
#endregion
#region
/// <summary>
///
/// </summary>
/// <param name="myRtb"></param>
/// <param name="strTemp"></param>
public delegate void MyInitDelegate(RichTextBox myRtb, string strTemp);
public void DelegateInitMethod(RichTextBox myRtb, string strTemp)
{
myRtb.AppendText(strTemp + System.Environment.NewLine);
}
/// <summary>
/// 所有的串口类型
/// </summary>
public enum HardwareEnum
{
Win32_Processor,
Win32_PhysicalMemory,
Win32_Keyboard,
Win32_PointingDevice,
Win32_FloppyDrive,
Win32_DiskDrive,
Win32_CDROMDrive,
Win32_BaseBoard,
Win32_BIOS,
Win32_ParallelPort,
Win32_SerialPort,
Win32_SerialPortConfiguration,
Win32_SoundDevice,
Win32_SystemSlot,
Win32_USBController,
Win32_NetworkAdapter,
Win32_NetworkAdapterConfiguration,
Win32_Printer,
Win32_PrinterConfiguration,
Win32_PrintJob,
Win32_TCPIPPrinterPort,
Win32_POTSModem,
Win32_POTSModemToSerialPort,
Win32_DesktopMonitor,
Win32_DisplayConfiguration,
Win32_DisplayControllerConfiguration,
Win32_VideoController,
Win32_VideoSettings,
Win32_TimeZone,
Win32_SystemDriver,
Win32_DiskPartition,
Win32_LogicalDisk,
Win32_LogicalDiskToPartition,
Win32_LogicalMemoryConfiguration,
Win32_PageFile,
Win32_PageFileSetting,
Win32_BootConfiguration,
Win32_ComputerSystem,
Win32_OperatingSystem,
Win32_StartupCommand,
Win32_Service,
Win32_Group,
Win32_GroupUser,
Win32_UserAccount,
Win32_Process,
Win32_Thread,
Win32_Share,
Win32_NetworkClient,
Win32_NetworkProtocol,
Win32_PnPEntity,
}
/// <summary>
/// 获取所有串口数据(2)
/// </summary>
public static string[] MulGetHardwareInfo(HardwareEnum hardType, string propKey)
{
List<string> stringList = new List<string>();
try
{
ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("select * from " + (object)hardType);
foreach (ManagementBaseObject managementBaseObject in managementObjectSearcher.Get())
{
if (managementBaseObject.Properties[propKey].Value != null)
{
string s = managementBaseObject.Properties[propKey].Value.ToString();
int num = s.LastIndexOf("(COM");
if (num != -1 && char.IsNumber(s, num + 4))
stringList.Add(managementBaseObject.Properties[propKey].Value.ToString());
}
}
managementObjectSearcher.Dispose();
return stringList.ToArray();
}
catch
{
MessageBox.Show("MulGetHardwareInfo!");
return stringList.ToArray();
}
finally
{
}
}
/// <summary>
/// 获取所有串口数据(1)
/// </summary>
private void frmMain_Load()
{
try
{
string[] hardwareInfo = MulGetHardwareInfo(HardwareEnum.Win32_PnPEntity, "Name");
int length = hardwareInfo.Length;
List<ListItem> listItem = new List<ListItem>();
for (int index = 0; index < length; ++index)
{
listItem.Add(new ListItem((string)hardwareInfo[index], (string)hardwareInfo[index]));
}
this.textBox1.DataSource = listItem;
this.textBox1.DisplayMember = "VALUE";
this.textBox1.ValueMember = "KEY";
}
catch
{
MessageBox.Show("frmMain_Load!");
}
}
public string CodeName = string.Empty;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string text = this.textBox1.SelectedValue.ToString();
int num = text.LastIndexOf("COM");
if (num == -1)
return;
char ch1 = text[num + 3];
char ch2 = text[num + 4];
if ((int)ch2 == 41)
CodeName = "COM" + (object)ch1;
else
CodeName = "COM" + (object)ch1 + (object)ch2;
}
catch
{
MessageBox.Show("comboBox1_SelectedIndexChanged!");
}
}
public string Weigh_str = string.Empty;
private SerialPort serialPort1 = new SerialPort();
/// <summary>
/// 获取设备返回结果
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void serialPort1_DataReceived(object sender, EventArgs e)
{
try
{
int bytesToRead = this.serialPort1.BytesToRead;
if (bytesToRead == 0)
return;
//TBRCV.Text = "";
bool flag = true;
while (flag)
{
Thread.Sleep(50);
if (this.serialPort1.BytesToRead == bytesToRead)
flag = false;
else
bytesToRead = this.serialPort1.BytesToRead;
}
byte[] numArray1 = new byte[bytesToRead];
this.serialPort1.Read(numArray1, 0, bytesToRead);
byte[] numArray2 = callcrc(numArray1, bytesToRead - 2);
string str = string.Empty;
for (int index = 0; index < numArray1.Length; ++index)
str = (int)numArray1[index] >= 16 ? str + Convert.ToString(numArray1[index], 16) + " " : str + "0" + Convert.ToString(numArray1[index], 16) + " ";
//Weigh_str = str.ToUpper();
if ((int)numArray2[0] == (int)numArray1[bytesToRead - 2] &&
(int)numArray2[1] == (int)numArray1[bytesToRead - 1])
{
Weigh_str = str.ToUpper();
TBRCV.BeginInvoke(new MyInitDelegate(DelegateInitMethod), new object[] { TBRCV, str.ToUpper() });
Weigh_str = Weigh_str.Trim();
Weigh_str = Weigh_str.Substring(Weigh_str.Length - 11, 2) + Weigh_str.Substring(Weigh_str.Length - 8, 2);
Weigh_str = Convert.ToInt32(Weigh_str, 16).ToString();
foreach (var t in List_tSWeighRecores)
{
t.Weigh = Weigh_str;
agent.InvokeServiceFunction<DataResult<int>>(QMAPP.ServicesAgent.DictService.TSWeighRecoreBLL_Insert.ToString(), t);
}
List_tSWeighRecores = new List<TSWeighRecore>();
}
else
{
Weigh_str = "接收错误";
this.TBRCV.Text = str.ToUpper() + "接收错误 CRC有误";
}
}
catch
{
MessageBox.Show("serialPort1_DataReceived!");
}
}
public static byte[] strToToHexByte(string hexString)
{
try
{
hexString = hexString.Replace(" ", "");
if (hexString.Length % 2 != 0)
hexString += "0";
byte[] numArray = new byte[hexString.Length / 2];
for (int index = 0; index < numArray.Length; ++index)
{
try
{
numArray[index] = Convert.ToByte(hexString.Substring(index * 2, 2), 16);
}
catch
{
int num = (int)MessageBox.Show("输入可能错误");
}
}
return numArray;
}
catch
{
MessageBox.Show("strToToHexByte!");
return new byte[] { };
}
}
public static byte[] addCrcHexByte(byte[] strHexByte)
{
try
{
byte[] numArray = new byte[strHexByte.Length + 2];
for (int index = 0; index < strHexByte.Length; ++index)
{
try
{
numArray[index] = strHexByte[index];
}
catch
{
int num = (int)MessageBox.Show("输入可能错误");
}
}
byte[] numArray2 = callcrc(strHexByte, strHexByte.Length);
numArray[strHexByte.Length + 0] = numArray2[0];
numArray[strHexByte.Length + 1] = numArray2[1];
return numArray;
}
catch
{
MessageBox.Show("addCrcHexByte!");
return new byte[] { };
}
}
public static byte[] callcrc(byte[] ss, int num)
{
try
{
ushort num1 = ushort.MaxValue;
byte[] numArray = ss;
for (byte index1 = 0; (int)index1 < num; ++index1)
{
num1 ^= (ushort)numArray[(int)index1];
for (byte index2 = 0; (int)index2 < 8; ++index2)
{
if (((int)num1 & 1) > 0)
num1 = (ushort)((uint)(ushort)((uint)num1 >> 1) ^ 40961U);
else
num1 >>= 1;
}
}
byte num2 = (byte)((uint)num1 >> 8);
return new byte[2]
{
(byte)((uint) num1 & (uint) byte.MaxValue),
num2
};
}
catch
{
MessageBox.Show("callcrc!");
return new byte[] { };
}
}
/// <summary>
/// 打开设备通讯
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCom_Click(object sender, EventArgs e)
{
try
{
if (CodeName == "")
{
comboBox1_SelectedIndexChanged(sender, e);
}
serialPort1.BaudRate = Convert.ToInt32(19200);
serialPort1.Parity = Parity.None;
serialPort1.DataBits = 8;
serialPort1.StopBits = StopBits.One;
serialPort1.ReadBufferSize = 4068;
serialPort1.WriteBufferSize = 4068;
serialPort1.ReadTimeout = 200;
serialPort1.WriteTimeout = 200;
serialPort1.PortName = CodeName;
serialPort1.Open();
this.TBSEND.Text = "连接设备";
}
catch
{
MessageBox.Show("btnCom_Click!");
}
}
/// <summary>
/// 发送连接请求
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCommSend_Click(object sender, EventArgs e)
{
try {
//btnCom_Click();
if (serialPort1.IsOpen)
{
byte[] toHexByte = strToToHexByte("01" + "03" + "0FA1" + "0002");
byte[] buffer = addCrcHexByte(toHexByte);
serialPort1.Write(buffer, 0, buffer.Length);
//TBRCV.Text = "";
TBSEND.Text = "";
string str = string.Empty;
for (int index = 0; index < buffer.Length; ++index)
str = (int)buffer[index] >= 16 ? str + Convert.ToString(buffer[index], 16) + " " : str + "0" + Convert.ToString(buffer[index], 16) + " ";
TBSEND.Text = str.ToUpper();
}
else
{
int num1 = (int)MessageBox.Show("请打开设备连接!");
}
}
catch
{
MessageBox.Show("btnCommSend_Click!");
}
}
#endregion
}
}