電路原理圖如下:
51hei.png (58.35 KB, 下載次數(shù): 40)
下載附件
2022-5-15 21:02 上傳
51hei.png (45.3 KB, 下載次數(shù): 39)
下載附件
2022-5-15 21:02 上傳
本系統(tǒng)實(shí)現(xiàn)了Zigbee組網(wǎng)監(jiān)測,應(yīng)用于變電站使用,多節(jié)點(diǎn)監(jiān)測,上位機(jī)軟件實(shí)時顯示狀態(tài),同時檢測到有人入侵就會報警。上位機(jī)將數(shù)據(jù)實(shí)時存到mysql數(shù)據(jù)庫中。便于后續(xù)管理查詢。Zigbee協(xié)調(diào)器連接上位機(jī),Zigbee終端連接傳感器。主控芯片采用CC2530 上位機(jī)采用VS2019進(jìn)行編程開發(fā),Zigbee代碼采用IAR開發(fā),硬件電路圖采用AD17 展示視頻鏈接: https://www.bilibili.com/video/BV1wY4y1t7fJ
上位機(jī)源代碼如下: using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;//添加對MySql.Data.MySqlClient的引用。 namespace Test
{
public partial class Form1 : Form
{
MySqlConnection conn;//定義數(shù)據(jù)庫連接
MySqlCommand cmd = new MySqlCommand();//定義數(shù)據(jù)庫執(zhí)行操作類
MySqlDataAdapter adapter;
DateTime dtStart;//用于在批量添加測試時,記錄添加數(shù)據(jù)庫記錄的開始時間
DateTime dtEnd;//用于在批量添加測試時,記錄添加數(shù)據(jù)庫記錄的結(jié)束時間
private int sum = 0;//用于在批量添加測試時,記錄要添加數(shù)據(jù)庫記錄的總數(shù)
string user_data_tebles_ck ="cktables";
string user_data_tebles_ck2 ="cktables2";
string user_data_tebles_log = "log"; string server_ip = "127.0.0.1";
string server_port = "3306";
string mysql_user = "root";
string mysql_pass = "0000000000";
string mysql_dataname = "info";
// CREATE Database `spdata` DEFAULT CHARACTER SET utf8;
// CREATE Database `test` DEFAULT CHARACTER SETutf8;
//CREATE TABLE `user` (
// `id` int (11) NOT NULL AUTO_INCREMENT,
// `序列號` varchar(45) DEFAULT NULL,
// `商品名稱` varchar(45)DEFAULT NULL,
// `商品價格` varchar(45)DEFAULT NULL,
// PRIMARY KEY(`id`)
//) ENGINE=InnoDB DEFAULT CHARSET=utf8;
//CREATE TABLE `log` (
// `id` int (11) NOT NULL AUTO_INCREMENT,
// `time` varchar(45) DEFAULT NULL,
// `states` varchar(45) DEFAULT NULL,
// PRIMARY KEY(`id`)
//) ENGINE=InnoDB DEFAULT CHARSET=utf8; public Form1()
{
InitializeComponent();
}
private bool OpenConnection()
{
try
{
String connetStr ="server='" + server_ip + "';port='" + server_port +"';user='" + mysql_user + "';password='" + mysql_pass +"'; database='" + mysql_dataname + "';" +"charset=utf8"; ; //server=127.0.0.1/localhost 代表本機(jī),端口號port默認(rèn)是3306可以不寫
conn = newMySqlConnection(connetStr);
conn.Open();//打開通道,建立連接,可能出現(xiàn)異常,使用try catch語句
Console.WriteLine("連接正常!");
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("不能連接服務(wù)器!");
break;
case1045:
MessageBox.Show("賬號密碼錯誤!");
break;
case1046:
MessageBox.Show("數(shù)據(jù)庫未選擇");
break; default:
MessageBox.Show("未知錯誤!",ex.Number.ToString() + ex);
break; }
return false;
} }
void ShowMsg(string str)
{
Console.Write(str +"\r\n");
Write_SaveTxtFile(str +"\r\n"); // txtMsg.Items.Add(str +"\r\n");
}
public void Write_SaveTxtFile(string txtStr) //保存文本文件 到軟件運(yùn)行目錄下
{
string str =System.Windows.Forms.Application.StartupPath;//獲取軟件的運(yùn)行目錄
File.AppendAllText(@str +"\\" + "config.txt", txtStr); //在軟件運(yùn)行目錄下保存log信息
}
void create_tables()
{
//CREATE TABLE `log` (
// `id` int (11) NOT NULLAUTO_INCREMENT,
// `time` varchar(45) DEFAULTNULL,
// `states` varchar(45) DEFAULTNULL,
// PRIMARY KEY(`id`)
//int primary keyauto_increment,value 自動遞增
string createStatement = "CREATETABLE "+ user_data_tebles_ck+ "(id int primary keyauto_increment,value VarChar(50),time VarChar(50) )";
string createStatement2 ="CREATE TABLE " + user_data_tebles_ck2 + "(id int primary keyauto_increment,value VarChar(50),time VarChar(50) )";
String sqlConn = "server='"+ server_ip + "';port='" + server_port + "';user='" +
mysql_user +"';password='" + mysql_pass + "'; database='" +mysql_dataname + "';" + "Charset=utf8;";
conn = newMySqlConnection(sqlConn);//
conn.Open();
try
{
// 建表
using (MySqlCommand cmd= new MySqlCommand(createStatement, conn))
{
cmd.ExecuteNonQuery();
}
using (MySqlCommand cmd= new MySqlCommand(createStatement2, conn))
{
cmd.ExecuteNonQuery();
}
// 改表或者增加行
//using (MySqlCommandcmd = new MySqlCommand(alterStatement, conn))
//{
// cmd.ExecuteNonQuery();
//}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
Application.Exit();//直接推出
}
}
void init_mysql()
{
//
//mysql_dataname ="liuhao11";
String sqlConn = "server="+server_ip+"; port="+ server_port+"; user="+mysql_user+"; password=" + mysql_pass + ";";
MySqlConnection conn = newMySqlConnection(sqlConn);//
string sqlDB = "SELECT * FROM information_schema.SCHEMATAwhere SCHEMA_NAME='"+ mysql_dataname+"';";
MySqlDataAdapter adp = newMySqlDataAdapter(sqlDB, conn);
DataSet ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
MessageBox.Show("數(shù)據(jù)庫初始化成功!");
}
else
{
conn.Open();
// MySqlCommand cmd =new MySqlCommand(string.Format("CREATE DATABASE IF NOT EXISTS '"+mysql_dataname+"';"));
MySqlCommand cmd = newMySqlCommand("CREATE DATABASE "+ mysql_dataname+";", conn);
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("數(shù)據(jù)庫初始化成功!");
}
else {
MessageBox.Show("數(shù)據(jù)庫初始化失敗!");
}
create_tables();
//stringcreateStatement = "CREATE TABLE "+ user_data_tebles_ck+" (Field1VarChar(50), Field2 Integer)";
//string alterStatement= "ALTER TABLE Test1 ADD Field3 Boolean";
//try
//{
// // 建表
// using(MySqlCommand cmd1 = new MySqlCommand(createStatement, conn))
// {
// cmd1.ExecuteNonQuery();
// } // //改表或者增加行
// //using(MySqlCommand cmd = new MySqlCommand(alterStatement, conn))
// //{
// // cmd.ExecuteNonQuery();
// //}
//}
//catch (MySqlExceptionex)
//{
// MessageBox.Show(ex.Message);
// Application.Exit();//直接推出
//}
}
}
private void Form1_Load(object sender, EventArgs e)
{
string[] ports =System.IO.Ports.SerialPort.GetPortNames();//獲取電腦上可用串口號
comboBox1.Items.AddRange(ports);//給comboBox1添加數(shù)據(jù)
comboBox1.SelectedIndex =comboBox1.Items.Count > 0 ? 0 : -1;//如果里面有數(shù)據(jù),顯示第0個
comboBox2.Text ="115200";/*默認(rèn)波特率:115200*/
comboBox3.Text = "1";/*默認(rèn)停止位:1*/
comboBox4.Text = "8";/*默認(rèn)數(shù)據(jù)位:8*/
comboBox5.Text = "無";/*默認(rèn)奇偶校驗位:無*/
init_mysql();//初始化數(shù)據(jù)庫
// radioButton1.ForeColor =Color.Red;
// radioButton1.Checked = true;
// dataGridView1.RowHeadersVisible =false; //隱藏首列
//String sqlConn ="server="+ server_ip +";port=3306;user=root;password=licoo1128;database=test;Charset=utf8;";//定義連接字符串,Charset=utf8使可以填充中文字符不出現(xiàn)亂碼
String sqlConn = "server='"+ server_ip + "';port='" + server_port + "';user='" +
mysql_user +"';password='" + mysql_pass + "'; database='" +mysql_dataname + "';" + "Charset=utf8;";
conn = newMySqlConnection(sqlConn);//
conn.Open();
try
{
cmd.Connection = conn;
adapter = newMySqlDataAdapter("select * from " + user_data_tebles_ck, conn);
DataSet ds = newDataSet();
adapter.Fill(ds);//填充數(shù)據(jù)至ds數(shù)據(jù)集
bindingSource1.DataSource = ds.Tables[0];//綁定數(shù)據(jù)
bindingNavigator1.BindingSource = bindingSource1;//為導(dǎo)航控件綁定數(shù)據(jù)
dataGridView1.DataSource = bindingSource1;//為DataGridView數(shù)據(jù)控件綁定數(shù)據(jù)
dataGridView1.Columns[0].ReadOnly = true;//設(shè)置第1列,即id列不可編輯 dataGridView1.Columns[0].Width = 40;//設(shè)置列寬度
dataGridView1.Columns[1].Width= 50;//設(shè)置列寬度
dataGridView1.Columns[2].Width = 115;//設(shè)置列寬度
//dataGridView1.Columns[3].Width = 120;//設(shè)置列寬度、
this.dataGridView1.FirstDisplayedScrollingRowIndex = this.dataGridView1.Rows.Count- 1;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
Application.Exit();//直接推出
}
/*****************非常重要************************/
//serialPort1.DataReceived += newSerialDataReceivedEventHandler(port_DataReceived);//必須手動添加事件處理程序
} private void Form1_FormClosed(object sender,FormClosedEventArgs e)
{
rec_start_falg = false;
try
{//防止意外錯誤
serialPort1.Close();//關(guān)閉串口
}
catch (Exception) { }
timer1.Enabled = false;
conn.Close();
try
{
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
Application.Exit();//直接推出
}
Application.Exit();//直接推出 }
private void btnDelete_Click(object sender,EventArgs e)
{
foreach (DataGridViewRow dgr indataGridView1.SelectedRows)//注意,我們刪除的是整行選擇的記錄,選擇某個單元格不算選擇
{
cmd.CommandText =string.Format("DELETE FROM " + user_data_tebles_ck + " WHEREid='{0}';", dgr.Cells[0].Value.ToString());
if (cmd.ExecuteNonQuery()> 0)
dataGridView1.Rows.Remove(dgr);//如果成功從數(shù)據(jù)中刪除了記錄,則從列表中同步刪除。
else
MessageBox.Show(string.Format("從數(shù)據(jù)庫中刪除id為{0}的記錄失敗",dgr.Cells[0].Value.ToString()));
}
}
private void btnFind_Click(object sender,EventArgs e)
{
string sql =string.Format("select * from " + user_data_tebles_ck + " where 序列號 like '%{0}%' or 商品名稱 like'%{0}%' or 商品價格 like '%{0}%';", tbInfo.Text);
adapter = new MySqlDataAdapter(sql,conn);
DataSet ds = new DataSet();
adapter.Fill(ds);//填充數(shù)據(jù)至ds數(shù)據(jù)集
bindingSource1.DataSource =ds.Tables[0];//綁定數(shù)據(jù)
bindingNavigator1.BindingSource =bindingSource1;//為導(dǎo)航控件綁定數(shù)據(jù)
dataGridView1.DataSource =bindingSource1;//為DataGridView數(shù)據(jù)控件綁定數(shù)據(jù)
dataGridView1.Columns[0].ReadOnly =true;//設(shè)置第1列,即id列不可編輯
// Console.WriteLine(bindingSource1.DataSource.ToString());
//dataGridView1.Columns[0].Width =80;//設(shè)置列寬度
//dataGridView1.Columns[1].Width =120;//設(shè)置列寬度
//dataGridView1.Columns[2].Width =120;//設(shè)置列寬度
//dataGridView1.Columns[3].Width =120;//設(shè)置列寬度
}
private void backgroundWorker1_DoWork(objectsender, DoWorkEventArgs e)
{
dtStart = DateTime.Now;
BackgroundWorker worker = sender asBackgroundWorker;
for (int i = 0; i < sum; i++)
{
cmd.CommandText =string.Format("INSERT INTO " + user_data_tebles_ck + " (序列號, 商品名稱, 商品價格) VALUES ('南京{0}', '徐{0}', '18012341234');", i);
cmd.ExecuteNonQuery();
worker.ReportProgress(i);
}
} private void backgroundWorker1_ProgressChanged(objectsender, ProgressChangedEventArgs e)
{
//labelSum.Text =string.Format("已添加{0}條記錄", (e.ProgressPercentage + 1).ToString());
//progressBar1.Value++;
} private void backgroundWorker1_RunWorkerCompleted(objectsender, RunWorkerCompletedEventArgs e)
{
dtEnd = DateTime.Now;
TimeSpan ts = dtEnd - dtStart;
string sInfo = string.Format("添加完畢!用時:{0}天{1}小時{2}分{3}秒{4}毫秒", ts.Days, ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds);
MessageBox.Show(sInfo);
cmd.Connection = conn;
MySqlDataAdapter adp = newMySqlDataAdapter("select * from " + user_data_tebles_ck, conn);
DataSet ds = new DataSet();
adp.Fill(ds);
bindingSource1.DataSource =ds.Tables[0];
bindingNavigator1.BindingSource =bindingSource1;
dataGridView1.DataSource =bindingSource1;
} private void btnClearAll_Click(object sender,EventArgs e)
{
cmd.CommandText =string.Format("delete from " + mysql_dataname + "." +user_data_tebles_ck);
if (cmd.ExecuteNonQuery() > 0)
MessageBox.Show("清空數(shù)據(jù)庫成功");
else
MessageBox.Show("操作失敗");
adapter = newMySqlDataAdapter("select * from " + user_data_tebles_ck, conn);
DataSet ds = new DataSet();
adapter.Fill(ds);//填充數(shù)據(jù)至ds數(shù)據(jù)集
bindingSource1.DataSource =ds.Tables[0];//綁定數(shù)據(jù)
bindingNavigator1.BindingSource =bindingSource1;//為導(dǎo)航控件綁定數(shù)據(jù)
dataGridView1.DataSource =bindingSource1;//為DataGridView數(shù)據(jù)控件綁定數(shù)據(jù)
}
/// 獲取當(dāng)前系統(tǒng)時間的方法
/// 當(dāng)前時間
static DateTime GetCurrentTime()
{
DateTime currentTime = newDateTime();
currentTime = DateTime.Now;
return currentTime;
} private void button2_Click(object sender,EventArgs e)
{
//string sql = string.Format("select* from " + user_data_tebles_log + " where 交易時間 like '%{0}%' or 支付金額 like'%{0}%';", tbInfo.Text);
string sql =string.Format("select * from " + user_data_tebles_ck);
adapter = new MySqlDataAdapter(sql,conn);
DataSet ds = new DataSet();
adapter.Fill(ds);//填充數(shù)據(jù)至ds數(shù)據(jù)集
bindingSource1.DataSource =ds.Tables[0];//綁定數(shù)據(jù)
bindingNavigator1.BindingSource =bindingSource1;//為導(dǎo)航控件綁定數(shù)據(jù)
dataGridView1.DataSource = bindingSource1;//為DataGridView數(shù)據(jù)控件綁定數(shù)據(jù)
dataGridView1.Columns[0].ReadOnly =true;//設(shè)置第1列,即id列不可編輯
// dataGridView1.Columns[0].Width =60;//設(shè)置列寬度
// dataGridView1.Columns[1].Width =180;//設(shè)置列寬度
//// dataGridView1.Columns[3].Width =80;//設(shè)置列寬度
// dataGridView1.Columns[2].Width =200;//設(shè)置列寬度
}
private void button1_Click_1(object sender,EventArgs e)
{
cmd.CommandText =string.Format("delete from " + mysql_dataname + "." +user_data_tebles_log);
if (cmd.ExecuteNonQuery() > 0)
MessageBox.Show("清空數(shù)據(jù)庫成功");
else
MessageBox.Show("操作失敗"); adapter = newMySqlDataAdapter("select * from " + user_data_tebles_log, conn);
DataSet ds = new DataSet();
adapter.Fill(ds);//填充數(shù)據(jù)至ds數(shù)據(jù)集
bindingSource1.DataSource =ds.Tables[0];//綁定數(shù)據(jù)
bindingNavigator1.BindingSource =bindingSource1;//為導(dǎo)航控件綁定數(shù)據(jù)
dataGridView1.DataSource = bindingSource1;//為DataGridView數(shù)據(jù)控件綁定數(shù)據(jù)
}
String serialPortName;
private void button3_Click(object sender, EventArgse)
{
if (button3.Text == "打開串口")
{//如果按鈕顯示的是打開
try
{ serialPort1.PortName = comboBox1.Text;//獲取comboBox1要打開的串口號
serialPortName = comboBox1.Text;
serialPort1.BaudRate = int.Parse(comboBox2.Text);//獲取comboBox2選擇的波特率
serialPort1.DataBits = int.Parse(comboBox4.Text);//設(shè)置數(shù)據(jù)位
/*設(shè)置停止位*/
if(comboBox3.Text == "1") { serialPort1.StopBits = StopBits.One; }
else if(comboBox3.Text == "1.5") { serialPort1.StopBits =StopBits.OnePointFive; }
else if(comboBox3.Text == "2") { serialPort1.StopBits = StopBits.Two; }
/*設(shè)置奇偶校驗*/
if(comboBox5.Text == "無") { serialPort1.Parity= Parity.None; }
else if(comboBox5.Text == "奇校驗") {serialPort1.Parity = Parity.Odd; }
else if(comboBox5.Text == "偶校驗") {serialPort1.Parity = Parity.Even; } serialPort1.Open();//打開串口
button3.Text = "關(guān)閉串口";//按鈕顯示關(guān)閉串口
timer1.Enabled = true;
}
catch (Exception err)
{
MessageBox.Show("打開失敗" + err.ToString(),"提示!");//對話框顯示打開失敗
} }
else
{//要關(guān)閉串口
try
{//防止意外錯誤
serialPort1.Close();//關(guān)閉串口
}
catch (Exception) { }
button3.Text = "打開串口";//按鈕顯示打開
rec_start_falg = false;
timer1.Enabled = false;
}
}
void real_time_addmysql(bool sta)
{
if (sta)
{
cmd.CommandText =string.Format("INSERT INTO " + mysql_dataname + "." +user_data_tebles_ck2 + "(value,time) values('{0}','{1}');", "有人", GetCurrentTime());
}
else
{
cmd.CommandText =string.Format("INSERT INTO " + mysql_dataname + "." +user_data_tebles_ck2 + "(value,time) values('{0}','{1}');", "無人", GetCurrentTime());
}
if (cmd.ExecuteNonQuery() > 0)
Console.WriteLine("添加成功");
else
Console.WriteLine("添加失敗");
} void trigger_addmysql() //有人觸發(fā)了
{
cmd.CommandText = string.Format("INSERTINTO " + mysql_dataname + "." + user_data_tebles_ck +"(value,time) values('{0}','{1}');", "有人",GetCurrentTime());
if (cmd.ExecuteNonQuery() > 0)
Console.WriteLine("添加成功");
else
Console.WriteLine("添加失敗");
adapter = newMySqlDataAdapter("select * from " + user_data_tebles_ck, conn);
DataSet ds = new DataSet();
adapter.Fill(ds);//填充數(shù)據(jù)至ds數(shù)據(jù)集
bindingSource1.DataSource =ds.Tables[0];//綁定數(shù)據(jù)
bindingNavigator1.BindingSource =bindingSource1;//為導(dǎo)航控件綁定數(shù)據(jù)
dataGridView1.DataSource =bindingSource1;//為DataGridView數(shù)據(jù)控件綁定數(shù)據(jù)
}
private void button4_Click_1(object sender,EventArgs e)
{
cmd.CommandText =string.Format("INSERT INTO " + mysql_dataname + "." +user_data_tebles_ck + "(value,time) values('{0}','{1}');", "有人", GetCurrentTime());
if (cmd.ExecuteNonQuery() > 0)
MessageBox.Show("添加成功");
else
MessageBox.Show("添加失敗");
adapter = newMySqlDataAdapter("select * from " + user_data_tebles_ck, conn);
DataSet ds = new DataSet();
adapter.Fill(ds);//填充數(shù)據(jù)至ds數(shù)據(jù)集
bindingSource1.DataSource = ds.Tables[0];//綁定數(shù)據(jù)
bindingNavigator1.BindingSource =bindingSource1;//為導(dǎo)航控件綁定數(shù)據(jù)
dataGridView1.DataSource =bindingSource1;//為DataGridView數(shù)據(jù)控件綁定數(shù)據(jù)
}
bool rec_start_falg = false;
bool lock_flag = false;
bool rt_glo_status=false;//人體感應(yīng)全局狀態(tài)
private void serialPort1_DataReceived(objectsender, SerialDataReceivedEventArgs e)
{
Byte[] InputBuf = new Byte[10];
//開辟接收緩沖區(qū)
byte[] ReDatas = newbyte[serialPort1.BytesToRead];
//從串口讀取數(shù)據(jù)
serialPort1.Read(ReDatas, 0,ReDatas.Length);
if (ReDatas.Length == 3 &&ReDatas[0] == 0xAA && ReDatas[2] == 0xFA)
{
rec_start_falg = true;
Console.WriteLine("okoko");
rt_glo_status =ReDatas[1] > 0 ? true : false;
Invoke((new Action(()=>
{
if(ReDatas[1] == 1)
{
rt_radio.Checked = true; if (lock_flag == false)
{
lock_flag = true;//鎖定
trigger_addmysql();//添加一條記錄
}
}
else
{
rt_radio.Checked = false;
lock_flag = false;//取消鎖定
}
})));
} } private void timer1_Tick(object sender,EventArgs e)
{
if (rec_start_falg) //可以開始保存數(shù)據(jù)了
{
real_time_addmysql(rt_glo_status);
}
} private voidtabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl1.SelectedIndex == 0)//也可以判斷tabControl1.SelectedTab.Text的值
{
//執(zhí)行相應(yīng)的操作
//tabPageSubject.Parent = tabControlExtract;//顯示
adapter = newMySqlDataAdapter("select * from " + user_data_tebles_ck, conn);
DataSet ds = newDataSet();
adapter.Fill(ds);//填充數(shù)據(jù)至ds數(shù)據(jù)集
bindingSource1.DataSource = ds.Tables[0];//綁定數(shù)據(jù)
bindingNavigator1.BindingSource = bindingSource1;//為導(dǎo)航控件綁定數(shù)據(jù)
dataGridView1.DataSource = bindingSource1;//為DataGridView數(shù)據(jù)控件綁定數(shù)據(jù)
this.dataGridView1.FirstDisplayedScrollingRowIndex =this.dataGridView1.Rows.Count - 1;
}
else if (tabControl1.SelectedIndex ==1)
{
//執(zhí)行相應(yīng)的操作
//tabPageSubject.Parent = null; dataGridView2 查詢歷史記錄
cmd.Connection = conn;
adapter = newMySqlDataAdapter("select * from " + user_data_tebles_ck2, conn);
DataSet ds = newDataSet();
adapter.Fill(ds);//填充數(shù)據(jù)至ds數(shù)據(jù)集
bindingSource1.DataSource = ds.Tables[0];//綁定數(shù)據(jù)
bindingNavigator1.BindingSource = bindingSource1;//為導(dǎo)航控件綁定數(shù)據(jù)
dataGridView2.DataSource = bindingSource1;//為DataGridView數(shù)據(jù)控件綁定數(shù)據(jù)
dataGridView2.Columns[0].ReadOnly = true;//設(shè)置第1列,即id列不可編輯
dataGridView2.Columns[0].Width = 40;//設(shè)置列寬度
dataGridView2.Columns[1].Width = 50;//設(shè)置列寬度
dataGridView2.Columns[2].Width= 115;//設(shè)置列寬度
this.dataGridView2.FirstDisplayedScrollingRowIndex =this.dataGridView2.Rows.Count - 1;
} }
int delcnt = 0;
private void button6_Click(object sender, EventArgse)
{
int idex = 0;
if (++delcnt > 3)
{
delcnt = 0;
cmd.CommandText =string.Format("delete from " + mysql_dataname + "." +user_data_tebles_ck);
if(cmd.ExecuteNonQuery() > 0)
idex++;
else
idex = 0;
cmd.CommandText =string.Format("delete from " + mysql_dataname + "." +user_data_tebles_ck2);
if(cmd.ExecuteNonQuery() > 0)
idex++;
else
idex = 0;
if (idex >= 2)MessageBox.Show("清空數(shù)據(jù)庫成功!");
else
{
MessageBox.Show("清空數(shù)據(jù)庫失敗!");
}
adapter = new MySqlDataAdapter("select* from " + user_data_tebles_ck, conn);
DataSet ds = newDataSet();
adapter.Fill(ds);//填充數(shù)據(jù)至ds數(shù)據(jù)集
bindingSource1.DataSource = ds.Tables[0];//綁定數(shù)據(jù)
bindingNavigator1.BindingSource = bindingSource1;//為導(dǎo)航控件綁定數(shù)據(jù)
dataGridView1.DataSource = bindingSource1;//為DataGridView數(shù)據(jù)控件綁定數(shù)據(jù)
}
}
}
}
Zigbee終端節(jié)點(diǎn)代碼
#include "OSAL.h"
#include "ZGlobals.h"
#include "AF.h"
#include "aps_groups.h"
#include "ZDApp.h"
#include "SampleApp.h"
#include "SampleAppHw.h"
#include "OnBoard.h"
#include <math.h> #include "MT_UART.h"
#include "MT_APP.h"
#include "MT.h"
#include "hal_uart.h"
#include "hal_adc.h"
#include <stdio.h>
#include "string.h"
#include <stdlib.h>
#include "public.h"
#include <stdlib.h>
#include "hal_types.h"
#include "bh1750.h"
#include "dht11.h"
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned long u32; typedef unsigned int uint16_t; void user_time_loop_task(void);
void App_GatherTask(void);
// This list should be filled with Application specific Cluster IDs.
const cId_t SD_App_ClusterList[SD_APP_MAX_CLUSTERS] =
{
SD_APP_BROADCAST_CLUSTERID,
SD_APP_POINT_TO_POINT_CLUSTERID
};//這就是每一個端點(diǎn)里面的簇有2個并且簇的ID分別是1,2
const SimpleDescriptionFormat_t SD_App_SimpleDesc =
{
SD_APP_ENDPOINT, // int Endpoint;
SD_APP_PROFID, // uint16 AppProfId[2];
SD_APP_DEVICEID, // uint16 AppDeviceId[2];
SD_APP_DEVICE_VERSION, // int AppDevVer:4;
SD_APP_FLAGS, // int AppFlags:4;
SD_APP_MAX_CLUSTERS, // uint8 AppNumInClusters;
(cId_t *)SD_App_ClusterList, // uint8 *pAppInClusterList;
SD_APP_MAX_CLUSTERS, // uint8 AppNumInClusters;
(cId_t *)SD_App_ClusterList // uint8 *pAppInClusterList;
};
// This is the Endpoint/Interface description. It is defined here,but
// filled-in in SD_App_Init(). Another way to go would be to fill
// in the structure here and make it a "const" (in code space). The
// way it's defined in this sample app it is define in RAM.
endPointDesc_t SD_App_epDesc;//定義的端點(diǎn)描述符 /*********************************************************************
* LOCAL VARIABLES
*/
uint8 SD_App_TaskID; // Task ID for internal task/event processing
// This variable will be received when
// SD_App_Init() is called. devStates_t SD_App_NwkState; uint8 SD_App_TransID; // This is the unique message ID (counter) afAddrType_t SD_App_Broadcast_DstAddr;
afAddrType_t SD_App_Point_To_Point_DstAddr; /*********************************************************************
* LOCAL FUNCTIONS
*/
void SD_App_MessageMSGCB( afIncomingMSGPacket_t *pckt ); /* 串口基本定義 */
#define MY_DEFINE_UART_PORT 0 //自定義串口號(0,1);
#define RX_MAX_LENGTH 20 //接收緩沖區(qū)最大值: 20個字節(jié);
uint8 RX_BUFFER[RX_MAX_LENGTH]; //接收緩沖區(qū);
void UartCallBackFunction(uint8 port , uint8 event); //回調(diào)函數(shù)聲明,定義在最后面;
#define LED_PIN P1_1 //燈io
/* 配置串口 */
halUARTCfg_t uartConfig; //定義串口配置結(jié)構(gòu)體變量;
void Uart_Config(void); //函數(shù)聲明;
void Uart_Config(void) //函數(shù)定義;
{
uartConfig.configured = TRUE; //允許配置;
uartConfig.baudRate =HAL_UART_BR_115200;//波特率;
uartConfig.flowControl = FALSE;
uartConfig.flowControlThreshold = 64; //don't care - seeuart driver.
uartConfig.rx.maxBufSize = 128; //串口接收緩沖區(qū)大小
uartConfig.tx.maxBufSize = 128; //串口發(fā)送緩沖區(qū)大小
uartConfig.idleTimeout = 6; //don't care - see uart driver.
uartConfig.intEnable = TRUE;//使能中斷
uartConfig.callBackFunc =UartCallBackFunction; //指定回調(diào)函數(shù)名;
}
/*********************************************************************
* @fn SD_App_Init
*
* @brief Initialization function for the Generic App Task.
* This is called during initializationand should contain
* any application specificinitialization (ie. hardware
* initialization/setup, tableinitialization, power up
* notificaiton ... ).
*
* @param task_id - the ID assigned by OSAL. This ID shouldbe
* used to send messages and set timers.
*
* @return none
*/
void SD_App_Init( uint8 task_id )
{
SD_App_TaskID = task_id; SD_App_NwkState = DEV_INIT;
SD_App_TransID = 0;
#if defined ( BUILD_ALL_DEVICES )
// The "Demo" target is setup to have BUILD_ALL_DEVICES andHOLD_AUTO_START
// We are looking at a jumper (defined in SD_AppHw.c) to be jumpered
// together - if they are - we will start up a coordinator. Otherwise,
// the device will start as a router.
if ( readCoordinatorJumper() )
zgDeviceLogicalType = ZG_DEVICETYPE_COORDINATOR;
else
zgDeviceLogicalType = ZG_DEVICETYPE_ROUTER;
#endif // BUILD_ALL_DEVICES #if defined ( HOLD_AUTO_START )
// HOLD_AUTO_START is a compile option that will surpress ZDApp
// from starting the device and wait for the application to
// start the device.
ZDOInitDevice(0);
#endif /* 串口操作 */
Uart_Config(); //配置串口
HalUARTOpen(MY_DEFINE_UART_PORT , &uartConfig); //打開串口
HalUARTWrite(MY_DEFINE_UART_PORT ,"HAL_UART_OK\r\n" , 15);
// Setup for the periodic message's destination address
// Broadcast to everyone
SD_App_Broadcast_DstAddr.addrMode = (afAddrMode_t)AddrBroadcast;//廣播模式
SD_App_Broadcast_DstAddr.endPoint = SD_APP_ENDPOINT;
SD_App_Broadcast_DstAddr.addr.shortAddr = 0xFFFF; SD_App_Point_To_Point_DstAddr.addrMode =(afAddrMode_t)Addr16Bit;
SD_App_Point_To_Point_DstAddr.endPoint = SD_APP_ENDPOINT;
SD_App_Point_To_Point_DstAddr.addr.shortAddr = 0x0000; // // Fill out the endpoint description.
SD_App_epDesc.endPoint = SD_APP_ENDPOINT;
SD_App_epDesc.task_id = &SD_App_TaskID;
SD_App_epDesc.simpleDesc
= (SimpleDescriptionFormat_t*)&SD_App_SimpleDesc;
SD_App_epDesc.latencyReq = noLatencyReqs;
//
// // Register the endpoint description with the AF
afRegister( &SD_App_epDesc );
// Start sending the periodic message in a regular interval.
//這個定時器只是為發(fā)送周期信息開啟的,設(shè)備啟動初始化后從這里開始
//觸發(fā)第一個周期信息的發(fā)送,然后周而復(fù)始下去
P0DIR&=~0x80;
P1DIR|=0x03;
//SYSTEM_TICK_Init(user_time_loop_task,20);
LED_PIN=0;
system_delay_ms(100);
LED_PIN=1;
osal_start_timerEx(SD_App_TaskID,
SAMPLEAPP_SEND_PERIODIC_MSG_EVT,
SAMPLEAPP_SEND_PERIODIC_MSG_TIMEOUT); } char rxbuffer[30]={0}; uint8 SendData[10]={0};//發(fā)送數(shù)據(jù)緩存區(qū)
#define RT_Input P0_7
char RT_InFlag=0;//感應(yīng)標(biāo)志
uint16 ifg_Rt =0;//計時
char Send_Flag=0;
uint8 delaycnt=0;
void App_GatherTask(void)
{
SendData[0]=0xAA;
SendData[2]=0xFA;//幀尾
if(++delaycnt>50) //上電延時一段時間
{
delaycnt=52;
if(RT_Input==1)
{
LED_PIN=0;//報警
SendData[1]=1; //有人
ifg_Rt=0;
// HalUARTWrite(MY_DEFINE_UART_PORT ,"On\r\n", 4);
}
else
{
ifg_Rt++;
if(ifg_Rt>15)//計時
{
SendData[1]=0;//沒人
ifg_Rt=0;
LED_PIN=1;//不報警
// HalUARTWrite(MY_DEFINE_UART_PORT ,"Off\r\n", 4);
}
}
}
AF_DataRequest(&SD_App_Broadcast_DstAddr, //發(fā)送目的地址+端點(diǎn)地址和傳送模式
&SD_App_epDesc,//源(答復(fù)或確認(rèn))終端的描述(比如操作系統(tǒng)中任務(wù)ID等)源EP
SD_APP_BROADCAST_CLUSTERID, //被Profile指定的有效的集群號
3, // 發(fā)送數(shù)據(jù)長度
SendData,// 發(fā)送數(shù)據(jù)緩沖區(qū)
&SD_App_TransID, // 任務(wù)ID號
AF_DISCV_ROUTE, // 有效位掩碼的發(fā)送選項
AF_DEFAULT_RADIUS );//傳送跳數(shù),通常設(shè)置為AF_DEFAULT_RADIUS
}
//用戶應(yīng)用任務(wù)的事件處理函數(shù)
//task_id 任務(wù)id號,events 事件id號
uint16 SD_App_ProcessEvent( uint8 task_id, uint16 events )
{
afIncomingMSGPacket_t *MSGpkt;
(void)task_id; // Intentionally unreferenced parameter if ( events & SYS_EVENT_MSG )//接收系統(tǒng)消息事件 再進(jìn)行判斷
{
//接收屬于本應(yīng)用任務(wù)SampleApp的消息,以SampleApp_TaskID標(biāo)記
MSGpkt = (afIncomingMSGPacket_t *)osal_msg_receive( SD_App_TaskID); //根據(jù)不同任務(wù)id號接收消息在強(qiáng)制轉(zhuǎn)換
while ( MSGpkt )
{
switch ( MSGpkt->hdr.event )
{
case CMD_SERIAL_MSG:
break;
// Received when a messages is received (OTA) forthis endpoint
case AF_INCOMING_MSG_CMD: //接收數(shù)據(jù)事件,調(diào)用函數(shù)AF_DataRequest()接收數(shù)據(jù)
//注冊完了之后我們就能收到外面從這個端點(diǎn)進(jìn)來的數(shù)據(jù)信息了
SD_App_MessageMSGCB( MSGpkt );//調(diào)用回調(diào)函數(shù)對收到的數(shù)據(jù)進(jìn)行處理
break;
case ZDO_STATE_CHANGE: //只要網(wǎng)絡(luò)狀態(tài)發(fā)生改變,就通過ZDO_STATE_CHANGE事件通知所有的任務(wù)。
//同時完成對協(xié)調(diào)器,路由器,終端的設(shè)置
SD_App_NwkState =(devStates_t)(MSGpkt->hdr.status);
if ((SD_App_NwkState == DEV_ZB_COORD)//判斷是否為協(xié)調(diào)器
|| (SD_App_NwkState ==DEV_ROUTER)
|| (SD_App_NwkState ==DEV_END_DEVICE))
{
if(SD_App_NwkState == DEV_ZB_COORD)
{
// LS164_BYTE(11);//'C'協(xié)調(diào)器
HalUARTWrite(MY_DEFINE_UART_PORT,"Coordinator_OK!!\r\n" , 18);
}
if(SD_App_NwkState == DEV_ROUTER)
{
// LS164_BYTE(12);//‘R’路由器
HalUARTWrite(MY_DEFINE_UART_PORT,"Router_OK!!\r\n" , 13);
}
if(SD_App_NwkState == DEV_END_DEVICE)
{
// LS164_BYTE(13);//‘E’終端
HalUARTWrite(MY_DEFINE_UART_PORT,"EndDevice_OK!!\r\n" ,16);
}
}
else
{
// Device is no longerin the network
}
break; default:
break;
} // Release the memory 釋放內(nèi)存
osal_msg_deallocate( (uint8 *)MSGpkt ); // Next - if one is available 指針指向下一個放在緩沖區(qū)的待處理的事件,
//返回while ( MSGpkt )判斷重新處理事件,直到緩沖區(qū)沒有等待處理事件為止
MSGpkt = (afIncomingMSGPacket_t *)osal_msg_receive(SD_App_TaskID );
}
// return unprocessed events返回未處理的事件
return (events ^ SYS_EVENT_MSG);
}
// Send a message out - This event is generated by a timer
// (setup in SampleApp_Init()).
if ( events & SAMPLEAPP_SEND_PERIODIC_MSG_EVT )//發(fā)送消息-此事件由計時器生成
{
// Send the periodic message 處理周期性事件,
//利用SampleApp_SendPeriodicMessage()處理完當(dāng)前的周期性事件,然后啟動定時器
//開啟下一個周期性事情,這樣一種循環(huán)下去,也即是上面說的周期性事件了,
//可以做為傳感器定時采集、上傳任務(wù)
App_GatherTask();
// Setup to send message again in normal period (+ a littlejitter)
osal_start_timerEx( SD_App_TaskID,SAMPLEAPP_SEND_PERIODIC_MSG_EVT,
(SAMPLEAPP_SEND_PERIODIC_MSG_TIMEOUT + (osal_rand()& 0x00FF)) );//再次啟動
// 返回未處理的事件
return (events ^ SAMPLEAPP_SEND_PERIODIC_MSG_EVT);
}
return 0;
}
//接收數(shù)據(jù),參數(shù)為接收到的數(shù)據(jù)
void SD_App_MessageMSGCB( afIncomingMSGPacket_t *pkt )
{
//收到廣播數(shù)據(jù)
switch ( pkt->clusterId )//判斷簇ID
{
case SD_APP_POINT_TO_POINT_CLUSTERID: //簇1
break; case SD_APP_BROADCAST_CLUSTERID: //簇2
// osal_memset(rxbuffer,0,30);
// osal_memcpy((uint8*)rxbuffer,&pkt->cmd.Data[0],pkt->cmd.DataLength);
//
break;
}
}
Zigbee協(xié)調(diào)器應(yīng)用代碼
char showbuff[16]={0};
uint8 sendblueFlag=0;//發(fā)送標(biāo)志位 // This list should be filled with Application specific Cluster IDs.
const cId_t SD_App_ClusterList[SD_APP_MAX_CLUSTERS] =
{
SD_APP_BROADCAST_CLUSTERID,
SD_APP_POINT_TO_POINT_CLUSTERID
};//這就是每一個端點(diǎn)里面的簇有2個并且簇的ID分別是1,2
const SimpleDescriptionFormat_t SD_App_SimpleDesc =
{
SD_APP_ENDPOINT, // int Endpoint;
SD_APP_PROFID, // uint16 AppProfId[2];
SD_APP_DEVICEID, // uint16 AppDeviceId[2];
SD_APP_DEVICE_VERSION, // int AppDevVer:4;
SD_APP_FLAGS, // int AppFlags:4;
SD_APP_MAX_CLUSTERS, // uint8 AppNumInClusters;
(cId_t *)SD_App_ClusterList, // uint8 *pAppInClusterList;
SD_APP_MAX_CLUSTERS, // uint8 AppNumInClusters;
(cId_t *)SD_App_ClusterList // uint8 *pAppInClusterList;
};
// This is the Endpoint/Interface description. It is defined here,but
// filled-in in SD_App_Init(). Another way to go would be to fill
// in the structure here and make it a "const" (in code space). The
// way it's defined in this sample app it is define in RAM.
endPointDesc_t SD_App_epDesc;//定義的端點(diǎn)描述符 /*********************************************************************
* LOCAL VARIABLES
*/
uint8 SD_App_TaskID; // Task ID for internal task/event processing
// This variable will be received when
// SD_App_Init() is called. devStates_t SD_App_NwkState; uint8 SD_App_TransID; // This is the unique message ID (counter) afAddrType_t SD_App_Broadcast_DstAddr;
afAddrType_t SD_App_Point_To_Point_DstAddr; /*********************************************************************
* LOCAL FUNCTIONS
*/
void SD_App_MessageMSGCB( afIncomingMSGPacket_t *pckt );
void SD_App_SendBroadcastMessage( void );
void SD_App_SendPointToPointMessage(void);
void App_KeyCheck(void);
/* 串口基本定義 */
#define MY_DEFINE_UART_PORT 0 //自定義串口號(0,1);
#define RX_MAX_LENGTH 30 //接收緩沖區(qū)最大值: 20個字節(jié);
uint8 RX_BUFFER[RX_MAX_LENGTH]; //接收緩沖區(qū);
void UartCallBackFunction(uint8 port , uint8 event); //回調(diào)函數(shù)聲明,定義在最后面;
void App_userTask(void);
void sys_delay_us(unsigned int n); /* 配置串口 */
halUARTCfg_t uartConfig; //定義串口配置結(jié)構(gòu)體變量;
void Uart_Config(void); //函數(shù)聲明;
void Uart_Config(void) //函數(shù)定義;
{
uartConfig.configured = TRUE; //允許配置;
uartConfig.baudRate =HAL_UART_BR_115200;//波特率;
uartConfig.flowControl = FALSE;
uartConfig.flowControlThreshold = 64; //don't care - seeuart driver.
uartConfig.rx.maxBufSize = 128; //串口接收緩沖區(qū)大小
uartConfig.tx.maxBufSize = 128; //串口發(fā)送緩沖區(qū)大小
uartConfig.idleTimeout = 6; //don't care - see uart driver.
uartConfig.intEnable = TRUE;//使能中斷
uartConfig.callBackFunc =UartCallBackFunction; //指定回調(diào)函數(shù)名;
} /*********************************************************************
* @fn SD_App_Init
*
* @brief Initialization function for the Generic App Task.
* This is called during initializationand should contain
* any application specificinitialization (ie. hardware
* initialization/setup, tableinitialization, power up
* notificaiton ... ).
*
* @param task_id - the ID assigned by OSAL. This ID shouldbe
* used to send messages and set timers.
*
* @return none
*/ void SD_App_Init( uint8 task_id )
{
SD_App_TaskID = task_id; SD_App_NwkState = DEV_INIT;
SD_App_TransID = 0;
#if defined ( BUILD_ALL_DEVICES )
// The "Demo" target is setup to have BUILD_ALL_DEVICES andHOLD_AUTO_START
// We are looking at a jumper (defined in SD_AppHw.c) to be jumpered
// together - if they are - we will start up a coordinator. Otherwise,
// the device will start as a router.
if ( readCoordinatorJumper() )
zgDeviceLogicalType = ZG_DEVICETYPE_COORDINATOR;
else
zgDeviceLogicalType = ZG_DEVICETYPE_ROUTER;
#endif // BUILD_ALL_DEVICES #if defined ( HOLD_AUTO_START )
// HOLD_AUTO_START is a compile option that will surpress ZDApp
// from starting the device and wait for the application to
// start the device.
ZDOInitDevice(0);
#endif
/* 串口操作 */
Uart_Config(); //配置串口
HalUARTOpen(MY_DEFINE_UART_PORT , &uartConfig); //打開串口
// HalUARTWrite(MY_DEFINE_UART_PORT ,"HAL_UART_OK\r\n" , 15);
// Setup for the periodic message's destination address
// Broadcast to everyone
SD_App_Broadcast_DstAddr.addrMode = (afAddrMode_t)AddrBroadcast;//廣播模式
SD_App_Broadcast_DstAddr.endPoint = SD_APP_ENDPOINT;
SD_App_Broadcast_DstAddr.addr.shortAddr = 0xFFFF; SD_App_Point_To_Point_DstAddr.addrMode = (afAddrMode_t)Addr16Bit;//點(diǎn)對點(diǎn)模式
SD_App_Point_To_Point_DstAddr.endPoint = SD_APP_ENDPOINT;
SD_App_Point_To_Point_DstAddr.addr.shortAddr = 0x0000;//發(fā)送到目標(biāo)的地址 // // Fill out the endpoint description.填寫端點(diǎn)描述。
SD_App_epDesc.endPoint = SD_APP_ENDPOINT;
SD_App_epDesc.task_id = &SD_App_TaskID;
SD_App_epDesc.simpleDesc
= (SimpleDescriptionFormat_t*)&SD_App_SimpleDesc;
SD_App_epDesc.latencyReq = noLatencyReqs;
//
// // Register the endpoint description with the AF向af注冊端點(diǎn)描述。
afRegister( &SD_App_epDesc );
// Start sending the periodic message in a regular interval.
//這個定時器只是為發(fā)送周期信息開啟的,設(shè)備啟動初始化后從這里開始
//觸發(fā)第一個周期信息的發(fā)送,然后周而復(fù)始下去
osal_start_timerEx(SD_App_TaskID,
SAMPLEAPP_SEND_PERIODIC_MSG_EVT,
SAMPLEAPP_SEND_PERIODIC_MSG_TIMEOUT);
//SYSTEM_TICK_Init(Key_Scan,20);//設(shè)置一個定時器 20ms運(yùn)行一次掃描按鍵
}
//32MHZ us延時函數(shù);
#pragma optimize=none
void sys_delay_us(unsigned int n)
{
n>>=1;
while(n--)
{
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
asm("NOP");
}
}
//用戶應(yīng)用任務(wù)的事件處理函數(shù)
//task_id 任務(wù)id號,events 事件id號
uint16 SD_App_ProcessEvent( uint8 task_id, uint16 events )
{ afIncomingMSGPacket_t *MSGpkt;
(void)task_id; // Intentionally unreferenced parameter if ( events & SYS_EVENT_MSG )//接收系統(tǒng)消息事件 再進(jìn)行判斷
{
//接收屬于本應(yīng)用任務(wù)SampleApp的消息,以SampleApp_TaskID標(biāo)記
MSGpkt = (afIncomingMSGPacket_t *)osal_msg_receive( SD_App_TaskID); //根據(jù)不同任務(wù)id號接收消息在強(qiáng)制轉(zhuǎn)換
while ( MSGpkt )
{
switch ( MSGpkt->hdr.event )
{
case CMD_SERIAL_MSG:
break;
// Received when a key is pressed
case KEY_CHANGE://按鍵事件
break;
// Received when a messages is received (OTA) forthis endpoint
case AF_INCOMING_MSG_CMD: //接收數(shù)據(jù)事件,調(diào)用函數(shù)AF_DataRequest()接收數(shù)據(jù)
//注冊完了之后我們就能收到外面從這個端點(diǎn)進(jìn)來的數(shù)據(jù)信息了
SD_App_MessageMSGCB( MSGpkt );//調(diào)用回調(diào)函數(shù)對收到的數(shù)據(jù)進(jìn)行處理
break;
case ZDO_STATE_CHANGE: //只要網(wǎng)絡(luò)狀態(tài)發(fā)生改變,就通過ZDO_STATE_CHANGE事件通知所有的任務(wù)。
//同時完成對協(xié)調(diào)器,路由器,終端的設(shè)置
SD_App_NwkState =(devStates_t)(MSGpkt->hdr.status);
if ((SD_App_NwkState == DEV_ZB_COORD)//判斷是否為協(xié)調(diào)器
|| (SD_App_NwkState ==DEV_ROUTER)
|| (SD_App_NwkState ==DEV_END_DEVICE))
{
if(SD_App_NwkState == DEV_ZB_COORD)
{
// );//'C'協(xié)調(diào)器
HalUARTWrite(MY_DEFINE_UART_PORT,"Coordinator_OK!!\r\n" , 18);
}
if(SD_App_NwkState == DEV_ROUTER)
{
// ;//‘R’路由器
HalUARTWrite(MY_DEFINE_UART_PORT,"Router_OK!!\r\n" , 13);
}
if(SD_App_NwkState == DEV_END_DEVICE)
{
// LS164_BYTE(13);//‘E’終端
HalUARTWrite(MY_DEFINE_UART_PORT,"EndDevice_OK!!\r\n" ,16);
}
}
else
{
// Device is no longerin the network
}
break; default:
break;
} // Release the memory 釋放內(nèi)存
osal_msg_deallocate( (uint8 *)MSGpkt ); // Next - if one is available 指針指向下一個放在緩沖區(qū)的待處理的事件,
//返回while ( MSGpkt )判斷重新處理事件,直到緩沖區(qū)沒有等待處理事件為止
MSGpkt = (afIncomingMSGPacket_t *)osal_msg_receive(SD_App_TaskID );
}
// return unprocessed events返回未處理的事件
return (events ^ SYS_EVENT_MSG);
}
if ( events & SAMPLEAPP_SEND_PERIODIC_MSG_EVT )//發(fā)送消息-此事件由計時器生成
{
// Send the periodic message 處理周期性事件,
//利用SampleApp_SendPeriodicMessage()處理完當(dāng)前的周期性事件,然后啟動定時器
//開啟下一個周期性事情,這樣一種循環(huán)下去,也即是上面說的周期性事件了,
//可以做為傳感器定時采集、上傳任務(wù)
App_userTask();
osal_start_timerEx( SD_App_TaskID,SAMPLEAPP_SEND_PERIODIC_MSG_EVT,
(SAMPLEAPP_SEND_PERIODIC_MSG_TIMEOUT + (osal_rand()& 0x00FF)) );//再次啟動
// 返回未處理的事件
return (events ^ SAMPLEAPP_SEND_PERIODIC_MSG_EVT);
}
return 0;
} uint8 tx_flag=0;
uint8 uart_len=0;
uint8 rxbff[5]={0};//接收緩存
uint16 delayCnt=0;
void App_userTask(void) //顯示任務(wù)
{
}
//接收數(shù)據(jù),參數(shù)為接收到的數(shù)據(jù)
void SD_App_MessageMSGCB( afIncomingMSGPacket_t *pkt )
{
//收到數(shù)據(jù)
switch (pkt->clusterId)//判斷簇ID
{
case SD_APP_POINT_TO_POINT_CLUSTERID: //簇1
break;
case SD_APP_BROADCAST_CLUSTERID: //簇2
if(pkt->cmd.Data[0]==0xAA&&pkt->cmd.Data[2]==0xFA)
{
osal_memcpy(rxbff,&pkt->cmd.Data[0],3);
HalUARTWrite(MY_DEFINE_UART_PORT , rxbff ,3);//發(fā)送到上位機(jī)軟件
}
break;
}
} /*********************************************************************
*
* 函數(shù)名: UartCallBackFunction
* 函數(shù)功能:串口回調(diào)函數(shù),接收到數(shù)據(jù)時會調(diào)用到該函數(shù);
* 傳入?yún)?shù):port:串口號 event:事件
* 返回參數(shù):無
*
*********************************************************************/
static void UartCallBackFunction(uint8 port , uint8 event)
{
uint8 RX_Length = 0; //接收到字符串大;
RX_Length = Hal_UART_RxBufLen(MY_DEFINE_UART_PORT); //讀取接收字符串大;
if(RX_Length != 0) //有數(shù)據(jù)存在;
{
//讀取串口數(shù)據(jù);
HalUARTRead(MY_DEFINE_UART_PORT , RX_BUFFER ,RX_Length);
uart_len = RX_Length;
// tx_flag=1;
delayCnt=0;
//發(fā)送回給電腦,使用 hal_uart.h 的接口函數(shù):
//HalUARTWrite(MY_DEFINE_UART_PORT , RX_BUFFER ,RX_Length);
}
} 以上為本設(shè)計所有應(yīng)用代碼為原創(chuàng)設(shè)計,可以用于個人學(xué)習(xí)使用,禁止用于學(xué)術(shù)文檔使用,違者必究!
附件內(nèi)只提供IAR編譯器的CC2530代碼,僅供參考:
CoordinatorEB.zip
(104.4 KB, 下載次數(shù): 32)
2022-5-15 15:30 上傳
點(diǎn)擊文件名下載附件
Zigbee源碼 下載積分: 黑幣 -5
|