[英]SQL update using data collected by C# from Arduino Serial
我正在嘗試編寫一個簡單的C#程序,它將讀取通過串行連接的Arduino的數據輸出,將相關數據從格式化為便於理解的文本字符串中移出串行監視器,並顯示兩個信息在兩個用作計數器的只讀文本框中(每次更新信息時都會覆蓋),並使用這些數字來更新SQL表。
例:
Arduino輸出:
'Day Users: 234231'
'All Users: 433241'
C#在textbox1中顯示完整消息
C#在textbox2中顯示234231
C#在textbox3中顯示433241
C#UPDATES SQL表類似於:
SqlCommand myCommand = new SqlCommand("UPDATE USER_NUMBERS
SET NUMBERZ= 234231
WHERE UPTIME = DAYHK");
但是顯然,'234231'是一個變量,由Arduino的輸入指定,然后通知textbox2的內容和更新SQL表所需的值。
我是C#的新手,但到目前為止,我有一個程序可以讀取Arduino的串行數據,並將整個輸出放入textbox1中,但僅此而已。
我如何在要分配給值的傳入數據中指定一部分作為textbox2(或textbox3)中的文本輸出,然后使用它來做這件事和更新SQL表中保存的值?
到目前為止,我的代碼是:
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 Serial_Reader
{
public partial class Form1 : Form
{
string RxString;
public Form1()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM3";
serialPort1.BaudRate = 9600;
serialPort1.Open();
if (serialPort1.IsOpen)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
buttonSQL.Enabled = true;
textBox1.ReadOnly = false;
}
}
private void buttonStop_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
buttonStart.Enabled = true;
buttonStop.Enabled = false;
buttonSQL.Enabled = false;
textBox1.ReadOnly = true;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// If the port is closed, don't try to send a character.
if (!serialPort1.IsOpen) return;
// If the port is Open, declare a char[] array with one element.
char[] buff = new char[1];
// Load element 0 with the key character.
buff[0] = e.KeyChar;
// Send the one character buffer.
serialPort1.Write(buff, 0, 1);
// Set the KeyPress event as handled so the character won't
// display locally. If you want it to display, omit the next line.
e.Handled = true;
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadExisting();
this.Invoke(new EventHandler(DisplayText));
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen) serialPort1.Close();
}
private void DisplayText(object sender, EventArgs e)
{
textBox1.AppendText(RxString);
}
private void buttonSQL_Click(object sender, EventArgs e)
{
}
}
}
你可以從“我”擅長評論,但不稱職的節目中,我使用的代碼從輝煌教程看這里 :和所有我的計划將有額外的一個按鈕,開始SQL通信,當串行通信被攔停,和兩個額外的文本框。
編輯 :
輸入的格式為:
Someone got up from seat number 9
All-time users on seat number 9 is: 5
Today's total users: 17
All-time total users: 17
這樣,非程序員檢查串行監視器就可以輕松理解輸出。 第一行始終是“有人從那里站起來”或“有人坐下來”,在第二行上,只有數字改變了,在第三和第四行上又改變了,但是在第三和第四行上(這種情況是相同的,因為系統運行時間少於一天)是需要解析的系統。
編輯2 (新代碼):
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.Data.SqlClient;
namespace Serial_Reader
{
public partial class Form1 : Form
{
string RxString;
public Form1()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM3";
serialPort1.BaudRate = 9600;
serialPort1.Open();
if (serialPort1.IsOpen)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
buttonSQL.Enabled = true;
textBox1.ReadOnly = true;
}
}
private void buttonStop_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
buttonStart.Enabled = true;
buttonStop.Enabled = false;
buttonSQL.Enabled = false;
textBox1.ReadOnly = true;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// If the port is closed, don't try to send a character.
if (!serialPort1.IsOpen) return;
// If the port is Open, declare a char[] array with one element.
char[] buff = new char[1];
// Load element 0 with the key character.
buff[0] = e.KeyChar;
// Send the one character buffer.
serialPort1.Write(buff, 0, 1);
// Set the KeyPress event as handled so the character won't
// display locally. If you want it to display, omit the next line.
e.Handled = true;
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadExisting();
this.Invoke(new EventHandler(DisplayText));
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen) serialPort1.Close();
}
private void DisplayText(object sender, EventArgs e)
{
textBox1.AppendText(RxString);
}
private void buttonSQL_Click(object sender, EventArgs e)
{
// SqlConnection myConnection = new SqlConnection("user id=username;" +
// "password=password;server=serverurl;" +
// "Trusted_Connection=yes;" +
// "database=database; " +
// "connection timeout=30");
do
{
string dayUsers, allUsers;
string s1 = "Today's total users: ";
string s2 = "All-time total users: ";
if (RxString.Contains(s1))
{
dayUsers = RxString.Replace(s1, "");
textDU.Text = dayUsers;
// string queryDay = "UPDATE USER_NUMBERS SET NUMBERZ=" + dayUsers + "WHERE UPTIME=DAYHK";
}
if (RxString.Contains(s2))
{
allUsers = RxString.Replace(s2, "");
textAU.Text = allUsers;
// string queryAll = "UPDATE USER_NUMBERS SET NUMBERZ=" + allUsers + "WHERE UPTIME=ALLHK";
}
}
while (serialPort1.IsOpen);
}
private void textDU_TextChanged(object sender, EventArgs e)
{
}
private void textAU_TextChanged(object sender, EventArgs e)
{
}
}
}
編輯3 (傳入數據):
if (abs (then [i] - now[i]) > THRESH)
{
Serial.print ("Someone ");
if (now [i] > then [i])
{
Serial.print ("sat on");
allusers++;
dayusers++;
digitalWrite(counterPin, HIGH); // hit counter
delay(75);
digitalWrite(counterPin, LOW);
val[i]++;
}
else
{
Serial.print ("got up from");
}
Serial.print (" seat number ");
Serial.println (i);
Serial.print ("All-time users on seat number ");
Serial.print (i);
Serial.print (" is: ");
Serial.println (val[i]);
Serial.print ("Today's total users: ");
Serial.println (dayusers);
Serial.print ("All-time total users: ");
Serial.println (allusers);
}
如果您知道輸入字符串始終采用相同的格式,並且數字始終具有6位數字,則可以使用簡單的子字符串:
int dayUsers, allUsers;
Int32.TryParse(RxString.Substring(12, 6), out dayUsers);
Int32.TryParse(RxString.Substring(32, 6), out allUsers);
否則,您可以使解析更加復雜:
int dayUsers, allUsers;
string[] parts = RxString.Split('\'', ':');
if (parts.Length > 5)
{
Int32.TryParse(parts[2].Trim(), out dayUsers);
Int32.TryParse(parts[5].Trim(), out allUsers);
}
然后,只需使用文本框中的數字和SQL查詢即可:
textBox2.Text = dayUsers.ToString();
textBox3.Text = allUsers.ToString();
string query = "UPDATE USER_NUMBERS SET NUMBERZ=" + dayUsers + "WHERE UPTIME=DAYHK"
編輯:鑒於textBox1中有四行數據,您可以使用類似這樣的方法來提取包含數字的字符串:
string[] inputLines = textBox1.Text.Split('\n');
if (inputLines.Length == 4)
{
string dayUsers = inputLines[2].Substring(inputLines[2].IndexOf(':') + 1).Trim();
string allUsers = inputLines[3].Substring(inputLines[3].IndexOf(':') + 1).Trim();
}
編輯2:建議代碼解析TextBox1中的數據可能不完整:
private void buttonSQL_Click(object sender, EventArgs e)
{
// Get unsaved input from text box
string input = textBox1.Text;
string[] inputLines = input.Split('\n');
// Find and process relevant input
foreach(string line in inputLines)
{
if (line.EndsWith("\r")) // Make sure line is complete
{
if (line.StartsWith("Today's total users: "))
{
string dayUsers = line.Substring(20).Trim();
textDU.Text = dayUsers;
// SQL query...
}
else if (line.StartsWith("All-time total users: "))
{
string allUsers = line.Substring(21).Trim();
textAU.Text = allUsers;
// SQL query...
}
}
}
// Only keep unparsed text in text box
textBox1.Text = inputLines[inputLines.Length - 1];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.