Sie sind auf Seite 1von 46

SCHOOLOFDIGITALMEDIAANDINFOCOMMTECHNOLOGY(DMIT)

ST0324InternetofThings(IoT)

Practical11Code
anIoTappusing
AmazonWeb
Services(AWS)

Whatyouwilllearn/dointhislab
1. LearnhowtocodeanIoTappusingAmazonWebServices(AWS)
2. LearnhowtocreateAWSIoTrules
3. LearnhowtouploadimagestoAWSsS3bucketsandtouseits
Rekognitionservicetoperformimagerecognition

06Jul17
08:55PM

Table of Contents

1. Overview....................................................................................................................................3
Whatyouwilldoforthislab............................................................................................3
IntrotoAmazonWebServices(AWS).............................................................................3
WhydevelopIoTappsonCloud?....................................................................................3
2. SignupforAWSEducateaccount..............................................................................................4
SetupanewAWSaccount..............................................................................................4
3. SignintoAWSIoTConsole........................................................................................................6
SignintotheAWSIoTConsole........................................................................................6
4. RegisteryourRaspberryPiasaThing........................................................................................7
CreateandregisteryourThing.....................................................................................7
CopyRESTAPIendpointofyourThing.........................................................................9
CreateCertificates.........................................................................................................10
CreateaSecurityPolicyforyourRPi..............................................................................12
AttachSecurityPolicyandThingtoyourCert...............................................................13
5. InstalltheAWSPythonSDK.....................................................................................................16
InstalltheAWSPythonlibrary.......................................................................................16
6. CodetheIoTapp......................................................................................................................17
AsimpleAWSpubsubprogram.....................................................................................17
7. Runtheapp..............................................................................................................................19
CopytherequiredSecurityfiles.....................................................................................19
HardwareSetup.............................................................................................................20
EnsurePahoMQTTisinstalled......................................................................................20
Runtheprogram............................................................................................................21
ViewMQTTmessages....................................................................................................22
8. AWSIoTRulesPart1................................................................................................................23
CreateanAWSSNSTopic..............................................................................................23
SubscribetoanAmazonSNSTopic................................................................................24
CreateanAWSIoTRule.................................................................................................26
TesttheAWSIoTRule....................................................................................................30
9. UploadimagestoS3................................................................................................................32
IntrotoAWSS3..............................................................................................................32
CreateabucketonAmazonS3......................................................................................33

CreatedbyDora Page1of45

06Jul17
08:55PM

InstallBotoonRaspberryPi...........................................................................................34
InstallAWSCLIonRaspberryPi.....................................................................................34
Setupauthenticationcredentials...................................................................................35
Setupauthenticationcredentials...................................................................................37
CodethePythonfile......................................................................................................38
RunthePythoncode......................................................................................................39
CheckthatfileisuploadedinS3Console..........................................................................40
10. RecogniseimagesusingRekognition.......................................................................................41
WhatIsAmazonRekognition?.......................................................................................41
Whatwillyoudointhissection?...................................................................................41
CodethePythonfile......................................................................................................41
RunthePythoncode......................................................................................................44
11. AWSRegions............................................................................................................................45
AWSS3Regions.............................................................................................................45

CreatedbyDora Page2of45

06Jul17
08:55PM

1. Overview

What you will do for this lab

Inthislab,youaregoingtolearnhowtocreateanIoTappusingtheAmazonWebServices(AWS)
platform.

Intro to Amazon Web Services (AWS)

AmazonWebServices,asubsidiaryofAmazon.com,offersasuiteofcloudcomputingservicesthat
operatefrom16geographicalregionsacrosstheworld.

Cloudcomputingistheondemanddeliveryofcomputepower,databasestorage,applications,
andotherITresourcesthroughacloudservicesplatformviatheinternetwithpayasyougo
pricing.

Withcloudcomputing,companiesneednotmakelargeupfrontinvestmentsinhardwareandspend
alotoftimeonmanagingthathardware.Instead,theycanprovisionexactlytherighttypeandsize
ofcomputingresourcestheyneedfromcloudproviderslikeAWS,andpayAWSbasedonthe
configurationoftheresourcestheyuse,andtheamountofusagetheyincur.

Why develop IoT apps on Cloud?

InmanytypicalIoTdeployments,thecentralsystemmightbecollectingdatafromhundredsor
eventhousandsofsensordevices.Itrequirestremendousamountofresourcestomaintainthe
infrastructureneededtomanagethecollectionofdatafromthedevicesandtoprocessthem,ifthe
hardwareisallmaintainedbytheorganisationutilisingtheIoTsolution.

UsingIoTCloudVendorssuchasAWS,MicrosoftAzure,IBMWatson,GoogleCloudtomanagethe
collectionofsensordata,organisationscanberestassuredthatthelatencyoftheirIoTappsiskept
lowasthesecloudvendorscantypicallyscaletobillionsofdevicesandtrillionsofmessages.The
cloudvendorswouldalsohelptoensurethesecurityofthecloud,whichtakesanotherloadoffthe
IoTdeveloper.

CreatedbyDora Page3of45

06Jul17
08:55PM

2. Sign up for AWS Educate account

TobegincodingIoTappsusingAWS,youwillneedtosetupanAWSEducateaccountifyoudonot
alreadyhaveone.

TheAWSEducateisAmazon'sprogrammetohelpstudentslearnrealworldcloudtechnologyskills
beforegraduating.Underthisprogramme,studentswillgetarenewableannualcreditofUSD100
ofAWSservices.Nocreditcardisnecessarytosignupforthisaccount.However,onceyouhave
useduptheUSD100credit,youraccountwillautomaticallyberenderedunusable.

Set up a new AWS account

No Task

a) AccessAWSEducatewebsite:https://aws.amazon.com/education/awseducate/apply/
SelectStudentsoption

b) SelectRoleasStudent

CreatedbyDora Page4of45

06Jul17
08:55PM

No Task

c) Onthesignupform,ensurethefollowingsettingsarespecified,andfillintherestof
theformasappropriateandthenclickNextbutton.

d) Institutionnameis
SingaporePolytechnic
SchoolofEEE
EmailisyourSPichatemail
address

Clickheretoselectan
AWSEducateStarter
accountisselected

e) Followtheinstructionstoverifyyour
accountbyprovidingaverificationcode
thatissenttoyourichatemailaccount.

f) Onceyour
AWS
accountis
readyfor
use,you
willreceive
anemail
similarto
thisone

CreatedbyDora Page5of45

06Jul17
08:55PM

3. Sign in to AWS IoT Console

AfteryouhavereceivedtheemailconfirmationfromAWS,youarenowreadytologintotheAWS
IoTconsoletostartthelab.

Sign in to the AWS IoT Console

No Task

a) TurnonyourRaspberryPiandconfirmyouhaveanInternetconnection.

b) SigninwithyourAWSconsoleathttps://aws.amazon.com

c) IntheAWSdashboard,typeAWSIoTtoaccesstheAWSIoTservice.

d) OntheWelcome
page,chooseGet
started

CreatedbyDora Page6of45

06Jul17
08:55PM

4. Register your Raspberry Pi as a Thing

Inthissection,youwilllearnhowtocreateandregisteryourRaspberryPiasaThingwithAWS
IoT.

Create and register your Thing

No Task

a) Intheleftnavigationpane,clickRegistrytoexpandit,
thenchooseThings.

b) OnthepagethatsaysYoudon'thave
anythingsyet,chooseRegistera
thing.

Ifyouhavecreatedathingbefore,
chooseCreate.

CreatedbyDora Page7of45

06Jul17
08:55PM

No Task

c) AthingrepresentsadevicewhosestatusordataisstoredintheAWScloud.TheThing
Shadowsisthestateofthedevice,e.g.isitonoroff,isitredorgreenetc.

OurthinghereisourRPi,soletstypeMyRaspberryPiforthename.

ClickCreatething

CreatedbyDora Page8of45

06Jul17
08:55PM

Copy REST API endpoint of your Thing

No Task

a) OntheDetailspage,chooseInteract.

b) Copyandpastethe
RESTAPIendpoint
intoaNotepad.

Youwillneedthis
valuelater.

CreatedbyDora Page9of45

06Jul17
08:55PM

Create Certificates

No Task

a) Next,chooseSecurity

b) ChooseCreatecertificatetogenerateanX.509certificateandkeypair.

CreatedbyDora Page10of45

06Jul17
08:55PM

No Task

c) Afterawhile,you
shouldseethe
followingscreen,
wherethereareatotal
offourdownloadlinks.

d) CreateaworkingdirectorycalleddeviceSDK
anddownloadallthe4filesaboveinthis
deviceSDKdirectory,renamingthemwith
friendlynameslikewhatIhavedone.

e) Next,clicktheActivatebutton.

Almostimmediately,youshouldsee
Successfullyactivatedcertificateand
theActivatebuttonchangesto
Deactivate

CreatedbyDora Page11of45

06Jul17
08:55PM

Create a Security Policy for your RPi

Task

a) Next,clickontheAttachapolicybuttonthat
isnearthebottoomrighthandcornerofthe

page.

b) Onthenextpage,chooseCreatenewpolicy

c) OntheCreateapolicypage,keyin Field Typethisin


thefollowingconfigurationandthen Name MyRaspberryPiSecurityPolicy
clickCreate Action iot:*
ResourceARN *


Allow Checked

CreatedbyDora Page12of45

06Jul17
08:55PM

Task

d) Youwillseeapagesimilartothatbelow,moveaheadtoclicktheBackarrowto
returntothepreviouspageandcontinuewiththeinstructionsinthenextsection.

Attach Security Policy and Thing to your Cert

Inthissection,youwillattachbothyoursecuritypolicyandyourThingtoyourX.509certificate

Task

a) Ontheleftnavbar,clickSecurity,Certificates

CreatedbyDora Page13of45

06Jul17
08:55PM

Task

b) TheX.509certificateyou
createdearlierisshown.

Clickthecheckboxbeside
it,thenclickActions
buttonandchoose
AttachPolicy

c) Checkthe
MyRaspberryPiSecurityPolicy
youcreatedearlierandclick
Attachbutton.

d) LetsattachtheThingtothis
certificate.

ClickActionsbuttonandchoose
AttachThing

CreatedbyDora Page14of45

06Jul17
08:55PM

Task

e) IntheAttachthingsto
certificate(s)dialogbox,selectthe
checkboxnexttothethingyou
createdtorepresentyour
RaspberryPi,andthenchoose
Attach

CreatedbyDora Page15of45

06Jul17
08:55PM

5. Install the AWS Python SDK

Bynow,youhavecompletedthefirstpartoftheprocesstoconnectyourdevicetoAWScloud.

Inthenextfewsections,youwillbegintocodeyourapp.However,beforeyoucanstartcodingan
IoTappontheAWSCloud,youwillneedtoinstalltheAWSPythonsoftwarelibrariesfirst.

Install the AWS Python library

No Task

a) InstalltheAWSPythonlibrarywiththiscommand
sudopipinstallAWSIoTPythonSDK

CreatedbyDora Page16of45

06Jul17
08:55PM

6. Code the IoT app

Inthissection,youwillwriteasimplePythonprogramthatreadsthevaluesfromyourMCP3008
ADCandsendittoAWS.

A simple AWS pubsub program

No Task

a) Createafilenamedaws_pubsub.pywiththefollowingcode

aws_pubsub.py

#ImportSDKpackages
fromAWSIoTPythonSDK.MQTTLibimportAWSIoTMQTTClient
fromtimeimportsleep
fromgpiozeroimportMCP3008

adc=MCP3008(channel=0)

#CustomMQTTmessagecallback
defcustomCallback(client,userdata,message):
print("Receivedanewmessage:")
print(message.payload)
print("fromtopic:")
print(message.topic)
print("\n\n")

host="YourEndPoint.amazonaws.com"
rootCAPath="rootca.pem"
certificatePath="certificate.pem.crt"
privateKeyPath="private.pem.key"

my_rpi=AWSIoTMQTTClient("basicPubSub")
my_rpi.configureEndpoint(host,8883)
my_rpi.configureCredentials(rootCAPath,privateKeyPath,certificatePath)

my_rpi.configureOfflinePublishQueueing(1)#InfiniteofflinePublishqueueing

CreatedbyDora Page17of45

06Jul17
08:55PM

No Task

my_rpi.configureDrainingFrequency(2)#Draining:2Hz
my_rpi.configureConnectDisconnectTimeout(10)#10sec
my_rpi.configureMQTTOperationTimeout(5)#5sec

#ConnectandsubscribetoAWSIoT
my_rpi.connect()
my_rpi.subscribe("sensors/light",1,customCallback)
sleep(2)

#Publishtothesametopicinaloopforever
loopCount=0
whileTrue:
light=round(1024(adc.value*1024))
my_rpi.publish("sensors/light",str(light),1)
sleep(5)

CreatedbyDora Page18of45

06Jul17
08:55PM

7. Run the app

Congratulations,youarealmostdone!

Towrapupthislab,runyourprogramtoverifythatyoucanconnecttoAWSandpublishand
receivesensormessagesusingtheMQTTprotocolasshownintheinstructionsbelow.

Copy the required Security files

No Task

a) Beforeyourunyourprogram,itisessentialthatyouplaceyourRootCA,privatekey
andthingcertificateinthesamefolderaswhereyouhadcodedaws_pubsub.py.

Renameyourfilesasshownhere,toensurethecodegiveninSection6matchesthe
filenames.

CreatedbyDora Page19of45

06Jul17
08:55PM

Hardware Setup

Ensureyouhavethefollowinghardwaresetup,whichissimilartothatofPractical6and10.

No Task

a) UsethesamehardwaresetupasinPractical6(Blynk)andPractical10(Bluemix)
MCP3008+10Kohmsresistor+LightDependantResistor(LDR)
LEDlight+330ohmsresistor

b) ConnecttheLDRtoPinA0ontheMCP3008andtheLEDlighttoBCMPin4(OrPin18
ifPin4doesntworkforyou)

Ensure Paho MQTT is installed

No Task

a) TheAWSPythonSDKhasdependencyonpahomqtt,somakesureitisinstalledon
yourRPI.
sudopipinstallpahomqtt

CreatedbyDora Page20of45

06Jul17
08:55PM

Run the program

No Task

a) Runtheaws_pubsub.py
sudopythonaws_pubsub.py

b) Afterawhile,youshouldseethevalues
oftheLDRbeingreceivedbythe
subscriberlikethis.

CreatedbyDora Page21of45

06Jul17
08:55PM

View MQTT messages

YoucanusetheAWSIoTMQTTclienttoviewtheMQTTmessagessentbyyourRPi.

No Task

a) IntheAWSIoTconsole,intheleftnavigationpane,chooseTest.

Typeinthetopiconwhichyourthingpublishes.Inourcase,itissensors/light

ClickSubscribetotopic

b) Clickonthesensors/lighttopic.YoushouldseethevaluespublishedbyyourRpiin
theconsoleasshown.

CreatedbyDora Page22of45

06Jul17
08:55PM

8. AWS IoT Rules Part 1

Intheprevioussection,yousuccessfullysentmessagesfromyourRaspberryPitoyourAWS
account.However,itisnotmuchuseifyoukeepsendingthemessagestothecloudwithoutstoring
themorprocessingthem.

Whatrealworldapplicationsdo,afterreceivingmessagesinthecloudistoactonthemessages
received,eitherbychannellingthemtopermanentstoragelikearelationaldatabaseortoperform
somerealtimeanalysisonthem.

Inthissection,youwilllearnhowtouseaspecialfeatureknownasAWSIoTRulestotake
informationfromanincomingMQTTmessageandwriteittoaAWSSimpleNotificationService
(SNS)topicwhichthenssendsemailtoyou.Havefun!

Create an AWS SNS Topic

No Task

a) OpentheAmazonSNSconsole
(https://apsoutheast
1.console.aws.amazon.com/sns/v2)and
chooseGetStarted

b) ChooseTopics

c) ChooseCreatenew
topic

d) Typeatopicnameandadisplayname,andthenchooseCreatetopic.

CreatedbyDora Page23of45

06Jul17
08:55PM

No Task

e) MakeanoteoftheARNforthetopicyoujustcreated.

Subscribe to an Amazon SNS Topic

Inthissection,youwilllearnhowtocreateanAmzonSNStopicwhichallowsyoutoreceiveemails
wheneverIoTdataispublishedattheIoTHubyouconfiguredearlier.

No Task

a) IntheAmazonSNSconsole,selectthecheckboxnexttothetopicyoujustcreated.
FromtheActionsmenu,chooseSubscribetotopic.

CreatedbyDora Page24of45

06Jul17
08:55PM

No Task

b) OnCreatesubscription,fromtheProtocoldropdownlist,chooseSMS.

IntheEndpointfield,typeyouremailaddressandthenchooseCreatesubscription.

c) Youwillreceiveanemailthatconfirmsyousuccessfullycreatedthesubscription.Clickon
thelinktoconfirmsubscription.

CreatedbyDora Page25of45

06Jul17
08:55PM

No Task

d)

Create an AWS IoT Rule

TheAWSIoTrulesenginelistensforincomingMQTTmessagesthatmatcharule.Whenamatching
messageisreceived,theruletakessomeactionwiththedataintheMQTTmessage.Inthisstep,
youwillcreateandconfigurearuletosendthedatareceivedfromadevicetoanAmazonSNStopi

No Task

a) IntheAWSIoTconsole,intheleftnavigationpane,choose
Rules,thenCreatearule

CreatedbyDora Page26of45

06Jul17
08:55PM

No Task

b) OntheCreatearulepage,inthe
Namefield,typeanameforyour
rule.IntheDescriptionfield,typea
descriptionfortherule.

c) ScrolldowntoMessage
source.Choosethelatest
versionfromtheUsingSQL
versiondropdownlist.Inthe
Attributefield,type*.This
specifiesthatyouwantto
sendtheentireMQTT
messagethattriggeredthe
rule.

CreatedbyDora Page27of45

06Jul17
08:55PM

No Task

d) Therulesengineusesthe
topicfiltertodeterminewhich
rulestotriggerwhenanMQTT
messageisreceived.

IntheTopicfilterfield,type
sensors/light

Leavetheconditionblank

e) InSetoneormoreactions,chooseAddaction.

f) OntheSelectanactionpage,select
SendamessageasanSNSpush
notification,andthenchoose
Configureaction.

g) OntheConfigureactionpage,from
theSNStargetdropdownlist,
choosetheAmazonSNStopicyou
createdearlier.

h) NowyouneedtogiveAWSIoTpermissiontopublishtotheAmazonSNStopiconyour
behalfwhentheruleistriggered.

ChooseCreateanewrole.EnteranameforyournewroleintheIAMrolenamefield.

CreatedbyDora Page28of45

06Jul17
08:55PM

No Task

i) Afteryouhaveenteredthename,chooseCreateanewroleagain.Selectthenewly
createdrolefromtheIAMrolenamedropdownlist.

ChooseUpdateroletoapplythepermissionstothenewlycreatedrole,andthen
chooseAddaction.

j) Choose Add action.

You will be returned to the previous


screen as shown below.

CreatedbyDora Page29of45

06Jul17
08:55PM

No Task

k) OntheCreateaRulepage,chooseCreaterule.

l) OntheOverviewpagefortherule,choosetheleftarrowtoreturntotheAWSIoT
dashboard.

Test the AWS IoT Rule

No Task

a) Runtheaws_pubsub.py
sudo python aws_pubsub.py

b) Afterawhile,youshouldreceiveanemailfromAWSSNSnotifyingyouofthelight
valuesasshownbelow.

c) Clickonthelinktounsubscribetothetopic!

CreatedbyDora Page30of45

06Jul17
08:55PM

No Task

CreatedbyDora Page31of45

06Jul17
08:55PM

9. Upload images to S3

http://boto3.readthedocs.io/en/latest/guide/quickstart.html

Inthissection,youwilllearnhowtouploadimagesyoutakewithyourPicamtocloudstorage,
specifically,AmazonscloudstorageknownasS3.YouwillautomatetheuploadingofthepiCam
imageusingtheBotoPythonAPIprovidedbyS3andbeamazedbyhowlittlecodeyouneedto
achievethis.Havefun

Intro to AWS S3

AmazonSimpleStorageService(S3)isAmazonsstorageservicefortheInternet
https://console.aws.amazon.com/s3/

S3providesasimplewebservicesinterfacethatyoucanusetostoreandretrieveanyamountof
data,atanytime,fromanywhereontheweb.

TostoredataonS3,youwillneedtocreateanS3BucketinaspecifiedAWSregion.AnS3bucket
servesasacontainerforyoutoorganisetheobjectsyouwanttostoreinthecloudandhasa
standardURLforaccessingtheobjects.

Forexample,Icancreateabucketnameddorachuabucketinuswest2,whichisthedatacenter
inUSAOregon.IfIthenuploadafilenameddora.jpgtothisbucket,thefilewouldhaveanURL
ofhttps://s3uswest2.amazonaws.com/dorachuabucket/dora.jpg

Inthenextsection,youwilllearnhowtocreateabucketonS3usingtheAWSconsole.
Subsequently,insectionsCtoG,youwilllearnhowtoprogrammaticallyuploadimagestotheS3
bucketyouhavecreated.

CreatedbyDora Page32of45

06Jul17
08:55PM

Create a bucket on Amazon S3

No Task

a) LoginyourAWSconsoleandsearchfor
S3

b) ClickCreatebucket

c) Typeinaunique
nameforyour
bucketandchoose
RegionasUS
West(Oregon)
whichisuswest2

ClickCreate
button

d) Afterawhile,yournewlycreatedbucketshouldappearinthelist.

CreatedbyDora Page33of45

06Jul17
08:55PM

No Task

Install Boto on Raspberry Pi

No Task

a) TypethefollowingcommandtoinstallBoto,thePythonlibraryforAWSonyour
RaspberryPi
sudo pip install boto3

Install AWS CLI on Raspberry Pi

No Task

a) TypethefollowingcommandtoinstalltheAWSCommandLineInterfaceClienton
yourRaspberryPi
sudo pip install awscli

CreatedbyDora Page34of45

06Jul17
08:55PM

Setup authentication credentials

InorderthatyouareabletouseAPIcallstowritetoAmazonS3buckets,youwillneedtosetup
credentialsforit.

Task

a) LoginyourAWSconsoleandsearchforIAM



b) ClickonUsers
submenu,Add
user

c) Createanewuser
botouserand
enable
Programmatic
access

CreatedbyDora Page35of45

06Jul17
08:55PM

Task

d) Inthenextscreen,
clickAttach
existingpolicies
directly

e) Scrolltothe
bottomofthe
page,searchfor
s3andthen
checkthe
AmazonS3FullAcc
essoption

f) Next,searchforRekognition
andthencheckthe
AmazonRekognitionFullAcces
soption

CreatedbyDora Page36of45

06Jul17
08:55PM

Task

g) ClicktheNext:Reviewbuttonatthe
bottomofthepageontheright,then
onthenextpage,clickCreateuser

h) Youshouldseethesuccesspageabovewithalinktodownloadacsvfile.

Makesureyoudownloadthe.csvfiletoyourlaptop

Youwillneedtorefertothemlater.

Setup authentication credentials

No Task

a) OnyourRaspberryPi,navigatetothedirectorywhereyourPythoncodewillbestored
cd ~/labs/p11

b) TypethefollowingcommandinyourRaspberryPiterminalsothatyoucanusethe
AWSCLItoconfigureyourcredentialsfile:
aws configure

c) EntertheAccessKeyIDandSecretAccessKeyidyouobtainedfromtheprevious
sectionwhenyoucreatedthebotouseraccountbyreferringtothe.csvfileyou
downloaded.

CreatedbyDora Page37of45

06Jul17
08:55PM

No Task

Code the Python file

No Task

a) CreatethefollowingfilewiththePythoncodebelowwhichusesthePicamtotakea
photo,andthenuploadsittoAmazonS3.

Replacebucket_namewiththenameofyourownS3bucket.

boto_s3_1.py
importboto3
importbotocore
frompicameraimportPiCamera
fromtimeimportsleep

#CreateanS3resource
s3=boto3.resource('s3')

camera=PiCamera()
sleep(5)
full_path='/home/pi/Desktop/image1.jpg'
file_name='image1.jpg'
camera.capture(full_path)
sleep(3)

#Setthefilenameandbucketname
bucket_name='dorachuabucket1'#replacewithyourownuniquebucketname
exists=True

CreatedbyDora Page38of45

06Jul17
08:55PM

No Task


try:
s3.meta.client.head_bucket(Bucket=bucket_name)
exceptbotocore.exceptions.ClientErrorase:
error_code=int(e.response['Error']['Code'])
iferror_code==404:
exists=False

ifexists==False:
s3.create_bucket(Bucket=bucket_name,CreateBucketConfiguration={
'LocationConstraint':'uswest2'})

#Uploadanewfile
s3.Object(bucket_name,file_name).put(Body=open(full_path,'rb'))
print("Fileuploaded")

#s3.upload_file(full_path,bucket_name,file_name)

Run the Python code

No Task

a) ImportantEnsureyouDONOTusesudo
python boto_s3_1.py

b) Youshouldseeoutputsimilartothatbelow.

CreatedbyDora Page39of45

06Jul17
08:55PM

Check that file is uploaded in S3 Console

No Task

a) Gobacktothe
S3consolein
AWS,and
checkthatthe
filehasbeen
successfully
uploadedas
showninAWS
console

CreatedbyDora Page40of45

06Jul17
08:55PM

10. Recognise images using Rekognition

http://boto3.readthedocs.io/en/latest/reference/services/rekognition.html#rekognition

What Is Amazon Rekognition?

AmazonRekognitionisaservicethatenablesyoutoaddimageanalysistoyourapplications.With
Rekognition,youcandetectobjects,scenes,andfacesinimages.Youcanalsosearchandcompare
faces.

What will you do in this section?

Inthissection,youwillusetheAmazonRekognitionDetectLabelsAPIoperationtodetectobjects,
concepts,andscenesinanimage(JPEGorPNG)thatyouprovideasinput.Youwillbetakinga
photowithyourpiCam,uploadittoyourAmazonS3bucketandspecifytheobjectkeynameforthe
APItoperformtherecognition.

Code the Python file

No Task

a) CreatethefollowingfilewhichcontainsPythoncodewhichusesthePicamtotakea
photo,andthenuploadsittoAmazonS3.

Replacebucket_namewiththenameofyourownS3bucket.

picam_s3_rekognition_2.py
importboto3
importbotocore
frompicameraimportPiCamera
fromtimeimportsleep

#Setthefilenameandbucketname
BUCKET='dorachuabucket1'#replacewithyourownuniquebucketname
location={'LocationConstraint':'uswest2'}
file_path="/home/pi/Desktop"
file_name="test.jpg"

CreatedbyDora Page41of45

06Jul17
08:55PM

No Task


deftakePhoto(file_path,file_name):

withPiCamera()ascamera:
#camera.resolution=(1024,768)
full_path=file_path+"/"+file_name
camera.capture(full_path)
sleep(3)

defuploadToS3(file_path,file_name,bucket_name,location):
s3=boto3.resource('s3')#CreateanS3resource
exists=True

try:
s3.meta.client.head_bucket(Bucket=bucket_name)
exceptbotocore.exceptions.ClientErrorase:
error_code=int(e.response['Error']['Code'])
iferror_code==404:
exists=False

ifexists==False:
s3.create_bucket(Bucket=bucket_name,CreateBucketConfiguration=location)

#Uploadthefile
full_path=file_path+"/"+file_name
s3.Object(bucket_name,file_name).put(Body=open(full_path,'rb'))
print("Fileuploaded")


defdetect_labels(bucket,key,max_labels=10,min_confidence=90,region="uswest2"):
rekognition=boto3.client("rekognition",region)
response=rekognition.detect_labels(
Image={
"S3Object":{
"Bucket":bucket,
"Name":key,
}

CreatedbyDora Page42of45

06Jul17
08:55PM

No Task

},
MaxLabels=max_labels,
MinConfidence=min_confidence,
)
returnresponse['Labels']


takePhoto(file_path,file_name)
uploadToS3(file_path,file_name,BUCKET,location)
forlabelindetect_labels(BUCKET,file_name):

print("{Name}{Confidence}%".format(**label))

CreatedbyDora Page43of45

06Jul17
08:55PM

Run the Python code

No Task

a) BeforerunningyourPythoncode,aim
yourPicamatanobjectthatiseasily
recognisable,e.g.aflowerinan
environmentwithgoodlighting.

Iaimedmineatmyfanathome!


b) ImportantEnsureyouDONOTusesudo
python picam_s3_rekognition_2.py

c) Ifyoumanagedtotakeagoodandclearphoto,youshouldseeoutputsimilartothat
below,showingwhattheRekognitionservicehasidentifiedyourphotoas.

Inmycase,itmanagedtorecogniseitisanelectricfan!

CreatedbyDora Page44of45

06Jul17
08:55PM

11. AWS Regions

AWS S3 Regions

http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region

Region Name Region Endpoint Location


Constraint

US East (N. us-east-1 s3.amazonaws.com (none required)


Virginia)
US East (Ohio) us-east-2 s3.us-east-2.amazonaws.com us-east-2
US West (N. us-west-1 s3-us-west-1.amazonaws.com us-west-1
California)
US West (Oregon) us-west-2 s3-us-west-2.amazonaws.com us-west-2
Asia Pacific ap- s3-ap-southeast- ap-southeast-1
(Singapore) southeast-1
1.amazonaws.com




EndofPractical

CreatedbyDora Page45of45

Das könnte Ihnen auch gefallen