82
ArduinoWeb IoT 林信良 [email protected] http://openhome.cc 1

Arduino、Web 到 IoT

Embed Size (px)

Citation preview

Page 1: Arduino、Web 到 IoT

Arduino、Web 到 IoT

林信良 [email protected]

http://openhome.cc 1

Page 2: Arduino、Web 到 IoT

內容

• IoT 與 Arduino

• Arduino 與 Web 伺服器

• 硬體上的網路支援

• 雲端 IoT 服務

2

Page 3: Arduino、Web 到 IoT

IoT 與 Arduino

• IoT

• Internet of Things

• 物聯網

程式

硬體

資料

網路

3

Page 4: Arduino、Web 到 IoT

硬體裝置

通訊協定

資料倉儲

商務邏輯

IoT 組成

4

Page 5: Arduino、Web 到 IoT

硬體裝置

資料的收集、產生

5

Page 6: Arduino、Web 到 IoT

6

Page 8: Arduino、Web 到 IoT

資料倉儲

資料儲存、分析工具與系統

8

Page 9: Arduino、Web 到 IoT

9

Page 10: Arduino、Web 到 IoT

商務邏輯

Domain knowledge? 10

Page 11: Arduino、Web 到 IoT

Arduino

最初是針對不會寫程式,也不懂電子學,沒有任何技術背景的學生而設計,他們是

義大利北部伊夫雷亞(Ivrea)互動設計學院(Interaction Design Institute Ivrea)

的學生,身為Arduino計劃共同開發者之一的Massimo Banzi,曾在〈超越兆赫的

人們〉中提到「我們給了這些學生2到4星期的時間,讓他們製作物理運算的物品,

當時,市售的工具幾乎都是以工程師為對象,所以不管是配件或是跳線、接頭的數

量都很多。這對學生來說,似乎太過複雜,使得學生不知道該如何處置。」為了解

決這些問題,於2005年誕生的就是Arduino!

11

Page 12: Arduino、Web 到 IoT

12

Page 13: Arduino、Web 到 IoT

CO2 感應模組

LCD 顯示模組

原型擴充板

Arduino

溫濕度感應模組

13

Page 14: Arduino、Web 到 IoT

14

Page 16: Arduino、Web 到 IoT

http://www.arduino.cc/en/Main/Products 16

Page 17: Arduino、Web 到 IoT

Arduino 與 Web 伺服器

從 S4A 開始 17

Page 18: Arduino、Web 到 IoT

18

Page 19: Arduino、Web 到 IoT

Web 伺服器

19

Page 20: Arduino、Web 到 IoT

20

Page 21: Arduino、Web 到 IoT

Firmware

USB

21

Page 22: Arduino、Web 到 IoT

Firmware

USB

瀏覽器

代理程式

22

Page 23: Arduino、Web 到 IoT

瀏覽器

網路

23

Page 26: Arduino、Web 到 IoT

Arduino and Python >>> import serial

>>> ser = serial.Serial('/dev/tty.usbserial', 9600)

>>> while True:

... print ser.readline()

'1 Hello world!\r\n'

'2 Hello world!\r\n'

'3 Hello world!\r\n'

>>> import serial # if you have not already done so

>>> ser = serial.Serial('/dev/tty.usbserial', 9600)

>>> ser.write('5')

http://playground.arduino.cc/interfacing/python 26

Page 28: Arduino、Web 到 IoT

硬體上的網路支援

28

Page 29: Arduino、Web 到 IoT

Arduino Ethernet Shield

https://www.arduino.cc/en/Main/ArduinoEthernetShield 29

Page 31: Arduino、Web 到 IoT

有批 Wifi 晶片好便宜,有需要就打這個電話吧

31

Page 32: Arduino、Web 到 IoT

Arduino Yún

32

Page 34: Arduino、Web 到 IoT

34

Page 35: Arduino、Web 到 IoT

arduino.local (必須支援 Bonjour 服務)

35

Page 36: Arduino、Web 到 IoT

36

Page 37: Arduino、Web 到 IoT

無線網卡模式

37

Page 38: Arduino、Web 到 IoT

無線上傳 Sketch

38

Page 39: Arduino、Web 到 IoT

39

Page 40: Arduino、Web 到 IoT

void setup() {

pinMode(13, OUTPUT);

}

void loop() {

digitalWrite(13, HIGH);

delay(1000);

digitalWrite(13, LOW);

delay(1000);

}

40

Page 41: Arduino、Web 到 IoT

41

Page 42: Arduino、Web 到 IoT

#include <Bridge.h>

char state[2];

void setup() {

pinMode(13, OUTPUT);

Bridge.begin();

}

void loop() {

Bridge.get("state", state, 2);

digitalWrite(13, atoi(state));

delay(500);

} 42

Page 43: Arduino、Web 到 IoT

Python 點亮光明燈

43

Page 44: Arduino、Web 到 IoT

44

Page 45: Arduino、Web 到 IoT

import sys

sys.path.insert(0, '/usr/lib/python2.7/bridge/')

from bridgeclient import BridgeClient

state = sys.argv[1]

BridgeClient().put('state', state)

root@arduino:~# python lightUpL13.py 1

root@arduino:~# python lightUpL13.py 0

45

Page 47: Arduino、Web 到 IoT

import sys

import SimpleHTTPServer

import SocketServer

sys.path.insert(0, '/usr/lib/python2.7/bridge/')

from bridgeclient import BridgeClient

class LedRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

def do_GET(self):

if self.path == '/ledOn':

BridgeClient().put('state', '1')

elif self.path == '/ledOff':

BridgeClient().put('state', '0')

self.path = '/led.html'

return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

server = SocketServer.TCPServer(('0.0.0.0', 8000), LedRequestHandler)

server.serve_forever()

47

Page 48: Arduino、Web 到 IoT

led.html

<html>

<head>

<meta content="text/html; charset=UTF-8" http-equiv="content-

type">

<title></title>

</head>

<body>

<p><a href="ledOn">On</a>&nbsp; <a href="ledOff">Off</a></p>

</body>

</html>

48

Page 49: Arduino、Web 到 IoT

YunServer 與 YunClient

#include <Bridge.h>

#include <YunServer.h>

#include <YunClient.h>

YunServer server;

void setup() {

pinMode(13,OUTPUT);

digitalWrite(13, HIGH);

Bridge.begin();

server.listenOnLocalhost();

server.begin();

digitalWrite(13, LOW);

}

49

Page 50: Arduino、Web 到 IoT

void loop() {

YunClient client = server.accept();

if(client) {

process(client);

client.stop();

}

delay(500);

}

void process(YunClient client) {

String command = client.readStringUntil('\r');

if (command == "ledOn") {

digitalWrite(13, HIGH);

}

else if (command == "ledOff") {

digitalWrite(13, LOW);

}

}

50

Page 52: Arduino、Web 到 IoT

雲端 IoT 服務

52

Page 54: Arduino、Web 到 IoT

54

Page 55: Arduino、Web 到 IoT

55

Page 56: Arduino、Web 到 IoT

#include "Bridge.h"

#include "HttpClient.h"

//ThingSpeak Settings

String thingSpeakAPI = "api.thingspeak.com";

String talkBackAPIKey = "IIR7WFDPFM7DSHP9";

String talkBackID = "5129";

const int checkTalkBackInterval = 15 * 1000;

// Variable Setup

long lastConnectionTime = 0;

void setup() {

// Setup On-board LED

pinMode(13, OUTPUT);

digitalWrite(13, LOW);

delay(1000);

digitalWrite(13, HIGH);

delay(1000);

digitalWrite(13, LOW);

Bridge.begin();

}

void loop() {

checkTalkBack();

delay(checkTalkBackInterval);

}

56

Page 57: Arduino、Web 到 IoT

void checkTalkBack() {

HttpClient client;

String talkBackCommand;

char charIn;

String talkBackURL = "http://" + thingSpeakAPI + "/talkbacks/" +

talkBackID + "/commands/execute?api_key=" + talkBackAPIKey;

client.get(talkBackURL);

while (client.available()) {

charIn = client.read();

talkBackCommand += charIn;

}

if (talkBackCommand == “TURN_ON”) {

digitalWrite(13, HIGH);

}

else if (talkBackCommand == “TURN_OFF”) {

digitalWrite(13, LOW);

}

delay(1000);

}

57

Page 58: Arduino、Web 到 IoT

Temboo

58

Page 60: Arduino、Web 到 IoT

60

Page 61: Arduino、Web 到 IoT

61

Page 62: Arduino、Web 到 IoT

/*

IMPORTANT NOTE about TembooAccount.h

TembooAccount.h contains your Temboo account information and must be included

alongside your sketch. To do so, make a new tab in Arduino, call it TembooAccount.h,

and copy this content into it.

*/

#define TEMBOO_ACCOUNT "caterpillar" // Your Temboo account name

#define TEMBOO_APP_KEY_NAME "myFirstApp" // Your Temboo app key name

#define TEMBOO_APP_KEY "e2f55cf1c2524ae59e70a89d3f96f831" // Your Temboo app key

/*

The same TembooAccount.h file settings can be used for all Temboo SDK sketches.

Keeping your account information in a separate file means you can share the

main .ino file without worrying that you forgot to delete your credentials.

*/

TembooAccount.h

62

Page 63: Arduino、Web 到 IoT

#include <Bridge.h>

#include <Temboo.h>

#include "TembooAccount.h" // contains Temboo account information, as described below

int numRuns = 1; // Execution count, so this doesn't run forever

int maxRuns = 10; // Maximum number of times the Choreo should be executed

void setup() {

Serial.begin(9600);

// For debugging, wait until the serial console is connected

delay(4000);

while(!Serial);

Bridge.begin();

}

void loop() {

if (numRuns <= maxRuns) {

Serial.println("Running GetWeatherByAddress - Run #" + String(numRuns++));

TembooChoreo GetWeatherByAddressChoreo;

// Invoke the Temboo client

GetWeatherByAddressChoreo.begin();

// Set Temboo account credentials

GetWeatherByAddressChoreo.setAccountName(TEMBOO_ACCOUNT);

GetWeatherByAddressChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);

GetWeatherByAddressChoreo.setAppKey(TEMBOO_APP_KEY);

// Set Choreo inputs

GetWeatherByAddressChoreo.addInput("Address", "Taipei");

// Identify the Choreo to run

GetWeatherByAddressChoreo.setChoreo("/Library/Yahoo/Weather/GetWeatherByAddress");

// Run the Choreo; when results are available, print them to serial

GetWeatherByAddressChoreo.run();

while(GetWeatherByAddressChoreo.available()) {

char c = GetWeatherByAddressChoreo.read();

Serial.print(c);

}

GetWeatherByAddressChoreo.close();

}

Serial.println("Waiting...");

delay(30000); // wait 30 seconds between GetWeatherByAddress calls

}

透過 USB 連接

TembooAccount.ino

63

Page 64: Arduino、Web 到 IoT

64

Page 65: Arduino、Web 到 IoT

Parse for IoT

65

Page 67: Arduino、Web 到 IoT

67

Page 68: Arduino、Web 到 IoT

草稿碼 → Include Library… → Manage Libraries…

parse

安裝 Parse Arduino SDK

68

Page 69: Arduino、Web 到 IoT

69

Page 70: Arduino、Web 到 IoT

70

Page 71: Arduino、Web 到 IoT

#include <Bridge.h>

String revision = "1.0.2-1_ar71xx";

String location =

"https://raw.githubusercontent.com/ParsePlatform/parse-embedded-

sdks/1.0.2/yun/linux_package/";

void downloadPackage(String file) {

Serial.println("Download: " + location + file + revision + ".ipk");

Process p;

p.begin("curl");

p.addParameter("--stderr");

p.addParameter("-");

p.addParameter("-#");

p.addParameter("-s");

p.addParameter("-S");

p.addParameter("-k");

p.addParameter("-o");

p.addParameter("/tmp/" + file + revision + ".ipk");

p.addParameter(location + file + revision + ".ipk");

p.run();

while (p.available()) {

Serial.print((char)p.read());

}

}

71

Page 72: Arduino、Web 到 IoT

void installPackage(String file) {

Serial.println("Install: /tmp/" + file + revision + ".ipk");

Process p;

p.begin("opkg");

p.addParameter("install");

p.addParameter("--force-reinstall");

p.addParameter("--force-downgrade");

p.addParameter("/tmp/" + file + revision + ".ipk");

p.run();

while(p.available()) {

Serial.print((char)p.read());

}

}

void setup() {

Bridge.begin();

Serial.begin(115200);

while(!Serial);

Serial.println("Downloading packages");

downloadPackage("parse-embedded_");

downloadPackage("parse-embedded-yun_");

Serial.println("Installing packages");

installPackage("parse-embedded_");

installPackage("parse-embedded-yun_");

Serial.println("\nDone.");

} 72

Page 73: Arduino、Web 到 IoT

73

Page 74: Arduino、Web 到 IoT

儲存物件

#include <Bridge.h>

#include <Parse.h>

void setup() {

// Initialize digital pin 13 as an output.

pinMode(13, OUTPUT);

// Initialize Bridge

Bridge.begin();

// Initialize Serial

Serial.begin(9600);

while (!Serial); // wait for a serial connection

Serial.println("Parse Starter Project");

// Initialize Parse

Parse.begin("dOpHkBs6A2XOToydYC7r7r1BmFxCgd6nU7JQ85Fw",

"BGyFLJuHJvje0LB6Ms9ZN30Mh1DfoKE43V3bq3FN");

74

Page 75: Arduino、Web 到 IoT

ParseObjectCreate create;

create.setClassName("TestObject");

create.add("foo", "bar");

ParseResponse response = create.send();

Serial.println("\nResponse for saving a TestObject:");

Serial.print(response.getJSONBody());

if (!response.getErrorCode()) {

String objectId = response.getString("objectId");

Serial.print("Test object id:");

Serial.println(objectId);

} else {

Serial.println("Failed to save the object");

}

response.close(); // Do not forget to free the resource

}

75

Page 76: Arduino、Web 到 IoT

76

Page 77: Arduino、Web 到 IoT

Push 通知 #include <Bridge.h>

#include <Parse.h>

void setup() {

pinMode(13, OUTPUT);

Bridge.begin();

Serial.begin(9600);

while (!Serial);

Serial.println("Parse Starter Project");

Parse.begin("dOpHkBs6A2XOToydYC7r7r1BmFxCgd6nU7JQ85Fw",

"BGyFLJuHJvje0LB6Ms9ZN30Mh1DfoKE43V3bq3FN");

// Start push service

Parse.startPushService();

Serial.print("Push Installation ID:");

Serial.println(Parse.getInstallationId());

}

77

Page 78: Arduino、Web 到 IoT

void loop() {

// Check if there is a new push

// A push with message {"alert":"A test push from Parse!"}

// will turn on LED for 3 seconds

if (Parse.pushAvailable()) {

ParsePush push = Parse.nextPush();

String message = push.getJSONBody();

Serial.print("New push message size: ");

Serial.println(message.length());

Serial.print("New push message content: ");

Serial.println(message);

String command = push.getString("alert");

if (command == "A test push from Parse!") {

digitalWrite(13, HIGH); // turn on LED

delay(3000); // wait 3 seconds

digitalWrite(13, LOW); // turn off LED

}

// NOTE: ensure to close current push message

// otherwise next push won't be available

push.close();

}

}

78

Page 79: Arduino、Web 到 IoT

79

Page 80: Arduino、Web 到 IoT

80

Page 82: Arduino、Web 到 IoT

Orz 林信良 [email protected]

http://openhome.cc 82