Top Banner
James Devine's Blog Where I write down my geeky stuff to share with others… Tag Archives: sl4a FEB 03 2013 2 COMMENTS UNCATEGORIZED The Robot Photo Booth
19

Sl4a James Devine's Blog

Nov 08, 2015

Download

Documents

asdasd asdasd

Sl4a - James Devine's Blog android sl4a script python development
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 1/19

    JamesDevine'sBlog

    WhereIwritedownmygeekystufftosharewithothers

    TagArchives:sl4a

    FEB0320132COMMENTS

    UNCATEGORIZED

    TheRobotPhotoBooth

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 2/19

    (https://pingu98.files.wordpress.com/2013/02/roboto.jpg)CanItakeyourphoto?

    IhadanideasometimeagotocreatealightweightphotoboothclientusingjustanandroidphoneandPythonrunninginSL4A.Thefunctionalityisasfollows:

    1. Speakagreetingtotheuser2. ScanaQRcodecontainingtheuserstwittername3. Taketheirphoto4. Tweetthephoto@them5. Saythankyouandrepeat!

    Addedtothis,Iwantedtogivetheboothanattitudebycreatingascriptofrandomthingsforittosay(atrandomtimeintervals).Themostdifficultpartoftheprojectwasfindingawaytoruntheattitudescriptwhenthemainprocessissittingwaitingforabarcodetoscan.Itriedvariousapproaches,includingusingmultiprocess/threads,howevernoneofthesewereabletocreateatimeoutinthescanBarCode()function.Thesimplesolutionwastocreatetwoscripts,onetoprovidetherandomtalkingscriptrunningasabackgroundprocessandanothertohandlethe

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 3/19

    maingruntworkofscanningbarcodes,takingphotosandtweeting.ThedevelopmentplatformwasaSamsungGalaxyPocket(http://www.gsmarena.com/samsung_galaxy_pocket_s53004612.php),becauseitsverycheapandhasallthenecessaryfunctionality.

    ThescriptrunsinSL4Ar6andPythonr5(NBthatIwastedasignificantquantityoftimerunningPythonr1whichwouldntrunanyofthescriptsIfoundonthewebfortweeting),withtheTweepylibrarytotweet.TheTweepylibraryisaspecialforkthatsupportsthestatus_update_with_mediamethod,andcanbefoundhere(https://github.com/laiso/tweepy).ThankstoDrDrangforhispostonhowtotweetimagesusingregularPython(http://www.leancrew.com/allthis/2012/01/tweetingimages/).Iinstalledthetweepypluginbydownloadingthemain.eggfileandthenreplacingthe.pyfilesfromtheforkwithmedia,seemstoworkfine.

    Hereisthecodeforthebarcodescanningandphototakingportion.NotethattheQRcodesshouldnthavethepreceding@fortwitternamesalthoughthiscaneasilybemodified.Ivebeenusinggoqr.me(http://goqr.me)togeneratemystandardcode:

    (https://pingu98.files.wordpress.com/2013/02/jpqr.jpg)

    Hereisthemaincode(whichIcalledshoot.py)

    importandroid

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 4/19

    importandroidimporttweepyimporttime

    droid=android.Android()droid.wakeLockAcquirePartial()CONSUMER_KEY=keyhereCONSUMER_SECRET=keyhereACCESS_KEY=keyhereACCESS_SECRET=keyheredroid.makeToast(StartingAuth)auth=tweepy.OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)droid.makeToast(StartingAuthset)auth.set_access_token(ACCESS_KEY,ACCESS_SECRET)droid.makeToast(StartingAPI)api=tweepy.API(auth)

    picdir=/sdcard/pbooth/pictemp=picdir+%05i.jpegpiccount=1

    runcontinuous=True

    while(runcontinuous==True):time.sleep(10)droid.ttsSpeak(Hello,Imtherobotphotobooth!PleaseshowmeyourQRcode)code=droid.scanBarcode()droid.ttsSpeak(Smile!Takingpicturenow.)time.sleep(1)droid.cameraCapturePicture(pictemp%piccount)tweet=@+code[1][extras][SCAN_RESULT]+hereisyourpicture.Haveaniceday!api.status_update_with_media(pictemp%piccount,status=tweet)droid.ttsSpeak(Allfinished.Yourpicturehasnowbeentweeted.Thankyou)#time.sleep(10))piccount+=1

    Picturefilenamesareincremented,sothedirectorywillbeoverwritteneachtimeyourestartthescript.Thetalkingscriptishere:

    importandroid,time,random

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 5/19

    importandroid,time,randomruncontinuous=Truedroid=android.Android()

    dialogues={0:Hello,Imtherobotphotobooth!PleaseshowmeyourQRcodesandIwilltakeyourpictureand tweet itback toyou.PleaseputyourQRcode in frontof the cameranow,1:IcantseeyourQRcodeproperly,isitupsidedown?,2:Imbored.Pleasecomeandplaywithme,3:Sorry,itsnearlymybedtimebutIlljusttakeonemorepicture,4:Help!Help!Someonehasunpluggedme}

    while(runcontinuous==True):droid.ttsSpeak(dialogues[random.randrange(0,4,2)])time.sleep(random.randrange(20,70,2))

    Thedictionaryofphrasescanbeaddedtointheformatnumber:text,.Becarefulnottopasteinnonasciicharactersifusingquotesandjokespastedfromtheweb.

    Whensettingupwithtwitter,gotodev.twitter.com(http://dev.twitter.com)andregisteryournewapplication.RemembertoselectReadandWriteaccessforyourapplication,otherwiseyouwillwasteafairamountoftimeasIdid.

    Youcanfindtheoutputofmyphotoboothontwitterhere:http://www.twitter.com/RobotPhotoBooth(http://twitter.com/RobotPhotoBooth)

    TheremainingpartsoftheprojectaretoprintoutaniceA0sizerobot,includingsomeinstructionsandsellotapethecameraonthebackofit.Jobdone!

    Tagged android,barcode,DIY,photobooth,photobooth,postimagestotwitterfromSL4A,posttotwitterfromSL4A,python,QRcode,robotphotobooth,robotphotobooth,samsunggalaxypocket,scripting,sl4a,tweetingfromSL4A,twitterJUL152012

    3COMMENTSUNCATEGORIZED

    HighAltitudeBallooningonabudget!

    Almostexactlyayearago,Ifinallysetoutonajourneytorealisemydreamoftakingphotosfromtheedgeoftheworld.AvideoofthewholeadventureisuponYoutubehere(http://www.youtube.com/watch?v=FEiOSJEya4&feature=plcp).HereshowIdidit(withalittlehelpfrommyfriendstoo!)

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 6/19

    (https://pingu98.files.wordpress.com/2012/07/01075.jpg)Thisphotowastakenrightatthetopoftheflightpath

    Thingsyouwillneed(thetotalcostaslaunchedwas199CHF,excludinghelium):

    AballoonAparachuteAnandroidphoneAsingleusehandwarmerTransparentplasticbox(forwaterproofing)Apolystyrenebox(forinsulation)SomeheliumString+sellotapeAtarpaulinFriends(whoareascrazyasyouare)

    Howtogetstarted:

    Hardware

    Buythethingsyouneed,IpurchasedmyballoonsfromRandomSolutions(http://www.randomsolutions.co.uk/Random_Aerospace/Welcome.html)andtheparachutefromSpherachutes(http://spherachutes.com/)intheUSA.FortheandroidphoneIpurchasedaSamsungGalaxyMiniGTS5570(http://www.gsmarena.com/samsung_galaxy_mini_s5570

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 7/19

    3725.php)onprepayfrommylocalmobilephonestore.ObviouslythephoneyouuseshouldhaveacameraandaGPS,areasonablebatterylifeisalsoagoodidea.Ipickedupthehandwarmersfromalocalsportsshop,theywereinaboxbythecounter.

    Software

    TheGalaxyMinirunsAndroid2.3.4withsomeSamsungstuffonthetop.IfirstrootedthephoneusingSuperuser(http://androidsu.com/superuser/),thenconfiguredittohavethelowestscreenbrightness(maximisebatterylife),turnedoffthewifi,bluetoothandanythingelsenoncriticalthatwilleatpreciouspower.NextinstallSL4A(http://code.google.com/p/androidscripting/)toallowtheuseofscriptinglanguagessuchasPython,dontforgetthatyouwillalsoneedtoinstallthescriptingpackageforyourchosenlanguage,whichifyouwanttousePythonyoucanfindhere(http://code.google.com/p/androidscripting/downloads/detail?name=PythonForAndroid_r4.apk).

    OnceyouhaveinstalledtheSL4AenvironmentandPython,youcanrunascripttodowhatyouneedfortheHighAltitudeBalloonPayload:

    TakePicturesataregularinterval(Ichose7seconds)LogtheGPScoordinatesofthephonescurrentpositionLogalltheextradatathatAndroidmakesavailable(batterylife,magnetometerreadings,accelerometerreadingsetc.)SendyoutextmessagesatregularintervalswiththeGPSpositionsothatyoucanfindthephoneonlanding!

    Thesourcecodeforthescriptisattheendofthisblogpost.

    Practice:

    Beforethelaunchdayitsagoodideatodoatestassemblyrunofthepayloadpackage.Puttheandroidphone(besttotestit)andthehandwarmer(noneedtoactivateituntiltherealthing)insidethetransparentplasticbox,sellotapetheedgesoftheboxtomakesurenowaterwillgetin.Thenmounttheboxinsidethepolystyreneouterboxthisisagoodopportunitytocheckthatthecameracanseeclearly.Ididabatterytestbyputtingthewholelotinmyfreezer(rememberits50Cinthestratospheresotemperatureperformanceisanissue)toseehowlongitwillrunfor(about5hoursinmycase).Doingatestalsogivesagoodindicationthatthescriptisworkingcorrectly.

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 8/19

    (https://pingu98.files.wordpress.com/2012/07/00026.jpg)Preassemblyandtestingishighlyrecommendedtomakesurethecameragetsagoodview

    Prediction:

    IntheweekleadinguptoyourplannedlaunchitsagoodideatorunanumberofsimulationsusingthefantasticCUSFLandingPredictortool(http://habhub.org/predict/).Ididanumberofsimulationswithvariousassumptionsforgasfill,takeofftime(becauseasImusuallylate)andlaunchpositionforeachplannedlaunchday.RemembertoarchivetheKMLofyourpredictionsifyouwanttocomparethemwiththeactualperformance!Itsalsoagoodideatokeepacloseeyeontheweather.Forthelaunchdayyouwantacleardrydaywithlowsurfacewinds.

    Makesurethattheflighttimedoesntexceedtheexpectedbatterylifeofthephoneandremembertokeepamarginofsafetyasthescriptwillonlysendatextmessageevery20minutessoifyoulandwithonly19minutesofbatteryliferemainingyoumaynevergetitback!

    Onlaunchday:

    Whenthelaunchdaycomes,startearly(wegotupat5am),drivetoyourchosenlaunchsiteandstartfillingtheballoon.Spreadthetarpaulinoutontheground,foldedinhalf.Unrolltheballoonbetweenthefoldsofthetarpandstarttofillitveryslowly.Tryingtofilltheballoontoofastwillcausetheheliumtocoolsignificantly,asIdiscoveredtomycostwithtwofailedlaunchattempts.Onthefinal,successfulattemptweusedastringtiedroundtheballooninflationnozzleonthe

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 9/19

    heliumcanistertostabilisethevolumeofgasgoingintotheballoon,suchthatthefilltimewasabout1hourforabout2m3ofhelium.Keepingtheballoonfoldedinsidethetarpduringinflationwillmakesureitdoesntblowaway.

    (https://pingu98.files.wordpress.com/2012/07/00060.jpg)Theballoonfullyfilledwith1.4m3ofhelium

    Whilsttheballoonisfilling,assemblethepayloadpackage,activatethehandwarmerandstartthescript.Unmodified,thescriptwillsendatextmessagewiththelocationapproximatelyevery20minutes,soitsagoodideatowaituntilyouhavethefirstmessagereceivedbeforelettinggooftheballoon.Alsobesuretoopenthehandwarmer,otherwisethephonewillfreezeandyouwillnevergetitback!Justincasesomethingdoesgowrong,itsagoodideatofilmyourfinalassemblysothatyoucancheckitwasdonecorrectly.Oncethepayloadboxiscorrectlyassembled,securelyattachtheparachute(alandscapeorientationisbestifyouwanttomakeamovieoutofthephotoslater).Finallyattacha2mlengthofstringtothetopoftheparachuteandusethistoconnectittotheballoon.Thisstringneedstobereasonablylong(andwellsecuredateachend)asitpreventstheballoonfromgettingtangledupintheparachute.

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 10/19

    (https://pingu98.files.wordpress.com/2012/07/00067.jpg)Ioannis,Morag,Manoharandme!

    Readyfortakeoff:

    Oncetheballoonisfilled,closetheneckusingacabletie.OnourfirstattemptItiedtheneckoftheballooninthesamewayyouwouldtieapartyballoon,withthepayloadattachedonastringthroughtheknot.Thisdidntworkandtheballooncameundoneatabout3000m,hencetheuseofcableties.Afterthefirstcabletieissecure,formtheremainderoftheballoonneckintoaUshape,tiethepayloadontobottomoftheUandcloseitwithanothercabletie.Makesurethateverythingiscorrectlyandsecurelyattached,otherwisetheflightmightendprematurely!

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 11/19

    (https://pingu98.files.wordpress.com/2012/07/00074.jpg)Makesurethateverythingiffirmlyattachedbeforelettinggo!

    Takeoff!

    Onceeverythingisattachedtothefilledballoon,crossyourfingersandletgo.

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 12/19

    (https://pingu98.files.wordpress.com/2012/07/00095.jpg)Lettinggooftheballoon!

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 13/19

    (https://pingu98.files.wordpress.com/2012/07/00518.jpg)Agreatshotfromthetop1/3rdoftheflight.

    Recovery.

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 14/19

    (https://pingu98.files.wordpress.com/2012/07/01279.jpg)Thereentrywasveryrapid.

    Assumingeverythinghasworkedcorrectly,youshouldgetatextmessagefromyourballoonafter34hourswiththecoordinatesofthelandingspot.Forcollectionitsagoodideatohaveyourhikinggear,andawalkingGPS.LoadthecoordinatesintothehikingGPSandgo!Becarefulnottofollowitblindlyintoanywheredangerous!

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 15/19

    (https://pingu98.files.wordpress.com/2012/07/01502.jpg)Thepayloadlandedfacedowninthegrasshalfwayupamountain!

    Download

    Thebestbit.Ifyourphonestillhasanybatteryremainingyouwillbeabletoseethephotosimmediately.GooglePicassaisgreatforcomposingtimelapsephotos.

    LegalStuff

    Youshouldhaveinsuranceincasetheballooncausesdamagewhenitlands(asthepredictionisntanexactscience),youshouldalsohavepermissionfromthelandownerfortheplacewhereyoulaunch,andfromwhereyourecover(ifitisntapublicrightofway).WelaunchedinSwitzerland,wherethefollowingrulesapply(http://www.bazl.admin.ch/dienstleistungen/02007/index.html?lang=fr)andwecompliedwiththem.

    Sourcecodeuseatyourownrisk!

    importosimporttimeimportandroid

    phoneNumber=123456#Insertyourphonenumberhere,completewithinternationalcode00

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 16/19

    phoneNumber=123456#Insertyourphonenumberhere,completewithinternationalcode00period=5#secondsgpsperiod=1#takeagpspositionevery5secondssensorperiod=1#takeasensorsnapeverysecondpicperiod=2#takeaphotoevery20secondssmsperiod=190#textmeevery20minutes

    #FORTESTINGruncontinuous=True#runinaloopgpsflag=True#takegpsdatasensorflag=True#recordthesensorvaluessmsflag=True#textthecellnumberpicflag=True#takephotoslogmode=a#writemodeFORTESTING(forreplyusea)bufsize=0

    droid=android.Android()droid.startSensingTimed(1,5000)droid.wakeLockAcquirePartial()droid.startLocating(5000)#periodms,distdroid.batteryStartMonitoring()

    sensorlog=open(/sdcard/balloon/devicelog.txt,logmode,bufsize)picdir=/sdcard/balloon/pics/pictemp=picdir+%05i.jpglastloc=droid.wakeLockPartial()tick=0piccount=1

    #sendaninitialtextwiththepositionofthephone#time.sleep(300)#r=droid.readLocation()#loc=r.result

    #packet=loc[gps]#al=packet.get(altitude,0.0)#lo=packet.get(longitude,0.0)#ti=packet.get(time,0)#la=packet.get(latitude,0.0)#sp=packet.get(speed,0)#ac=packet.get(accuracy,0)#lastloc=Payloadonline:1,%i,http://maps.google.com/maps?q=%.5f,+%.5f,hl=en,t=h(http://maps.google.com/maps?q=%.5f,+%.5f,hl=en,t=h),%.5f,%.5f,%i%(ti,la,lo,al,sp,ac)batlevel=droid.batteryGetLevel()droid.smsSend(phoneNumber,Payloadonline.Batterylevel%i%batlevel.result)

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 17/19

    #time.sleep(900)#batlevel=droid.batteryGetLevel()#droid.smsSend(phoneNumber,Houstonwearegoforlaunch.Batterylevel%i%batlevel.result)

    while(runcontinuous==True):logline=if((tick%sensorperiod)==0)andsensorflag:

    #Preparetheloglinelogline=available_sensors=

    #Logmagnetometer*ONLY*ifthereadvaluesarevalid#(Otherwiseweareprobablymissingamagnitometeroritsinaweirdstate)magr=droid.sensorsReadMagnetometer()mag=magr.resultif(not(magisNone))and(type(mag)islist)and(len(mag)==3)and(not(mag[0]isNone)):available_sensors+=Mlogline+=,%.5f,%.5f,%.5f%(mag[0],mag[1],mag[2])else:logline+=,,,

    #Logaccelerometer*ONLY*ifthereadvaluesarevalid#(Otherwiseweareprobablymissinganaccelerometeroritsinaweirdstate)

    accr=droid.sensorsReadAccelerometer()acc=accr.resultif(not(accisNone))and(type(acc)islist)and(len(acc)==3)and(not(acc[0]isNone)):available_sensors+=Alogline+=,%.5f,%.5f,%.5f%(acc[0],acc[1],acc[2])else:logline+=,,,

    #Logorientation*ONLY*ifthereadvaluesarevalid#(Otherwiseweareprobablymissingthesensororitsinaweirdstate)orir=droid.sensorsReadOrientation()ori=orir.resultif(not(oriisNone))and(type(ori)islist)and(len(ori)==3)and(not(ori[0]isNone)):available_sensors+=Ologline+=,%.5f,%.5f,%.5f%(ori[0],ori[1],ori[2])else:logline+=,,,

    #Logbattery*ONLY*ifthereadvaluesarevalid#(Otherwiseweareprobablymissingthesensororitsinaweirdstate)bathealth=droid.batteryGetHealth()batlevel=droid.batteryGetLevel()

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 18/19

    battemp=droid.batteryGetTemperature()if((not(bathealthisNone))and(not(batlevelisNone))and(not(battempisNone))):available_sensors+=Blogline+=,%i,%i,%i%(bathealth.result,batlevel.result,battemp.result)else:logline+=,,,

    #Writedownthelinesensorlog.write(SENSORS,%i,%s,%s\n%(time.time(),available_sensors,logline))

    if((tick%picperiod)==0)andpicflag:#droid.webcamAdjustQuality(3,20)#droid.cameraStartPreview(5000,100,picdir)#droid.cameraStart(5000,100,picdir)#time.sleep(1)#droid.cameraStop()droid.cameraCapturePicture(pictemp%piccount,True)piccount+=1if((tick%gpsperiod)==0)andgpsflag:r=droid.readLocation()loc=r.result#printLOC:,locifgpsinloc:ifnot(loc[gps]isNone):packet=loc[gps]al=packet.get(altitude,0.0)lo=packet.get(longitude,0.0)ti=packet.get(time,0)la=packet.get(latitude,0.0)sp=packet.get(speed,0)ac=packet.get(accuracy,0)lastloc=1,%i,http://maps.google.com/maps?q=%.5f,+%.5f(http://maps.google.com/maps?q=%.5f,+%.5f),%.5f,%.5f,%i%(ti,la,lo,al,sp,ac)sensorlog.write(GPS,%i,1,%.5f,%.5f,%.5f,%.5f,%i\n%(ti,la,lo,al,sp,ac))elifnetworkinloc:ifnot(loc[network]isNone):packet=loc[network]al=packet.get(altitude,0.0)lo=packet.get(longitude,0.0)ti=packet.get(time,0)la=packet.get(latitude,0.0)sp=packet.get(speed,0)ac=packet.get(accuracy,0)lastloc=0,%i,http://maps.google.com/maps?q=%.5f,+%.5f(http://maps.google.com/maps?q=%.5f,+%.5f),%.5f,%.5f,%i%(ti,la,lo,al,sp,ac)sensorlog.write(GPS,%i,0,%.5f,%.5f,%.5f,%.5f,%i\n%(ti,la,lo,al,sp,ac))

  • 27.05.2015 sl4a|JamesDevine'sBlog

    https://pingu98.wordpress.com/tag/sl4a/ 19/19

    if((tick%smsperiod)==0)andsmsflag:#printSMS:,lastlociflastloc!=:try:droid.smsSend(phoneNumber,lastloc)sensorlog.write(SMSOK,%i,\%s\\n%(time.time(),lastloc))except:sensorlog.write(SMSFAIL,%i,\%s\\n%(time.time(),lastloc))time.sleep(period)tick+=1

    Tagged android,curvatureoftheearth,gpslocation,hab,highaltitude,highaltitudeballoon,highaltitudeballoonswitzerland,highaltitudephotos,howto,howtoandroid,howtohighaltitudeballoon,photosfromspace,python,scriptingforhighaltitudeballoon,sl4a,switzerland,timelapse

    CreateafreewebsiteorblogatWordPress.com.|TheChunkTheme.