0% found this document useful (0 votes)
28 views10 pages

Form1 Bai4KTTN - Cs

The document describes code for connecting to a PLC and reading/writing registers. It includes functions for connecting to a socket, reading/writing data, parsing responses, and plotting data on a chart. The code is part of a GUI application for communicating with a PLC over TCP/IP.

Uploaded by

Vine Sandra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views10 pages

Form1 Bai4KTTN - Cs

The document describes code for connecting to a PLC and reading/writing registers. It includes functions for connecting to a socket, reading/writing data, parsing responses, and plotting data on a chart. The code is part of a GUI application for communicating with a PLC over TCP/IP.

Uploaded by

Vine Sandra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\...\Bai4KTTN\C#\GUIBai3KTTN\Bai3KTTN\Bai3KTTN\Form1.

cs 1
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;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO.Ports;
using System.Windows.Forms.DataVisualization.Charting;

namespace Bai3KTTN
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private const int READ_BUFFER_SIZE = 50;
private const int WRITE_BUFFER_SIZE = 50;
private byte[] bufferReceiver = null;
private byte[] bufferSender = null;
private Socket mSocket = null;
int counter = 0;
double pv;
double sp;
ushort pwm;
bool ctrlen;
int countctrl;
public void Connect()
{
this.mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.bufferReceiver = new byte[READ_BUFFER_SIZE];
this.bufferSender = new byte[WRITE_BUFFER_SIZE];
this.mSocket.SendBufferSize = READ_BUFFER_SIZE;
this.mSocket.ReceiveBufferSize = WRITE_BUFFER_SIZE;
IPEndPoint sever = new IPEndPoint(IPAddress.Parse(txtIPAddress.Text), Convert.ToInt16(txtPort.
Text));
this.mSocket.Connect(sever);
}

public void Disconnect()


{
if (this.mSocket == null) return;
if (this.mSocket.Connected)
{
this.mSocket.Close();
}
}

public int Write(byte[] frame)


{
return this.mSocket.Send(frame, frame.Length, SocketFlags.None);
}

public byte[] Read()


{
NetworkStream ns = new NetworkStream(this.mSocket);
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\...\Bai4KTTN\C#\GUIBai3KTTN\Bai3KTTN\Bai3KTTN\Form1.cs 2
if (ns.CanRead)
{
int rs = this.mSocket.Receive(this.bufferReceiver, this.bufferReceiver.Length, SocketFlags.
None);
}
return this.bufferReceiver;
}

public void CheckValidate(byte[] messageReceived)


{
try
{
switch (messageReceived[1])
{
case 129://Hex: 81
case 130:
case 131:
case 132:
case 133:
case 134:
case 143:
case 144:
switch (messageReceived[2])
{
case 1:
throw new Exception("01/0x01: Illegal Function.");
case 2:
throw new Exception("02/0x02: Illegal Data Address.");
case 3:
throw new Exception("03/0x03: Illegal Data Value.");
case 4:
throw new Exception("04/0x04: Failure In Associated Device.");
case 5:
throw new Exception("05/0x05: Acknowledge.");
case 6:
throw new Exception("06/0x06: Slave Device Busy.");
case 7:
throw new Exception("07/0x07: NAK - Negative Acknowledgements.");
case 8:
throw new Exception("08/0x08: Memory Parity Error.");
case 10:
throw new Exception("10/0x0A: Gateway Path Unavaliable.");
case 11:
throw new Exception("11/0x0B: Gateway Target Device Failed to respond.");
default:
break;
}
break;
}
}
catch (Exception ex)
{
//txtError.Text = ex.Message;
MessageBox.Show(ex.Message);
}
}

private string Display(byte[] data)


{
string result = string.Empty;
foreach (var item in data)
{
result += string.Format("{0:X2} ", item);
}
return result;
}
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\...\Bai4KTTN\C#\GUIBai3KTTN\Bai3KTTN\Bai3KTTN\Form1.cs 3

private string Display1(ushort data)


{
string result = string.Empty;
result = string.Format("Register {0}: ", data);
return result;
}

public static short ConvertByteArrayToInt(byte HiVal, byte LoVal)


{
return (short)(HiVal * 256 + LoVal);
}

public static short[] ConvertByteArrayToIntArray(byte[] bytes)


{
short[] values = new short[bytes.Length / 2];
int counter = 0;
for (int cnt = 0; cnt < bytes.Length / 2; cnt++)
{
values[cnt] = ConvertByteArrayToInt(bytes[counter++], bytes[counter++]);
}
return values;
}

public static byte[] ConvertIntToByteArray(short value)


{
byte[] byteArray = BitConverter.GetBytes(value);
Array.Reverse(byteArray);
return byteArray;
}

public static byte[] ConvertIntArrayToByteArray(ushort[] value)


{
byte[] arr = new byte[value.Length * 2];
int counter = 0;
for (int cnt = 0; cnt < value.Length; cnt++)
{
arr[counter++] = (byte)(value[cnt] >> 8);
arr[counter++] = (byte)(value[cnt]);
}
return arr;
}

private byte[] WriteMultipleRegistersMsg(ushort id, byte slaveAddress, ushort starAddress, byte


function, byte[] values)
{
// Sinh vien bo sung chuong trinh tao frame ghi nhieu thanh ghi mot luc

int byteCount = values.Length;


byte[] frame = new byte[13 + byteCount];
frame[0] = (byte)(id >> 8);
frame[1] = (byte)id;
frame[2] = 0;
frame[3] = 0;
frame[4] = 0;
frame[5] = (byte)(7 + byteCount);
frame[6] = slaveAddress;
frame[7] = function;
frame[8] = (byte)(starAddress >> 8);
frame[9] = (byte)starAddress;
ushort amount = (ushort)(byteCount / 2);
frame[10] = (byte)(amount >> 8);
frame[11] = (byte)amount;
frame[12] = (byte)byteCount;
Array.Copy(values, 0, frame, 13, byteCount);
return frame;
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\...\Bai4KTTN\C#\GUIBai3KTTN\Bai3KTTN\Bai3KTTN\Form1.cs 4
}
private byte[] ReadHoldingRegisterMsg(ushort id, byte slaveAddress, ushort starAddress, byte
function, uint numberOfPoints)
{
// Sinh vien bo sung chuong trinh tao frame doc nhieu thanh ghi mot luc
byte[] frame = new byte[12];
frame[0] = (byte)(id >> 8);
frame[1] = (byte)id;
frame[2] = 0;
frame[3] = 0;
frame[4] = 0;
frame[5] = 6;
frame[6] = slaveAddress;
frame[7] = function;
frame[8] = (byte)(starAddress >> 8);
frame[9] = (byte)starAddress;
frame[10] = (byte)(numberOfPoints >> 8);
frame[11] = (byte)numberOfPoints;
return frame;
}

private void PlotChart(double dataX, double dataY)


{
chart1.Series[0].Points.AddXY(dataX, dataY);

var chartArea = chart1.ChartAreas[0];


if (dataX > chartArea.AxisX.Maximum)
{
chartArea.AxisX.Maximum = dataX;

if (dataX / chartArea.AxisX.Interval == 10)


chartArea.AxisX.Interval = dataX / 5;
}
if (dataY > chartArea.AxisY.Maximum)
{
chartArea.AxisY.Maximum += 20;
}
}

//Form1_Load to assign parameter


private void Form1_Load(object sender, EventArgs e)
{
//Form 1 load thuc hien gan cac gia tri ban dau:IP, Port va Chart
txtIPAddress.Text = "192.168.0.1";
txtPort.Text = "502";

chart1.Titles.Add("Do thi dien ap theo thoi gian");


var chartArea = chart1.ChartAreas[0];
chartArea.AxisX.LabelStyle.Format = "";
chartArea.AxisY.LabelStyle.Format = "";
chartArea.AxisX.LabelStyle.IsEndLabelVisible = true;
chartArea.AxisY.LabelStyle.IsEndLabelVisible = true;

chartArea.AxisX.Minimum = 0;
chartArea.AxisY.Minimum = 0;
chartArea.AxisX.Maximum = 100;
chartArea.AxisY.Maximum = 12;

chartArea.AxisX.Interval = 20;
chartArea.AxisY.Interval = 20;

chartArea.AxisX.Title = "Thoi gian (s)";


chartArea.AxisY.Title = "Dien ap (V)";

chart1.Series[0].ChartType = SeriesChartType.Line;
chart1.Series[0].Color = Color.Red;
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\...\Bai4KTTN\C#\GUIBai3KTTN\Bai3KTTN\Bai3KTTN\Form1.cs 5
chart1.Series[0].BorderWidth = 2;
chart1.Series[0].IsVisibleInLegend = false;
}

//Connecting to PLC
private void butConnect_Click(object sender, EventArgs e)
{
try
{
Connect();
label9.Text = "Connected";
butConnect.Enabled = false;
//Enable timer1
timer1.Enabled = true;
}
catch (Exception ex)
{
label9.Text = "IP Address of Port not Available";
}
}

//Disconnecting to PLC
private void ForMain_FormClosing(object sender, FormClosedEventArgs e)
{
try
{
Disconnect();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

//Timer1 for READING actual value, draw chart1 and run ON/OFF controller
private void timer1_Tick(object sender, EventArgs e)
{

//Doc 6 thanh ghi cung luc tu dia chi 0 den 5


//I0.0 Reg0
//I0.1 Reg1
//Analog Reg2
//PWM Reg3
try
{
byte slaveAddress = 1;
byte function = 3;
ushort id = function;
ushort startAddress = 0; //doc tu vi tri thanh ghi dau tien
uint numberOfPoints = 6; //doc lan 6 thanh ghi
byte[] frame = ReadHoldingRegisterMsg(id, slaveAddress, startAddress, function,
numberOfPoints);
//txtSendMess.Text = Display(frame);
this.Write(frame); Thread.Sleep(10);
byte[] buffReceiver = this.Read();
int SizeByte = bufferReceiver[8];
short[] temp = null;
if (function != bufferReceiver[7])
{
byte[] byteMsg = new byte[9];
Array.Copy(bufferReceiver, 0, byteMsg, 0, byteMsg.Length);
//txtRecMess.Text = Display(byteMsg);
byte[] errorbytes = new byte[3];
Array.Copy(bufferReceiver, 6, errorbytes, 0, errorbytes.Length); this.CheckValidate
(errorbytes);
}
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\...\Bai4KTTN\C#\GUIBai3KTTN\Bai3KTTN\Bai3KTTN\Form1.cs 6
else
{
byte[] byteMsg = new byte[9 + SizeByte];
Array.Copy(bufferReceiver, 0, byteMsg, 0, byteMsg.Length);
byte[] data = new byte[SizeByte];
//txtRecMess.Text = Display(byteMsg);
Array.Copy(bufferReceiver, 9, data, 0, data.Length);
temp = ConvertByteArrayToIntArray(data);
}
if (temp == null) return;
string result = string.Empty;
foreach (var item in temp)
{
result += string.Format("{0} / ", item);
}

//Hien thi gia tri Analog


pv = temp[0] * 0.022606 - 125;
pvtb.Text = pv.ToString();

//Hien thi gia tri PWM


cvtb.Text = temp[1].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

//Draw chart
PlotChart((double)timer1.Interval / 1000.0 * (double)counter, pv);
counter++;

//Enable ON/OFF Controller


if (ctrlen == true)
{
// Bo sung chuong trinh ghi 1 thanh ghi tai vi tri
countctrl = 1;
try
{
sp = Convert.ToDouble(setvaluetb.Text);
}
catch
{
MessageBox.Show("Nhap gia tri Set Value!");
}

if ((pv - sp) > 3)


{
pwm = 0;
}
if ((pv - sp) < -3)
{
pwm = 50;
}
}

if (ctrlen == false)
{
pwm = 0;
}
try
{
byte slaveAddress = 1;
byte function = 16;
ushort id = function;
ushort startAddress = 5;
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\...\Bai4KTTN\C#\GUIBai3KTTN\Bai3KTTN\Bai3KTTN\Form1.cs 7
ushort value1;
value1 = pwm;
ushort[] input = new ushort[1] { value1 };
byte[] values = ConvertIntArrayToByteArray(input);
//txtError.Text = string.Empty;
byte[] frame = WriteMultipleRegistersMsg(id, slaveAddress, startAddress, function,
values);
//txtSendMess.Text = Display(frame);
int code = this.Write(frame);

//Co the bo qua doan code check loi nay cho nhanh, neu khong thi cu viet lai
//txtError.Text = "OK";
/*Thread.Sleep(20);
byte[] buffReceiver = this.Read();
int SizeByte = bufferReceiver[8];
byte[] byteMsg = null;
if (function != bufferReceiver[7])
{
byte[] errorbytes = new byte[3];
Array.Copy(bufferReceiver, 6, errorbytes, 0, errorbytes.Length);
this.CheckValidate(errorbytes);
byteMsg = new byte[9];
Array.Copy(bufferReceiver, 0, byteMsg, 0, byteMsg.Length);
}
else
{
byteMsg = new byte[READ_BUFFER_SIZE];
Array.Copy(bufferReceiver, 0, byteMsg, 0, byteMsg.Length);
}
//txtRecMess.Text = Display(byteMsg);*/
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

//Enable ON/OFF Control


private void butstart_Click(object sender, EventArgs e)
{
if (countctrl == 0)
{
ctrlen = true;
butstart.Text = "STOP";
}
if (countctrl == 1)
{
ctrlen = false;
countctrl = 0;
butstart.Text = "START";
}
}

}
}

You might also like