Form1 Bai3KTTN - Cs

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\...\Bai3KTTN\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 AI;
int ctnQ00 = 0, ctnQ01 = 0;
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);
if (ns.CanRead)
{
int rs = this.mSocket.Receive(this.bufferReceiver, this.bufferReceiver.Length, SocketFlags.
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\...\Bai3KTTN\C#\GUIBai3KTTN\Bai3KTTN\Bai3KTTN\Form1.cs 2
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;
}

private string Display1(ushort data)


{
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\...\Bai3KTTN\C#\GUIBai3KTTN\Bai3KTTN\Bai3KTTN\Form1.cs 3
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;
}
private byte[] ReadHoldingRegisterMsg(ushort id, byte slaveAddress, ushort starAddress, byte
function, uint numberOfPoints)
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\...\Bai3KTTN\C#\GUIBai3KTTN\Bai3KTTN\Bai3KTTN\Form1.cs 4
{
// 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;
chart1.Series[0].BorderWidth = 2;
chart1.Series[0].IsVisibleInLegend = false;
}
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\...\Bai3KTTN\C#\GUIBai3KTTN\Bai3KTTN\Bai3KTTN\Form1.cs 5

//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 and draw chart1


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);
}
else
{
byte[] byteMsg = new byte[9 + SizeByte];
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\...\Bai3KTTN\C#\GUIBai3KTTN\Bai3KTTN\Bai3KTTN\Form1.cs 6
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 tin hieu ngo vao I0.0


if (temp[0] == 0)
{
rectangleShape1.BackColor = Color.White;
}
else
{
rectangleShape1.BackColor = Color.Green;
}

//Hien thi tin hieu ngo vao I0.1


if (temp[1] == 0)
{
rectangleShape2.BackColor = Color.White;
}
else
{
rectangleShape2.BackColor = Color.Green;
}

//Hien thi gia tri Analog


AI = temp[2] * 10.0 / 27648.0;
analogtbox.Text = AI.ToString();

//Hien thi gia tri PWM


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

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

//butQ00_click for WRITING value to output port Q00


private void butQ00_Click(object sender, EventArgs e)
{
// Bo sung chuong trinh ghi 1 thanh ghi tai vi tri 10
try
{
byte slaveAddress = 1;
byte function = 16;
ushort id = function;
ushort startAddress = 10;
ushort value1 = 0;
if (ctnQ00 == 0)
{
value1 = 1;
ctnQ00 = 1;
}
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\...\Bai3KTTN\C#\GUIBai3KTTN\Bai3KTTN\Bai3KTTN\Form1.cs 7
else
{
value1 = 0;
ctnQ00 = 0;
}
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);
}
}

//butQ01_click for WRITING value to output port Q01


private void buQ01_Click(object sender, EventArgs e)
{
// Bo sung chuong trinh ghi 1 thanh ghi tai vi tri 11
try
{
byte slaveAddress = 1;
byte function = 16;
ushort id = function;
ushort startAddress = 11;
ushort value1 = 0;
if (ctnQ01 == 0)
{
value1 = 1;
ctnQ01 = 1;
}
else
{
value1 = 0;
ctnQ01 = 0;
}
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);
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\...\Bai3KTTN\C#\GUIBai3KTTN\Bai3KTTN\Bai3KTTN\Form1.cs 8

//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);
}
}

//WRITING to PWM Register


private void butset_Click(object sender, EventArgs e)
{
// Bo sung chuong trinh ghi 1 thanh ghi tai vi tri 12
try
{
byte slaveAddress = 1;
byte function = 16;
ushort id = function;
ushort startAddress = 12;
ushort value1 = 0;
value1 = (ushort)Convert.ToInt16(textBox3.Text);
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);
}
D:\STUDY-BKHCM\2022-2023-HK2\DoluongvaDieukhienMT\...\Bai3KTTN\C#\GUIBai3KTTN\Bai3KTTN\Bai3KTTN\Form1.cs 9
//txtRecMess.Text = Display(byteMsg);*/
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

}
}

You might also like