using HslCommunication.Profinet.Omron;
using HslCommunication.Profinet.Panasonic;
using SajetClass;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace BYQTEST
{
public partial class fTermianL : Form
{
public fTermianL(bool bConfig)
{
InitializeComponent();
}
string g_sIniFactoryID = "0";
string g_sFCID = "0";
string g_sIniFile = Application.StartupPath + "\\Sajet.ini";
string sSQL;
DataSet dsTemp;
string g_sTerminalID= "10014421";
string g_sIniSection = fMain.g_sProgram;
public string g_sUserID;
private OmronHostLink _plc_ohl = new OmronHostLink();
private PanasonicMewtocol _plc_mewtocol = new PanasonicMewtocol();
bool g_flag = false;
string g_sLineID="100542";
private void fTermianL_Load(object sender, EventArgs e)
{
SajetCommon.SetLanguageControl(this);
SajetInifile sajetInifile1 = new SajetInifile();
this.Text = this.Text + "( " + SajetCommon.g_sFileVersion + " )";
//tabPage2.SelectedIndex = 0;
//Read Ini File
g_sIniFactoryID = sajetInifile1.ReadIniFile(g_sIniFile, "System", "Factory", "0");
// g_sTerminalID = sajetInifile1.ReadIniFile(g_sIniFile, g_sIniSection, "Terminal Name", "0");
//Factory
sSQL = "Select FACTORY_ID,FACTORY_CODE,FACTORY_NAME "
+ "From SAJET.SYS_FACTORY "
+ "Where ENABLED = 'Y' "
+ "Order By Factory_COde ";
dsTemp = ClientUtils.ExecuteSQL(sSQL);
string sFind = "";
for (int i = 0; i <= dsTemp.Tables[0].Rows.Count - 1; i++)
{
// combFactory.Items.Add(dsTemp.Tables[0].Rows[i]["FACTORY_CODE"].ToString());
if (g_sIniFactoryID == dsTemp.Tables[0].Rows[i]["FACTORY_ID"].ToString())
{
sFind = dsTemp.Tables[0].Rows[i]["FACTORY_CODE"].ToString();
}
}
if (sFind != "")
{
// combFactory.SelectedIndex = combFactory.FindString(sFind);
}
else
{
// combFactory.SelectedIndex = 0;
}
initCOM2();
//initTcp();
}
public void initCOM2()
{
string[] portNames = SerialPort.GetPortNames();
cbbComList2.Items.AddRange(portNames);
string sql = string.Format(@"SELECT
SN_SCAN_TYPE,
PORT_NAME,
BAUD_RATE,
PARITY,
DATA_BITS,
STOP_BITS,
SN1_ORDER,
SN2_ORDER,
SN3_ORDER,
SN4_ORDER,
SN5_ORDER,
SEGMENT1,
SEGMENT2,
SEGMENT3,
SEGMENT4,
SEGMENT5,
SEGMENT6,
SEGMENT7
FROM
SAJET.SYS_TERMINAL_ACTION_COM
WHERE
TERMINAL_ID = " + g_sTerminalID + " and del_flag = '0' and com_type = '2'", g_sTerminalID);
DataTable dataTable = ClientUtils.ExecuteSQL(sql).Tables[0];
if (dataTable.Rows.Count > 0)
{
SerialPortEntity entity = new SerialPortEntity();
entity.SnScanType = dataTable.Rows[0]["SN_SCAN_TYPE"].ToString();
entity.PortName = dataTable.Rows[0]["PORT_NAME"].ToString();
entity.BaudRate = Convert.ToInt32(dataTable.Rows[0]["BAUD_RATE"]);
entity.Parity = Convert.ToInt32(dataTable.Rows[0]["PARITY"]);
entity.DataBits = Convert.ToInt32(dataTable.Rows[0]["DATA_BITS"]);
entity.StopBits = Convert.ToInt32(dataTable.Rows[0]["STOP_BITS"]);
entity.Sn1 = dataTable.Rows[0]["SN1_ORDER"].ToString();
entity.Sn2 = dataTable.Rows[0]["SN2_ORDER"].ToString();
entity.Sn3 = dataTable.Rows[0]["SN3_ORDER"].ToString();
entity.Sn4 = dataTable.Rows[0]["SN4_ORDER"].ToString();
entity.Sn5 = dataTable.Rows[0]["SN5_ORDER"].ToString();
entity.Segment1 = dataTable.Rows[0]["SEGMENT1"].ToString();
entity.Segment2 = dataTable.Rows[0]["SEGMENT2"].ToString();
entity.Segment3 = dataTable.Rows[0]["SEGMENT3"].ToString();
entity.Segment4 = dataTable.Rows[0]["SEGMENT4"].ToString();
entity.Segment5 = dataTable.Rows[0]["SEGMENT5"].ToString();
entity.Segment6 = dataTable.Rows[0]["SEGMENT6"].ToString();
entity.Segment7 = dataTable.Rows[0]["SEGMENT7"].ToString();
if (cbbComList2.Items.Count > 0)
{
if (portNames.Contains(entity.PortName))
{
cbbComList2.SelectedIndex = cbbComList2.Items.IndexOf(entity.PortName.ToString());
}
else
{
cbbComList2.SelectedIndex = 0;
}
}
cbbBaudRate2.SelectedIndex = cbbBaudRate2.Items.IndexOf(entity.BaudRate.ToString());
cbbDataBits2.SelectedIndex = cbbDataBits2.Items.IndexOf(entity.DataBits.ToString());
cbbStopBits2.SelectedIndex = cbbStopBits2.Items.IndexOf(entity.StopBits.ToString());
cbbParity2.SelectedIndex = entity.Parity;
textBoxSN1OK.Text = entity.Sn1;
textBoxSN2NG.Text = entity.Sn2;
textBox8.Text = entity.Segment1;
textBox9.Text = entity.Segment2;
textBox10.Text = entity.Segment3;
textBox11.Text = entity.Segment4;
textBox1.Text = entity.Segment6;
textBox5.Text = entity.Segment7;
if ("1".Equals(entity.Segment5))
{
radioButton2.Checked = true;
}
else if ("2".Equals(entity.Segment5))
{
radioButton1.Checked = true;
}
}
else
{
cbbBaudRate2.SelectedIndex = 5;
cbbDataBits2.SelectedIndex = 0;
cbbParity2.SelectedIndex = 0;
cbbStopBits2.SelectedIndex = 0;
}
pictureBox2.BackgroundImage = ClientUtils.LoadImage("red.png");
// ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);//绑定事件
}
private void buttonOK2_Click_1(object sender, EventArgs e)
{
SajetInifile sajetInifile1 = new SajetInifile();
sajetInifile1.WriteIniFile(g_sIniFile, g_sIniSection, "Terminal", g_sTerminalID);
sajetInifile1.WriteIniFile(g_sIniFile, "System", "Factory", g_sFCID);
sajetInifile1.WriteIniFile(g_sIniFile, g_sIniSection, "Terminal", g_sTerminalID);
SerialPortEntity serialPortEntity = new SerialPortEntity
{
PortName = cbbComList2.SelectedItem.ToString(),
BaudRate = Convert.ToInt32(cbbBaudRate2.SelectedItem.ToString()),
Parity = Convert.ToInt32(cbbParity2.SelectedIndex.ToString()),
DataBits = Convert.ToInt32(cbbDataBits2.SelectedItem.ToString()),
StopBits = Convert.ToInt32(cbbStopBits2.SelectedItem.ToString()),
Sn1 = textBoxSN1OK.Text,
Sn2 = textBoxSN2NG.Text,
Segment1 = textBox8.Text,
Segment2 = textBox9.Text,
Segment3 = textBox10.Text,
Segment4 = textBox11.Text,
Segment5 = (radioButton2.Checked ? "1" : "2"),
Segment6 = textBox1.Text,
Segment7 = textBox5.Text
};
InsertTerminalIDCOMplc(serialPortEntity);
SajetCommon.Show_Message("保存设置 OK", -1);
DialogResult = DialogResult.OK;
}
private void InsertTerminalIDCOMplc(SerialPortEntity entity)
{
g_sUserID = ClientUtils.UserPara1;
string sql = @"MERGE INTO SAJET.SYS_TERMINAL_ACTION_COM C USING ( SELECT :TERMINAL_ID TERMINAL_ID FROM DUAL ) NC ON (C.TERMINAL_ID = NC.TERMINAL_ID AND C.COM_TYPE = '2')
WHEN MATCHED THEN
UPDATE
SET C.PDLINE_ID = :PDLINE_ID,
C.STAGE_ID = :STAGE_ID,
C.PROCESS_ID = :PROCESS_ID,
C.PORT_NAME = :PORT_NAME,
C.BAUD_RATE = :BAUD_RATE,
C.PARITY = :PARITY,
C.DATA_BITS = :DATA_BITS,
C.STOP_BITS = :STOP_BITS,
C.SN1_ORDER = :SN1_ORDER,
C.SN2_ORDER = :SN2_ORDER,
C.SEGMENT1 = :SEGMENT1,
C.SEGMENT2 = :SEGMENT2,
C.SEGMENT3 = :SEGMENT3,
C.SEGMENT4 = :SEGMENT4,
C.UPDATE_BY = :UPDATE_BY,
C.UPDATE_DATE = SYSDATE ,
C.SEGMENT5 = :SEGMENT5,
C.SEGMENT6 = :SEGMENT6,
C.SEGMENT7 = :SEGMENT7
WHERE
C.TERMINAL_ID = :TERMINAL_ID AND C.COM_TYPE = '2'
WHEN NOT MATCHED THEN
INSERT (
PDLINE_ID,
STAGE_ID,
PROCESS_ID,
TERMINAL_ID,
COM_TYPE,
PORT_NAME,
BAUD_RATE,
PARITY,
DATA_BITS,
STOP_BITS,
SN1_ORDER,
SN2_ORDER,
SEGMENT1,
SEGMENT2,
SEGMENT3,
SEGMENT4,
CREATE_BY,
CREATE_DATE,
UPDATE_BY,
SEGMENT5,SEGMENT6,SEGMENT7,
UPDATE_DATE
)
VALUES
(
:PDLINE_ID, :STAGE_ID, :PROCESS_ID, :TERMINAL_ID,
'2', :PORT_NAME, :BAUD_RATE, :PARITY, :DATA_BITS,
:STOP_BITS, :SN1_ORDER, :SN2_ORDER, :SEGMENT1, :SEGMENT2,
:SEGMENT3,:SEGMENT4, :CREATE_BY,
SYSDATE, :UPDATE_BY,:SEGMENT5,:SEGMENT6,:SEGMENT7,
SYSDATE
)";
object[][] sqlParams = new object[20][];
sqlParams[0] = new object[] { ParameterDirection.Input, OracleType.Number, "PDLINE_ID", g_sLineID };
sqlParams[1] = new object[] { ParameterDirection.Input, OracleType.Number, "STAGE_ID", "10021" };
sqlParams[2] = new object[] { ParameterDirection.Input, OracleType.Number, "PROCESS_ID", "101132" };
sqlParams[3] = new object[] { ParameterDirection.Input, OracleType.Number, "TERMINAL_ID", g_sTerminalID };
sqlParams[4] = new object[] { ParameterDirection.Input, OracleType.VarChar, "PORT_NAME", entity.PortName };
sqlParams[5] = new object[] { ParameterDirection.Input, OracleType.Number, "BAUD_RATE", entity.BaudRate };
sqlParams[6] = new object[] { ParameterDirection.Input, OracleType.Number, "PARITY", entity.Parity };
sqlParams[7] = new object[] { ParameterDirection.Input, OracleType.Number, "DATA_BITS", entity.DataBits };
sqlParams[8] = new object[] { ParameterDirection.Input, OracleType.Number, "STOP_BITS", entity.StopBits };
sqlParams[9] = new object[] { ParameterDirection.Input, OracleType.VarChar, "SN1_ORDER", "0" };
sqlParams[10] = new object[] { ParameterDirection.Input, OracleType.VarChar, "SN2_ORDER", "0" };
sqlParams[11] = new object[] { ParameterDirection.Input, OracleType.VarChar, "SEGMENT1", entity.Segment1 };
sqlParams[12] = new object[] { ParameterDirection.Input, OracleType.VarChar, "SEGMENT2", entity.Segment2 };
sqlParams[13] = new object[] { ParameterDirection.Input, OracleType.VarChar, "SEGMENT3", entity.Segment3 };
sqlParams[14] = new object[] { ParameterDirection.Input, OracleType.VarChar, "SEGMENT4", entity.Segment4 };
sqlParams[15] = new object[] { ParameterDirection.Input, OracleType.Number, "CREATE_BY", g_sUserID };
sqlParams[16] = new object[] { ParameterDirection.Input, OracleType.Number, "UPDATE_BY", g_sUserID };
sqlParams[17] = new object[] { ParameterDirection.Input, OracleType.VarChar, "SEGMENT5", entity.Segment5 };
sqlParams[18] = new object[] { ParameterDirection.Input, OracleType.VarChar, "SEGMENT6", entity.Segment6 };
sqlParams[19] = new object[] { ParameterDirection.Input, OracleType.VarChar, "SEGMENT7", entity.Segment7 };
ClientUtils.ExecuteSQL(sql, sqlParams);
//保存历史记录
ClientUtils.ExecuteSQL(string.Format(@"INSERT INTO SAJET.SYS_TERMINAL_ACTION_COM_HT SELECT * FROM SAJET.SYS_TERMINAL_ACTION_COM where TERMINAL_ID = {0}", g_sTerminalID));
}
private void button1_Click(object sender, EventArgs e)
{
if (cbbComList2.Items.Count <= 0)
{
MessageBox.Show("没有发现串口,请检查线路!");
return;
}
if (radioButton2.Checked)
{
if (!_plc_ohl.IsOpen())
{
_plc_ohl.SerialPortInni(cbbComList2.SelectedItem.ToString(),
Convert.ToInt32(cbbBaudRate2.SelectedItem.ToString()),
Convert.ToInt32(cbbDataBits2.SelectedItem.ToString()),
(StopBits)Convert.ToInt32(cbbStopBits2.SelectedItem.ToString()),
(Parity)Convert.ToInt32(cbbParity2.SelectedIndex.ToString()));//串口信息
if (!string.IsNullOrEmpty(textBox8.Text))
{
_plc_ohl.UnitNumber = Convert.ToByte(textBox8.Text.ToString());//PLC站号
}
if (!string.IsNullOrEmpty(textBox9.Text))
{
_plc_ohl.DA2 = Convert.ToByte(textBox9.Text.ToString());//PLC单元号
}
if (!string.IsNullOrEmpty(textBox10.Text))
{
_plc_ohl.SA2 = Convert.ToByte(textBox10.Text.ToString());//上位机单元号
}
if (!string.IsNullOrEmpty(textBox11.Text))
{
_plc_ohl.SID = Convert.ToByte(textBox11.Text.ToString());//设备标识号
}
try
{
_plc_ohl.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
button1.Text = "关闭串口";
pictureBox2.BackgroundImage = ClientUtils.LoadImage("green.png");
}
else
{
try
{
_plc_ohl.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
button1.Text = "打开串口";
pictureBox2.BackgroundImage = ClientUtils.LoadImage("red.png");
}
cbbComList2.Enabled = !_plc_ohl.IsOpen();
cbbBaudRate2.Enabled = !_plc_ohl.IsOpen();
cbbParity2.Enabled = !_plc_ohl.IsOpen();
cbbDataBits2.Enabled = !_plc_ohl.IsOpen();
cbbStopBits2.Enabled = !_plc_ohl.IsOpen();
}
else if (radioButton1.Checked)
{
if (!_plc_mewtocol.IsOpen())
{
_plc_mewtocol.SerialPortInni(cbbComList2.SelectedItem.ToString(),
Convert.ToInt32(cbbBaudRate2.SelectedItem.ToString()),
Convert.ToInt32(cbbDataBits2.SelectedItem.ToString()),
(StopBits)Convert.ToInt32(cbbStopBits2.SelectedItem.ToString()),
(Parity)Convert.ToInt32(cbbParity2.SelectedIndex.ToString()));//串口信息
try
{
_plc_mewtocol.Open();
g_flag = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
button1.Text = "关闭串口";
pictureBox2.BackgroundImage = ClientUtils.LoadImage("green.png");
}
else
{
try
{
_plc_mewtocol.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
button1.Text = "打开串口";
pictureBox2.BackgroundImage = ClientUtils.LoadImage("red.png");
}
cbbComList2.Enabled = !_plc_mewtocol.IsOpen();
cbbBaudRate2.Enabled = !_plc_mewtocol.IsOpen();
cbbParity2.Enabled = !_plc_mewtocol.IsOpen();
cbbDataBits2.Enabled = !_plc_mewtocol.IsOpen();
cbbStopBits2.Enabled = !_plc_mewtocol.IsOpen();
}
}
private void btnSend2_Click(object sender, EventArgs e)
{
byte[] sendData = null;
if (rbtnSendHex2.Checked)
{
sendData = strToHexByte(txtSendData2.Text.Trim());
}
else if (rbtnSendASCII2.Checked)
{
sendData = Encoding.ASCII.GetBytes(txtSendData2.Text.Trim());
}
else if (rbtnSendUTF82.Checked)
{
sendData = Encoding.UTF8.GetBytes(txtSendData2.Text.Trim());
}
else if (rbtnSendUnicode2.Checked)
{
sendData = Encoding.Unicode.GetBytes(txtSendData2.Text.Trim());
}
else
{
sendData = Encoding.ASCII.GetBytes(txtSendData2.Text.Trim());
}
if (this.SendData2(txtSendData2.Text.Trim()))//发送数据成功计数
{
lblSendCount2.Invoke(new MethodInvoker(delegate {
lblSendCount2.Text = (int.Parse(lblSendCount2.Text) + txtSendData2.Text.Length).ToString();
}));
}
}
public bool SendData2(string data)
{
try
{
if (radioButton2.Checked)
{
_plc_ohl.Write(textBox1.Text, (ushort)Convert.ToInt32(data));
/*if (!_plc_ohl.IsOpen())
{
_plc_ohl.Write(textBox1.Text, (ushort)Convert.ToInt32(data));
return true;
}
else
{
MessageBox.Show("串口未打开", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}*/
}
else
{
_plc_mewtocol.Write(textBox1.Text, (ushort)Convert.ToInt32(data));
// mewtocol.Write(textBox1.Text, (ushort)Convert.ToUInt32(data));
//if (!_plc_mewtocol.IsOpen())
//{
// _plc_mewtocol.Write(textBox1.Text, (ushort)Convert.ToInt32(data));
// return true;
//}
//else
//{
// MessageBox.Show("串口未打开", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
//}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}
private byte[] strToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0) hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Replace(" ", ""), 16);
return returnBytes;
}
}
}
2.fmian.cs页面
private void initPlcConfig()
{
//PLC端口
string sSQL1 = string.Format(@"SELECT PORT_NAME,BAUD_RATE,PARITY,DATA_BITS,STOP_BITS,SEGMENT6,SEGMENT5 ,SEGMENT7 FROM SAJET.SYS_TERMINAL_ACTION_COM WHERE COM_TYPE = '2' AND TERMINAL_ID={0} ", g_sTerminalID);
DataSet dsTemp = ClientUtils.ExecuteSQL(sSQL1);
for (int i = 0; i <= dsTemp.Tables[0].Rows.Count - 1; i++)
{
g_serialPort_com = dsTemp.Tables[0].Rows[i]["PORT_NAME"].ToString();//PLC端口
// g_serialPort_com = "COM3";
g_serialPort_BaudRate = Convert.ToInt32(dsTemp.Tables[0].Rows[i]["BAUD_RATE"].ToString()); //PLC波特率
g_serialPort_Parity = Convert.ToInt32(dsTemp.Tables[0].Rows[i]["PARITY"].ToString()); //PLC校验位
g_serialPort_DataBits = Convert.ToInt32(dsTemp.Tables[0].Rows[i]["DATA_BITS"].ToString()); //PLC数据位
g_serialPort_StopBits = Convert.ToInt32(dsTemp.Tables[0].Rows[i]["STOP_BITS"].ToString()); //PLC停止位
g_SendserialPort_address = dsTemp.Tables[0].Rows[i]["SEGMENT6"].ToString();//寄存器地址
g_Send2serialPort_address = dsTemp.Tables[0].Rows[i]["SEGMENT7"].ToString();
string comType = "2";
if (dsTemp.Tables[0].Rows[i]["SEGMENT5"].ToString() == "2")
{
IsCheckSx = true;
}
}
}
private void OpenSerialPort()
{
if (IsCheckSx)
{
if (mewtocol != null)
{
mewtocol.Close();
}
try
{
mewtocol.SerialPortInni(g_serialPort_com, g_serialPort_BaudRate, g_serialPort_DataBits, (StopBits)g_serialPort_StopBits, (Parity)g_serialPort_Parity);//串口信息
mewtocol.Open();//链接PLC
}
catch (Exception e){
SajetCommon.SetLanguage(e.Message, 1);
}
if (sxthread == null)
{
sxthread = new Thread(ClientSXPLC);
sxthread.IsBackground = true;
sxthread.Start();
}
}
else
{
mewtocol.SerialPortInni(g_serialPort_com, g_serialPort_BaudRate, g_serialPort_DataBits, (StopBits)g_serialPort_StopBits, (Parity)g_serialPort_Parity);//串口信息
mewtocol.Open();//链接PLC
}
}
if (!mewtocol.IsOpen())//发送数据功能,直接引用
{
OpenSerialPort();
}
if (mewtocol.IsOpen())
{
Thread.Sleep(g_plc_sleep);
mewtocol.Write(g_SendserialPort_address, (ushort)Int32.Parse("2"));
}
在调试阶段,碰到一个BUG。如果在fmian加载时候就打开串口的话。发送数据的时候会报错。
查找不到原因,只能每次发送数据完就关闭串口