Beruflich Dokumente
Kultur Dokumente
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
Inthislab,youaregoingtolearnhowtocreateanIoTappusingtheAmazonWebServices(AWS)
platform.
AmazonWebServices,asubsidiaryofAmazon.com,offersasuiteofcloudcomputingservicesthat
operatefrom16geographicalregionsacrosstheworld.
Cloudcomputingistheondemanddeliveryofcomputepower,databasestorage,applications,
andotherITresourcesthroughacloudservicesplatformviatheinternetwithpayasyougo
pricing.
Withcloudcomputing,companiesneednotmakelargeupfrontinvestmentsinhardwareandspend
alotoftimeonmanagingthathardware.Instead,theycanprovisionexactlytherighttypeandsize
ofcomputingresourcestheyneedfromcloudproviderslikeAWS,andpayAWSbasedonthe
configurationoftheresourcestheyuse,andtheamountofusagetheyincur.
InmanytypicalIoTdeployments,thecentralsystemmightbecollectingdatafromhundredsor
eventhousandsofsensordevices.Itrequirestremendousamountofresourcestomaintainthe
infrastructureneededtomanagethecollectionofdatafromthedevicesandtoprocessthem,ifthe
hardwareisallmaintainedbytheorganisationutilisingtheIoTsolution.
UsingIoTCloudVendorssuchasAWS,MicrosoftAzure,IBMWatson,GoogleCloudtomanagethe
collectionofsensordata,organisationscanberestassuredthatthelatencyoftheirIoTappsiskept
lowasthesecloudvendorscantypicallyscaletobillionsofdevicesandtrillionsofmessages.The
cloudvendorswouldalsohelptoensurethesecurityofthecloud,whichtakesanotherloadoffthe
IoTdeveloper.
CreatedbyDora Page3of45
06Jul17
08:55PM
TobegincodingIoTappsusingAWS,youwillneedtosetupanAWSEducateaccountifyoudonot
alreadyhaveone.
TheAWSEducateisAmazon'sprogrammetohelpstudentslearnrealworldcloudtechnologyskills
beforegraduating.Underthisprogramme,studentswillgetarenewableannualcreditofUSD100
ofAWSservices.Nocreditcardisnecessarytosignupforthisaccount.However,onceyouhave
useduptheUSD100credit,youraccountwillautomaticallyberenderedunusable.
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
AfteryouhavereceivedtheemailconfirmationfromAWS,youarenowreadytologintotheAWS
IoTconsoletostartthelab.
No Task
a) TurnonyourRaspberryPiandconfirmyouhaveanInternetconnection.
b) SigninwithyourAWSconsoleathttps://aws.amazon.com
c) IntheAWSdashboard,typeAWSIoTtoaccesstheAWSIoTservice.
d) OntheWelcome
page,chooseGet
started
CreatedbyDora Page6of45
06Jul17
08:55PM
Inthissection,youwilllearnhowtocreateandregisteryourRaspberryPiasaThingwithAWS
IoT.
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
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
Task
a) Next,clickontheAttachapolicybuttonthat
isnearthebottoomrighthandcornerofthe
page.
b) Onthenextpage,chooseCreatenewpolicy
CreatedbyDora Page12of45
06Jul17
08:55PM
Task
d) Youwillseeapagesimilartothatbelow,moveaheadtoclicktheBackarrowto
returntothepreviouspageandcontinuewiththeinstructionsinthenextsection.
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
Bynow,youhavecompletedthefirstpartoftheprocesstoconnectyourdevicetoAWScloud.
Inthenextfewsections,youwillbegintocodeyourapp.However,beforeyoucanstartcodingan
IoTappontheAWSCloud,youwillneedtoinstalltheAWSPythonsoftwarelibrariesfirst.
No Task
a) InstalltheAWSPythonlibrarywiththiscommand
sudopipinstallAWSIoTPythonSDK
CreatedbyDora Page16of45
06Jul17
08:55PM
Inthissection,youwillwriteasimplePythonprogramthatreadsthevaluesfromyourMCP3008
ADCandsendittoAWS.
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
Congratulations,youarealmostdone!
Towrapupthislab,runyourprogramtoverifythatyoucanconnecttoAWSandpublishand
receivesensormessagesusingtheMQTTprotocolasshownintheinstructionsbelow.
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)
No Task
a) TheAWSPythonSDKhasdependencyonpahomqtt,somakesureitisinstalledon
yourRPI.
sudopipinstallpahomqtt
CreatedbyDora Page20of45
06Jul17
08:55PM
No Task
a) Runtheaws_pubsub.py
sudopythonaws_pubsub.py
b) Afterawhile,youshouldseethevalues
oftheLDRbeingreceivedbythe
subscriberlikethis.
CreatedbyDora Page21of45
06Jul17
08:55PM
YoucanusetheAWSIoTMQTTclienttoviewtheMQTTmessagessentbyyourRPi.
No Task
a) IntheAWSIoTconsole,intheleftnavigationpane,chooseTest.
Typeinthetopiconwhichyourthingpublishes.Inourcase,itissensors/light
ClickSubscribetotopic
b) Clickonthesensors/lighttopic.YoushouldseethevaluespublishedbyyourRpiin
theconsoleasshown.
CreatedbyDora Page22of45
06Jul17
08:55PM
Intheprevioussection,yousuccessfullysentmessagesfromyourRaspberryPitoyourAWS
account.However,itisnotmuchuseifyoukeepsendingthemessagestothecloudwithoutstoring
themorprocessingthem.
Whatrealworldapplicationsdo,afterreceivingmessagesinthecloudistoactonthemessages
received,eitherbychannellingthemtopermanentstoragelikearelationaldatabaseortoperform
somerealtimeanalysisonthem.
Inthissection,youwilllearnhowtouseaspecialfeatureknownasAWSIoTRulestotake
informationfromanincomingMQTTmessageandwriteittoaAWSSimpleNotificationService
(SNS)topicwhichthenssendsemailtoyou.Havefun!
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.
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)
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.
CreatedbyDora Page29of45
06Jul17
08:55PM
No Task
k) OntheCreateaRulepage,chooseCreaterule.
l) OntheOverviewpagefortherule,choosetheleftarrowtoreturntotheAWSIoT
dashboard.
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
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
No Task
a) TypethefollowingcommandtoinstallBoto,thePythonlibraryforAWSonyour
RaspberryPi
sudo pip install boto3
No Task
a) TypethefollowingcommandtoinstalltheAWSCommandLineInterfaceClienton
yourRaspberryPi
sudo pip install awscli
CreatedbyDora Page34of45
06Jul17
08:55PM
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.
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
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)
No Task
a) ImportantEnsureyouDONOTusesudo
python boto_s3_1.py
b) Youshouldseeoutputsimilartothatbelow.
CreatedbyDora Page39of45
06Jul17
08:55PM
No Task
a) Gobacktothe
S3consolein
AWS,and
checkthatthe
filehasbeen
successfully
uploadedas
showninAWS
console
CreatedbyDora Page40of45
06Jul17
08:55PM
http://boto3.readthedocs.io/en/latest/reference/services/rekognition.html#rekognition
AmazonRekognitionisaservicethatenablesyoutoaddimageanalysistoyourapplications.With
Rekognition,youcandetectobjects,scenes,andfacesinimages.Youcanalsosearchandcompare
faces.
Inthissection,youwillusetheAmazonRekognitionDetectLabelsAPIoperationtodetectobjects,
concepts,andscenesinanimage(JPEGorPNG)thatyouprovideasinput.Youwillbetakinga
photowithyourpiCam,uploadittoyourAmazonS3bucketandspecifytheobjectkeynameforthe
APItoperformtherecognition.
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
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
AWS S3 Regions
http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region
EndofPractical
CreatedbyDora Page45of45