Você está na página 1de 77

Programming the Internet of Things Using

Node.js* and HTML5


Michael McCool – Principal Engineer, Intel K.K. (Japan)
Geoff Lowney – Intel Fellow, Intel Corporation
Ramesh Peri – Principal Engineer, Intel Corporation

SFTL001
Agenda
• Internet of Things
• Building a Thing
• Program the Thing
• Control the Thing’s Hardware
Break
• Networking the Thing
• Talk to a Service
• Summary and Conclusion
• Do your Own Thing

2
Agenda
• Internet of Things
• Building a Thing
• Program the Thing
• Control the Thing’s Hardware
Break
• Networking the Thing
• Talk to a Service
• Summary and Conclusion
• Do your Own Thing

3
The Internet of Things is…
Internet of
Things

Personal Internet Mobile


Computing Computing

1975 1985 1995 2005 2015

The Next Compute Transformation


4
Basically…
Things… …on the Internet.
• Devices with embedded computers • Communicating globally
• Often without displays • Variety of networking protocols
• Reading physical sensors • Interface to existing infrastructure
• Controlling physical actuators • Autonomous operation modes
• Limited power, memory, compute • Coordinated operation modes

5
Basically…
Things… …on the Internet.
• Devices with embedded computers • Communicating globally
• Often without displays • Variety of networking protocols
• Reading physical sensors • Interface to existing infrastructure
• Controlling physical actuators • Autonomous operation modes
• Limited power, memory, compute • Coordinated operation modes

Think “system”, not “device”


6
IoT: Examples and Use Cases
Industrial and Municipal Consumer and Mobile
• Factory equipment monitoring • Health monitoring (wearable)
• HVAC system monitoring and • Information access (wearable)
control • Home security
• Lighting systems • Delivery management
• Security • Automotive monitoring
• Maintenance (wearable)
• Family status monitoring (wearable)
• Point of Sale
• Home maintenance
• Inventory tracking
• Personal communication (wearable)
• Precision agriculture
• Energy consumption management
• Energy consumption management

7
Internet of Things (IoT) Systems

Endpoint

Endpoint Gateway

Wired Analysis
Wi-Fi*
Gateway (Server)

LTE
Human
Interface
Prototypical Example: Smart Light
Starting point: Using only JavaScript* (in the form of both
Node.js* and HTML5) we’ll be building a “smart light” as a
prototypical IoT system…

9
Demo!
Demo of working smart
light system that we will
be building…

10
Why JavaScript* for IoT?
JavaScript* is in wide use
• Large numbers of web developers are familiar with it
• Well-documented with a strong ecosystem
• Already standardized and with multiple implementations

JavaScript is consistent with web programming and portable mobile apps


• It is used by HTML5, and HTML5 is useful for developing UI “companion apps” for Internet of Things devices

JavaScript is well-suited to embedded device programming


• Supports asynchronous function calls and I/O
• Asynchronous calls are useful for event-driven hardware programming
• The Node.js* engine in particular has many useful features for both web services and embedded devices

JavaScript engines are high-performance


• Chrome* V8 is nearly as fast as C/C++! Fastest “high-productivity” language available.
• Recent developments, such as SIMD.js, even expose high-performance computation features

11
Why Node.js* for IoT?
Strong ecosystem and package management system
• Thousands (74K+) of packages available via the npm package manager
Programming model well-suited to embedded devices as well as servers
• Event-driven asynchronous programming model, support for asynchronous functions
• Lack of explicit event loop means transparent power state management can be implemented
• Good support for interfacing to native C libraries
Community is already using Node.js* for embedded device control
• For example: http://nodebots.io/, Firmata, JohnnyFive, JSrobotics, …
Web services can also be built with Node.js
• A complete end-to-end endpoint/gateway/mobile/browser/server Internet of Things solution is
possible
Good documentation
• Both online and in book form, although mostly focused on web services

12
Node.js* vs. HTML5 JavaScript*
Node.js* JavaScript* Browser (HTML5) JavaScript
JavaScript with bindings to C/C++ JavaScript with bindings to an HTML5
libraries and OS services document/view
• Designed for “Server side” • Designed for “Client side”
- Headless (no UI by default) - Generate and control a UI
• Asynchronous and event-driven - Alter HTML5 document content
- Nonblocking asynchronous I/O - Control a browser (open panes, etc.)
• C++ Bindings (can call C++ libs) • Communicates asynchronously using http
• Communicate over variety of protocols • Limited/semi-standardized hardware support
- Including but not limited to http - Depends on platform/browser
• No built-in sandbox; focus on functionality - Ex: webcam, accelerometer, GPS

• Community driven module repository • Sandboxed; focus on security


- Wide variety of modules available, including support - Specific set of standardized built-in libraries
for parallelism, computer vision, etc. - Other JavaScript-only libraries can be downloaded
- Automated download and install via http dynamically
- Modules can include native components

13
JavaScript* for IoT Servers

Interface
Devices
Developer View Cloud
Services

HTML5
Use HTML5 to create UI to
IoT devices.

Embedded
Devices
• Edit Node.js* app
• Send app to device
• Run app remotely
• Remote debug
Node.js
Intel® XDK IoT Edition Use Node.js to define
Development System behavior of IoT devices.

14
Intel® XDK IoT Edition – HTML5 Application Development

15
Intel® XDK IoT Edition – Node.js* Application Development

•Full featured
code editor

•NPM package
fetching

•Remote
execution and
debugging

16
Agenda
• Internet of Things
• Building a Thing
• Program the Thing
• Control the Thing’s Hardware
Break
• Networking the Thing
• Talk to a Service
• Summary and Conclusion
• Do your Own Thing

17
Hardware Kit
Intel® Galileo Gen 2 Development Board
• Intel® Quark™ processor X1000
• Arduino* compatible hardware interfaces
• Yocto* Linux* based Intel® IoT
Development Kit software
- On micro SD card

• 12V power supply


Seeed* Studio Grove Starter Kit Plus
• Intel® IoT Edition
• Base shield and collection of useful
modules
• Cables: USB, Network, Serial
18
Intel® Galileo Gen 2 Development Kit
• 12V 1.5A power
supply included
• Note: You cannot
power the Intel®
Galileo Gen 2 board
off USB

19
Seeed* Grove Starter Kit Plus Contents
• Set of useful Seeed
Grove modules with
base shield
• Micro USB-B to USB-
A cable
• RJ45 network cable
• FDTI USB-to-serial
cable

20
Build It!
Switching to video…

21
Final Assembly
• Moved picture up • Seeed* Grove shield attached
• Added bullets
• Push button on D2
• LED on D3
• Light sensor on A0
• Rotation sensor on A1
• Micro SD card inserted
• Serial cable attached
- Black towards GND

• 12V power connected


• Network cable, USB, and serial
cables to computer
22
Agenda
• Internet of Things
• Building a Thing
• Program the Thing
• Control the Thing’s Hardware
Break
• Networking the Thing
• Talk to a Service
• Summary and Conclusion
• Do your Own Thing

23
Intro to JavaScript* Objects and associative arrays are the same
C-like syntax, but “;” are optional
dog['ear'] = 'up';
Strings dog.ear = 'up';
'this is a string' Object prototypes cloned with “new” operator
"so is this"
dog = new Dog();
Declaring a variable
Functions are values. The ‘this’ variable can be
var my_variable; used to refer to current object
Points to note: dog.raise_ear = function() {
• Types are dynamic, all numbers are this.ear = 'up';
floats };

• Scope is function, not block JSON-like syntax for object properties

• Scope is generally static, except for ‘this’ dog = {


ear: 'up';
raise_ear: function (…) {…};
24 }
Intro to Node.js*
High-performance, Chrome* V8-based JavaScript* “engine” with:
• Good system interfacing, with an emphasis on asynchronous functions
• Basic server functionality, with an architecture capable of scaling to thousands
of requests
• Event-based programming model supporting both pub/sub notifications and
timing
• Package manager (npm) capable of supporting both JavaScript and native
modules loadable over the internet
• Extensive set (74K+) of publically-available modules for a wide range of
functionality

25
Agenda
• Internet of Things
• Building a Thing
• Program the Thing
• Control the Thing’s Hardware
Break
• Networking the Thing
• Talk to a Service
• Summary and Conclusion
• Do your Own Thing

26
Embedded Hardware Interfaces
GPIO: General-purpose digital I/O. I2C: Two-wire (clock and data) half-
Can read or write 0’s or 1’s. Need to duplex serial interface using a shared
set direction (input or output). bus. Devices on the bus have fixed
address and a set of registers that can
Analog: Input. Senses a voltage
be read or written. Each device has its
between 0 and reference value
own registers and interface
(usually the power supply value).
specification. Speed:100KHz and
PWM: Pulse-width modulation output. 400KHz.
Rapidly switches between 0 and the
SPI: 3 or 4-wire (clock, Tx and Rx data,
power supply value. If averaged,
chip select) full-duplex serial interface.
approximates an analog output.
Higher performance than I2C (up to
Can also be used (if set to the right
25MHz) but more complex wiring.
frequency) to control RC servos.

27
Embedded Hardware Interfaces
GPIO: General-purpose digital I/O. I2C: Two-wire (clock and data) half-
Can read or write 0’s or 1’s. Need to duplex serial interface using a shared
set direction (input or output). bus. Devices on the bus have fixed
address and a set of registers that can
Analog: Input. Senses a voltage
be read or written. Each device has its
between 0 and reference value
own registers and interface
(usually the power supply value).
specification. Speed:100KHz and
PWM: Pulse-width modulation output. 400KHz.
Rapidly switches between 0 and the
SPI: 3 or 4-wire (clock, Tx and Rx data,
power supply value. If averaged,
chip select) full-duplex serial interface.
approximates an analog output.
Higher performance than I2C (up to
Can also be used (if set to the right
25MHz) but more complex wiring.
frequency) to control RC servos.

28
Hardware Interface Libraries in Node.js*
Intel-Developed Third Party
mraa: Open source library for Intel® Galileo johnny-five: Open source I/O library with
and Intel® Edison boards. Low-level access plugins for various boards including Intel
to GPIOs, PWM, and Analog IO ports. Galileo boards (Gen 2 support is in the works).
Developed by Intel Developer Relations. The Intel Galileo board uses direct interfacing
rather than going through Firmata when using
upm: Open source, high level library for the galileo-io adapter module.
specific sensors and actuators that use mraa.
Developed by Intel Developer Relations. onoff: Open source I/O library that can be
used to manipulate ‘raw’ GPIO/PWM via sysfs
iot-io: Open source library for Intel interface.
Galileo/Edison boards. Uses an API similar to
the Arduino* API. Also provides remote i2c: Node.js* I2C library using sysfs.
access via RPC. Developed by Intel Labs
China. Note: Using sysfs requires understanding the
mapping from CPU GPIO pins to board GPIO
pins.
29
Hardware Interface Libraries in Node.js*
Intel-Developed Third Party
mraa: Open source library for Intel® Galileo johnny-five: Open source I/O library with
and Intel® Edison boards. Low-level access plugins for various boards including Intel
to GPIOs, PWM, and Analog IO ports. Galileo boards (Gen 2 support is in the works).
Developed by Intel Developer Relations. The Intel Galileo board uses direct interfacing
rather than going through Firmata when using
upm: Open source, high level library for the galileo-io adapter module.
specific sensors and actuators that use mraa.
Developed by Intel Developer Relations. onoff: Open source I/O library that can be
used to manipulate ‘raw’ GPIO/PWM via sysfs
iot-io: Open source library for Intel interface.
Galileo/Edison boards. Uses an API similar to
the Arduino* API. Also provides remote i2c: Node.js* I2C library using sysfs.
access via RPC. Developed by Intel Labs
China. Note: Using sysfs requires understanding the
mapping from CPU GPIO pins to board GPIO
pins.
30
MRAA Setup
var mraa = require("mraa"); Load the module

var button = new mraa.Gpio(2); Enable GPIO 2 (D2)


button.dir(mraa.DIR_IN); Put it into input mode

var led = new mraa.Pwm(3); Configure PWM output on D3


led.period(1); Set period to 1ms
led.enable(true); Turn on PWM output

var knob = new mraa.Aio(1); Enable Analog input on A1

31
MRAA Hello World
setInterval(function() { Do something periodically
var push = button.read(); Read state of button
if (push) { If the button is pressed
led.write( Read the knob state and write it to
knob.read()/4096 the LED
);
}
}, 100); // every 0.1s (100ms) Repeat every 0.1s (100ms)

32
Assignment 1 (5 Minutes)
setInterval(function() { This code really just updates the state
var push = button.read(); of the LED based on the knob when
if (push) { the button is pushed, and ignores it
led.write( otherwise.
knob.read()/4096
); The button does not actually turn the
} light on and off.
}, 100); // every 0.1s (100ms) Modify this part of the code so that the
light is only on when the button is
pressed.

33
Assignment 1: Solution
setInterval(function() { Do something periodically
var push = button.read(); Read state of button
if (push) { If the button is pressed
led.write( Read the knob state and write it to
knob.read()/4096 the LED
);
} else { Otherwise
led.write( 0 ); Turn off the light
}
}, 100); // every 0.1s (100ms) Repeat every 0.1s (100ms)

34
Assignment 2 (5 Minutes)
setInterval(function() { We don’t actually want to hold the
var push = button.read(); button down all the time.
if (push) {
led.write( Modify this code further so the button
knob.read()/4096 toggles the light state on and off.
);
} else {
led.write( 0 );
}
}, 100); // every 0.1s (100ms)

35
Assignment 2: Solution
var light_on = false; Keep track of light power-on state
var push_last = button.read(); Keep track of last button push state
setInterval(function() { Do something periodically
var push = button.read(); Read state of button
if (push && !push_last) { If the button is pressed
light_on = !light_on; Toggle the light power state
}
push_last = push;
if (light_on) { If the light power state is true
led.write( Read the knob state and write it to
knob.read()/4096 the LED
);
} else { Otherwise
led.write( 0 ); Turn off the light
}
}, 100); // every 0.1s (100ms) Repeat every 0.1s (100ms)
36
Summary: Controlling the Thing’s Hardware
• Have reviewed hardware interfaces for GPIOs, PWMs, and Analog Inputs
• Have shown how to control these types of interfaces from MRAA
• Have implemented a program that gives thing a useful default behavior:
- Turn on and off a light when a button is pressed
- Modulate intensity with knob
- Modulate intensity based on ambient light

• Have edited and loaded code with the Intel® XDK


- Lets us debug the code
- Makes code persistent (when board reboots it will be run automatically)

37
Agenda
• Internet of Things
• Building a Thing
• Program the Thing
• Control the Thing’s Hardware
Break
• Networking the Thing
• Talk to a Service
• Summary and Conclusion
• Do your Own Thing

38
Agenda
• Internet of Things
• Building a Thing
• Program the Thing
• Control the Thing’s Hardware
Break
• Networking the Thing
• Talk to a Service
• Summary and Conclusion
• Do your Own Thing

39
Communication
Physical:
UART: Serial communication
Wireless: Bluetooth®, Zigbee*, Wi-Fi*
Protocols: TCP, UDP
Modules:
net: TCP sockets
http: web protocols
socket.io, shoe: websockets
dnode: remote procedure calls
mqtt: status and configuration

40
Communication
Physical:
UART: Serial communication
Wireless: Bluetooth®, Zigbee*, Wi-Fi*
Protocols: TCP, UDP
Modules:
net: TCP sockets
http: web protocols
socket.io, shoe: websockets
dnode: remote procedure calls
mqtt: status and configuration

41
Interfaces for Things
• Things don’t often have displays
• But IoT devices do have network
connections (by definition)
• Users can be assumed to have web
browsers and smartphones
• HTML5 can be used to build portable
graphical user interfaces
- Can be installable apps
- Can be served directly from thing
- Can be served by cloud service
- Can run on smartphones or tablets
- Can run in browsers on computers
42
Letting a Thing Serve its Own Interface
• In some cases, if only a few users will
ever connect to a device, it can make
sense for a device to serve its own
HTML5 interface
• This example also shows how to use
dnode and websockets to export a
RPC API to an HTML page
• The RPC API can even have callbacks,
giving very general communication
between code in the HTML5 and on
the thing

43
System Architecture

http request

Browser IoT Device

43
44
System Architecture

http request

http response (JS + html)


Browser IoT Device

44
45
System Architecture

http request

http response (JS + html)


Browser IoT Device
Web socket/RPC API request

45
46
System Architecture

http request

http response (JS + html)


Browser IoT Device
Web socket/RPC API request

RPC
RPC
APIAPI
connection
connection

46
47
Basic HTML5 Template for Smart Light UI
<!doctype html>
Simplified doctype for HTML5.
<html>
<head>
<title>Light</title>
<script src="jquery.js">
</script> We’ll use jQuery to get handles on
</head> objects.
<body>
<img src="images/off.jpg" This image is set by default to a light
id="light_button"> bulb in the “off” state, but we give it an
</img> id so we can manipulate it later.
<script src="bundle.js"> The “bundle.js” script will be created
</script> with “browserify” from Node.js code
</body> and will contain our application logic.
</html>
48
47
Client Script (client.js)
var dnode = require("dnode"); Get some modules. We will
var shoe = require("shoe"); use the “browserify” Node.js
app to package these for the
browser.

var sock = shoe("/api"); Connect to server websocket.

49
Client Script (client.js)
var light_button = $('#light_button'); Use jQuery to get handles
on appropriate UI
elements.
function set_light_state(err,state) {
Define helper function to
if (state) {
manage light images.
console.log("turning light on");
light_button.attr("src","images/on.jpg");
} else {
console.log("turning light off");
light_button.attr("src","images/off.jpg");
}
}

50
Client Script (client.js)
var dn = dnode(); Get RPC API and when
web page is loaded…
dn.on("remote", function (remote) {
light_button.click(function() Set up action to take
remote.toggle(function(err,state) { when image is clicked.
set_light_state(err,state);
});
});
remote.light_state(function(err,state) {
set_light_state(err,state); Set up notifier
}); callback functions to
remote.set_notify_light(set_light_state); update light state.
});
sock.pipe(dn).pipe(sock); Connect dnode RPC
server to web socket.
51
Client Script (client.js)
var dn = dnode(); Get RPC API and when
web page is loaded…
dn.on("remote", function (remote) {
light_button.click(function() Set up action to take
remote.toggle(function(err,state) { when image is clicked.
set_light_state(err,state);
});
});
remote.light_state(function(err,state) {
set_light_state(err,state); Set up notifier
}); callback functions to
remote.set_notify_light(set_light_state); update light state.
});
sock.pipe(dn).pipe(sock); Connect dnode RPC
server to web socket.
52
Client Script (client.js)
var dn = dnode(); Get RPC API and when
web page is loaded…
dn.on("remote", function (remote) {
light_button.click(function() Set up action to take
remote.toggle(function(err,state) { when image is clicked.
set_light_state(err,state);
});
});
remote.light_state(function(err,state) {
set_light_state(err,state); Set up notifier
}); callback functions to
remote.set_notify_light(set_light_state); update light state.
});
sock.pipe(dn).pipe(sock); Connect dnode RPC
server to web socket.
53
Thing Behavior and Server Script (main.js)
var http = require("http"); Basic web server
var dnode = require("dnode"); RPC service
var shoe = require("shoe"); Web socket wrapper/emulator
var ecstatic = Serve static resources to client
require("ecstatic")
(__dirname);
Callback to notify client of changes in
var notify_light = null;
state; “null” value means it has not
been initialized by client yet.

54
53
Thing Behavior and Server Script (main.js)
var api = { Specify the API interfaces.
toggle: function(cb) { Toggle light state, then return current
light_on = !light_on; state in a callback.
cb(null, light_on);
},
state: function(cb) { Read the current value of the light
cb(null, light_on); without changing it.
},
set_notify: function(cb) {
notify_light = cb; Register a callback to call if state
} changes.
};

55
54
Thing Behavior and Server Script (main.js)
var serv = Start up a simple static web
http.createServer(ecstatic); server.
serv.listen( Listen to a test port (note we
process.env.PORT || 8080); use port 8080 rather than the
standard 80).

var sock = shoe( Start up a web socket server


function (stream) { and install the RPC API on it
var d = dnode(api); using dnode.
stream.pipe(d).pipe(stream);
});
sock.install(serv, "/api");

56
55
Thing Behavior and Server Script (main.js)
var mraa = require("mraa"); Same as previous example…

var button = new mraa.Gpio(2);


button.dir(mraa.DIR_IN);

var led = new mraa.Pwm(3);


led.period(1);
led.enable(true);
var light = new mraa.Aio(0);
var knob = new mraa.Aio(1);
var light_on = false;
var last_push = button.read()

57
56
Thing Behavior and Server Script (main.js)
setInterval(function() { A slight change here.
var push = button.read();
if (push && !last_push) { Can you spot it?
light_on = !light_on;
if (null != notify_light) {
notify_light(null,light_on);
}
}
last_push = push;
if (light_on) {
led.write((knob.read()/4096) * (light.read()/4096));
} else {
led.write( 0 );
}
}, 100);
58
57
Thing Behavior and Server Script (main.js)
setInterval(function() { Call non-null notifier callback
var push = button.read(); when state changes.
if (push && !last_push) {
light_on = !light_on;
if (notify_light) {
notify_light(null,light_on);
}
}
last_push = push;
if (light_on) {
led.write((knob.read()/4096) * (light.read()/4096));
} else {
led.write( 0 );
}
}, 100);
59
58
Agenda
• Internet of Things
• Building a Thing
• Program the Thing
• Control the Thing’s Hardware
Break
• Networking the Thing
• Talk to a Service
• Summary and Conclusion
• Do your Own Thing

60
Prototypical Example: Smart Light
Starting point: Using only JavaScript* (in the form of both
Node.js* and HTML5) we’ll be building a “smart light” as a
prototypical IoT system…

61
Web Services
Server (using Express) Client (using Request)
// Create Express application object // Get the “request” client
var express = require('express'); var request = require('request');
var app = express();
// Make a request to a web server
// Return some dynamic content request('http://192.168.0.3/time.txt:8080',
var time = require('time'); function (error, response, body) {
app.get('/time.txt', function(req, res){ if (!error && response.statusCode == 200) {
var now = time.Date(); console.log(body) // Print the time
res.send('The time is ‘ }
+now.getHours() });
+':‘
+now.getMinutes());
});

// Start listening for connections


var server = app.listen(8080,
function() {
console.log('Listening on port %d',
server.address().port);
});
62
MQTT Server using Mosca and MongoDB*
var mosca = require('mosca') server.on('ready', setup);
// Called when server is ready
var ascoltatore = { function setup() {
// Using ascoltatore backend console.log('Mosca is up');
type: 'mongo', }
url:
'mongodb://localhost:27017/mqtt', // Called when client connects
pubsubCollection: server.on('clientConnected',
'ascoltatori', function(client) {
mongo: {} console.log('client connected',
}; client.id);
});
var settings = {
port: 1883, // Called when message is received
backend: ascoltatore server.on('published',
}; function(packet, client) {
console.log('Published', I
var server = new mosca.Server(settings); packet.payload);
I });
63
MQTT Client Communications
Publish Subscribe
var mqtt = require('mqtt');
var mqtt = require('mqtt');
// Create an MQTT client (here using static IP of server)
// Create an MQTT client (here using static IP of server) client = mqtt.createClient(1883,
client = mqtt.createClient(1883, ‘192.168.0.2');
‘192.168.0.2');
// Indicate what topics we care about
// Publish a message client.subscribe('presence');
client.publish('presence', 'Hello mqtt');

// Respond to message on subscribed topic(s)


client.on('message',
function (topic, message) {
console.log(topic,": ",message);
}
);

// Exit after 10s whether or not we get a message


setTimeout(function() {
client.end();
},10000)
64
Extend Light…
Publish Subscribe
var mqtt = require('mqtt') var mqtt = require('mqtt')

// Create an MQTT client // Create an MQTT client


client = mqtt.createClient(1883, client = mqtt.createClient(1883,
‘192.168.0.2'); ‘192.168.0.2');

// Get my hostname // Indicate what topics we care about (anything about any light)
var os = require("os"); client.subscribe(‘light/#');
var hn = os.hostname();
// Respond to any messages on subscribed topic(s)
// Check knob periodically, publish state when it changes client.on('message',
var knob_state = knob.read()/4096.0; function (topic, message) {
setInterval(function() { console.log(topic,": ",message);
var new_knob_state = knob.read()/4096.0; }
if (new_knob_state != knob_state) { );
knob_state = new_knob_state;
client.publish(‘light/’ + hn + ‘/knob', // Hang around until killed
knob_state); setInterval(function() {
} console.log(“still listening”);
},100); },10000)

65
Agenda
• Internet of Things
• Building a Thing
• Program the Thing
• Control the Thing’s Hardware
Break
• Networking the Thing
• Talk to a Service
• Summary and Conclusion
• Do your Own Thing

66
Summary
• The Internet of Things combines internet and embedded programming
• Embedded things also need to interface with mobile devices and services
• Mobile devices can act as user interfaces to things
• One language can be used to program all of these: JavaScript*
• JavaScript is used in both Node.js* (services, things) and HTML5 (devices)
• A variety of libraries are available for hardware interfacing
• A variety of mechanisms and libraries are available for communication
• Things can talk to web services and even provide their own services
• The Intel® XDK IoT Edition provides a convenient way to program and
debug both mobile devices using HTML5 and things using Node.js

67
Call to Action
What have you done?
• You have seen how to build a complete Internet of Things system
- Not just a single thing, but a thing talking to other devices and services
- You have done this all using a single programming language, JavaScript*
• This programming model is a power tool that can scale to thousands of devices
What can you do?
Pretty much anything....
• Home automation and security systems
• Smart devices to manage energy or monitor the environment
• Swarms of robot minions helpers to do your bidding…
So go do it…

68
Additional Sources of Information
Intel® IoT Dev Kit: https://software.intel.com/en-us/blogs/2014/04/07/getting-
started-with-the-intel-galileo-development-kit

Additional Seeed* Grove sensors: http://www.seeedstudio.com/wiki/GROVE_System

Node.js* home page: http://nodejs.org/

Other Node.js packages (over 74K+ to choose from…): https://www.npmjs.org/

List of further reading: http://stackoverflow.com/questions/2353818/how-do-i-get-


started-with-node-js

Other references used in the preparation of these notes: next page

69
References
1. Marc Wandschneider, Learning Node.js: A Hands-on Blogs and articles:
Guide to Building Web Applications in JavaScript,
Addison-Wesley 2013 http://ejohn.org/blog/node-js-stream-
2. David Mark Clements, Node Cookbook, Packt playground/
Publishing 2012

3. Sandro Pasquali, Mastering Node.js, Packt Publishing http://nodestreams.com/


2013

4. Brad Dayley, Node.js, MongoDB, and AngularJS Web


Development, Addison-Wesley 2014
http://tableflip.io/building-a-dnode-
rpc-server-in-50-lines-of-code
5. Jim R. Wilson, Node.js the Right Way: Practical,
Server-Side JavaScript that Scales, The Pragmatic
Programmers 2013

6. Colin J. Ihrig, Pro Node.js for Developers, Apress 2013

7. Pedro Teixeira, Professional Node.js: Building


JavaScript Based Scalable Software, Wrox 2013

70
Agenda
• Internet of Things
• Building a Thing
• Program the Thing
• Control the Thing’s Hardware
Break
• Talking to the Thing
• Give the Thing an Interface
• Talk to a Service
• Summary and Conclusion
• Do your Own Thing

71
Do Your Own Thing: Make-a-Thing-a-Thon!
1. The Lab will remain open until 6:00, and instructors will remain and assist
2. Make an interesting thing of your own design using the parts in your kit;
team up with other people to make a distributed app if you want!
3. Program your thing in Node.js*
4. Program services and interfaces as appropriate – server accounts will be made
available upon request
5. At 5:45, everyone will be invited to give a flash (30s) presentation on their “thing”

You may keep the Seeed* Grove Starter Kit Plus and the Intel® Galileo board
• Go Make some other things!
• Check out the Seeed site for more sensors and shields
72
Legal Disclaimer
INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH INTEL PRODUCTS. NO LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY
INTELLECTUAL PROPERTY RIGHTS IS GRANTED BY THIS DOCUMENT. EXCEPT AS PROVIDED IN INTEL'S TERMS AND CONDITIONS OF SALE FOR SUCH PRODUCTS,
INTEL ASSUMES NO LIABILITY WHATSOEVER AND INTEL DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF INTEL PRODUCTS
INCLUDING LIABILITY OR WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR
OTHER INTELLECTUAL PROPERTY RIGHT.
A "Mission Critical Application" is any application in which failure of the Intel Product could result, directly or indirectly, in personal injury or death. SHOULD YOU
PURCHASE OR USE INTEL'S PRODUCTS FOR ANY SUCH MISSION CRITICAL APPLICATION, YOU SHALL INDEMNIFY AND HOLD INTEL AND ITS SUBSIDIARIES,
SUBCONTRACTORS AND AFFILIATES, AND THE DIRECTORS, OFFICERS, AND EMPLOYEES OF EACH, HARMLESS AGAINST ALL CLAIMS COSTS, DAMAGES, AND
EXPENSES AND REASONABLE ATTORNEYS' FEES ARISING OUT OF, DIRECTLY OR INDIRECTLY, ANY CLAIM OF PRODUCT LIABILITY, PERSONAL INJURY, OR DEATH
ARISING IN ANY WAY OUT OF SUCH MISSION CRITICAL APPLICATION, WHETHER OR NOT INTEL OR ITS SUBCONTRACTOR WAS NEGLIGENT IN THE DESIGN,
MANUFACTURE, OR WARNING OF THE INTEL PRODUCT OR ANY OF ITS PARTS.
Intel may make changes to specifications and product descriptions at any time, without notice. Designers must not rely on the absence or characteristics of any features
or instructions marked "reserved" or "undefined". Intel reserves these for future definition and shall have no responsibility whatsoever for conflicts or incompatibilities
arising from future changes to them. The information here is subject to change without notice. Do not finalize a design with this information.
The products described in this document may contain design defects or errors known as errata which may cause the product to deviate from published
specifications. Current characterized errata are available on request.
Contact your local Intel sales office or your distributor to obtain the latest specifications and before placing your product order.
Copies of documents which have an order number and are referenced in this document, or other Intel literature, may be obtained by calling 1-800-548-4725, or go
to: http://www.intel.com/design/literature.htm

Intel, Quark, Look Inside and the Intel logo are trademarks of Intel Corporation in the United States and other countries.

*Other names and brands may be claimed as the property of others.

Copyright ©2014 Intel Corporation.

73
Legal Disclaimer
Software Source Code Disclaimer: Any software source code reprinted in this document is furnished under a software license and may
only be used or copied in accordance with the terms of that license.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

74
Optimization Notice

Intel's compilers may or may not optimize to the same degree for non-Intel
microprocessors for optimizations that are not unique to Intel microprocessors. These
optimizations include SSE2, SSE3, and SSE3 instruction sets and other optimizations. Intel
does not guarantee the availability, functionality, or effectiveness of any optimization on
microprocessors not manufactured by Intel.

Microprocessor-dependent optimizations in this product are intended for use with Intel
microprocessors. Certain optimizations not specific to Intel microarchitecture are reserved
for Intel microprocessors. Please refer to the applicable product User and Reference
Guides for more information regarding the specific instruction sets covered by this notice.

Notice revision #20110804

75
Risk Factors
The above statements and any others in this document that refer to plans and expectations for the second quarter, the year and the future are forward-
looking statements that involve a number of risks and uncertainties. Words such as “anticipates,” “expects,” “intends,” “plans,” “believes,” “seeks,”
“estimates,” “may,” “will,” “should” and their variations identify forward-looking statements. Statements that refer to or are based on projections,
uncertain events or assumptions also identify forward-looking statements. Many factors could affect Intel’s actual results, and variances from Intel’s
current expectations regarding such factors could cause actual results to differ materially from those expressed in these forward-looking statements.
Intel presently considers the following to be important factors that could cause actual results to differ materially from the company’s expectations.
Demand for Intel's products is highly variable and, in recent years, Intel has experienced declining orders in the traditional PC market segment. Demand
could be different from Intel's expectations due to factors including changes in business and economic conditions; consumer confidence or income
levels; customer acceptance of Intel’s and competitors’ products; competitive and pricing pressures, including actions taken by competitors; supply
constraints and other disruptions affecting customers; changes in customer order patterns including order cancellations; and changes in the level of
inventory at customers. Intel operates in highly competitive industries and its operations have high costs that are either fixed or difficult to reduce in the
short term. Intel's gross margin percentage could vary significantly from expectations based on capacity utilization; variations in inventory valuation,
including variations related to the timing of qualifying products for sale; changes in revenue levels; segment product mix; the timing and execution of
the manufacturing ramp and associated costs; excess or obsolete inventory; changes in unit costs; defects or disruptions in the supply of materials or
resources; and product manufacturing quality/yields. Variations in gross margin may also be caused by the timing of Intel product introductions and
related expenses, including marketing expenses, and Intel's ability to respond quickly to technological developments and to introduce new products or
incorporate new features into existing products, which may result in restructuring and asset impairment charges. Intel's results could be affected by
adverse economic, social, political and physical/infrastructure conditions in countries where Intel, its customers or its suppliers operate, including
military conflict and other security risks, natural disasters, infrastructure disruptions, health concerns and fluctuations in currency exchange rates. Intel’s
results could be affected by the timing of closing of acquisitions, divestitures and other significant transactions. Intel's results could be affected by
adverse effects associated with product defects and errata (deviations from published specifications), and by litigation or regulatory matters involving
intellectual property, stockholder, consumer, antitrust, disclosure and other issues, such as the litigation and regulatory matters described in Intel's SEC
filings. An unfavorable ruling could include monetary damages or an injunction prohibiting Intel from manufacturing or selling one or more products,
precluding particular business practices, impacting Intel’s ability to design its products, or requiring other remedies such as compulsory licensing of
intellectual property. A detailed discussion of these and other factors that could affect Intel’s results is included in Intel’s SEC filings, including the
company’s most recent reports on Form 10-Q, Form 10-K and earnings release.
Rev. 4/15/14

76
Node.js* Key Features and Conventions
Modules
Packages and the Package Manager
Timers and Intervals
Events
Streams
Asynchronous Callback Convention

77

Você também pode gostar