網(wǎng)絡(luò)控制就轧,就是通過前端頁面點擊控制按鈕嗜价,然后通過ajax來出發(fā)后端函數(shù)將命令存入數(shù)據(jù)庫,然后后端TCP服務(wù)端將命令從數(shù)據(jù)庫取出默怨,發(fā)送給單片機讯榕。當(dāng)然只是簡單的一個命令實現(xiàn)。
代碼地址:https://github.com/klren0312/stm32_wifi
2017.5.1
搭建簡易的物聯(lián)網(wǎng)服務(wù)端和客戶端目錄
網(wǎng)絡(luò)控制
1.建立一個存儲命令的表
(1)比如staus表
2.編寫express接口
提供給前端按鈕通過AJAX觸發(fā)
(1)當(dāng)觸發(fā)/buttonclick1,則將命令1存入數(shù)據(jù)庫;
當(dāng)觸發(fā)/buttonclick0,則將命令0存入數(shù)據(jù)庫愚屁。
//按鈕api
app.get('/buttonclick1',function(req,res){
//增加
var post = {status:1};
conn.query('INSERT INTO status SET ?', post ,function(error,result,fields){
if(error) throw error;
});
res.send("1");
res.end();// 如果不執(zhí)行end(), 那么前端網(wǎng)頁則會一直等待response
})
app.get('/buttonclick0',function(req,res){
//增加
var post = {status:0};
conn.query('INSERT INTO status SET ?', post ,function(error,result,fields){
if(error) throw error;
});
res.send("0");
res.end();// 如果不執(zhí)行end(), 那么前端網(wǎng)頁則會一直等待response
})
3.編寫前端按鈕
(1)HTML
就兩個button济竹,一個開,一個關(guān)
<button onclick="buttonclk1()">開啟</button>
<button onclick="buttonclk0()">關(guān)閉</button>
(2)javascript
ajax觸發(fā)霎槐,使用fetch
function status(response){
if(response.status>=200 && response.status<300){
return Promise.resolve(response);
}else{
return Promise.reject(new Error(response.statusText));
}
}
function json(response){
return response.json();
}
//開啟按鈕觸發(fā)函數(shù)
function buttonclk1(){
fetch("http://127.0.0.1:3000/buttonclick1")//后端提供的buttonclick1接口
.then(status)
.then(json)
.then(function(data){
console.log("請求成功送浊,JSON解析后的響應(yīng)數(shù)據(jù)為:",data);
})
.catch(function(err){
console.log("Fetch錯誤:"+err);
});
}
//關(guān)閉按鈕觸發(fā)函數(shù)
function buttonclk0(){
fetch("http://127.0.0.1:3000/buttonclick0")///后端提供的buttonclick0接口
.then(status)
.then(json)
.then(function(data){ console.log("請求成功,JSON解析后的響應(yīng)數(shù)據(jù)為:",data);
})
.catch(function(err){
console.log("Fetch錯誤:"+err);
});
}
(3)點擊觸發(fā)結(jié)果
4.TCP服務(wù)端
在和單片機建立通信后丘跌,就會一直從數(shù)據(jù)庫獲取最新的命令袭景,然后發(fā)送給單片機。
(1)代碼
將其寫入socket.on內(nèi)
conn.query('SELECT * FROM status',function(err,rows,fields){
if (err) throw err;
socket.write(rows[rows.length-1].status+"");//必須要字符串才能發(fā)闭树,用toString()報錯耸棒,有人知道為啥嗎?
})
5.STM32代碼
當(dāng)然還是基于onenet的代碼报辱,感謝中移物聯(lián)与殃,代碼寫的很易讀!具體只放處理數(shù)據(jù)的代碼碍现。
(1)處理數(shù)據(jù),控制LED的開關(guān)
void Net_Event(unsigned char *dataPtr){
if(strstr((char *)dataPtr, "1"))
{
UsartPrintf(USART_DEBUG, "?a\r\n");
Led4_Set(LED_ON);
}
else if(strstr((char *)dataPtr,"0")){
UsartPrintf(USART_DEBUG,"1?\r\n");
Led4_Set(LED_OFF);
}
}
6.串口截圖
@治電小白菜20170501