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

12345

The document is a C# Windows Forms application that interfaces with a USB HID device to receive temperature and light data, processes it, and displays it in a UI. It includes functionality for UDP communication, database connectivity for data storage, and automated HTTP requests to a specified URL. The application utilizes multithreading for handling data reception and UI updates, ensuring a responsive user experience.

Uploaded by

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

12345

The document is a C# Windows Forms application that interfaces with a USB HID device to receive temperature and light data, processes it, and displays it in a UI. It includes functionality for UDP communication, database connectivity for data storage, and automated HTTP requests to a specified URL. The application utilizes multithreading for handling data reception and UI updates, ensuring a responsive user experience.

Uploaded by

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

using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
using System.Net.NetworkInformation;
using System.Data.SqlClient;
using HIDLib;

namespace CuoiKy
{
public partial class Form1 : Form
{
string url = "";
Boolean autorequest = false;
HIDDevice dev = new HIDDevice();
long countChar = 0;
string InputDataTime = String.Empty; // Khai báo string buff dùng cho hiển
thị dữ liệu sau này.
public Thread eh;
float temp, light;
delegate void SetTextCallback(string text); //Khai bao delegate
SetTextCallBack voi tham so string
static int i = 0;
Boolean startread = true;

byte[] data = new byte[9];


public Form1()
{
InitializeComponent();
timer1.Start();
timer1.Interval = 1000;
timer1.Tick += timer1_Tick;
timer1.Start();
chart1.ChartAreas[0].AxisX.Minimum = 0;
chart1.ChartAreas[0].AxisX.Interval = 5;
chart1.ChartAreas[0].AxisX.Maximum = 20;
try
{
dev.vid = 0x1234;
dev.pid = 0x0001;
dev.in_size = 64;
dev.out_size = 64;
dev.Initialize();
}
catch
{
MessageBox.Show("PID & VID Error");
}
KetNoiCSDL();
if (dataGridView1.Rows.Count - 1 > 0)
{
i = Int32.Parse(dataGridView1.Rows[dataGridView1.Rows.Count -
2].Cells[0].Value.ToString());
i++;
}
else
{
i = 1;
}
}
string dataReceive = string.Empty;
UdpClient clientsock, serversock;
Boolean startServer = false;
string ipclient;
int portServer;
IPEndPoint remoteEP;
SqlConnection con = new SqlConnection(@"Data Source=DUONGWCAN\
SQL2008;Initial Catalog=CNTDuong_DTVT_K151;Integrated Security=True");
public delegate void logCallback(string logLine);
private void SetText(string text)
{

if (InvokeRequired) this.Invoke(new Action(() => getDATA.Text += text +


Environment.NewLine));
else getDATA.AppendText(text + Environment.NewLine);

if (this.getDATA.InvokeRequired)
{

SetTextCallback d = new SetTextCallback(SetText); // khởi tạo 1


delegate mới gọi đến SetText

this.Invoke(d, new object[] { text });

else
{
getDATA.Text += text;//hien thi list du lieu
//===============tu dong cuon du lieu textbox
getDATA.SelectionStart = getDATA.Text.Length;
getDATA.ScrollToCaret();
}
}
private void acceptClient()
{
while (startServer)
{
try
{
byte[] data = serversock.Receive(ref remoteEP);
dataReceive = Encoding.ASCII.GetString(data);
if (dataReceive != string.Empty)
{
SetText(dataReceive);
ipclient = remoteEP.Address.ToString();
int portclient = remoteEP.Port;
ipc.Invoke(new MethodInvoker(delegate { ipc.Text = ipclient
+ ":" + portclient.ToString(); }));
ProcessReceivedData(dataReceive);
}
}
catch { }
}

}
private void KetNoiCSDL()
{
string sql = "select * from LAN_UDP";
SqlConnection con = new SqlConnection(@"Data Source=DUONGWCAN\
SQL2008;Initial Catalog=CNTDuong_DTVT_K151;Integrated Security=True");
SqlCommand com = new SqlCommand(sql, con);
com.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.RowCount
- 1;
}
private delegate void dlgAutoUpdateDatabases(long id, string temp, string
light, string Time);
private void AutoUpdateDatabases(long id, string temp, string light, string
Time)
{
if (this.dataGridView1.InvokeRequired)
{
this.Invoke(new dlgAutoUpdateDatabases(AutoUpdateDatabases), id,
temp, light, Time);
}
else
{
SqlConnection con = new SqlConnection(@"Data Source=DUONGWCAN\
SQL2008;Initial Catalog=CNTDuong_DTVT_K151;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO LAN_UDP (ID, Temp,
Light, TimeCreat) VALUES (@ID,@Temp,@Light,@TimeCreat)", con);
cmd.Parameters.AddWithValue("@ID", id);
cmd.Parameters.AddWithValue("@Temp", temp);
cmd.Parameters.AddWithValue("@Light", light);
cmd.Parameters.AddWithValue("@TimeCreat", Time);
try
{
cmd.ExecuteNonQuery();
}
catch
{
con.Close();
return;
}
KetNoiCSDL();
}

}
private void ProcessReceivedData(string data)
{
try
{
if (dataReceive.IndexOf('@') != -1 && dataReceive.IndexOf('#') != -
1)
{
float temp = 0;
float light = 0;

if (dataReceive.IndexOf('$') != -1 && dataReceive.IndexOf('@')


< (dataReceive.IndexOf('$') - 1))
{
string tempStr =
dataReceive.Substring(dataReceive.IndexOf('@') + 1, dataReceive.IndexOf('$') -
dataReceive.IndexOf('@') - 1);
temp = float.Parse(tempStr);

// Hiển thị lên getTemp


if (getTemp.InvokeRequired)
{
getTemp.Invoke((MethodInvoker)delegate { getTemp.Text =
temp.ToString(); });
}
else getTemp.Text = temp.ToString();
}

if (dataReceive.IndexOf('$') < (dataReceive.IndexOf('#') - 1))


{
string lightStr =
dataReceive.Substring(dataReceive.IndexOf('$') + 1, dataReceive.IndexOf('#') -
dataReceive.IndexOf('$') - 1);
light = float.Parse(lightStr);

// Hiển thị lên getLight


if (getLight.InvokeRequired)
{
getLight.Invoke((MethodInvoker)delegate { getLight.Text
= light.ToString(); });
}
else getLight.Text = light.ToString();
}

string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


AutoUpdateDatabases(i, temp.ToString(), light.ToString(),
time); // Lưu vào database
i++;
}
else
{
MessageBox.Show("Dữ liệu không đúng định dạng.");
}
}
catch (Exception ex)
{
MessageBox.Show("Lỗi xử lý dữ liệu: " + ex.Message);
}
}

private void btOpen_Click(object sender, EventArgs e)


{
String strHostName = Dns.GetHostName();
IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);
foreach (IPAddress ipaddress in iphostentry.AddressList)
{
lanip.Text = ipaddress.ToString();
}
startServer = true;
try
{
portServer = int.Parse(t_port.Text);
}
catch
{
return;
}
try
{
serversock = new UdpClient(portServer);
remoteEP = new IPEndPoint(IPAddress.Any, portServer);
Thread thClient = new Thread(acceptClient);
thClient.Start();
}
catch { }
}
private void btClose_Click(object sender, EventArgs e)
{
if (serversock != null)
{
serversock.Close();
}
startServer = false;
ipc.Invoke(new MethodInvoker(delegate { ipc.Text = ""; }));
getDATA.Text = "";
}

private void btSend_Click(object sender, EventArgs e)


{
string datasend = tbSend.Text;
if (string.IsNullOrEmpty(tbSend.Text))
{
MessageBox.Show("Chưa nhập lệnh. Gửi mặc định");
datasend = "Test theo UDP default";
}
byte[] command = Encoding.UTF8.GetBytes(datasend);
if (remoteEP != null)
{
clientsock = new UdpClient();
clientsock.Send(command, command.Length, remoteEP);
clientsock.Close();
}
else MessageBox.Show("Chưa nhận được Client nào");
}

private void btSave_Click(object sender, EventArgs e)


{
string strIPclient = ipc.Text;
string[] parts = strIPclient.Split(':');
string ipClient = parts[0]; //lấy phần IP
int portClient = int.Parse(parts[1]); //Chuyển phần Port sang số nguyên
remoteEP = new IPEndPoint(IPAddress.Parse(ipClient), portClient);
}

private void Form1_Load(object sender, EventArgs e)


{
// TODO: This line of code loads data into the
'cNTDuong_DTVT_K151DataSet.LAN_UDP' table. You can move, or remove it, as needed.
this.lAN_UDPTableAdapter.Fill(this.cNTDuong_DTVT_K151DataSet.LAN_UDP);

private void getUSB_Click(object sender, EventArgs e)


{
startread = true;
Thread.Sleep(100);
eh = new Thread(new ThreadStart(ReceiveTEMP));
eh.Start();//chạy Thread
}
private DataTable dataTable = new DataTable();
private void ReceiveTEMP()
{
do
{
try
{
dev.Initialize();
byte[] reData = new byte[64];
string var1 = "0", var2 = "0"; // Giá trị mặc định
reData = dev.Receive();
InputDataTime = DateTime.Now.ToString("yyyy-MM-dd
HH:mm:ss.fff");

// Chuyển dữ liệu sang dạng chuỗi


System.Text.Encoding enc = System.Text.Encoding.ASCII;
string stringReData = enc.GetString(reData);

// Hiển thị dữ liệu trên TextBox getData (đã có xử lý Invoke


bên trong SetText)
SetText(stringReData);
SetText("\r\n");

// Kiểm tra dữ liệu có định dạng hợp lệ không (@...$...#)


if ((stringReData.IndexOf('@') != -1) &&
(stringReData.IndexOf('#') != -1))
{
string timestamp = getDatetime.Text; // Lấy thời gian từ
timer1

// Lấy giá trị Temp


if ((stringReData.IndexOf('$') != -1) &&
(stringReData.IndexOf('@') < (stringReData.IndexOf('$') - 1)))
{
var1 = stringReData.Substring(stringReData.IndexOf('@')
+ 1,
stringReData.IndexOf('$') -
stringReData.IndexOf('@') - 1);
temp = float.Parse(var1);

// Cập nhật TextBox getTemp an toàn trên UI thread


if (getTemp.InvokeRequired)
getTemp.Invoke((MethodInvoker)delegate
{ getTemp.Text = temp.ToString(); });
else
getTemp.Text = temp.ToString();
}

// Lấy giá trị Light


if (stringReData.IndexOf('$') < (stringReData.IndexOf('#')
- 1))
{
var2 = stringReData.Substring(stringReData.IndexOf('$')
+ 1,
stringReData.IndexOf('#') -
stringReData.IndexOf('$') - 1);
light = float.Parse(var2);

// Cập nhật TextBox getLight an toàn trên UI thread


if (getLight.InvokeRequired)
getLight.Invoke((MethodInvoker)delegate
{ getLight.Text = light.ToString(); });
else
getLight.Text = light.ToString();
}

// Cập nhật biểu đồ


countChar++;
if (countChar > 20)
{
// Xóa series của chart1 an toàn trên UI thread
// if (chart1.InvokeRequired)
// {
// chart1.Invoke(new Action(() =>
// {
// chart1.Series.Clear();
// }));
// }
// else
// {
// chart1.Series.Clear();
// }
// countChar = 0;
}
// Hàm drawChar() phải tự xử lý Invoke bên trong nếu cần
drawChar();
i++;

// Thêm dữ liệu vào DataGridView an toàn trên UI thread


if (dataGridView1.InvokeRequired)
{
dataGridView1.Invoke((MethodInvoker)delegate
{
dataTable.Rows.Add(idCounter++, temp, light,
timestamp);
});
}
else
{
dataTable.Rows.Add(idCounter++, temp, light,
timestamp);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Lỗi nhận dữ liệu: " + ex.Message);
}
}
while (startread == true);
}
private int idCounter = 1; // ID tự tăng

protected override void WndProc(ref Message m)


{
dev.DeviceChange(ref m);
base.WndProc(ref m);
if (!dev.AttachedState)
{
status.Text = "Disconnected!"; status.ForeColor = Color.Red;
}
else
{
status.Text = "Connected!"; status.ForeColor = Color.Green;
}

}
private delegate void dlgdrawChar();
private void drawChar()
{
if (this.chart1.InvokeRequired)
{
this.Invoke(new dlgdrawChar(drawChar));
}
else
{
try
{
this.chart1.Series["Temp"].Points.AddXY(countChar, temp);
this.chart1.Series["Light"].Points.AddXY(countChar, light);
}
catch { }
}

}
private void BTStop_Click(object sender, EventArgs e)
{
startread = false;
try
{
eh.Abort();
Thread.Sleep(100);
}
catch
{
eh = new Thread(new ThreadStart(ReceiveTEMP));//khởi tạo thread
chạy hàm nhận dữ liệu từ USB
eh.Start();
Thread.Sleep(100);
eh.Abort();//Chạy Thread
}
}
private void BTDelAll_Click(object sender, EventArgs e)
{
getDATA.Text = string.Empty;
}

private void btGET_Click(object sender, EventArgs e)


{
url = tbViewData.Text;
autorequest = false;
if (string.IsNullOrEmpty(url))
{
MessageBox.Show("Nhập Link Web");
return;
}
else
{
try
{
httprequest(url);
}
catch
{
MessageBox.Show("Lỗi Request");
}
}
}

private void btAUTOGET_Click(object sender, EventArgs e)


{
url = tbViewData.Text;
if (String.IsNullOrEmpty(url))
{
autorequest = false;
MessageBox.Show("Nhập Link Web");
return;
}
else autorequest = !autorequest;
}
private void httprequest(String url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
try
{
using (HttpWebResponse response =
(HttpWebResponse)request.GetResponse())
using (StreamReader reader = new
StreamReader(response.GetResponseStream()))
{
string responseText = reader.ReadToEnd();
getDATA.Text = responseText;
}
}
catch (WebException ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}

private void timer1_Tick(object sender, EventArgs e)


{
try
{
if (autorequest) httprequest(url);
}
catch (Exception ex)
{
autorequest = false;
MessageBox.Show("Timer1: " + ex.Message);
}
}
}
}

You might also like