Skip to content

Instantly share code, notes, and snippets.

@yuta-imai
Created February 25, 2019 13:35
Show Gist options
  • Save yuta-imai/97454e6ecd7dae4dae2390f3e3493c4b to your computer and use it in GitHub Desktop.
Save yuta-imai/97454e6ecd7dae4dae2390f3e3493c4b to your computer and use it in GitHub Desktop.
import boto3
import requests
import time
from datetime import datetime
from dateutil.tz import tzlocal
from picamera import PiCamera
region_name = 'YOUR_AWS_REGION'
s3_bucket_name = 'YOUR_S3_BUCKET'
krypton_url = 'https://krypton.soracom.io:8036/v1/provisioning/aws/cognito/open_id_tokens'
metadata_url = 'http://metadata.soracom.io/v1/subscriber'
credential_refresh_interval = 15 * 60
cognito_client = boto3.client('cognito-identity',region_name=region_name)
credential = ''
s3_client = ''
camera = PiCamera()
camera.resolution = (640,480)
camera.start_preview()
time.sleep(2)
def get_metadata():
response = requests.get(metadata_url)
metadata = response.json()
return metadata
def define_image_file_name():
metadata = get_metadata()
image_file_name = metadata['imsi'] + '.jpg'
return image_file_name
def is_camera_enabled():
metadata = get_metadata()
if metadata['tags']['camera'] == '1':
return True
else:
return False
def get_identity():
data = requests.get(krypton_url)
data = data.json()
return data
def get_credential(identity):
credential = cognito_client.get_credentials_for_identity(
IdentityId=identity['identityId'],
Logins= {
'cognito-identity.amazonaws.com':identity['token']
}
)
return credential
def get_s3_client(credential):
secret_key = credential['Credentials']['SecretKey']
access_key = credential['Credentials']['AccessKeyId']
token = credential['Credentials']['SessionToken']
session = boto3.session.Session(
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
aws_session_token=token,
region_name=region_name
)
return session.client('s3')
def capture_image(file_name):
camera.capture(file_name)
image_file_name = define_image_file_name()
print('Our file name is ' + image_file_name)
identity = get_identity()
while True:
if is_camera_enabled():
print('Camera flag is ON!')
if not credential or credential['Credentials']['Expiration'] < datetime.now(tz=tzlocal()):
credential = get_credential(identity)
s3_client = get_s3_client(credential)
capture_image(image_file_name)
with open(image_file_name,'rb') as img:
result = s3_client.put_object(
Bucket=s3_bucket_name,
Body=img.read(),
Key='rpi_camera/'+image_file_name
)
print(result)
else:
print('Camera flag is OFF! Sleep for 60 seconds..')
#time.sleep(60)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment