106 lines
3.7 KiB
C#
106 lines
3.7 KiB
C#
using Microsoft.VisualBasic.Devices;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel;
|
|
using System.Data;
|
|
using System.Drawing;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Windows.Forms;
|
|
|
|
namespace SLC1_N
|
|
{
|
|
public partial class Form_PLCconnect : Form
|
|
{
|
|
public Form_PLCconnect()
|
|
{
|
|
InitializeComponent();
|
|
}
|
|
|
|
private void Form_PLCconnect_Load(object sender, EventArgs e)
|
|
{
|
|
// PLC
|
|
cb_PLCPortName.Text = Form1.f1.HCPLC_client.SerialPort;
|
|
cb_PLCBaudRate.Text = Form1.f1.HCPLC_client.Baudrate.ToString();
|
|
if (Form1.f1.HCPLC_client.Connected)
|
|
{
|
|
lb_PLCCom_status.Text = "已连接";
|
|
lb_PLCCom_status.ForeColor = Color.Green;
|
|
bt_PLCConnect.Enabled = false;
|
|
cb_PLCPortName.Enabled = false;
|
|
cb_PLCBaudRate.Enabled = false;
|
|
}
|
|
else
|
|
{
|
|
lb_PLCCom_status.Text = "未连接";
|
|
lb_PLCCom_status.ForeColor = Color.Red;
|
|
bt_PLCConnect.Enabled = true;
|
|
cb_PLCPortName.Enabled = true;
|
|
cb_PLCBaudRate.Enabled = true;
|
|
}
|
|
}
|
|
|
|
// 连接
|
|
private void bt_PLCConnect_Click(object sender, EventArgs e)
|
|
{
|
|
try
|
|
{
|
|
if (Form1.f1.HCPLC_client != null && Form1.f1.HCPLC_client.Connected)
|
|
{
|
|
lock (Form1.f1.plcLock) // 加锁
|
|
Form1.f1.HCPLC_client.Disconnect();
|
|
}
|
|
|
|
Form1.f1.HCPLC_client.SerialPort = cb_PLCPortName.Text;
|
|
Form1.f1.HCPLC_client.Baudrate = Convert.ToInt32(cb_PLCBaudRate.Text); // 波特率
|
|
Form1.f1.HCPLC_client.Parity = System.IO.Ports.Parity.None; // 无校验
|
|
Form1.f1.HCPLC_client.StopBits = System.IO.Ports.StopBits.Two; // 停止位
|
|
|
|
lock (Form1.f1.plcLock) // 加锁
|
|
Form1.f1.HCPLC_client.Connect();
|
|
|
|
// Form1.f1.PLC_client.Open();
|
|
if (Form1.f1.HCPLC_client != null && Form1.f1.HCPLC_client.Connected)
|
|
{
|
|
lb_PLCCom_status.Text = "已连接";
|
|
lb_PLCCom_status.ForeColor = Color.Green;
|
|
cb_PLCPortName.Enabled = false;
|
|
cb_PLCBaudRate.Enabled = false;
|
|
bt_PLCConnect.Enabled = false;
|
|
|
|
var jsconfig = new JsonConfig("config.json");
|
|
|
|
jsconfig.SetValue("PLC_PortName", cb_PLCPortName.Text);
|
|
jsconfig.SetValue("PLC_BaudRate", cb_PLCBaudRate.Text);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"PLC连接异常: {ex.Message}");
|
|
}
|
|
}
|
|
// 刷新
|
|
private void bt_PLCRefresh_Click(object sender, EventArgs e)
|
|
{
|
|
cb_PLCPortName.Items.Clear();
|
|
string[] ports = System.IO.Ports.SerialPort.GetPortNames();
|
|
cb_PLCPortName.Items.AddRange(ports);
|
|
}
|
|
// 断开
|
|
private void bt_PLCBreak_Click(object sender, EventArgs e)
|
|
{
|
|
if (Form1.f1.HCPLC_client.Connected)
|
|
{
|
|
lock (Form1.f1.plcLock) // 加锁
|
|
Form1.f1.HCPLC_client.Disconnect();
|
|
}
|
|
lb_PLCCom_status.Text = "未连接";
|
|
lb_PLCCom_status.ForeColor = Color.Red;
|
|
cb_PLCPortName.Enabled = true;
|
|
cb_PLCBaudRate.Enabled = true;
|
|
bt_PLCConnect.Enabled = true;
|
|
}
|
|
}
|
|
}
|