Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
TheInternetofThingsvsTheWebofThings
MASTERDEGREEINCOMPUTERSCIENCEDEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
Coursewebsite:h8p://www.cs.unibo.it/projects/iot/
2
IoTProtocolStack
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
3
IoTProtocolStack
IEEE802.3 IEEE802.11 IEEE802.15 IEEE802.16
IPv4andIPv6+6LoWPAN
TCP UDP
MQTT CoAP AMQP HTTP OTHERS
PHY/MACPROTOCOLS
NETWORKPROTOCOLS
TRANSPORTPROTOCOLS
MESSAGINGPROTOCOLS
OPENANDPROPRIETARY
STACKS
OTHERS
TCP/IPSTACK
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
4
TheWebofThings(WoT)q Overviewq Backgroundq WebThing:CharacterisVcsq WebThing:ArchitecturesandTechnologiesq Findabilityproblem:TheWebThingModelandthe
semanVcWebq ImplemenVngtheWoTwithNode.js
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
5
TheWebofThings(WoT)
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
BuildingtheWebofThingsD.D.GuinardandV.M.TrifaMANNINGEdiVons,2016
h8ps://webo\hings.org/book/
6
TheWebofThings(WoT)q IDEA:UsetheWorldWideWeb(WWW)ecosystem
andinfrastructuretobuildapplicaVonsfortheIoT.² InteractwithThingsviawebbrowsers.² ExploretheWebofThingsassurfingtheweb.² Retrieve, process and display sensor data by using web
technologies,likeJavaScript,JSON,WebSockets.
² Novelparadigm,butalsocomplementarytotheIoT.² The term appeared first in 2007, at present several research
groupsworkingoncloselyrelatedconcepts(e.g.ThePhysicalWeb).THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
7
TheWebofThings(WoT)q ADVANTAGESoftheWoT
² Abstractthecomplexityandvarietyoflower-layerprotocolbehindthesimplemodeloftheWWW.
² FacilitatetheintegraVonofallsortsofIoTdevices.² EasetheapplicaVondeploymentandmaintenance.² Relyonwidelyusedsecurityandprivacymechanisms.
q SHORTCOMINGSoftheWoT² WoTdevicesmustsupporttheTCP/IPstack.² Performanceonresource-constraineddevices.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
8
TheWebofThings(WoT)q TheWoTisimplementedontopoftheTCP/IPstack
(i.e.attheApplica[onLayer).
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
TechnologiesenablingtheconnecVonamongThings.
MakeThingsdiscoverableandusablebyWebapps.
SharetheWoTdatainasecureway.
Createmesh-updataapplicaVonsinvolvingmulVpleWebThingsandexternalWebservices.
TheWoTarchitectureisnotcomposedoflayersinthestrictsense,rathersoflevelsaddingfuncVonaliVes.
9
TheWebofThings(WoT)q Overviewq Backgroundq WebThing:CharacterisVcsq WebThing:ArchitecturesandTechnologiesq Findabilityproblem:TheWebThingModelandthe
semanVcWebq ImplemenVngtheWoTwithNode.js
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
10
Reference:TheWWWq Internetapplica[on,Client-serverarchitecture
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
WEBSERVER WEBCLIENT
Managetheresources(e.g.HTMLdocuments)
QuerytheServerinordertoperformoperaVonsonthe
resources(e.g.GETanHTMLdoc)
REQUEST
RESPONSE
q BasedontheHTTP(HypertextTransferProtocol)Protocol² Stateless,textual,request-responseprotocol² Versions:HTTP/1.1,HTTP/1.2,HTTP/2² LimitedsetofoperaVons:GET,POST,HEAD,PUT,OPTIONS,…
11
Reference:TheRESTPrinciplesq Representa[onalStateTransfer(REST)àsetof
architecturalprinciplesfordistributedsystems.1. ClientServeràInteracVonsbasedonarequest-response
communicaVonpa8ern.2. UniformInterfacesàUnambigousstandardinterfacefor
accessingtheresources(e.g.theURI).3. Statelessàclientcontextandstatearenotstoredontheserver.4. Cacheableàdataarecachedbyclientsandintermediaries.5. LayeredSystemàintermediatecomponentscanhidewhatis
behindthem(e.g.contentdeliverynetworks).THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
12
Reference:TheJSONLanguage
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
q JavaScriptObjectNota[onàDatadescrip[onformat² AJSONfileisalsocalleda“Document”.² JSONdocumentcanbeeasilyparsedbymachines.² Generalsyntax,appliableonthousandsofdifferentuse-cases² Favoursystemintegra[onandinteroperabilityamongthird-partyso\warecomponents.ü AJSONdocumentissurroundedbybrackets{}ü Eachdataentryisa<key,value>couple.
{givenname:“mario”}{givenname:“mario”,lastname:“rossi”}
JSONW3CTutorial:h8ps://www.w3schools.com/js/js_json_intro.asp
13
Reference:TheJSONLanguage
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
² ValueàNumber,integerorreal{name:“mario”,age:15,score:13.45}² ValueàString,surroundedbyquotes{givenname:“mario”,lastname:“rossi”}² ValueàBoolean,i.e.trueorfalse{name:“mario”,employed:true}² ValueàArray,surroundedbysquarebrackets{name:“mario”,codes:[“134”,”042”]}² ValueàJSONObject,surroundedbybrackets{name:“mario”,address:{city:“bologna”,nation:“italy”}}
14
Reference:TheJSONLanguage
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
{givenname:“Mario”,lastname:“Rossi”,age:45,employed:true,salary:1200.00,phones:[“0243434”,“064334343”],office:[{name:“A”,street:Zamboni,number:7},{name:“B”,street:Irnerio,number:49}]}
JSONDocument
15
TheWebofThings(WoT)q Overviewq Backgroundq WebThing:Characteris[csq WebThing:ArchitecturesandTechnologiesq Findabilityproblem:TheWebThingModelandthe
semanVcWebq ImplemenVngtheWoTwithNode.js
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
16
WebThing:Characteris[csq UniforminterfaceàThingsfollowthesamerules
ofthewebRESTfulcomponents,i.e.:.² Addressableresources.Everyresourcemusthaveaunique
idenVfierandshouldbeaddressableusingauniquemechanism.² RepresentaVonofresources.ServerscanmanagemulVple
representaVonoftheresources;clientscanqueryforaspecificrepresentaVonoftheavailableresources.
² Self-descripVvemessages.ClientsmustuseandimplementonlythemethodsprovidedbytheHTTPprotocol.
² HypermediaastheengineoftheapplicaVonstate(HATEOS)THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
17
q EverydeviceontheWebofThingsmusthavearootURLcorrespondingtoitsnetworkaddress.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
<scheme>”:”<authority><path>[“?”query][“#”fragment]
http://gateway.api.com/devices/TVhttps://kitchen:3000/fridge/http://192.168.1.23/buildings/devices/raspberryPI
² WebThingsmustbeanHTTPserver.² WebThingsshouldusesecureHTTPconnecVons(HTTPS).² WebThingsmustexposetheirproperVesusingahierarchicalstructure.
WebThing:Characteris[cs
18
q ResourcesontheWoTcanbeorganizedinahierarchydefinedbyaURLpath(talkmorelater).
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
http://gateway.api.com/devices/raspi
actuators/
sensors/
temperature/
gyroscope/
accelerometer/
RootDeviceURL
Actuators
Sensors
Temperature
Gyroscope
Accelerometer
led/
LEDs 1/
1/
1/
2/
1/
2/
WebThing:Characteris[cs
19
q UniforminterfaceàThingsfollowthesamerulesofthewebRESTfulcomponents,i.e.:.² Addressableresources.Everyresourcemusthaveaunique
idenVfierandshouldbeaddressableusingauniquemechanism.² RepresentaVonofresources.ServerscanmanagemulVple
representaVonoftheresources;clientscanqueryforaspecificrepresentaVonoftheavailableresources.
² Self-descripVvemessages.ClientsmustuseandimplementonlythemethodsprovidedbytheHTTPprotocol.
² HypermediaastheengineoftheapplicaVonstate(HATEOS)THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
WebThing:Characteris[cs
20
q AWebThingcansupportmul[plerepresenta[ons(=mulVpledataformats)ofitsresources.
q ClientcanrequestapreferredrepresentaVonthroughtheHTTPcontentnego[a[onmechanism.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
GET/piHost:devices.webofthings.ioAccept:application/json
200OKContent-Type:application/json…
HTTPREQUESTHEADER
HTTPRESPONSEHEADER
WebThing:Characteris[cs
21
q UniforminterfaceàThingsfollowthesamerulesofthewebRESTfulcomponents,i.e.:.² Addressableresources.Everyresourcemusthaveaunique
idenVfierandshouldbeaddressableusingauniquemechanism.² RepresentaVonofresources.ServerscanmanagemulVple
representaVonoftheresources;clientscanqueryforaspecificrepresentaVonoftheavailableresources.
² Self-descripVvemessages.ClientsmustuseandimplementonlythemethodsprovidedbytheHTTPprotocol.
² HypermediaastheengineoftheapplicaVonstate(HATEOS)THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
WebThing:Characteris[cs
22
q AWebThingscanprovidebasicHTTP-basedopera[onsonresources:GET,POST,PUT,DELETE.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
GET/pi/sensors/temperature/valueHost:devices.webofthings.ioAccept:application/json
200OKHTTP/1.1Content-Type:application/json{“temperature”:”25”}
² Readthevalueofaresource.² SafeandidempotentoperaVon.
GEToperaVon
HTTPREQUEST
HTTPRESPONSE
WebThing:Characteris[cs
23
q AWebThingscanprovidebasicHTTP-basedopera[onsonresources:GET,POST,PUT,DELETE.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
POST/pi/display/messagesHTTP/1.1Host:devices.webofthings.ioContent-Type:application/json{“Content”:”Helloworld”,“duration”:10}
201CreatedHTTP/1.1Location:devices.webofthings.io/pi/display
/messages/2210
² Createanewinstanceofsomethingthatdoesn’thaveitsownURL.² Unsafeandnon-idempotentoperaVon.
POSToperaVon
HTTPREQUEST
HTTPRESPONSE
WebThing:Characteris[cs
24
q AWebThingscanprovidebasicHTTP-basedopera[onsonresources:GET,POST,PUT,DELETE.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
PUT/pi/leds/4HTTP/1.1Host:devices.webofthings.ioContent-Type:application/json{“red”:0,“green”:123”,“blue”:123}
200OKHTTP/1.1
² UpdatesomethingthatalreadyexistsandhasalreadyitsownURL.² UnsafeandidempotentoperaVon.
PUToperaVon
HTTPREQUEST
HTTPRESPONSE
WebThing:Characteris[cs
25
q AWebThingscanprovidebasicHTTP-basedopera[onsonresources:GET,POST,PUT,DELETE.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
DELETE/rules/24HTTP/1.1Host:devices.webofthings.io
200OKHTTP/1.1
² PermanentlyremovearesourcefromaThing.² UnsafeandidempotentoperaVon.
DELETEoperaVon
HTTPREQUEST
HTTPRESPONSE
WebThing:Characteris[cs
26
q AWebThingscanprovidebasicHTTP-basedopera[onsonresources:GET,POST,PUT,DELETE.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
HTTPdefinesalistofstandardstatuscodestobereturnedbytheserveruponrecepVonofeveryrequest:
² 200OK(SuccessfulcompleVVonofarequest)² 201CREATED(Returneda\erthecreaVonofaresource)² 202ACCEPTED(ReturnedbysynchoperaVonsa\errequest)² 401UNAUTHORIZED(AuthorizaVonfailedornotissued)² 404NOTFOUND(Resourceordocumenthasnotbeenfound)² 500INTERNALSERVERERROR(Errorinprocessingtherequest)² 501SERVICEUNAVAILABLE(Servercan’thandletherequest)
WebThing:Characteris[cs
27
q UniforminterfaceàThingsfollowthesamerulesofthewebRESTfulcomponents,i.e.:.² Addressableresources.Everyresourcemusthaveaunique
idenVfierandshouldbeaddressableusingauniquemechanism.² RepresentaVonofresources.ServerscanmanagemulVple
representaVonoftheresources;clientscanqueryforaspecificrepresentaVonoftheavailableresources.
² Self-descripVvemessages.ClientsmustuseandimplementonlythemethodsprovidedbytheHTTPprotocol.
² HypermediaastheengineoftheapplicaVonstate(HATEOS)THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
WebThing:Characteris[cs
28
q AWebThingscaninformtheclientsaboutthelistofoperaVonspermi8edonaspecificresource,byusingtheOPTIONSHTTPcommand.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
OPTIONSpi/sensors/humidity/HTTP/1.1Host:devices.webofthings.io
204NoContentHTTP/1.1Content-Length:0Allow:GET,OPTIONSAccept-Ranges:bytes
HTTPREQUEST
HTTPRESPONSE
WebThing:Characteris[cs
29
q TheWoTmodeldefinedin[1]statesthateachWebThingMUSTmeettheserequirements:
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
1) AWebThingMUSTatleastbeanHTTP/1.1server.
2) AWebThingMUSThavearootresourceaccessibleviaanHTTPURL.
3) AWebThingMUSTsupportGET,PUT,POST,andDELETEHTTPcommands.
4) AWebThingMUSTimplementHTTPstatuscodes:200,400and500.
5) AWebThingMUSTsupportJSONasdefaultrepresentaVon.
6) AWebThingMUSTsupportGETonitsrootURL.
[1]WebThingmodel,COMPOSEEUproject:h8p://model.webo\hings.io
WebThing:Characteris[cs
30
q TheWoTmodeldefinedin[1]statesthateachWebThingSHOULDmeettheserequirements:
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
1) AWebThingSHOULDusesecureHTTPconnecVons(HTTPS).
2) AWebThingSHOULDimplementtheWebSocketProtocol.3) AWebThingSHOULDsupporttheWebThingsmodel(seelater).
4) AWebThingSHOULDreturna204codeforallwriteoperaVons.
5) AWebThingSHOULDprovideadefaulthuman-readabledocumenta[on.
[1]WebThingmodel,COMPOSEEUproject:h8p://model.webo\hings.io
WebThing:Characteris[cs
31
q TheWoTmodeldefinedin[1]statesthateachWebThingMAYmeettheserequirements:
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
1) AWebThingMAYsupporttheHTTPOPTIONSverboneachresource.2) AWebThingMAYofferaHTML-baseduserinterface.
3) AWebThingMAYprovidepreciseinformaVonabouttheintendedmeaningofindividualpartsofthemodel(e.g.semanVcWebtechniques)
[1]WebThingmodel,COMPOSEEUproject:h8p://model.webo\hings.io
WebThing:Characteris[cs
32
TheWebofThings(WoT)q Overviewq Backgroundq WebThing:CharacterisVcsq WebThing:ArchitecturesandTechnologiesq Findabilityproblem:TheWebThingModelandthe
semanVcWebq ImplemenVngtheWoTwithNode.js
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
33
WebThing:EnablingTechnologiesq PROBLEM.HTTPimplementsarequest-response
communicaVonpa8ern.Whataboutpush-basedIoTapplicaVons?
² Usepollingmechanism² UseWebhooks/HTTPcallbacks² Uselong-pollingmechanism² UseWebSockets
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
34
q WebHooksàTheWebThingandtheWebclientservebothasHTTPclientandasHTTPserver.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
ApplicaVon
Thing
Subscribe
ApplicaVon
Thing
Publish
POST/pi/sensors/humidity/subsContent-Type:application/json{“callback”:”https://url-of-client/pubs”}
POST/pubsHTTP/1.1Host:https://url-of-client/Content-Type:application/json{“humidity”:50}
WebThing:EnablingTechnologies
35
q PROBLEM.HTTPimplementsarequest-responsecommunicaVonpa8ern.Whataboutpush-basedIoTapplicaVons?
² Usepollingmechanism² UseWebhooks/HTTPcallbacks² Uselong-pollingmechanism² UseWebSockets
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
WebThing:EnablingTechnologies
36
q LongPollingàAclientsendstheHTTPrequesttotheserver;theserverholdstherequestVllanewvalueoftheresourceisavailable,thenitsendsaresponse.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
Client WebThing SensorviaGPIORequest
NewvalueResponse
Request
NewvalueResponse
AssoonastheClientreceivestheresponse,itissuesanewrequest.
WebThing:EnablingTechnologies
37
q PROBLEM.HTTPimplementsarequest-responsecommunicaVonpa8ern.Whataboutpush-basedIoTapplicaVons?
² Usepollingmechanism² UseWebhooks/HTTPcallbacks² Uselong-pollingmechanism² UseWebSockets
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
WebThing:EnablingTechnologies
38
q WebSocketsenablefull-duplex(bidirecVonal)communicaVonoverasingleTCPconnecVon.² PartoftheHTML5specificaVon² Novelprotocol,alternaVvetotheHTTP² Muchshorterheader(2bytes)thanHTTP
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
1. ClientsendsanHTTPrequesttotheserver,askingforanupgradetoWebSockets.2. TheserverreplieswithCode101SwitchingProtocolsifitsupportsWebSockets3. AbidirecVonalTCPsocketisopenandusedforthedatatransfer.4. TheTCPsocketislong-living,i.e.terminedonlywhenClientorServertransmitaCloseframe.
WEBSOCKETSPROTOCOLHANDSHAKE
WebThing:EnablingTechnologies
WebSocketProtocolSpecifica[on:h8ps://tools.iet.org/html/rfc6455
39
q WebSocketsenablefull-duplex(bidirecVonal)communicaVonoverasingleTCPconnecVon.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
GET/pi/sensors/humidity/HTTP/1.1Host:devices.webofthings.ioUpgrade:websocketConnection:Upgrade
HTTP/1.1101SwitchingProtocolsConnection:Upgrade[]Upgrade:websocketAccess-Control-Allow-Origin:http://localhost:63342
WEBSOCKETSPROTOCOLHANDSHAKE
REQUESTforWEBSOCKETSUPGRADE
CONFIRMATIONofWEBSOCKETSUPGRADE
WebThing:EnablingTechnologies
WebSocketProtocolSpecifica[on:h8ps://tools.iet.org/html/rfc6455
40
q WebSocketsenablefull-duplex(bidirecVonal)communicaVonoverasingleTCPconnecVon.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
GET/pi/sensors/humidity/HTTP/1.1Host:devices.webofthings.ioUpgrade:websocketConnection:Upgrade
HTTP/1.1101SwitchingProtocolsConnection:Upgrade[]Upgrade:websocketAccess-Control-Allow-Origin:http://localhost:63342
WEBSOCKETSPROTOCOLHANDSHAKE
REQUESTforWEBSOCKETSUPGRADE
CONFIRMATIONofWEBSOCKETSUPGRADE
WebThing:EnablingTechnologies
WebSocketProtocolSpecifica[on:h8ps://tools.iet.org/html/rfc6455
41THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
WebThing:Architectures
WebSocketProtocolSpecifica[on:h8ps://tools.iet.org/html/rfc6455
² DirectConnec[vityWoTScenario² WebClientsandWeb
Thingscanbelongtothethesamenetworkortodifferentnetworks.
² EachWebThingimplementsanHTTPserverandtheWoTAPI.
² TheRouterisnotaWebThingObject.
42THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
WebThing:Architectures
WebSocketProtocolSpecifica[on:h8ps://tools.iet.org/html/rfc6455
² Gateway-basedConnec[vityWoTScenario
² NotalltheThingsareabletoimplementtheWoTAPIandtosupporttheWebSockets.
² TheGatewayisaWebThingObject,andworksasproxyfortheotherThings.
43THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
WebThing:Architectures
WebSocketProtocolSpecifica[on:h8ps://tools.iet.org/html/rfc6455
² Cloud-basedConnec[vityWoTScenario² Asinthepreviousscenario,
notalltheThingsareabletoimplementtheWoTAPIandtosupporttheWebSockets.
² Differentlyfromthepreviousscenario,thegateway/proxyisacloudserviceandnotanotherdevicelocatedwithinthesamenetwork.
44
TheWebofThings(WoT)q Overviewq Backgroundq WebThing:CharacterisVcsq WebThing:ArchitecturesandTechnologiesq Findabilityproblem:TheWebThingModeland
theseman[cWebq ImplemenVngtheWoTwithNode.js
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
45
q FindabilityàcapabilityofeasilydiscoverandunderstandanyenVtyoftheWebofThings.Threeseparatesub-problems:q HowtodiscoverWebThings.q Howtoknowwhatcommandstosendandhow.q Howtounderstandthemeaningofdatabeing
exchangedwiththeWebThing.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
WoTFindabilityProblem
46
q ThereareseveraldiscoveryprotocolsforLANs:mDNS,DLNA,UPnP,AppleBonjour,…
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
serviceup:{interfaceIndex:4type:{ name:‘http’ protocol:‘tcp’ fullyQualified:true}fullname;‘Man\\032MFC-8520DN._http._tcp.local.’host:‘EVT-BW-MAN.local’port:80addresses:[‘192.168.0.6’]….
}
mDNSmessage ² ClientslistenfornewmDNSmessagesandpopulatethelocalDNStable.
AserviceoftypeHTTP/TCPhasbeendiscovered.
Theserviceisreachableat:hep://evt-bw-man.local
WoTFindabilityProblem
47
q FindabilityàcapabilityofeasilydiscoverandunderstandanyenVtyoftheWebofThings.Threeseparatesub-problems:q HowtodiscoverWebThings.q Howtoknowwhatcommandstosendandhow.q Howtounderstandthemeaningofdatabeing
exchangedwiththeWebThing.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
WoTFindabilityProblem
48THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
h8p://model.webo\hings.io
WoTFindabilityProblem
49
q WebThingModelàconceptual,uniformdescripVonofaThingandofitscapabiliVes.² Flexibility:itshouldbeabletorepresentallsortsof
devicesandproducts,aswellasallsortsofinteracVons.² Viability:itshouldensurethatclientapplicaVonscan
interactwithnewThingsautomaVcally(withoutanyhumanintheloop)² Severalapproachesproposed,fewconsolidatedsoluVons.² Wefollowthemodelproposedin: hep://model.webofhings.io
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
WoTFindabilityProblem
50
q AlltheWebofThingshavearootURL,andimplementalogicaltreestructureforresources:² /modelàmetadatasuchasThingname,descripVonsor
configuraVons(aGETofthemodelwillreturnitscompletedescripVon).² /propertiesàinternalstateofaThing,expressedbyalist
of<key,value>tuples,wherethevaluecanbeanyJSONvalue.² /actionsàfuncVonsofferedbytheThingtoclients.² /ThingsàlistofThingsproxiedbythecurrentdevice.² /subscriptionsàlistofacVvesubscripVons(incase
publish-subscribeparadigmisimplemented).THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
WoTFindabilityProblem
51
q AlltheWebofThingshavearootURL,andimplementalogicalresourcetreestructure:
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
RootResourceoftheWebThingh8p://wt.mypi.local
Model/model
ProperVes/properties
AcVons/actions
Things/Things
Temperature/temperature
LEDs/leds
ledStateON/1234ledStateOFF/1235BLESpeaker/speaker
WoTFindabilityProblem
52
q InresponsetoaHTTPGETrequest(ontheURL),aWebofThingmustreturnaJSONrepresentaVonlikethis:
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
Fieldname Type Descrip[on
id String RelaVveURLoftheresource
createdAt String Timestampwhentheresourcewascreated
updatedAt String Timestampwhentheresourcewaslastupdated
name String Shorthuman-readablenameofaresource
description String Human-readabledescripVonofaresource
tags String Arrayoftags
customFields Objects JSONobjectwithkey-valuepairs
links Objects JSONObjectwiththelistofsub-resources
WoTFindabilityProblem
53THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
{"id":"myCar","name":"Mygreatcar","description":"Thisissuchagreatcar.","createdAt":"2012-08-24T17:29:11.683Z","updatedAt":"2012-08-24T17:29:11.683Z","tags":["cart","device","test"],"customFields":{"size":"20","color":"blue"},
"links":{"model":{"link":"model/","title":"ModelthisWebThing."},"properties":{"link":"properties/","title":"PropertiesofthisWebThing."},"actions":{"link":"actions/","title":"ActionsofthisWebThing."},...}}
WoTFindabilityProblem
54
q Eachresourcemaylinktodifferentsub-resources.q Eachlinkisdefinedbyarela[ontype(the"link
type"),theactualURLofthesub-resource(the"link"),andahuman-readableiden[fierfortherelaVon(the"Vtle").
q Linksshouldbeexposedintwoways:² Usingthelinks:fieldoftheJSONpayload.² UsingtheHTTPLinkheaderfield.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
WoTFindabilityProblem
55
q TheWTModelincludesthefollowinglinktypes:
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
Rela[ontype Descrip[on
model AlinktotheresourcedescripVon.
properties TheproperVesofthisresource.
actions TheacVonsthatthisresourcecanperform.
things TheWebthingsproxiedbythisresource.
subscriptions TheendpointtomanagesubscripVonstothisresource.
type TheinstanceoftheresourceidenVfiedbyatargetexternalURL.
product AlinktoauthoritaVveproductinformaVonforthisWebThing.
help AlinktotheonlinemanualpageforthisWebThing.
ui AlinktotheHTML-baseduserinterfaceforthisWebThing.
WoTFindabilityProblem
56
q EXAMPLES:LinksincludedintheJSONformat:
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
“links”:{"model":{"link":"model/","title":"ModelofthisWebThing."},"properties":{"link":"properties/","title":"PropertiesofthisThing."},"actions":{"link":"actions/","title":"ActionsofthisWebThing."},….
{..."links":{"<relType>":{"link":"<String>","title":"<String>"}"<_customRelType>":{"link":"<String>","title":"<String>"},...}}
WoTFindabilityProblem
57
q EXAMPLES:LinksincludedintheHTTPHeader:
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
-->REQUESTGET/http://wt.mypi.local<--RESPONSE200OKLink:<model/>;rel="model"Link:<properties/>;rel="properties"Link:<actions/>;rel="actions"Link:<product/>;rel="product"Link:<type/>;rel="type"Link:<help/>;rel="help"Link:<ui/>;rel="ui"Link:<_myCustomLinkRelType/>;rel="_myCustomLinkRelType”
…HereitfollowstheJSONrepresentaVonoftheWebThing….
WoTFindabilityProblem
58
q EXAMPLES:LinksincludedintheHTTPHeader:
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
-->REQUESTGET/http://wt.mypi.local<--RESPONSE200OKLink:<model/>;rel="model"Link:<properties/>;rel="properties"Link:<actions/>;rel="actions"Link:<product/>;rel="product"Link:<type/>;rel="type"Link:<help/>;rel="help"Link:<ui/>;rel="ui"Link:<_myCustomLinkRelType/>;rel=“myCustomLinkRelType”
…HereitfollowstheJSONrepresentaVonoftheWebThing….
WoTFindabilityProblem
59
q OPERATIONEXAMPLE:RetrieveproperVes’values
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
-->REQUESTGEThttp://wt.mypi.local/properties<--RESPONSE200OKLink:<model/>;rel=”model”[{"id":"temperature","name":"KitchenTemperatureSensor","values":{"temp":22,"timestamp":"2015-06-14T14:30:00.000Z"},
…]
WoTFindabilityProblem
60
q OPERATIONEXAMPLE:Updateaproperty
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
-->REQUESTPUT{wt}/properties/temperature/[{"temp":24}]<--RESPONSE204NOCONTENTLocation:{wt}/properties/temperature/
WoTFindabilityProblem
61
q OPERATIONEXAMPLE:RetrievethelistofacVons
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
-->REQUESTGEThttp://wt.mypi.local/properties<--RESPONSE200OKLink:<http://webofthings.org/actions/upgradefirmware>;rel="type”[{"id":"upgradeFirmware","name":"UpgradeDeviceFirmware"},{"id":"reboot","name":"Reboot"}]
WoTFindabilityProblem
62
q OPERATIONEXAMPLE:ExecuteanacVon
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
-->REQUESTPOSThttp://wt.mypi.local/actions/reboot{"delay":50,"mode":"debug"}<--RESPONSE204NORESPONSELocation:{wt}/actions/reboot/233
WoTFindabilityProblem
63
q OPERATIONEXAMPLE:RetrievetheacVonstatus
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
-->REQUESTGEThttp://wt.mypi.local/actions/reboot/233<--RESPONSE200OK{"id":"233","value":{"delay":50,"mode":"debug"},"status":"executing","timestamp":"2015-06-14T14:30:00.000Z"}
WoTFindabilityProblem
64
q FindabilityàcapabilityofeasilydiscoverandunderstandanyenVtyoftheWebofThings.Threeseparatesub-problems:q HowtodiscoverWebThings.q Howtoknowwhatcommandstosendandhow.q Howtounderstandthemeaningofdatabeing
exchangedwiththeWebThing.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
WoTFindabilityProblem
65THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
h8p://model.webo\hings.io
² TheWebThingModeldescribedsofarprovidestheabstracVonofanExtendedWebThing(i.e.Level3).
² ClientscandiscoverthewaytointeractwithWebThings…howevertheycannotinferthemeaningofdata,andrelaVonshipsamongdifferentdataentries.
WoTFindabilityProblem
66THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
² Seman[cWebreferstoasetoftechniquestoeasethefinding,sharingandprocessofwebcontentsthankstoacommonandextendibledatadescripVonandinterchangeformat.² MeaningisassociatedwithdataenVVesbyannotaVngthemeta-
datawithVocabularyelements.² Vocabularyelementscanalsohaverela[onshipswitheachother.² AreasonercanbeusedtoinferaddiVonalproperVesor
relaVonships.
WoTFindabilityProblem
67THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
² JavaScriptObjectNota[onforLinkedData(JSON-LD)² LightweightsyntaxtoserializeLinkedDatainJSON.² 100%compaVblewiththeJSONlanguage.² InaddiVon,itintroducessemanVcfeaturessuchas:
q Auniversaliden[fiermechanismforJSONobjectsviatheuseofIRIs.q AmechanisminwhichavalueinaJSONobjectmayrefertoaJSON
objectonadifferentsiteontheWeb.q Theabilitytoannotatestringswiththeirlanguage.q AwaytoassociatedatatypeswithvaluessuchasdatesandVmes.
WoTFindabilityProblem
JSON-LD1.0W3CSpecifica[ons:h8p://www.w3.org/TR/json-ld/
68THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
² JavaScriptObjectNota[onforLinkedData(JSON-LD)
ThecompletedescripVonofJSON-LDsyntaxtokensandkeywordscanbefoundat:http://www.w3.org/TR/json-ld/
Keyword Descrip[on Example
@context UsedtodefinethevocabolaryusedthroughoutaJSON-LDdocument
@id UsedtouniquelyidenVfythingswithIRI
@type Usedtosetthedatatypeofanode
@language UsedtospecifythelanguageforaparVcularstringvalue
WoTFindabilityProblem
69THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
² W3CThingDescrip[on(TD)h8ps://w3c.github.io/wot-thing-descripVon/ThingisanabstracVonofaphysicalenVty.
AThingDescripVondescribesthemetadataandinterfacesofThings.Itconsistsof:
² SemanVcmetadatafortheThing.
² Anarrow-waistinterac[onmodel.
² Seman[cschematomakedatamodelsmachine-understandable.
² FeaturesforWebLinkingtoexpressrelaVonsamongThings.
WoTFindabilityProblem
70THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
² W3CThingDescrip[on(TD)h8ps://w3c.github.io/wot-thing-descripVon/Threeinterac[onmodelsaredefinedintheW3CTDmodel:
² Property:readableand/orwriteabledata.
² Action:changesorprocessesonaThingthattakeacertainVmetocomplete.
² Event:mechanismforeventstobenoVfiedbyaThingonacertaincondiVon.
WoTFindabilityProblem
71THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
² ThingDescrip[oninstancesareserializedinJSON-LD{"@context":["http://w3c.github.io/wot/w3c-wot-td-context.jsonld"],"@type":["Thing"],"name":"MyLampThing","interaction":[{"@type":["Property"],"name":"status","outputData":{"type":"string"},"writable":false,"observable":true,"link":[{"href":"coaps://mylamp.example.com:5683/status","mediaType":"application/json“
WoTFindabilityProblem
72THEWEBOFTHINGS(WoT)
L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
}]},{"@type":["Action"],"name":"toggle","link":[{"href":"coaps://mylamp.example.com:5683/toggle","mediaType":"application/json"}]},{"@type":["Event"],"name":"overheating","outputData":{"type":"string"},"link":[{"href":"coaps://mylamp.example.com:5683/oh","mediaType":"application/json"}]}
WoTFindabilityProblem
73
TheWebofThings(WoT)q Overviewq Backgroundq WebThing:CharacterisVcsq WebThing:ArchitecturesandTechnologiesq Findabilityproblem:TheWebThingModelandthe
semanVcWebq Implemen[ngtheWoTwithNode.js
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
74
TheWebofThings(WoT)
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
WEBCLIENT WEBTHING(RaspberryPI)
ARDUINONANO+DHT22TEMPERATURE
SENSOR
HTTP/WebSocketsviaWi-FI
75
Reference:Node.jsFrameworkq Javascriptisthemostpopularprogramming
language,accordingtothenumberofpublicrepositoriesinGitHub.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
h8ps://github.com/madnight/githut
76
q Node.jsFramework² Opensourceserverframeworkfordeployinghigh-
performanceserver-sideapplicaVons.² Node.jsapplicaVonsaredeployedinJavascript.² Single-threaded,non-blockingwebservers.² Asynchronousprogramming.² Highlymodular,basedonthenpmpacketmanager.
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
Reference:Node.jsFramework
77
q Node.jsFramework
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
varhttp=require('http');http.createServer(function(req,res){res.writeHead(200,{'Content-Type':'text/html'});res.end('HelloWorld!');}).listen(8080);console.log(‘WebServerstartedonport8080);
first.jsCreateaserverandpassitafuncVontobe
calledwheneveranewclientsendsanHTTPrequest.
Theserverlistensonport8080
/home/raspi/$nodefirst.jsWebServerstartedonport8080
StarVngtheserverviacommand-line
Reference:Node.jsFramework
78
q Node.jsFramework
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
varhttp=require(’request');http.createServer(function(req,res){…
first.jsIncludean
externalModulenamedrequest.
/home/raspi/$npminstallrequest--saveInstalladdiVonalPackages
throughthenpmtool
first.jsrequest-modules/package.json
APPLICATIONSTRUCTURE
Reference:Node.jsFramework
79
q SynchronousServer-sideProgramming(e.g.PHP)
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
Request
Response
Reference:Node.jsFramework
Thread1
Request
Response
Thread2
Request
Response
Thread3
varresult=database.query(“SELECT ThingsFROM DeviceTable”);
console.log(result);
² Scriptworksinasequen[almanner.² ScriptexecuVonisblockedVllcurrentI/O
operaVonsarecompleted.² (INTHECODEABOVE)Themessageiswri8en
ontheconsoleAFTERthedatabasequeryhasbeencompleted.
80
q AsynchronousServer-sideProgramming
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
Request
Response
Reference:Node.jsFramework
Request
Response
Request
Response
database.query(“SELECT ThingsFROM DeviceTable”, functionresult{ //dosomethingwithresults
}};console.log(result);
² AsynchronousI/OoperaVons.² Anonymouscallbacksareexecutedoncea
requesthasbeencompleted.² (INTHECODEABOVE)Themessagemightbe
wri8enontheconsolebeforethequeryhasbeencompleted.
EVENTLOOP(onethread)
81
q LearnmoreaboutNode.jsprogramming
THEWEBOFTHINGS(WoT) L.BONONI,M.DiFELICE,DEPARTMENTOFCOMPUTERSCIENCEANDENGINEERING,UNIVERSITYOFBOLOGNA,ITALY
Reference:Node.jsFramework
W3CTutorial:https://www.w3schools.com/nodejs/
OfficialPage:https://nodejs.org/en/