欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

物联网测试总结---基于ESP32的串口和TCP通信的软件设计

程序员文章站 2022-03-19 16:03:35
物联网测试总结class1.cs 程序class db 数据库的类编写 class db //database数据库的类,用于后面进行实例化。 { static SqlConnection conn; //创建一个用于连接打开数据库的静态变量--conn public static Boolean Is_OK; //创建一个布尔类型的公共静态变量--Is_OK public static void Open_db() //在数据库类--...

物联网测试总结(基于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云平台设备上,可查询云端数据。

本工程的文件结构

物联网测试总结---基于ESP32的串口和TCP通信的软件设计

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 的程序

实现的效果

物联网测试总结---基于ESP32的串口和TCP通信的软件设计

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的程序

实现效果

物联网测试总结---基于ESP32的串口和TCP通信的软件设计

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 程序

实现效果

物联网测试总结---基于ESP32的串口和TCP通信的软件设计

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 程序

实现效果

物联网测试总结---基于ESP32的串口和TCP通信的软件设计

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://blog.csdn.net/qq_40700822/article/details/109631196