Professional Documents
Culture Documents
IoT Thai
IoT Thai
IoT Thai
2560
Outline
InternetofThing
Definition,IoT Architecture
Arduino Platform
Digital&AnalogInputOutput
LCD,I2C,Ethernet
InternetofthingsProtocol
MQTTProtocol,Websocket
BuildingIoT withArduino
NodeMCU
BasicforNodeMCU
BuildingIoT withNodeMCU
RaspberryPi
BasicforRaspberryPi
MQTTBroker
LocalBroker&PublicBroker
2
WhatisInternetofThings
InternetofThings IEEE 27May2015
(IEEE_IoT_Towards_Definition_Internet_of_Things_Revisi
on1_27MAY15.pdf)
AnIoT isanetworkthatconnectsuniquelyidentifiable
ThingstotheInternet.TheThingshave
sensing/actuationandpotentialprogrammability
capabilities.Throughtheexploitationofunique
identificationandsensinginformationabouttheThing
canbecollectedandthestateoftheThingcanbe
changedfromanywhere,anytime,byanything.
WhatisInternetofThings
InternetofThingsfeatures
InterconnectionofThings
ConnectionofThingstotheInternet
UniquelyIdentifiableThings
Ubiquity
Sensing/Actuationcapability
Embeddedintelligence
InteroperableCommunicationCapability
Selfconfigurability
Programmability
InternetofThings IoT
IoT Industry
4.0
IoT
1)
2)
Zigbee,6LowPAN,LowpowerBluetooth
3)
BigDataAnalytics
:
TheIoT:DifferentServices,Technologies,MeaningsforEveryone[1]
Source:http://www.mouser.com/applications/iotreality/?cm_mmc=PressReleasePR_Mouser_IoT_Site_Update_20150701
IoT LayerArchitecture
ITUTY.2060
IoT LayerArchitecture
Thedevicelayerliedevices(sensors,actuators,RFIDdevices)and
gatewaysusedtocollectthesensorreadingsforfurtherprocessing
Thenetworklayerprovidesthenecessarytransportandnetworking
capabilitiesforroutingtheIoT datatoprocessingplaces.
Thesupportlayerisamiddlewarelayerthatservestohidethe
complexityofthelowerlayerstotheapplicationlayerandprovide
specificandgenericservicessuchasstorageindifferentforms
(databasemanagementsystemsand/orcloudcomputingsystems)
andmanyotherservicessuchastranslation.
TheapplicationlayercontainsIoT applications.
TheInternetofThingsProtocolstack fromsensorsto
business value
Souce:https://entrepreneurshiptalk.wordpress.com/2014/01/29/theinternetofthingprotocolstackfromsensorstobusinessvalue/
TheInternetofThingsProtocolstack from
sensorstobusiness value
Connectivitylayer: Whatkindofphysicalconnectorsyou
canfind.RS232,RS485,ModBus,USB(asaconnectortype,
notthecommunicationprotocol),SPI,ODB2(inCars)
LinkProtocol: Howdothosedeviceactuallysendthedata.
Ethernet802.3,Wifi 802.11a/b/g/n,BlueTooth,BLE,Dash7,
ZigBee,RFid,GSM,6LoWPAN,802.14.5e.
TheInternetofThingsProtocolstack from
sensorstobusiness value
Session/Communication: Thissectionisaninteresting
bunchwithalotofnewprotocolsthathavebeenbuildfor
superhighvolumesandlargenetworksofthings.Themost
famousrightnowisMQTT, alsofindCoAP (kindofaREST
BasedprotocolbutmuchmoreefficientthanitsHTTP
counterpart),DDS,XMPP andAMQP thatareallwellsuited
forIoT andwillmapdifferentusecases.
DataAggregation/Processing: Thisiswhereitgets
reallyinteresting.Whendevicesenddata,lotsofdata,you
needanendpointtodosomethingwithit.Beitprocessingit
inrealtime(withStorm),butatminimumgettingthedata
andsendingitsomewhereelseatverylargescale,which
Kafka isagreatexampleof.Othersolutionexistslike
RapidMQ,Scribe,Plume,Luxun.
TheInternetofThingsProtocolstack from
sensorstobusiness value
DataStorage/Retrieval: TherealmofBigDatabackend
andNoSQL solutions.Hadoop,HBase,MongoDB and
Cassandra dominatethefield.
BusinessModel: Thislayeristryingtocapturethefact
thatbusinessvalueandbusinessprocessesalwaysrelyonan
underlyingbusinessmodel. OpenorClosed,Integratedor
platform,directsalesorindirect,cloudbasedoronpremise
(orprivatecloud),ondemandpricing,etc.
IoT SmartXApplication
SmartEnergy
SmartTransport
Smartbuilding
SmartHealth
1.1BasicComponentsofcomputer
input/output
monitor
Mouse,keyboard
Portusb,serial,parallel
CentralProcessorUnit
Harddisk
RAM
Microcontrollers
Memory
ROMRAM
CPU
Input/Output
Subsystems:
Timers,Counters,Analog
Asinglechip Interfaces,I/Ointerfaces
Microcontroller
1.CPU() : CPU
2.Memory():
ProgramMemory DataMemory Program
Memory Harddisk
DataMemory RAM
22
Microcontroller
4.Bus():
CPU,Memory Port DataBus,
AddressBus ControlBus
23
Wherewecanfindmicrocontroller?
1.2
MCS51 (8bit) intel
MCS96 (16bit) intel
PIC MicrochipTechnology
AVR Atmel
ARM ARMHoldings
68HC11 Motorola
Rabbit2000 RabbitSemiconductor
25
1.3 AVR
2 8bitAVR 32bitAVR
AVR 8
AVR ATMEL 1996
RISC(ReducedInstructionSetComputer)
Harvard
Flash
SRAM
EEPROM
26
1.4 AVR 8
tinyAVR
megaAVR ATmega
Tiny
27
XMEGA A/D10
12 DMAcontroller
I/O
FPSLIC(AVRcorewithFPGA)
(HDL:HardwareDescriptionLanguage)
VHDL Verilog
AVRcore
28
ApplicationSpecificAVR
USB
controller CANbus
AVR
29
1.5.1ATmega168
FLASH 16 Kbyte
SRAM 1Kbyte
EEPROM 512 byte
I2Cbus
20 ports
/ 8 2 16 1
PWM 6
10 6
1.85.5 Volts
20 MHz
30
ATmega168
31
1.5.2ATmega328
FLASH 32 Kbyte
SRAM 2 Kbyte
EEPROM 1 Kbyte
I2Cbus
22 ports
/ 8 2 16 1
PWM 6
10 8
1.85.5 Volts
20 MHz
32
ATmega328
33
1.6Platform
Platform Hardware Software
Application
Hardware
CPU x86 x8664
Software
MicrosoftWindows,MacOSXx86 ,MacOSX
PowerPC,Linuxx86,JavaPlatform
34
1.7WhatisArduino ?[1]
Arduino AVR Open
Source platform
DevelopmentBoard microcontroller AVR
IDE IDE Java
OS Linux,MACOS,Windows
IDE library Arduino
AVR Firmware
Firmware Compile IDE
35
WhatisArduino ?[2]
36
1.7.1Arduino HardwareVariety
37
1.7.2.Arduino Software
38
1.7.3 - Arduino
- c++ OOP
- ISP microcontroller
-
-
- opensource
Library
- c++
39
40
2.
arduinocube
42
2.1 Arduino
(DevelopmentCircle)
43
2.2Arduino Language
LanguageisstandardC(butmadeeasy)
corefunction
DigitalI/O AdvancedI/O Math RandomNumbers
pinMode() tone() min() randomSeed()
digitalWrite() noTone() max() random()
digitalRead() shiftOut() abs()
AnalogI/O shiftIn() constrain()
analogReference() pulseIn() map()
analogRead() Time pow()
analogWrite() PWM millis() sqrt()
Communication micros() Trigonometry
Serial delay() sin()
delayMicroseconds() cos()
tan() 44
2.3Someusefulfunction
pinMode() setapinasinputoroutput
digitalWrite() setadigitalpinhigh/low
digitalRead() readadigitalpinsstate
analogRead() readananalogpin
analogWrite() writeananalogvalue
delay() waitanamountoftime
millis() getthecurrenttime
45
2.4 Arduino
Arduino C/C++
sketchfiles
46
2.5
2.1. LEDBlink:HelloworldofMicrocontroller
DigitalPin13 ToturnonLEDuse
digitalWrite(13,HIGH)
schematic
19
47
48
49
50
LEDBlink 1
51
LEDBlink 2
52
2.1 Color LED
8 1
53
2.2 7-segment
1
LED 7segment
0-9 7segment
1 54
2.6
analogWrite()
Description
Writesananalogvalue(PWMwave)toapin.Can
beusedtolightaLEDatvaryingbrightnesses or
driveamotoratvariousspeeds.Afteracallto
analogWrite(), thepinwillgeneratea
steadysquarewaveofthespecifiedduty.The
frequencyofthePWMsignalisapproximately
490Hz.
OnmostArduino boards(thosewiththe
ATmega168orATmega328),thisfunction
worksondigitalpins3,5,6,9,10,and11.
YoudonotneedtocallpinMode()tosetthepin
asanoutputbeforecallinganalogWrite().
55
1.2 LEDFading
DigitalPin9
SamecircuitasBlinkcircuitbutpin9insteadofpin13
ThePWMpinsworkwiththeanalogWrite(pin,value)
commandwhere
pin:thepintowriteto.
value:thedutycycle:between0(alwaysoff)and255(alwayson).
ToturnLEDtohalfbright,useanalogWrite(9,128) 56
LEDFading:OfftoFullbright
57
ThingstoTryWithFading
Makeitgoreallyfastorreallyslow
Fadingfromhalf tofullbright
TryotherPWMpins
MultiplefadingLEDs,atdifferentrates
58
59
60
:
DigitalPin9
ToturnON: digitalWrite(9,HIGH)
ToturnOFF: digitalWrite(9,LOW)
Tosetbrightness: analogWrite(9,val)
61
3.
Forcesensor
Tactswitch
photocell
keypad
3.1 DigitalInput port
Resistorpullsinputto+5V
PressswitchisLOW
NotpressedisHIGH
63
3.1UsingdigitalRead()
64
3.1 DigitalInput
switch LED
Switch LED
Switch LED
66
3.1
Switch 4 Arduino
S1 7segment 1
S2 7segment 2
S3 7segment 3
S4 7segment 4
67
68
AnalogInput
69
Howtomakeavaryingvoltage?
++ +5V
Measurehere
Ground
70
3.2 Analog
AnalogPin2
0 5Volt
LED
Arduino
Board
73
ResistiveSensor
74
3.3LightSensor
RL =10k,VDD =5V
Analoginput SensingtheDark
LED
Analoginput
Sensor LED
LED
75
Outputvoltageislinearwithlightintensity
4.SerialCommunication
4.Communicatingwithother
77
4.1SerialCommunication
Serial
(ShiftBit)
Serial sync
baudrate start stop
(startbit)
(stopbit)
78
Serial Startbit
Stopbit
(Startbit) 1 LOW
(Databit)8
(Paritybit) 1
check Paritybit
(Stopbit)
HIGH
79
4.2Arduino Communications
Psst,ArduinodoesntreallydoUSB
Itreallyisserial,likeoldRS232serial
Allmicrocontrollerscandoserial
NotmanycandoUSB
Serialiseasy,USBishard
80
4.3Serialcommand
TalkingtootherusestheSerialcommand
Serial.begin() : preparetouseserial
Serial.print() : senddatatoserialport
Serial.println() : senddataandnewlinetoserialport
Serial.read() : readdatafromserialport
Serial.available() : readytoread
Serial.flush() : clearbufferatincomingserialdata
Serial.parseInt(): returnsthefirstvalid(long)integernumber
fromtheserialbuffer
Cantalktonotjustcomputers.
Mostthingsmorecomplexthansimple
sensors/actuatorsspeakserial.
81
4.1 SerialHelloworld!
int ledPin = 13;
int i = 0;
SendHelloWorldtocomputer
andBlinkLED void setup() {
pinMode(ledPin, OUTPUT);
ClickonSerialMonitorbutton Serial.begin(19200);
toseeoutput }
void loop(){
Serial.print(i++);
Serial.println(Hello world);
digitalWrite(ledPin,HIGH);
delay(500);
WatchLEDatDigitalPin13 digitalWrite(ledPin,LOW);
delay(500);
}
82
Note!!:Serial.print()
PrintsdatatotheserialportashumanreadableASCIItext.Thiscommandcan
takemanyforms.NumbersareprintedusinganASCIIcharacterforeachdigit.
FloatsaresimilarlyprintedasASCIIdigits,defaultingtotwodecimalplaces.
Bytesaresentasasinglecharacter.Charactersandstringsaresentasis.
Forexample:
Serial.print(78) gives"78"
Serial.print(1.23456) gives"1.23"
Serial.print(byte(78)) gives"N"(whoseASCIIvalueis78)
Serial.print('N') gives"N"
Serial.print("Helloworld.") gives"Helloworld."
Anoptionalsecondparameterspecifiesthebase(format)touse
Serial.print(78,BIN) gives"1001110" BIN :
Serial.print(78,OCT) gives"116" OCT :
Serial.print(78,DEC) gives"78" DEC :
Serial.print(78,HEX) gives"4E" HEX:
83
4.2SerialReadBasic
char inByte = 0;
void setup() {
Serial.begin(19200);
Serial.println("Hello,type something");
}
SerialMonitor,
void loop() {
Send if (Serial.available()) {
inByte = Serial.read();
Serial.print ("> ");
Serial.println (inByte);
}
}
Note!!!
Serial.available() tells
youifdatapresenttoread.
Alwayscheck
Serial.available() orif
Serial.read() != -1 to
determineiftheresactualdata
toread. 84
4.3Controllingfromcomputer
int ledPin = 13;
InSerialMonitor,Youtype void setup() {
H,PressSend pinMode(ledPin, OUTPUT);
Serial.begin(19200);
}
void loop(){
if( Serial.available() ){
WhenyoutypeH,LEDBlink. int val = Serial.read();
if (val == H) {
digitalWrite(ledPin,HIGH);
delay(500);
digitalWrite(ledPin,LOW);
delay(500);
}
}
}
85
4.1
0-9
7segment
4.2
0-255 LED
Digitalpin9.( analogWrite )
86
5.3
Analoginput( 3.2)
5.4
LightSensor ( 3.2)
Sensor
( Sensor )
87
5.LiquidCrystalDisplay
5.1LiquidCrystalDisplay:LCD
1.GND 2.VDD 3.Vb
4.RS(Registerselect) 5.R/W
6.E(Enable)
714 DataDB7DB0
89
5.2Function LCD
Arduino Library LCD chip
HitachiHD44780( chip compatible)
function Library LiquidCrystal.h
5.1HelloworldLCD
LCD
#include <LiquidCrystal.h>
Note!!!
lcd.setCursor(0, 1);
setthecursortocolumn0,line1
line1isthesecondrow,sincecountingbeginswith0
92
5.2 TextDirection
#include <LiquidCrystal.h>
LCD LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int thisChar = 'a';
void setup() {
lcd.begin(16, 2);
lcd.cursor();
}
void loop() {
if (thisChar == 'm') {
lcd.rightToLeft();
}
if (thisChar == 's') {
lcd.leftToRight();
}
if (thisChar > 'z') {
lcd.home();
thisChar = 'a';
}
lcd.write(thisChar);
Thisprogramprints delay(1000);
thisChar++;
athroughlrighttoleft, }
thenmthoughrlefttoright,
thensthroughzrighttoleftagain.
93
Createacustomcharacter
CreateacustomcharacterforuseontheLCD.
Uptoeightcharactersof5x8pixelsare
supported(numbered0to7).
Todisplayacustomcharacteronthescreen,
write()itsnumber.
94
5.3 Createcustomcharacter
LCD #include <LiquidCrystal.h>
byte newChar[8] = {
B00000,
B01110,
B10001,
B10001,
B10001,
B01010,
B11011,
B00000 };
void setup() {
lcd.createChar(1, newChar);
lcd.begin(16, 2);
lcd.write(1); }
void loop() {}
95
5
LCD
- I KMITL
-
LCD (01023)
( serial
monitor) LCD
96
6.InterIntegrateCircuitBus(I2C)
I2C,TwoWire
Synchronous serial bus with shared a data line
a little network for your gadgets
Philips Semiconductors
2 serial data (SDA)
serial clock (SCL)
MCU 2
99
ManyI2Cdevices
100
I2ConArduino
I2CbuiltinonArduinos ATmega168chip
UseWirelibrarytoaccessit
AnalogIn4isSDAsignal
AnalogIn5isSCKsignal
101
WirelibraryFunctions
Wire.begin() joini2cbus(master)
Wire.begin(4) joini2cbuswithaddress#4(Slave)
Wire.beginTransmission(112) transmittodevice#112
Wire.endTransmission() stoptransmitting
Wire.requestFrom(112, 2) request2bytesfromslave
device#112
Wire.available() Returnsthenumberofbytes
availableforreading
Wire.read() receiveabyte
Wire.write("x is ") sendsfivebyte
Wire.write(x) sendsonebyte
102
Arduino WireLibrary
Master Writing data to Slave
Load wire Library #include <Wire.h>
void setup()
{
Join i2c Wire.begin(); // join i2c bus (master)
}
byte x = 0;
void loop()
{
Start sending Wire.beginTransmission(4); // transmit to device #4
Send data Wire.write("x is ");
Wire.write(x);
//
//
sends five bytes
sends one byte
Stop sending Wire.endTransmission(); // stop transmitting
x++;
delay(500);
}
103
Arduino WireLibrary
Master Reading data from Slave
#include <Wire.h>
void setup()
{
Join i2c Wire.begin(); // join i2c bus (master)
Serial.begin(9600); // start serial for output
}
void loop()
{
Wire.requestFrom(2, 6); //request 6 bytes from device #2
Request data while(Wire.available()) //slave may send less than requested
Get data {
char c = Wire.read(); // receive a byte as character
Serial.print(c); // print the character
}
delay(500);
}
104
Temperature Sensor DS1621
Address 1001A2A1A0
48H-4FH
105
IC DS1621
DallasSemiconductor
I2C DS1621
- -55 +125
0.5
- 9
-
2.7-5.5
1
(thermostat) 1
-
I2C
8
106
107
DS1621
DS1621
#include<Wire.h>
voidsetup()
{
Serial.begin(9600);
Wire.begin();
Wire.beginTransmission(0x48);//connecttoDS1621(#0)
Wire.write(0xAC);//AccessConfig
Wire.write(0x02);//setforcontinuousconversion
Wire.beginTransmission(0x48);//restart
Wire.write(0xEE);//startconversions
Wire.endTransmission();
}
111
voidloop()
{
int8_tfirstByte;
int8_tsecondByte;
floattemp=0;
delay(1000);//givetimeformeasurement
Wire.beginTransmission(0x48);
Wire.write(0xAA);//readtemperaturecommand
Wire.endTransmission();
Wire.requestFrom(0x48,2);//requesttwobytesfromDS1621(0.5deg.resolution)
firstByte=Wire.read();//getfirstbyte
secondByte=Wire.read();//getsecondbyte
temp=firstByte;
if(secondByte) //ifthereisa0.5degdifference
temp+=0.5;
Serial.println(temp);
}
112
InternetofThingsProtocol
MQTTProtocol
InventedbyAndyStanfordClark (IBM)andArlenNipper(Eurotech)in1999
OriginallyenvisionedforuseoverSatellitelinkfromanoilpipeline
MQTTProtocol
MQTTProtocol
MQTTProtocol
Thepublish/subscribepattern
Bidirectional,Async PushCommunication
MQTT
Broker
MQTTProtocol
MQTTProtocol
Subscribe
Aclientneedstosenda SUBSCRIBE messagetotheMQTT
brokerinordertoreceiverelevantmessages.
Subscribe
Publish
Publish
Topics
AtopicisaUTF8string,whichisusedbythebrokertofiltermessagesforeachconnectedclient.Atopicconsists
ofoneormoretopiclevels.Eachtopiclevelisseparatedbyaforwardslash(topiclevelseparator).
QoS
AQualityofServiceLevel(QoS)forthismessage.Thelevel(0,1or2)determinestheguaranteeofamessage
reachingtheotherend
RetainFlag
Thisflagdeterminesifthemessagewillbesavedbythebrokerforthespecifiedtopicaslastknowngoodvalue.
Newclientsthatsubscribetothattopicwillreceivethelastretainedmessageonthattopicinstantlyafter
subscribing.( Broker Payload Subscribe )
Payload
Thisistheactualcontentofthemessage.
DUPflag
Theduplicateflagindicates,thatthismessageisaduplicateandisresentbecausetheotherenddidnt
acknowledgetheoriginalmessage.ThisisonlyrelevantforQoS greaterthan0
PacketIdentifier
Thepacketidentifierisauniqueidentifierbetweenclientandbrokertoidentifyamessageinamessageflow.
ThisisonlyrelevantforQoS greaterthanzero.
QoS
QoS 0 atmostonce
Theminimalleveliszeroanditguaranteesabesteffortdelivery.Amessagewont
beacknowledgedbythereceiverorstoredandredeliveredbythesender.
QoS 1 atleastonce
itisguaranteedthatamessagewillbedeliveredatleastoncetothereceiver.The
senderwillstorethemessageuntilitgetsanacknowledgementinformof
a PUBACK commandmessagefromthereceiver.
QoS
QoS 2 Exactlyonce
ThehighestQoS is2,itguaranteesthateachmessageisreceivedonlyoncebythe
counterpart. Itisthesafestandalsotheslowestqualityofservicelevel.The
guaranteeisprovidedbytwoflowsthereandbackbetweensenderandreceiver.
Retainmessages
Payload
Unsubscribe
Connect&Disconnect
7.1 PublicMQTTBroker
Website URL
http://www.hivemq.com/demos/websocketclient/
7.1 PublicMQTTBroker
Connect
Connect
Subscribe
AddTopicSubscription add subscribe
Subscribe
Publish
topic publish
publish
publish
MQTTbrokergetsWebsockets support
WebServer html javascript
WebBrowser Webapplication html WebServer
MQTTBroker WebSocket Javascript
7.2 RealTimegraph
Simpleexampleofplottinglivenumbereddatafroma
subscribedmqtt/websockets topicandplottingitusing
highcharts. http://www.highcharts.com/
WebServer Webhosting
html Javascript
livemqttchart.html plot Publish
livemqttchart1.html plot realtime
mqttws31.js
Subscribe Topic
7.2RealTimegraph
1. livemqttchart.html
Note!!BrokerITMQ
URL: http://neutron.it.kmitl.ac.th:3030/demo
html
Host:neutron.it.kmitl.ac.th
Port:1884
7.3 ControlviaWebsocket
control.html
Publish Topic
ON publish on Broker
OFF publish off Broker
7.3 ControlviaWebsocket
1. control.html
EthernetShield
TheArduino EthernetShieldallowsanArduino boardtoconnect
totheinternet.Itisbasedonthe Wiznet W5100ethernet chip.
TheWiznet W5100providesanetwork(IP)stackcapableofboth
TCPandUDP. Itsupportsuptofoursimultaneoussocket
connections.UsetheEthernetlibrarytowritesketcheswhich
connecttotheinternetusingtheshield.
Ethernet.begin()
Initializestheethernet libraryandnetworksettings.
Syntax
Ethernet.begin(mac);
Ethernet.begin(mac, ip);
Ethernet.begin(mac, ip, dns);
Ethernet.begin(mac, ip, dns, gateway);
Ethernet.begin(mac, ip, dns, gateway, subnet);
Example IP DHCPServer
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
void setup()
{ Note
Ethernet.begin(mac); Ethernet.begin(mac),returnsan
Serial.println(Ethernet.localIP()); int:1onasuccessfulDHCPconnection,
} Int:0onfailure
void loop () {
}
Note: Ethernet.localIP() IP Ethernetshield
Ethernet.begin()
Example FixIP
#include <SPI.h>
#include <Ethernet.h>
Client
Functions
read() byte Server
(Readthenextbytereceivedfromtheservertheclientisconnectedto(afterthelastcalltoread()).)
char c = client.read();
stop() server
client.stop();
https://github.com/knolleary/pubsubclient
download .zip
sketch>IncludeLibrary>Add.ziplibrary
LibraryPubSubClient
sketch>IncludeLibrary
ItcanonlypublishQoS 0messages.ItcansubscribeatQoS 0orQoS 1.
Themaximummessagesize,includingheader,is 128bytes bydefault.
PubSubClient Library
Constructors
PubSubClient ()
PubSubClient (client)
PubSubClient (server,port,[callback],client,[stream]) ***
Functions
boolean connect (clientID) ***
boolean connect (clientID,willTopic,willQoS,willRetain,willMessage)
boolean connect (clientID,username,password)
boolean connect (clientID,username,password,willTopic,willQoS,willRetain,willMessage)
void disconnect ()
int publish (topic,payload) ***
int publish (topic,payload,retained)
int publish (topic,payload,length)
int publish (topic,payload,length,retained)
int publish_P (topic,payload,length,retained)
boolean subscribe (topic,[qos]) ***
boolean unsubscribe (topic)
boolean loop ()
int connected ()
int state ()
PubSubClient setServer (server,port)
PubSubClient setCallback (callback)
PubSubClient setClient (client)
PubSubClient setStream (stream)
Other
ConfigurationOptions
SubscriptionCallback
8.1Publish
1. PublicMQTTBroker URL
http://www.hivemq.com/demos/websocketclient/
3. Subscriptions Addnewtopicsubscription
Topic
PublicBroker
WebBrowser
MQTTClient
(Arduino +EthernetShield)
8.1Publish
4. Arduino publish
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
char MQTT_SERVER[]=broker.mqttdashboard.com;
//byte MQTT_SERVER[] = { 161, 246, 38, 78 };
Note!!BrokerITMQ
URL:http://neutron.it.kmitl.ac.th:3030/demo
Host:neutron.it.kmitl.ac.th
Port:1883
8.1Publish
Arduino ( )
void setup() {
Serial.begin(9600);
Serial.println("Net begin");
if (client.connect(clientId)) {
Serial.println("Successfully connected with MQTT");
}
else {
Serial.println("cant connected with MQTT");
}
}
void loop()
{
client.publish(outTopic, payload);
delay(5000);
}
8.1Publish
5. Serialmonitor
(Message) publish Arduino
8.2Subscribe
1. Arduino Subcribe
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
char MQTT_SERVER[]=broker.mqttdashboard.com;
//byte MQTT_SERVER[] = { 161, 246, 38, 78 };
Serial.println(topic);
payload[length] = '\0';
String strPayload = String((char*)payload);
Serial.println(strPayload);
}
8.2Subscribe
Arduino Subcribe ( )
void setup() {
Serial.begin(9600);
Serial.println("Net begin");
delay(2000);
Serial.print("IP: "); // A little debug.. show IP address
Serial.println(Ethernet.localIP());
if (client.connect(clientId)) {
Serial.println("Successfully connected with MQTT");
client.subscribe(inTopic); // Subcribe
}
else { Serial.println("cant connected with MQTT"); }
}
void loop()
{
client.loop(); // loop for ever waiting for MQTT event
}
8.2Subscribe
2. Serialmonitor
publishMessage WebSocket
(Message) publish WebSocket
WebServer
PublicBroker
MQTTClient
(Arduino +EthernetShield)
WebBrowser
- LED LED website
Note website control.html
: LED&R
TeamA TeamB
PublicBroker
MQTTClient MQTTClient
(Arduino +EthernetShield)
(Arduino +EthernetShield)
: Arduino Internet
-
1. TeamA TeamB
2. TeamB sensor TeamA
LED
LED
TeamA TeamB
MQTTClient MQTTClient
(Arduino +EthernetShield) (Arduino +EthernetShield)
WebBrowser
TeamA Sensor 10
TeamB colorLED
020 2130
3140 50
- RealTime Webbrowser
InternetofThings
2560
RaspberryPi
WhatisRaspberryPi
TheRaspberryPiisalowcost, creditcardsized
computer thatplugsintoacomputermonitororTV,anduses
astandardkeyboardandmouse.Itisacapablelittledevice
thatenablespeopleofallagestoexplorecomputing,andto
learnhowtoprograminlanguageslikeScratchandPython.
RaspberryPi2ModelB
TheRaspberryPi2ModelBisthesecondgenerationRaspberryPi.Itreplaced
theoriginal RaspberryPi1ModelB+ inFebruary2015.Comparedtothe
RaspberryPi1ithas:
A900MHzquadcoreARMCortexA7CPU
1GBRAM
Likethe(Pi1)ModelB+,italsohas:
4USBports
40GPIOpins
FullHDMIport
Ethernetport
Combined3.5mmaudiojackandcompositevideo
Camerainterface(CSI)
Displayinterface(DSI)
MicroSDcardslot
VideoCore IV3Dgraphicscore
BecauseithasanARMv7processor,itcanrunthefullrangeofARMGNU/Linux
distributions,includingSnappyUbuntu Core,aswellas MicrosoftWindows10
RaspberryPi2ModelB
RaspberryPi3ModelB
TheRaspberryPi3isthethirdgenerationRaspberryPi.Itreplacedthe
RaspberryPi2ModelBinFebruary2016.Comparedtothe RaspberryPi2 it
has:
A1.2GHz64bitquadcoreARMv8CPU
802.11nWirelessLAN
Bluetooth4.1
BluetoothLowEnergy(BLE)
LikethePi2,italsohas:
1GBRAM
4USBports
40GPIOpins
FullHDMIport
Ethernetport
Combined3.5mmaudiojackandcompositevideo
Camerainterface(CSI)
Displayinterface(DSI)
MicroSDcardslot(nowpushpullratherthanpushpush)
VideoCore IV3Dgraphicscore
RaspberryPi3ModelB
1 Raspbian OS
OfficialSupport RaspberryPi
Raspbian OS Download
https://www.raspberrypi.org/downloads/
Win32DiskImager
1. Image
2. Device OS
3. Write
RaspberryPiConnect
connectviaaDVIconnection,commonly
availableonnewermonitorsanddigitalTVs.
RaspberryPiConnect
RaspberryPiRemoteConnections
SettingtheRaspberryPisIPaddress
QuickSetup/Settingupwhenyoudonthavea
monitor
EnsuretheRaspberryPiispoweredoff,andremovetheSDCard.
InserttheSDCardintoacardreaderandplugitintoyourlaptop.
Makeacopyof cmdline.txtandrenameit cmdline.normal
Edit cmdline.txtandaddtheIPaddressattheend(besureyou
dontaddanyextralines).10.30.4.1XXXX=
Windows Notepad
Editor Notepad++
2 RaspberryPi
SDCard OS IPAddress
RaspPi
LAN RaspPi
Adapter RaspPi
ping PC IPAddress
RaspPi
2 RaspberryPi
Putty RaspPi Secure
ShellV2(SSH)
IPAddress RaspPi
SSH
Open
2 RaspberryPi
Console RaspPi
username:pi Password raspberry
Login
BasicLinuxcommand
2 RaspberryPi
basiccommand Linux
ls
cd directory cd/,cd..
df h filesystem
expandfilesystem disk
sudo raspiconfig ExpandFileSystem
<Finish> RaspPi Reboot
2 RaspberryPi
Config StaticIPAddress Raspi filesystem
sudo nano /etc/dhcpcd.conf
interfaceeth0
staticip_address=10.30.4.1XX/24
staticrouters=10.30.4.1
staticdomain_name_servers=8.8.8.8
2 RaspberryPi
IPAddress cmdline.txt
python
print printHello
varint =10
+ */
==,>=,<=,>,<
if..else
ifx>10:
printxislarge
else:
printxissmall
loop
x=0
whilex<10
printHello
x=x+1
python
nano
nano helloworld.py
Run pythoninterpreter
python
pythonhelloworld.py
sudo pythonhelloworld.py
3 GPIOBlink
LED
100Ohm
GND
3 GPIOBlink
nano led.py
python
importRPi.GPIO asGPIO
importtime
GPIO.setmode (GPIO.BCM)
LIGHT=4
GPIO.setup(LIGHT,GPIO.OUT)
whileTrue:
GPIO.output(LIGHT,True)
time.sleep(0.5)
GPIO.output(LIGHT,False)
time.sleep(0.5)
3 GPIOBlink
whileTrue:
GPIO.output(LIGHT,True) # GPIO4 High
time.sleep(0.5) #delay0.5
GPIO.output(LIGHT,False) # GPIO4 Low
time.sleep(0.5) #delay0.5
8 1
4 GPIOInput
GPIO17 Switch 10
4 GPIOInput
GPIO17 Input
GPIO.setup(17,GPIO.IN) # GPIO17 Input
GPIO17
val =GPIO.input(17) # val
0 1
LED LED
5 MQTTBroker
MQTTBroker Mosquitto
Mosquitto
AnOpenSourceMQTTv3.1/v3.1.1Broker
MQTTBroker package3
mosquitto istheMQTTbroker(i.e.server)
mosquittoclients arethecommandlineclients
pythonmosquitto arethe Python Library
Repository
Windows
Ubuntu OS Linux
Ubuntu
repository
repository
Alpha,Beta default
repository
http://www.ubuntuthailand.com/
5 MQTTBroker
1. addkeyrepository mosquitto
wget http://repo.mosquitto.org/debian/mosquittorepo.gpg.key
sudo aptkeyaddmosquittorepo.gpg.key
2. source.list.d repository
cd/etc/apt/sources.list.d/
3.addrepository mosquitto
sudo wget http://repo.mosquitto.org/debian/mosquittowheezy.list
5 MQTTBroker
4. updateaptinformation
sudo aptgetupdate
5. package
sudo aptgetinstallmosquitto mosquittoclientspythonmosquitto
6 MQTTBroker
Terminal Subscribe
mosquitto_subh127.0.0.1ttopic
Terminal Publish
mosquitto_pub h127.0.0.1ttopicm"Helloworld
Publish Subscribe
Note:
h host
t topic
m message
WiFi RaspberryPi
Scan SSID sudo iwlist wlan0scan
Config filesystem
sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
network={
ssid="The_SSID_from_earlier"
psk="Your_wifi_password"
}
nano Ctrl+x savefile yes
IPAdress ifconfig
RaspberryPi Subscribe publish Broker
neutron.it.kmitl.ac.th,1883
161.246.38.194,1883
MQTTPublish python
nano pub.py
python
mqttc =mqtt.Client()
mqttc.connect("127.0.0.1",1883)
whileTrue:
mqttc.publish(test/pub",Hello)
time.sleep(2)
MQTTSubscribe python
nano sub.py
python
importpaho.mqtt.client asmqtt
def on_connect(client,userdata,rc):
print("Connectedwithresultcode"+str(rc))
client.subscribe(test/sub")
def on_message(client,userdata,msg):
print(msg.topic+""+str(msg.payload))
client=mqtt.Client()
client.on_connect =on_connect
client.on_message =on_message
client.connect("127.0.0.1",1883)
client.loop_forever()
Broker
ON LED
OFF LED
MQTTbrokergetsWebsockets support
WebServer html javascript
WebBrowser Webapplication html WebServer
MQTTBroker WebSocket Javascript
MQTTbrokergetsWebsockets support
Websocket RaspberryPi
Downloadwget http://www.it.kmitl.ac.th/~panwit/mosquittows.zip
unzip
unzipmosquittows.zip
folder unzip
cdmosquitto1_4ws
chmod +xinstall
sudo servicemosquitto stop
sudo ./install
sudo servicemosquitto start
7 RealTimegraph
Simpleexampleofplottinglivenumbereddatafromasubscribedmqtt/websockets
topicandplottingitusinghighcharts. http://www.highcharts.com/
WebServer Webhosting
html Javascript
livemqttchart.html plot Publish
livemqttchart1.html plot realtime
mqttws31.js
Subscribe Topic
7 RealTimegraph
1. livemqttchart.html
var MQTTbroker =IP Raspi'; //Raspi broker
var MQTTport =8888; //port Webseocket
var MQTTsubTopic ='temp'; // topic
2. Upload 2 webhosting
3. publish topic
Publish Publish Terminal Publish
mosquitto_pub h10.X.X.Xttempm"Helloworld
Note:
Raspberry Broker Default Websocket 8888
mosquitto.conf sudo nano /etc/mosquitto/mosquitto.conf
#listenerportnumber[ip address/hostname]
listener8888
8 ControlviaWebsocket
control.html
Publish Topic
ON publish on Raspi Broker
OFF publish off Raspi Broker
8 ControlviaWebsocket
1. control.html
var MQTTbroker =' IP Raspi '; //broker
var MQTTport =8888; //port Webseocket
var MQTTsubTopic ='temp'; // topic
2. Upload webhosting
3. Raspi Broker Subscribetopic
on,off Broker
WebServer
LocalBroker
MQTTClient
(Arduino +EthernetShield)
WebBrowser
- LED LED website
Note website control.html
: LED&R
TeamA TeamB
LocalBroker
MQTTClient MQTTClient
(Arduino +EthernetShield) (Arduino +EthernetShield)
: Arduino Internet
-
1. TeamA TeamB
2. TeamB sensor TeamA
LED
LED
BridgeBroker
ConfiguringBridges
connection name
Thisvariablemarksthestartofanewbridgeconnection.Itisalsousedtogivethe
bridgeanamewhichisusedastheclientidontheremotebroker.
ConfiguringBridges
topic pattern [[[out|in|both]qoslevel]localprefixremoteprefix]
Defineatopicpatterntobesharedbetweenthetwobrokers.Anytopicsmatchingthepattern
(whichmayincludewildcards)areshared.Thesecondparameterdefinesthedirectionthatthe
messageswillbesharedin,soitispossibletoimportmessagesfromaremotebrokerusing in,
exportmessagestoaremotebrokerusing out orsharemessagesinbothdirections.Ifthis
parameterisnotdefined,thedefaultof out isused.TheQoS leveldefinesthepublish/subscribe
QoS levelusedforthistopicanddefaultsto0.
Forincomingtopics,thebridgewillprependthepatternwiththeremoteprefixandsubscribeto
theresultingtopicontheremotebroker.Whenamatchingincomingmessageisreceived,the
remoteprefixwillberemovedfromthetopicandthenthelocalprefixadded.
Foroutgoingtopics,thebridgewillprependthepatternwiththelocalprefixandsubscribeto
theresultingtopiconthelocalbroker.Whenanoutgoingmessageisprocessed,thelocalprefix
willberemovedfromthetopicthentheremoteprefixadded.
9 BridgeBrokerConfiguration
Rasppi Broker SingleDirection
mosquitto.conf
sudo nano /etc/mosquitto/mosquitto.conf
connectionbridge_test
address161.246.38.194:1883
topiclocal
Restart
sudo /etc/init.d/mosquitto stop
Note:
sudo /etc/init.d/mosquitto start
Connection
Address address
Subscribe Broker Topiclocal
Publish RaspberryPiBroker Topiclocal
9 BridgeBrokerConfiguration
Rasppi Broker DualDirection
mosquitto.conf
sudo nano /etc/mosquitto/mosquitto.conf
connectionbridge_test
address161.246.38.194:1883
topic # both2local/topic/remote/topic/
Subscribe Broker Topicremote/topic
Publish RaspberryPi Topiclocal/topic
connectionbridge_test
address161.246.38.29:1883
topic # both2local/topic/remote/topic/
Subscribe Broker Topicremote/topic/test
Internet Home
Bridge
WebServer
PublicBroker
LocalBroker
MQTTClient
Pub/sub
Pub/sub
WebBrowser
Arduino
- Arduino RaspberryPi
RaspberryPi LED Arduino
RaspberryPi LED Arduino
Website Arduino
( Bridge)
InternetofThings
2560
NodeMCU V2
WhatisNodeMCU
Anopensourcefirmwareanddevelopmentkitthathelpsyouto
prototypeyourIOTproductwithinafewLua scriptlines.
Features
Opensource,Interactive,Programmable,Lowcost,Simple,Smart,
WIFIenabled
NodeMCU Specification
basedonWiFi ESP8266
GPIO, PWM,I2C,1Wire ADC
USBTTL IC CP2102 Slabs
PCBantenna
microUSB
A0 analog(ADC 10 )
100k/220k( 0V 3.3V 0V 1V)
3.3V
NodeMCU V2pinout
BoardNodeMCU Arduino IDE
Arduino IDE
File Preference
http://arduino.esp8266.com/stable/package_esp8266com_index.json
AdditionalBoardsManagerURLs OK
Tools Board BoardsManager
BoardNodeMCU Arduino IDE
Install
BoardNodeMCU Arduino IDE
nodeMCU Boards
GenericESP8266Module
ESP8266
Olimex MODWIFIESP8266(DEV)
ESP8366 Olimex
NodeMCU (ESP8266ESP12Module)
ESP8266 NodeMCU
WeMos D1
ESP8266 wemos
Driver USBTTL
DownloadDriver
http://www.it.kmitl.ac.th/~panwit/CP210x_Windows_Drivers.zip
Unzip driver
BasicOutput
DigitalOutput:Blink AnalogOutput:fading
voidsetup(){ intval;
pinMode(D1,OUTPUT); voidsetup()
} {
voidloop() pinMode(D1,OUTPUT);
{ }
digitalWrite(D1,LOW); voidloop()
delay(500); {
digitalWrite(D1,HIGH); for(val=0;val<1000;val+=50)
delay(500); {
} analogWrite(D1,val);
delay(100);
}
}
Note!! DutyCycle
0..1023 (0% 100%)
BasicInput
DigitalInput: Switch
voidsetup(){
pinMode(D0,OUTPUT); 3.3V
pinMode(D1,INPUT);
} NodeMCU
voidloop() 4.7k 220
{ D1 D0 LED
if(!digitalRead(D1)) Switch
digitalWrite(D0,HIGH);
else
digitalWrite(D0,LOW);
}
BasicInput
AnalogInput:
AnalogPin ADCPin Input
01v
const int AnalogIn = A0;
NodeMCU Pin Analog
1pin A0 int val = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
val = analogRead(AnalogIn);
Serial.println(val);
}
ConnectNodeMCU toWirelessNetwork
WiFi.begin()
Description
Initializesthe WiFi library'snetworksettingsandprovidesthe
currentstatus.
Syntax
WiFi.begin();
WiFi.begin(ssid);
WiFi.begin(ssid, pass);
Returns
WL_CONNECTED whenconnectedtoanetwork
WL_IDLE_STATUS whennotconnectedtoanetwork,but
poweredon
ConnectNodeMCU toWirelessNetwork
WiFi.status()
Description
Returntheconnectionstatus.
Syntax
WiFi.status();
Returns
WL_CONNECTED:assignedwhenconnectedtoa WiFi network;
WL_IDLE_STATUS:itisatemporarystatusassignedwhen WiFi.begin() is
calledandremainsactiveuntilthenumberofattemptsexpires
WL_NO_SSID_AVAIL:assignedwhennoSSIDareavailable;
WL_CONNECT_FAILED:assignedwhentheconnectionfailsforalltheattempts;
WL_CONNECTION_LOST:assignedwhentheconnectionislost;
WL_DISCONNECTED:assignedwhendisconnectedfromanetwork;
ConnectNodeMCU toWirelessNetwork
WiFi.localIP() WiFi.disconnect()
Description Description
Getsthe WiFi shield'sIPaddress Disconnectsthe WiFi fromthe
currentnetwork.
Syntax
WiFi.localIP(); Syntax
WiFi.disconnect();
Returns
theIPaddress Returns
nothing
ConnectNodeMCU toWirelessNetwork
#include <ESP8266WiFi.h> while (WiFi.status() != WL_CONNECTED)
{
const char* ssid = SSID_name"; delay(500);
const char* password = PASSWORD"; Serial.print(".");
}
void setup() {
Serial.begin(115200); Serial.println("");
delay(10); Serial.println("WiFi connected");
IoT withNodeMCU
Publish
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char buffer_str[40];
void setup() {
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
}
IoT withNodeMCU
Publish
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
IoT withNodeMCU
Publish
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection..."); // Attempt to connect
char clientID[15];
String("iot-" + String(random(1000000))).toCharArray(clientID, 15);
//Random Client ID
if (client.connect(clientID)) {
Serial.println("Successfully connected with MQTT");
Serial.print("Client: ");
Serial.println(clientID);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying
delay(1000);
}
}
}
IoT withNodeMCU
Publish
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
delay(10000);
}
DownloadCode
http://www.it.kmitl.ac.th/~panwit/nodeMCU_code.zip
IoT withNodeMCU
Subscribe
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback); //*****
}
IoT withNodeMCU
Subscribe
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
IoT withNodeMCU
Subscribe
void callback(char* topic, byte* payload, unsigned int length) {
String payload_str = "";
String topic_str = String(topic);
for (int i = 0; i < length; i++) {
payload_str += (char)payload[i];
}
Serial.print("Message arrived [");
Serial.print(topic_str);
Serial.print("] ");
Serial.println(payload_str);
}
IoT withNodeMCU
Subscribe
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection..."); // Attempt to connect
char clientID[15];
String("iot-" + String(random(1000000))).toCharArray(clientID, 15);
if (client.connect(clientID)) {
Serial.println("Successfully connected with MQTT");
Serial.print("Client: ");
Serial.println(clientID);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying
delay(1000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
Internet Local
PublicBroker
Bridge
WebSocket
Pub/sub
LocalBroker
Pub/sub
Pub/sub
WebBrowser
NodeMCU
Arduino
panwit@it.kmitl.ac.th
InternetofThings
Communication
Communication
ObjectCommunication
ObjectCommunication
ObjectCommunication
CartoCarCommunication
CartoCarCommunication
EmergencyVehicle
CartoCarCommunication
EmergencyVehicle
InternetofThings
43
Imagecourtesy:Wilgengebroed
Sensordevicesarebecomingwidelyavailable
- Programmable devices
- Off-the-shelf gadgets/tools
44
PeopleConnectingtoThings
ECG sensor
Internet
Motion sensor
Motion sensor
Motion sensor
45
MoreThings arebeingconnected
Home/daily-life devices
Business and
Public infrastructure
Health-care
46
ThingsConnectingtoThings
47
ApplicationScenario:Shopping
WhatisInternetOfThings
WhatisInternetOfThings
InternetofThings IEEE 27May2015
(IEEE_IoT_Towards_Definition_Internet_of_Things_Revision1_27MAY15.pdf)
AnIoT isanetworkthatconnectsuniquelyidentifiable
ThingstotheInternet.TheThingshave
sensing/actuationandpotentialprogrammability
capabilities.Throughtheexploitationofunique
identificationandsensing,informationabouttheThing
canbecollectedandthestateoftheThingcanbe
changedfromanywhere,anytime,byanything.
WhatisInternetOfThings
InternetofThingsfeatures
InterconnectionofThings
ConnectionofThingstotheInternet
UniquelyIdentifiableThings
Ubiquity
Sensing/Actuationcapability
Embeddedintelligence
InteroperableCommunicationCapability
Selfconfigurability
Programmability
MQTTProtocol
InventedbyAndyStanfordClark (IBM)andArlenNipper(Eurotech)in1999
OriginallyenvisionedforuseoverSatellitelinkfromanoilpipeline
MQTTProtocol
MQTTProtocol
MQTTProtocol
Thepublish/subscribepattern
Bidirectional,Async PushCommunication
MQTT
Broker
MQTTProtocol
MQTTProtocol
Subscribe
Aclientneedstosenda SUBSCRIBE messagetotheMQTT
brokerinordertoreceiverelevantmessages.
Subscribe
Publish
Publish
Topics
AtopicisaUTF8string,whichisusedbythebrokertofiltermessagesforeachconnectedclient.Atopicconsists
ofoneormoretopiclevels.Eachtopiclevelisseparatedbyaforwardslash(topiclevelseparator).
QoS
AQualityofServiceLevel(QoS)forthismessage.Thelevel(0,1or2)determinestheguaranteeofamessage
reachingtheotherend
RetainFlag
Thisflagdeterminesifthemessagewillbesavedbythebrokerforthespecifiedtopicaslastknowngoodvalue.
Newclientsthatsubscribetothattopicwillreceivethelastretainedmessageonthattopicinstantlyafter
subscribing.( Broker Payload Subscribe )
Payload
Thisistheactualcontentofthemessage.
DUPflag
Theduplicateflagindicates,thatthismessageisaduplicateandisresentbecausetheotherenddidnt
acknowledgetheoriginalmessage.ThisisonlyrelevantforQoS greaterthan0
PacketIdentifier
Thepacketidentifierisauniqueidentifierbetweenclientandbrokertoidentifyamessageinamessageflow.
ThisisonlyrelevantforQoS greaterthanzero.
QoS
QoS 0 atmostonce
Theminimalleveliszeroanditguaranteesabesteffortdelivery.Amessagewont
beacknowledgedbythereceiverorstoredandredeliveredbythesender.
QoS 1 atleastonce
itisguaranteedthatamessagewillbedeliveredatleastoncetothereceiver.The
senderwillstorethemessageuntilitgetsanacknowledgementinformof
a PUBACK commandmessagefromthereceiver.
QoS
QoS 2 Exactlyonce
ThehighestQoS is2,itguaranteesthateachmessageisreceivedonlyoncebythe
counterpart. Itisthesafestandalsotheslowestqualityofservicelevel.The
guaranteeisprovidedbytwoflowsthereandbackbetweensenderandreceiver.
Publishreceived Publishcomplete
Publishrelease
QoS
Retainmessages
Payload
Unsubscribe
Connect&Disconnect
1 PublicMQTTBroker
Website URL
http://www.hivemq.com/demos/websocketclient//
1 PublicMQTTBroker
Connect
Connect
Subscribe
AddTopicSubscription add subscribe
Subscribe
Publish
topic publish
publish
publish
MQTTbrokergetsWebsockets support
WebServer html javascript
WebBrowser Webapplication html WebServer
MQTTBroker WebSocket Javascript
IT@KMITL Web Hosting
100M
PHP MySQL
URL http://www.it.kmitl.ac.th/~username/
Direct Admin
http://ihost.it.kmitl.ac.th
Database phpmyadmin
Upload file ftp
2 RealTimegraph
Simpleexampleofplottinglivenumbereddatafromasubscribedmqtt/websockets
topicandplottingitusinghighcharts. http://www.highcharts.com/
WebServer Webhosting
html Javascript
livemqttchart.html plot Publish
livemqttchart1.html plot realtime
mqttws31.js
Subscribe Topic
2 RealTimegraph
1. livemqttchart.html
var MQTTbroker =xxx.xxx.xxx.xxx'; //broker
var MQTTport =3000; //port Webseocket
var MQTTsubTopic ='temp'; // topic
2. Upload 2 webhosting
3. publish topic
Publish Publish RaspberryPi Publish
Broker
Note:
Raspberry Broker Default Websocket 8888
mosquitto.conf sudo nano /etc/mosquitto/mosquitto.conf
#listenerportnumber[ip address/hostname]
listener8888
3 ControlviaWebsocket
control.html
Publish Topic
ON publish on Broker
OFF publish off Broker
3 ControlviaWebsocket
1. control.html
var MQTTbroker =xxx.xxx.xxx.xxx'; //broker
var MQTTport =3000; //port Webseocket
var MQTTsubTopic ='temp'; // topic
....
2. Upload webhosting
3. Broker Subscribetopic
on,off Broker