物聯網測驗總結基于ESP32的串口和TCP通信的軟體設計
- 物聯網測驗總結(基于ESP32的串口和TCP通信的軟體設計)
- 簡答題預測
- 1、程式的移植
- 2、WINDOWS表單應用程式與WPF應用程式的區別?
- 3、第三個實在是想不出來了,看看資料庫的添加程序吧,哈哈~祝各位好運~~😄😄😄
- 本工程的檔案結構
- class1.cs 程式
- class db 資料庫的類撰寫
- TCP類的撰寫
- Program.cs 程式
- class DataPointTest //創建用于連接Onenet的類
- Form1.cs 的程式
- 實作的效果
- class Form1 : Form //創建Form1的類
- FromTCP.cs的程式
- 實作效果
- class FormTCP : Form //創建TCP的類
- MainForm.cs 程式
- 實作效果
- class MainForm : Form
- FromDB.cs 程式
- 實作效果
- class FormDB_01 : Form 實作代碼
- ESP32連接Wi-Fi作為TCP Server端的python代碼:
- by iNBC form SDUT(2020.11.11 pm11:00)
- 考后總結:簡答題前兩個還有最后兩道大題竟然是原題和原題改編,不是說不考嗎?!哭了……😭😭😭程式移植還是猜對了!程式注釋還考了UDP,這是我沒想到的,其他的上面都提到了,也大差不差,唉,最慘的是我借了同學兩根筆,沒寫幾個字,都不下了,悲催!借了根筆,也斷油,寫的字超級難看,估計是紙打了蠟吧,希望老師能夠看懂吧,好了,大四上學期的考試至此完結,撒花🎉! 希望明天依然美好,各位晚安!!!(2020.11.13 21:24)
物聯網測驗總結(基于ESP32的串口和TCP通信的軟體設計)
具體的程式代碼請點擊這里獲取哦~🙃🙃🙃
簡答題預測
(純個人預測,不中請輕噴😶😶😶~)
1、程式的移植
——>首先新建WindowsForm程式或者WPF程式,
——>將 將要移植的程式或視窗復制到對應的WindowsForm程式或者WPF程式的目錄下,
——>再在資源管理器中右擊工程專案,
——>添加,
——>現有項,
——>再選擇移植到目錄下的視窗的XXXX.cs 檔案到當前的工程目錄下,
——>然后更改命名空間(namespace)為本程式的命名空間,
——>然后再添加移植過來的程式所需要的參考(Using),
——>最后編譯運行后,再修改報告的其他的錯誤,
僅供參考!!!
2、WINDOWS表單應用程式與WPF應用程式的區別?
WINDOWS表單應用程式與WPF應用程式的區別?
用WPF更容易做的漂亮
感覺有以下幾個大區別:
WPF的執行緒模型和winform的執行緒模型不同
WPF到處用到資料系結,winform在串列中才用的多
WPF支持3D,winform本身沒有,需要引入托管的DX
WPF有現成的影片機制,winform沒有
WPF的界面可以用XAML寫,后臺邏輯用C#,winform全部C#,也就是WPF真正做到界面與邏輯分離,
更詳細的區別請移步!!!👇👇👇👇
轉載于WINDOWS表單應用程式與WPF應用程式的區別?
3、第三個實在是想不出來了,看看資料庫的添加程序吧,哈哈~祝各位好運~~😄😄😄
程式注釋答題技巧:直接翻譯程式即可,有些簡單的地方我就忽略了,直接翻譯英語即可!!!
功能說明:
1、可以同時實作兩個ESP32的ADC資料的讀取和顯示,并且可以將采集的資料發送到所連接資料庫和所系結的Onenet云平臺設備上,
2、可以用pc同時實作與兩個ESP32進行TCP通信,并且可以將采集的資料發送到所連接資料庫和所系結的Onenet云平臺設備上,可查詢云端資料,
本工程的檔案結構

class1.cs 程式
class db 資料庫的類撰寫
using System;
using System.Collections.Generic; //呼叫資料收集庫
using System.Data; //呼叫系統資料的庫
using System.Data.SqlClient;//呼叫系統資料庫客戶端庫
using System.Linq;
using System.Text; //呼叫系統文本庫
using System.Threading.Tasks;//呼叫系統執行緒任務庫
using System.Windows.Forms; //呼叫系統表單庫
using System.Net; //呼叫系統網路庫
using System.Net.Sockets; //呼叫網路 Sockets庫
using System.Threading; //呼叫系統執行緒庫
using System.IO; //呼叫系統IO庫
namespace TEST //定義命名空間為 TEST
{
class db //database資料庫的類,用于后面進行實體化,
{
static SqlConnection conn; //創建一個用于連接資料庫的靜態變數--conn
public static Boolean Is_OK; //創建一個布爾型別的公共靜態變數--Is_OK
public static void Open_db() //在資料庫類--db 中類中創建一個名為公共靜態型別的方法--Open_db
{
//嘗試連接到資料庫
try
{
//server=.\SQLEXPRESS;
string ConStr = "server=.; database=test; uid=sa; pwd=`sql2012"; //定義資料庫的地址,資料庫名,登錄用戶名,密碼
conn = new SqlConnection(ConStr);//實體化一個資料庫的用戶的連接變數
conn.Open();//打開資料庫的連接
}
嘗試連接到資料庫失敗,彈出 "連接資料庫失敗" 視窗,
catch
{
MessageBox.Show("連接資料庫失敗");
}
}
//下面是上傳資料到資料庫的方法
//下面這個程式我改了,多加了幾個變數,更加的好用了,可以更加的方便選擇不同的資料表
//定義添加資料到資料庫的方法--Insert_data( id 為資料的名稱如:ADC1, val 為ADC對應的數值,dt 為對應的發送時間,dbname 為對應的資料庫名如歷史資料表, xuhao 為資料表里的序號變數,
// value 為資料表里的當前值變數, date 為資料表里的時間變數 )
public static void Insert_data(int id, double val, DateTime dt, string dbname, string xuhao, string value, string date)
{
if (conn.State == ConnectionState.Open)//檢測資料庫當前狀態是否打開
{
SqlCommand cmd = new SqlCommand();//初始化一個client(用戶)命令形式的型別的資料庫變數
cmd.Connection = conn;//設定連接資訊(即設定資料庫的基本資訊),用于連接資料庫
//string table = "[歷史資料表" + dt.ToString("yyMMdd") + "]";
string table = dbname;//把資料庫的表名賦值給 table
string strSQL = "INSERT INTO " + table + "(" + xuhao + "," + value + "," + date + ")"
+ "VALUES (" + id + ", " + val
+ ", '" + dt.ToString() + "')";//把所有的需要傳給資料庫的資料整合為一個長的字串賦值給strSQL
cmd.CommandText = strSQL; //插入資料SQL陳述句
cmd.CommandType = CommandType.Text;//指定如何解釋字串
cmd.ExecuteNonQuery();//回傳受影響的行數
//int i = Convert.ToInt32(cmd.ExecuteScalar());
}
}
//下面是老師的 Insert_data 的原程式,供大家對比參考學習
//if (conn.State == ConnectionState.Open)
//{
// SqlCommand cmd = new SqlCommand();
// cmd.Connection = conn;
// //string table = "[歷史資料表" + dt.ToString("yyMMdd") + "]";
// string table = "[歷史資料表]";
// string strSQL = "INSERT INTO " + table + " (系統序號 , 當前值, 時間) "
// + "VALUES (" + id + ", " + val
// + ", '" + dt.ToString() + "')";
// cmd.CommandText = strSQL; //插入資料SQL陳述句
// cmd.CommandType = CommandType.Text;
// cmd.ExecuteNonQuery();
// //int i = Convert.ToInt32(cmd.ExecuteScalar());
//}
}
TCP類的撰寫
什么是套接字呢?點擊這里查看!!!
class myTcp//創建TCP的所用的類
{
public string strOut = "";//宣告一個字串型別的公共變數--strOut
public string strIP = "127.0.0.1";//
//初始化要連接的ip和埠號
//public IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(strIP), 9050);
//創建套接字
public Socket server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);//實體化套接字
public void Tcp_Send(string str)//定義tcp發送資料的方法
{
if (server.Connected)//判斷是否連接到服務端
{
byte[] data = Encoding.UTF8.GetBytes(str);//將字串編碼為UTF8格式
server.Send(data);//將資料發送到服務端
}
}
public void Start()//打開tcp的執行緒
{
//當初始化一個執行緒,把Thread.IsBackground = true的時候,指示該執行緒為后臺執行緒,后臺執行緒將會隨著主執行緒的退出而退出,
new Thread(Thread_Receive) { IsBackground = true }.Start();//上面的注釋很清楚了
}
void Thread_Receive()//獲取執行緒的回傳值
{
int recv = 0;//
byte[] data = new byte[1024];//
while (true)
{
if (server.Connected)//判斷TCP是否連接到server端
{
try { recv = server.Receive(data); }//嘗試接收到緩沖區的資料
catch { }
strOut = Encoding.ASCII.GetString(data, 0, recv); //獲取回傳值
}
Thread.Sleep(10);//延時10ms
}
}
}
}
至此 class1.cs的主要兩個類程式寫完了,
Program.cs 程式
class DataPointTest //創建用于連接Onenet的類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using OneNET.Api; //呼叫OneNET的Api介面庫
using OneNET.Api.Entity; //呼叫OneNET的Api介面物體庫
using OneNET.Api.Request; //呼叫OneNET的Api介面請求庫
using Microsoft.VisualStudio.TestTools.UnitTesting; //呼叫Microsoft.VisualStudio測驗工具庫
namespace TEST
{
public class DataPointTest//創建用于連接Onenet的類
{
private const string url = "api.heclouds.com";//onenet的連接地址
//public string appkey = "DXfTvFsU5RXxygkwddwvqFXhD3s=";//您在OneNET平臺的APIKey
public string appkey = "5TK53JepiCvPJ4k79XrBti4YEtI=";//你的設備APIKey
public string strOut = "";//
public void TestAddNewDataPoint(int 設備號, string 資料流, string strVal)//創建用于傳輸到Onenet資料的方法
{
var client = new DefaultOneNETClient(url, appkey, "");//實體化一個OneNETClient(Onenet客戶端)
var streams = new List<DataStreamSimple> //創建資料流變數
{
new DataStreamSimple
{
ID = 資料流 ,
Datapoints = new List<DataPointSimple>{
new DataPointSimple
{
Value = strVal //賦值資料
}
}
}
};
var data = new NewDataPointData { DataStreams = streams };//資料流賦值給data用于傳輸
var req = new NewDataPointRequest { DeviceID = 設備號, Data = data };//獲取發送資料的請求
var rsp = client.Execute(req);//發送資料請求并獲取回傳值
Assert.IsFalse(rsp.IsError);//判斷Onenet回傳值是否正常
}
public void TestSearchDataPointWithCondition(string appkey1, string strDeviceID, string sensorName)//創建Onenet資料查詢的方法 變數分別為 APIKey ,設備號, 傳感器名
{
var client = new DefaultOneNETClient(url, appkey1, "");//實體化OneNETClient(客戶端)
//測驗帶參查詢
var req1 = new SearchDataPointRequest { DeviceID = strDeviceID, Protocol = Scheme.HTTP };//獲取資料查詢請求的請求
req1.DataStreamId = "loc," + sensorName;
var rsp1 = client.Execute(req1);//獲取請求的回傳值
Assert.IsFalse(rsp1.IsError); //判斷回傳值是否有錯
Assert.AreEqual(0, rsp1.Errno);
Assert.AreEqual("succ", rsp1.Error);
Assert.IsNotNull(rsp1.Data);
//Assert.IsTrue(rsp1.Data.Count > 0);
if (rsp1.Data.Count > 0) { //判斷回傳資料是否大于0
var val = rsp1.Data.Datastreams[0].Datapoints[0].GetValue();
Console.WriteLine("帶參查詢結果:" + rsp1.Body);
strOut = rsp1.Body; 獲取查詢的資料,賦值給strOut
}
else
{
strOut = "";
}
}
}
}
Form1.cs 的程式
實作的效果

class Form1 : Form //創建Form1的類
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.IO.Ports;
using System.Threading;
namespace TEST
{
public partial class Form1 : Form //創建Form1的類
{
//FormList fLst = new FormList();
//chart chart1 = new chart();
SerialPort sp1 = new SerialPort();
//SerialPort sp2 = new SerialPort();
string dbname = "[歷史資料表一]";
string xuhao = "系統序號01";
string value = "當前值01";
string date = "時間01";
string strComm = "";
public Form1()//Form1初始化
{
InitializeComponent();
}
private void btnSwitchSP_Click_1(object sender, EventArgs e)//打開/關閉串口按鈕的程式
{
if (btnSwitchSP.Text == "打開串口")//判斷按鈕是否為“打開串口”
{
sp1.Close();//防止串口未關閉,則先關閉串口
sp1.PortName = textBox1.Text;;//設定串口為textBox1.Text內的所設定的串口號
sp1.BaudRate = 115200;
try
{
sp1.Open();//打開串口
this.Text = "埠號:" + sp1.PortName + " 丨";
this.Text += "波特率:" + sp1.BaudRate + " 丨";
}
catch (Exception ex)
{
MessageBox.Show("錯誤:" + ex.Message, "C#串口通信");
}
btnSwitchSP.Text = "關閉串口";
}
else
{
sp1.Close();//關閉串口
btnSwitchSP.Text = "打開串口";
}
}
private void Form1_Load(object sender, EventArgs e)//加載Form1視窗
{
btnSwitchSP_Click_1(sender, e);
}
private void timer2_Tick(object sender, EventArgs e)//視窗的定時器函式,定時發送資料
{
if (sp1.IsOpen)
{
if (strComm.Length >= 15) //保證接收位元組大于一定數目后再處理
{
string str = strComm; 將輸入緩沖區中可用的位元組賦值給str 用于字串的分割和發送 // sp.ReadExisting();
txtRTC.Text = str;
textBox2.Text = str;
if (str != "")
{
string[] strArray = str.Split(new char[] { ',' });
if (listBox1.Items.Count > 0) listBox1.Items.Clear();
for (int i = 0; i < strArray.Length; i++)
{
if (strArray[i] != "")
listBox1.Items.Add(strArray[i]);
}
string KEY;
KEY = "\r\nADC:";
if (str.IndexOf(KEY) >= 0) 找到字串內 KEY 變數 所在的位置 即索引到str中的 ADC
{
Find_KEY_01(str, KEY); //查找關鍵字ADC,并將ADC的數值發送到云端
}
else
{
KEY = "KEY:";
Find_KEY_01(str, KEY); //查找關鍵字KEY,并將其代表的數值發送到Onenet云端
}
}
}
strComm = ""; //清空已發送的字串流
}
}
void sp1_ReadData()//用串口給esp32發送命令的方法
{
Thread.Sleep(10);
string t = "from machine import Pin,ADC,RTC,Timer\r\n"
+ "rtc = RTC()\r\n"
+ "adc1 = ADC(Pin(33))\r\n"
+ "adc2 = ADC(Pin(34))\r\n"
+ "adc3 = ADC(Pin(35))\r\n";
sp1.Write(t);
Thread.Sleep(100);
while (true)
{
try//防止程式崩潰的嘗試代碼
{
if (sp1.IsOpen)
{
t = "d = rtc.datetime()\r\nprint(str('ADC:1,%.3f,'%(adc1.read()/4095))+str('TIME:%04d-%02d-%02d %02d:%02d:%02d.%03d'%(d[0],d[1],d[2],d[4],d[5],d[6],int(d[7]/1000))))\r\n,";
sp1.Write(t);//發送上述命令到ESP32
Thread.Sleep(100);
if (sp1.BytesToRead >= 10)//如果接收到的字符大于10則…
{
strComm = sp1.ReadExisting(); //從輸入緩沖區中取用立即可用的位元組賦值給 strComm
}
t = "d = rtc.datetime()\r\nprint(str('ADC:2,%.3f,'%(adc2.read()/4095))+str('TIME:%04d-%02d-%02d %02d:%02d:%02d.%03d'%(d[0],d[1],d[2],d[4],d[5],d[6],int(d[7]/1000))))\r\n,";
sp1.Write(t);
Thread.Sleep(100);
if (sp1.BytesToRead >= 10)
strComm = sp1.ReadExisting();
t = "d = rtc.datetime()\r\nprint(str('ADC:3,%.3f,'%(adc3.read()/4095))+str('TIME:%04d-%02d-%02d %02d:%02d:%02d.%03d'%(d[0],d[1],d[2],d[4],d[5],d[6],int(d[7]/1000))))\r\n,";
sp1.Write(t);//發送上述命令到ESP32
Thread.Sleep(100);
if (sp1.BytesToRead >= 10)
strComm = sp1.ReadExisting();//從串口的緩沖區里讀取ESP32回傳的數值
}
}
catch
{
if (!sp1.IsOpen)
{
break;
}
}
Thread.Sleep(1); //防止串口沒有打開時,執行緒死鎖
}
}
private void BtnClear_Click(object sender, EventArgs e)
{
axTChart1.Series(0).Clear();
axTChart1.Series(1).Clear();
axTChart1.Series(2).Clear();
}
public void AddToChart(int id, double v, DateTime time)//將接受到的ESP32的ADC的數值添加到圖表中
{
if (id >= 0 && id <= 2) {
axTChart1.Series(id).Add(v, time.ToString("HH:mm:ss"), 1);//共添加三條 adc曲線
}
}
void Find_KEY_01(string str, string KEY1)//找到關鍵字,并把關鍵字后所表示變數取出,并分別賦值,最終一起用 Insert_data 發送給資料庫
{
//string KEY1 = "KEY:";
int index1 = str.IndexOf(KEY1); //在字串 str 中索引關鍵字 KEY1 并將此字串所在位作為 索引 0 **IndexOf(索引的物件,開始的索引號);**
string KEY2 = ",TIME:"; //定義關鍵字 KEY2 為 ",TIME:"
int index2 = str.IndexOf(KEY2); //在字串 str 中索引關鍵字 ",TIME:" 并將此字串所在位作為 索引 0
if (index1 >= 0 && index2 >= 0) //索引到關鍵字
{
int pos0 = str.IndexOf(",", index1 + KEY1.Length);//取接收到的字串的第一個逗號為索引
if (pos0 >= 0)
label2.Text = str.Substring(index1 + KEY1.Length, pos0 - (index1 + KEY1.Length)); //取出 “KEY1”打頭 “,”(逗號)結尾的一段字串,賦值給label2
int pos1 = str.IndexOf(",", pos0 + 1); //找到“,”并賦值其索引號 給pos1
if (pos1 >= 0)
label3.Text = str.Substring(pos0 + 1, pos1 - (pos0 + 1)); //取出 0號逗號和1號 之間的 字串
int pos2 = str.IndexOf(",", index2 + KEY2.Length); //找到“,”并賦值其索引號 給pos2
if (pos2 >= 0)
{
label4.Text = str.Substring(index2 + KEY2.Length, 23); // pos2 - (index2 + KEY2.Length)-2); //取出 KEY2 打頭 “,”結尾的一段字串
if (KEY1 == "\r\nADC:")
{
int id = Convert.ToInt32(label2.Text); //將label2.Text字串型別值轉換為32位整型賦給id
double v = Convert.ToDouble(label3.Text); //將label3.Text字串型別值轉換為雙精度型賦給v
DateTime time = Convert.ToDateTime(label4.Text); //將label4.Text字串型別值轉換為時間型別賦給time
if (label2.Text == "1")
{
}
db.Insert_data(id, v, time, dbname, xuhao, value, date); //上傳資料到資料庫 1
//db.Insert_data(id, v, time,dbname); //上傳資料庫 1
AddToChart(id,v, time);
DataPointTest dp = new DataPointTest();
dp.appkey = "5TK53JepiCvPJ4k79XrBti4YEtI=";//APIKEY
int devid = 561695299; //設備號
dp.TestAddNewDataPoint(devid, "ADC" + id, v.ToString()); //***發送ADC資料到onenet云平臺***
//資料串列
//fLst.AddToListView(label2.Text, label3.Text, label4.Text);
//fLst.Show();
}
}
}
}
private void button2_Click(object sender, EventArgs e) //初始化ESP32_01按鈕程式
{
Thread thread_sp1 = new Thread(new ThreadStart(sp1_ReadData));//創建串口執行緒
thread_sp1.Start();
}
private void button3_Click(object sender, EventArgs e)//FormDB_01按鈕
{
FormDB_01 f = new FormDB_01();
f.Show();
}
private void button4_Click(object sender, EventArgs e)//查詢按鈕未使用
{
}
private void btn_添加_Click(object sender, EventArgs e)// btn_添加_Click按鈕程式
{
DataPointTest dp = new DataPointTest();
dp.appkey = "3=Uaw=REPGSubU=rwVj8x=Hbb58=";
dp.TestAddNewDataPoint(Convert.ToInt32(txt設備號.Text), txt傳感器名.Text, txt數值.Text);
}
}
}
FromTCP.cs的程式
實作效果

class FormTCP : Form //創建TCP的類
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;//呼叫系統繪畫庫
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TEST
{
public partial class FormTCP : Form //創建TCP的類
{
myTcp tcp1 = new myTcp();
public int Station_Number = 0;
public FormTCP()
{
InitializeComponent();
}
private void btn_Connect_Click(object sender, EventArgs e)//連接按鈕程式
{
//if (tcp1.server.Connected)
this.Text = "連接關閉!";
tcp1.server.Close();
Thread.Sleep(100);
tcp1.server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(txtIP.Text), Convert.ToInt16(txtPort.Text));//TCP終端初始化
try//嘗試連接
{
if (!tcp1.server.Connected)
tcp1.server.Connect(ipep);
Thread.Sleep(10);
if (tcp1.server.Connected)
this.Text = "連接成功!";
}
catch (SocketException e2) //連接例外處理
{
//this.Text = e2
tcp1.server.Close();
}
}
private void button1_Click(object sender, EventArgs e)//關閉連接 按鈕程式
{
try{
tcp1.server.Close();
}
catch (SocketException e2) //連接例外處理
{
}
this.Text = "連接關閉!";
}
private void label7_Click(object sender, EventArgs e)//TCP發送的label 程式
{
tcp1.Tcp_Send(textBox2.Text);//發送textBox里的資料到Server端
}
private void timer2_Tick(object sender, EventArgs e)//Tcp的定時器2的程式用于查找分割好的字串并發送資料到Onenet云平臺
{
if (tcp1.strOut != "")
{
string str = tcp1.strOut;
textBox4.Text = str;
if (str != "")
{
string[] strArray = str.Split(new char[] { ',' });
string KEY;
KEY = "ADC:";
if (str.IndexOf(KEY) >= 0)
{
Find_KEY(str, KEY);
}
else
{
KEY = "KEY:";
Find_KEY(str, KEY);
}
}
tcp1.strOut = "";
}
}
void Find_KEY(string str, string KEY1)//用于分割接收到的字串
{
//string KEY1 = "KEY:";
int index1 = str.IndexOf(KEY1);
string KEY2 = ",TIME:";
int index2 = str.IndexOf(KEY2);
string label2_Text="", label3_Text="",label4_Text="";
if (index1 >= 0 && index2 >= 0)
{
int pos = str.IndexOf(",", index1 + KEY1.Length);
if (pos >= 0)
label2_Text = str.Substring(index1 + KEY1.Length, pos - (index1 + KEY1.Length));
int pos1 = str.IndexOf(",", pos + 1);
if (pos1 >= 0)
label3_Text = str.Substring(pos + 1, pos1 - (pos + 1));
int pos2 = str.IndexOf(",", index2 + KEY2.Length);
if (pos2 >= 0)
{
label4_Text = str.Substring(index2 + KEY2.Length, 23); // pos2 - (index2 + KEY2.Length)-2);
if (KEY1 == "ADC:")
{
int id = Convert.ToInt32(label2_Text);
double v = Convert.ToDouble(label3_Text);
DateTime time = Convert.ToDateTime(label4_Text);
DataPointTest dp = new DataPointTest();
dp.appkey = "5TK53JepiCvPJ4k79XrBti4YEtI=";
int devid = 561695299; //設備號
dp.TestAddNewDataPoint(devid, "ADC" + id, v.ToString()); //***發送ADC資料到onenet云平臺***
MainForm.Add_To_ListView_Form(Station_Number, id, v, time);//將資料添加到ListView_Form視窗
}
}
}
}
private void FormTCP_Load(object sender, EventArgs e)//打開TCP視窗時加載
{
tcp1.Start();
}
private void timer1_Tick(object sender, EventArgs e)//tcp定時器1的程式
{
if (checkBox回圈發送.Checked) //回圈發送ADC1,ADC2,ADC3
{
for (int i = 1; i <= 3; i++)
{
textBox2.Text = "ADC" + i;
Thread.Sleep(200);
tcp1.Tcp_Send(textBox2.Text);
}
}
}
}
}
MainForm.cs 程式
實作效果

class MainForm : Form
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.IO.Ports;
using System.Threading;
using System.IO;
using System.Collections;
namespace TEST
{
public partial class MainForm : Form
{
protected Boolean stop = false;
protected Boolean conState = false;
private StreamReader sRead;
//Form1 f1 = new Form1();
//Form1 f2 = new Form1();
//Form1 f3 = new Form1();
//FormList fLst = new FormList();
string strRecieve;
bool bAccept = false;
SerialPort sp = new SerialPort();
public static string strPortName = "";
public static string strBaudRate = "";
public static string strDataBits = "";
public static string strStopBits = "";
public static Form_ListView listViewForm; // = new Form_ListView();
public static FormTCP frmtcp1 = new FormTCP();
public static FormTCP frmtcp2 = new FormTCP();
public static chart frmChart1 = new chart();
public static chart frmChart2 = new chart();
public static void Add_To_ListView_Form(int Station_Number, int id, double v, DateTime time)
{
//if (gl_全域變數.Is_System_Exit) return;
if (listViewForm == null) listViewForm = new Form_ListView();
if (!listViewForm.Visible) listViewForm.Show();
string t;
//string str_MAC = ParseUtil.ToHexMAC(buf, 14, 6);
string str_MAC = Station_Number + "_" + id;
string str_KEY = "K" + str_MAC;
string str_Time = time.ToString("HH:mm:ss.fff");
if (listViewForm == null)
listViewForm = new Form_ListView();
int newid = Convert.ToInt32(Station_Number + "0" + id);
string dbname = "[歷史資料表一]";
string xuhao = "系統序號01";
string value = "當前值01";
string date = "時間01";
db.Insert_data(newid, v, time, dbname, xuhao, value, date); //上傳資料庫 1
if (Station_Number == 1)
{
frmChart1.AddToChart(id, v, time);
if (!frmChart1.Visible) frmChart1.Show();
}
if (Station_Number == 2)
{
frmChart2.AddToChart(id, v, time);
if (!frmChart2.Visible) frmChart2.Show();
}
//OneNet 使用新的傳感器序號 newid 101 、201
//DataPointTest dp = new DataPointTest();
//dp.appkey = "zsa=LDvUNxe6TUZq8M0V3HrA54k=";
//int devid = 578091985;
//dp.TestAddNewDataPoint(devid, "ADC" + newid, v.ToString());
ListViewItem item = null;
//if (listViewForm.listView1.Items.Count == 0){
item = listViewForm.listView1.Items.Add("", listViewForm.listView1.Items.Count.ToString(), 0);
t = str_Time; //SubItems[1]
item.SubItems.Add(t);
t = str_MAC; // ParseUtil.ToHexMAC(buf, 15, 6); //MAC SubItems[2]
item.SubItems.Add(t);
t = v.ToString();
item.SubItems.Add(t);
t = ""; //Header4 - 11
item.SubItems.Add(t);
item.SubItems.Add(t);
item.SubItems.Add(t);
item.SubItems.Add(t);
item.SubItems.Add(t);
item.SubItems.Add(t);
item.SubItems.Add(t);
item.SubItems.Add(t);
}
public MainForm()
{
InitializeComponent();
}
private void btnSetSP_Click(object sender, EventArgs e)//串口設定
{
timer1.Enabled = false;
sp.Close();
}
private void btnSwitchSP_Click(object sender, EventArgs e)//打開串口
{
if (btnSwitchSP.Text == "打開串口")
{
if (strPortName != "" && strBaudRate != "" && strDataBits != "" && strStopBits != "")
{
try
{
if (sp.IsOpen)
{
sp.Close();
sp.Open(); //打開串口
}
else
{
sp.Open();//打開串口
}
btnReceiveData_Click(sender,e);
btnSwitchSP.Text = "關閉串口";
groupBox1.Enabled = true;
groupBox2.Enabled = true;
this.toolStripStatusLabel1.Text = "埠號:" + sp.PortName + " 丨";
this.toolStripStatusLabel2.Text = "波特率:" + sp.BaudRate + " 丨";
this.toolStripStatusLabel3.Text = "資料位:" + sp.DataBits + " 丨";
this.toolStripStatusLabel4.Text = "停止位:" + sp.StopBits + " 丨";
this.toolStripStatusLabel5.Text = "";
}
catch (Exception ex)
{
MessageBox.Show("錯誤:" + ex.Message,"C#串口通信");
}
}
else
{
MessageBox.Show("請先設定串口!","RS232串口通信");
}
}
else
{
timer1.Enabled = false;
btnSwitchSP.Text = "打開串口";
sp.Close();
groupBox1.Enabled = false;
groupBox2.Enabled = false;
this.toolStripStatusLabel1.Text = "埠號:埠未打開丨";
this.toolStripStatusLabel2.Text = "波特率:埠未打開丨";
this.toolStripStatusLabel3.Text = "資料位:埠未打開丨";
this.toolStripStatusLabel4.Text = "停止位:埠未打開丨";
this.toolStripStatusLabel5.Text = "";
}
}
private void btnSendData_Click(object sender, EventArgs e)//資料發送
{
if (sp.IsOpen)
{
try
{
sp.Encoding = System.Text.Encoding.GetEncoding("GB2312");//GB2312即資訊交換用漢字編碼字符集
sp.Write(txtSend.Text);
}
catch (Exception ex)//若應用程式出現除錯問題
{
MessageBox.Show("錯誤:" + ex.Message);
}
}
else
{
MessageBox.Show("請先打開串口!");
}
}
delegate void DelegateAcceptData();
void fun()
{
while (bAccept )
{ AcceptData(); }
}
delegate void reaction();
void AcceptData()
{
if (textBox2.InvokeRequired)
{
try
{
DelegateAcceptData ddd = new DelegateAcceptData(AcceptData);
this.Invoke(ddd, new object[] { });
}
catch { }
}
else
{
try
{
strRecieve = sp.ReadExisting();
textBox2.Text += strRecieve;
}
catch (Exception e) { }
}
}
private void btnReceiveData_Click(object sender, EventArgs e)//接受資訊
{
if (sp.IsOpen)
{
sp.Encoding = System.Text.Encoding.GetEncoding("GB2312");//GB2312即資訊交換用漢字編碼字符集
timer2.Enabled = true;
}
else
{
MessageBox.Show("請先打開串口!");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
string str1;
str1 = sRead.ReadLine();
if (str1 == null)
{
timer1.Stop();
sRead.Close();
MessageBox.Show("檔案發送成功!","C#串口通信");
this.toolStripStatusLabel5.Text = "";
return;
}
byte[] data = Encoding.Default.GetBytes(str1);
sp.Write(data, 0, data.Length);
this.toolStripStatusLabel5.Text = " 檔案發送中...";
}
private void btnOutputInfo_Click(object sender, EventArgs e) //匯出資訊到檔案
{
try
{
string path = @"D:\output.txt";
string content = this.textBox2.Text;
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter write = new StreamWriter(fs);
write.Write(content);
write.Flush();
write.Close();
fs.Close();
MessageBox.Show("接收資訊匯出在" + path);
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
}
private void btnClearInfo_Click(object sender, EventArgs e)//清空接受區
{
this.textBox2.Text = "";
}
private void btnQueryFile_Click(object sender, EventArgs e)//設定檔案路徑
{
String filename;
OpenFileDialog Open1 = new OpenFileDialog();
Open1.FileName = "";
Open1.ShowDialog();
filename = Open1.FileName;
if (filename == "")
{
MessageBox.Show("請選擇要發送的檔案!", "Error");
return;
}
textBox1.Text = filename;
if (filename != null)
{
StreamReader sRead = new StreamReader(filename);
}
btnReceiveData.Enabled = true;
}
private void btnSendFile_Click(object sender, EventArgs e)//檔案發送
{
string fileName = textBox1.Text;
if (fileName == "")
{
MessageBox.Show("請選擇要發送的檔案!", "Error");
return;
}
else
{
sRead = new StreamReader(fileName);
}
timer1.Start();
}
private void timer2_Tick(object sender, EventArgs e)
{
if (sp.IsOpen)
{
string str = sp.ReadExisting();
string str4 = str.Replace("\r", "\r\n");
textBox2.AppendText(str4);
textBox2.ScrollToCaret();
}
}
private void MainForm_Load(object sender, EventArgs e)
{
groupBox1.Enabled = false;
groupBox2.Enabled = false;
this.toolStripStatusLabel1.Text = "埠號:埠未打開丨";
this.toolStripStatusLabel2.Text = "波特率:埠未打開丨";
this.toolStripStatusLabel3.Text = "資料位:埠未打開丨";
this.toolStripStatusLabel4.Text = "停止位:埠未打開丨";
this.toolStripStatusLabel5.Text = "";
}
private void btn_Form1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
f1.Show();
//f1.Left = this.Left-500;
//f1.Top = this.Top + 100;
f1.Text = "COM1";
//f1.textBox1.Text = "COM1";
//f1.textBox1.Text = "COM1";
}
private void button3_Click_1(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
//f2.Left = this.Left - 500;
//f2.Top = this.Top + 100;
f2.Text = "COM2";
}
private void btn_FormList_Click(object sender, EventArgs e)
{
//fLst.Show();
}
private void button1_Click(object sender, EventArgs e)
{
FormDB_01 f = new FormDB_01();
f.Show();
}
private void button2_Click(object sender, EventArgs e)
{
FormTCP frmtcp1 = new FormTCP(); //實體化FormTCP1視窗
frmtcp1.txtIP.Text = "10.1.1.64"; //設定TCP Server 地址
frmtcp1.txtPort.Text = "10000"; //設定TCP Server 埠號
frmtcp1.Station_Number = 1;
frmtcp1.Text = "TCP" + frmtcp1.Station_Number;
frmtcp1.Show();
frmtcp1.Left = this.Left + this.Width;
//f1.Top = this.Top + 500;
FormTCP frmtcp2 = new FormTCP();
frmtcp2.txtIP.Text = "10.1.1.52";
frmtcp2.txtPort.Text = "10000";
frmtcp2.Station_Number = 2;
frmtcp2.Text = "TCP" + frmtcp2.Station_Number;
frmtcp2.Show();
frmtcp2.Left = frmtcp2.Left;
//frmtcp2.Top = frmtcp2.Top + 500;
}
private void btn打開Tcp_Server_Click(object sender, EventArgs e)
{
FormTcpServer f1 = new FormTcpServer();
f1.txtIP.Text = "127.0.0.1";
f1.txtPort.Text = "9050";
f1.Show();
f1.Left = this.Left + this.Width;
//f1.Top = this.Top + 500;
}
}
}
FromDB.cs 程式
實作效果

class FormDB_01 : Form 實作代碼
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 TEST
{
public partial class FormDB_01 : Form
{
public FormDB_01()
{
InitializeComponent();
}
private void FormDB_01_Load(object sender, EventArgs e)
{
// TODO: 這行代碼將資料加載到表“testDataSet.歷史資料表一”中,您可以根據需要移動或洗掉它,
this.歷史資料表一TableAdapter.Fill(this.testDataSet.歷史資料表一);
}
private void button1_Click(object sender, EventArgs e)
{
DataPointTest dp = new DataPointTest();
dp.TestSearchDataPointWithCondition(txt_APIKEY.Text, txt設備號.Text, comboBox1.Text); //查詢 發送到onenet云平臺的資料
textBox2.Text = dp.strOut;
textBox2.Text = dp.strOut;
}
}
}
ESP32連接Wi-Fi作為TCP Server端的python代碼:
直接翻譯即可,簡單看看,個人感覺考的概率不大,
import network
import socket
import time
from machine import Pin, ADC, I2C, RTC,Timer
adc1 = ADC(Pin(32))
adc2 = ADC(Pin(34))
adc3 = ADC(Pin(35))
rtc = RTC()
SSID="NETGEAR64"
PASSWORD="88888888"
port=10000
wlan=None
listenSocket=None
def connectWifi(ssid,passwd):
global wlan
wlan=network.WLAN(network.STA_IF) #create a wlan object
wlan.active(True) #Activate the network interface
wlan.disconnect() #Disconnect the last connected WiFi
wlan.connect(ssid,passwd) #connect wifi
while(wlan.ifconfig()[0]=='0.0.0.0'):
time.sleep(1)
return True
try:
connectWifi(SSID,PASSWORD)
ip=wlan.ifconfig()[0] #get ip addr
print(ip)
listenSocket = socket.socket() #create socket
listenSocket.bind((ip,port)) #bind ip and port
listenSocket.listen(1) #listen message
listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #Set the value of the given socket option
print ('tcp waiting...')
while True:
print("accepting.....")
conn,addr = listenSocket.accept() #Accept a connection,conn is a new socket object
print(addr,"connected")
while True:
data = conn.recv(1024) #Receive 1024 byte of data from the socket
if(len(data) == 0):
print("close socket")
conn.close() #if there is no data,close
break
print(data)
d = rtc.datetime()
if bytes.decode(data)=="ADC1":
s1=str('ADC:1,%.3f,'%(adc1.read()/4095))+str('TIME:%04d-%02d-%02d %02d:%02d:%02d.%03d'%(d[0],d[1],d[2],d[4],d[5],d[6],int(d[7]/1000)))+','
print(s1)
conn.send(str(s1).encode())
elif bytes.decode(data)=="ADC2":
s2=str('ADC:2,%.3f,'%(adc2.read()/4095))+str('TIME:%04d-%02d-%02d %02d:%02d:%02d.%03d'%(d[0],d[1],d[2],d[4],d[5],d[6],int(d[7]/1000)))+','
print(s2)
conn.send(s2.encode())
elif bytes.decode(data)=="ADC3":
s3=str('ADC:3,%.3f,'%(adc3.read()/4095))+str('TIME:%04d-%02d-%02d %02d:%02d:%02d.%03d'%(d[0],d[1],d[2],d[4],d[5],d[6],int(d[7]/1000)))+','
print(s3)
conn.send(s3.encode())
#ret = conn.send(str(str('ADC1:%.3f '%(adc1.read()/4095))+str(' ADC2:%.3f '%(adc2.read()/4095))+str(' ADC3:%.3f '%(adc3.read()/4095))).encode())
#print(sdata)
#ret = conn.send(data) #send data
except:
if(listenSocket):
listenSocket.close()
wlan.disconnect()
wlan.active(False)
by iNBC form SDUT(2020.11.11 pm11:00)
考后總結:簡答題前兩個還有最后兩道大題竟然是原題和原題改編,不是說不考嗎?!哭了……😭😭😭程式移植還是猜對了!程式注釋還考了UDP,這是我沒想到的,其他的上面都提到了,也大差不差,唉,最慘的是我借了同學兩根筆,沒寫幾個字,都不下了,悲催!借了根筆,也斷油,寫的字超級難看,估計是紙打了蠟吧,希望老師能夠看懂吧,好了,大四上學期的考試至此完結,撒花🎉! 希望明天依然美好,各位晚安!!!(2020.11.13 21:24)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/214379.html
標籤:其他
