モチベーション
部品が揃ってきたので、ラズパイとAWSを連携。
ラズパイのボタンをプッシュしたら写真撮ってS3へ上げる。
環境
- RaspberryPi3B+
- Raspbian 9.8
- RPi.GPIO
- picamera
- amazon S3
- boto3
- python
準備
以下の2記事の複合技なので準備はこちらにお任せします。
Raspberry Pi カメラ画像をS3へアッロード
Raspberryでボタン押下をGPIOの割り込みで検出
pythonコード
takePicToS3.py
# coding: utf-8
import picamera
import boto3
import time
from datetime import datetime
def take_pic_from_picamera(filename):
print("take_pic_from_picamera:"+filename)
with picamera.PiCamera() as camera:
# camera.resolution = (1024, 768)
camera.resolution = (500, 500)
camera.start_preview()
camera.led = False
#camera warm-up time
time.sleep(2)
camera.capture(filename)
print("done")
def upload_to_S3(filename):
print("upload_to_S3:"+filename)
bucket_name = "atsmaru-bucket"
s3 = boto3.resource('s3')
s3.Bucket(bucket_name).upload_file('/home/pi/'+filename, filename)
print("done")
# main
# timestr = datetime.now().strftime('%Y%m%d%H%M%S')
# filename=timestr+'.jpg'
# take_pic_from_picamera(filename)
# upload_to_S3(filename)
button_to_S3.py
# coding: utf-8
import RPi.GPIO as GPIO
import time
import datetime
from datetime import datetime
import takePicToS3
BUTTON_PIN = 21
def main():
setup_gio()
try:
while(True):
time.sleep(1)
# Keyboard入力があれば終わり
except KeyboardInterrupt:
print("break")
teardown_gio()
def setup_gio():
GPIO.setwarnings(False)
# Set the layout for the pin declaration
GPIO.setmode(GPIO.BCM)
# BCMの21番ピンを入力に設定
GPIO.setup(BUTTON_PIN,GPIO.IN)
# callback登録(GIO.FALLING:立下りエッジ検出、bouncetime:300ms)
GPIO.add_event_detect(BUTTON_PIN, GPIO.FALLING, callback=callback, bouncetime=300)
def teardown_gio():
GPIO.cleanup()
def callback(channel):
print("button pushed %s"%channel)
timestr = datetime.now().strftime('%Y%m%d%H%M%S')
filename=timestr+'.jpg'
takePicToS3.take_pic_from_picamera(filename)
takePicToS3.upload_to_S3(filename)
if __name__ == "__main__":
main()
実行
pi@raspberrypi:~ $ python button_to_s3.py
button pushed 21
take_pic_from_picamera:20190318235340.jpg
done
upload_to_S3:20190318235340.jpg
done
button pushed 21
take_pic_from_picamera:20190318235348.jpg
done
upload_to_S3:20190318235348.jpg
done
done
^Cbreak