python-backend/index.py
2019-02-09 22:54:21 -06:00

55 lines
1.9 KiB
Python

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from PIL import Image
import time
import os
import urllib.request
import camera
import image_tools
import config
config.bootstrap()
# Use a service account
cred = credentials.Certificate(os.getenv('FIREBASE_CERT_FILE'))
firebase_admin.initialize_app(cred)
db = firestore.client()
doc_conf = db.collection('configurations').document(os.getenv('CONFIG_CODE')).get().to_dict()
print(doc_conf)
def poll():
doc_ref_lot = db.collection('lots').document(doc_conf['lot_id'])
# Get the reference image
lot_info = doc_ref_lot.collection('info').document('lotInfo').get().to_dict()
urllib.request.urlretrieve(os.getenv('BACKEND_URL')+'img/references/'+lot_info['refImage'], './ref-img.jpg')
reference = Image.open('./ref-img.jpg').load()
# Take the picture
img = Image.open(camera.capture(doc_conf['stream'])).load()
#img = Image.open('./lib/test-images-vert/lot-3-cars.jpg').load()
doc_ref_stalls = doc_ref_lot.collection('stalls').get()
for stall in doc_ref_stalls:
stall_obj = stall.to_dict()
color_reference = image_tools.average_color(stall_obj['locationX'], stall_obj['locationY'], stall_obj['width'], stall_obj['height'], reference)
color_compare = image_tools.average_color(stall_obj['locationX'], stall_obj['locationY'], stall_obj['width'], stall_obj['height'], img)
stall_occupied = image_tools.threshold(image_tools.differences(color_reference, color_compare), float(doc_conf['e_hat']))
stall_obj['open'] = not stall_occupied
print("Updated: "+stall.id)
doc_ref_lot.collection('stalls').document(stall.id).set(stall_obj)
start_time = time.time()
while True:
poll()
poll_time = float(os.getenv('POLL_FREQUENCY'))
time.sleep(poll_time - ((time.time() - start_time) % poll_time))