.
這篇所要達成的功能是接收從 arduino WebServer 上面的資料, arduino 的架設 WebServer
使用 Substring 來解析取得的資料,擷取需要的部分,以下範例為取得從Server端上傳來的
指定 analog pin 的值呈現在畫面上,之後每秒將取得的值儲存在Log中
- 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;
- using System.IO;
- using System.Threading;
-
- namespace WebRecieve_test
- {
- public partial class Form1 : Form
- {
- private Thread _th;
- private delegate void updateLabel(string str, Control ctl);
- private string[] _dataArray = new string[10];
-
- public Form1()
- {
- InitializeComponent();
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- _th = new Thread(ReadData);
- _th.Start();
- }
-
- private void Update_Label(string value, Control ctl)
- {
- if (this.InvokeRequired)
- {
- updateLabel uu = new updateLabel(Update_Label);
- this.Invoke(uu, value, ctl);
- }
- else
- {
- ctl.Text = value.ToString();
- }
- }
-
- private void ReadData()
- {
- while(true)
- {
- //將要取得HTML原如碼的網頁放在WebRequest.Create(@”網址” )
- WebRequest myRequest = WebRequest.Create(@"http://10.56.66.173/");
- //Method選擇GET
- myRequest.Method = "GET";
- //取得WebRequest的回覆
- WebResponse myResponse = myRequest.GetResponse();
- //Streamreader讀取回覆
- StreamReader sr = new
- StreamReader(myResponse.GetResponseStream());
- //將全文轉成string
- string result = sr.ReadToEnd();
- //關掉StreamReader
- sr.Close();
- //關掉WebResponse
- myResponse.Close();
- //搜尋頭尾關鍵字
- string temp_str = "";
-
- for (int i = 0; i <= 5; i++)
- {
- int first = result.IndexOf("analog input" + i + " is </td>
- <td ALIGN=CENTER");
- int last = result.LastIndexOf(" " + i + "</td></tr>");
- string HTMLCut = result.Substring(first + 39, last - first - 38);
- temp_str += "analog input"+i+" is "+HTMLCut + "\n";
- _dataArray[i] = HTMLCut;
- Update_Label(temp_str + "\n", label1);
- }
- store_data();
- Thread.Sleep(1000);
- }
- }
-
- private void store_data()
- {
- string str = System.Windows.Forms.Application.StartupPath;
- string file = str + "\\data\\" + DateTime.Now.Year.ToString() +
- DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() +
- DateTime.Now.Hour.ToString() + ".log";
-
- if (Directory.Exists(str + "\\data\\"))
- {
- //資料夾存在
- }
- else
- {
- //新增資料夾
- Directory.CreateDirectory(str + "\\data\\");
- }
-
- if (!System.IO.File.Exists(file))
- {
- FileStream filestream = new FileStream(file, FileMode.Create);
- filestream.Close();
- }
-
- StreamWriter sw = new StreamWriter(file, true);
- for(int i = 0 ; i <= 5 ; i++)
- {
- if(i < 5)
- {
- sw.Write("analog input"+ i+" is " + _dataArray[i] + ",");
- }
- else
- {
- sw.Write("analog input" + i + " is " + _dataArray[i]);
- }
- }
- sw.Write("\r\n");
- sw.Close();
- }
-
-
- private void Form1_FormClosed(object sender, FormClosedEventArgs e)
- {
- _th.Abort();
- _th.Join();
- }
- }
- }
執行結果
arduino 上 呈現的畫面
Client端 每秒接收的畫面
Log中儲存的資料