嘗試使用Bridge程式庫的Mailbox類別,接收從瀏覽器以RES API(網址/mailbox)傳入的訊息。
程式碼如下:
#include <Mailbox.h>
void setup(){
Serial.begin(57600);
while(!Serial){
}
Serial.print("Starting Bridge...");
Bridge.begin();
Serial.println("done.");
Serial.print("Starting Mailbox...");
Mailbox.begin();
Serial.println("done.");
}
String msg_send;
void loop(){
if(Mailbox.messageAvailable()){
String msg;
Mailbox.readMessage(msg);
Serial.println(msg);
}
while(Serial.available()){
char c = Serial.read();
if(c != '\n'){
msg_send += c;
}
else{
Mailbox.writeMessage(msg_send);
msg_send = "";
}
}
}
這支草稿碼可接收/傳送Mailbox訊息。燒錄後,開啟序列埠監控視窗,可看到:
Starting Bridge...done.
Starting Mailbox...done.
然後開啟瀏覽器,輸入網址「http://arduino.local/mailbox/helloworld」,請把arduino.local換成你的Yun的IP位址;這麼做會把訊息「helloworld」傳給Yun,而我們的草稿碼使用Mailbox進行接收,並顯示在序列埠監控視窗:
helloworld
Mailbox的REST API語法是:
http://arduino.local/mailbox/MESSAGE:會把訊息MESSAGE傳給Yun。
另外,若在序列埠監控視窗輸入東西(記得把右下角的換行字元改成NL),則會從ATmega32U4端傳訊息給Linux端,然後你可在Linux端撰寫Python程式接收訊息,譬如:
import socket
import json
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 5700))
while True:
result = json.loads(s.recv(1024))
print(result)
s.close()
命名檔案為mailbox_r.py,然後執行,並在序列埠監控視窗輸入「hello」與「123789」,可看到如下:
root@ArduinoYun:~# python mailbox_r.py
{u'request': u'raw', u'data': u'hello'}
{u'request': u'raw', u'data': u'123789'}
參考資料:
No comments:
Post a Comment