python-backend/index.py

55 lines
1.9 KiB
Python
Raw Normal View History

2019-02-09 07:59:14 +00:00
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
2019-02-09 09:05:07 +00:00
from PIL import Image
2019-02-09 21:33:44 +00:00
import time
import os
import urllib.request
2019-02-09 09:05:07 +00:00
import camera
import image_tools
2019-02-09 09:50:39 +00:00
import config
config.bootstrap()
2019-02-09 07:59:14 +00:00
# Use a service account
2019-02-09 09:50:39 +00:00
cred = credentials.Certificate(os.getenv('FIREBASE_CERT_FILE'))
2019-02-09 07:59:14 +00:00
firebase_admin.initialize_app(cred)
db = firestore.client()
2019-02-10 04:54:21 +00:00
doc_conf = db.collection('configurations').document(os.getenv('CONFIG_CODE')).get().to_dict()
print(doc_conf)
2019-02-09 21:33:44 +00:00
def poll():
2019-02-10 04:54:21 +00:00
doc_ref_lot = db.collection('lots').document(doc_conf['lot_id'])
2019-02-09 09:50:39 +00:00
2019-02-09 21:33:44 +00:00
# Get the reference image
lot_info = doc_ref_lot.collection('info').document('lotInfo').get().to_dict()
2019-02-09 23:20:12 +00:00
urllib.request.urlretrieve(os.getenv('BACKEND_URL')+'img/references/'+lot_info['refImage'], './ref-img.jpg')
2019-02-09 21:33:44 +00:00
reference = Image.open('./ref-img.jpg').load()
2019-02-09 09:50:39 +00:00
# Take the picture
2019-02-10 04:54:21 +00:00
img = Image.open(camera.capture(doc_conf['stream'])).load()
2019-02-09 22:43:19 +00:00
#img = Image.open('./lib/test-images-vert/lot-3-cars.jpg').load()
2019-02-09 09:50:39 +00:00
2019-02-09 21:33:44 +00:00
doc_ref_stalls = doc_ref_lot.collection('stalls').get()
2019-02-09 07:59:14 +00:00
2019-02-09 21:33:44 +00:00
for stall in doc_ref_stalls:
2019-02-09 09:50:39 +00:00
stall_obj = stall.to_dict()
2019-02-09 21:33:44 +00:00
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)
2019-02-10 04:54:21 +00:00
stall_occupied = image_tools.threshold(image_tools.differences(color_reference, color_compare), float(doc_conf['e_hat']))
2019-02-09 09:50:39 +00:00
stall_obj['open'] = not stall_occupied
2019-02-09 21:33:44 +00:00
print("Updated: "+stall.id)
doc_ref_lot.collection('stalls').document(stall.id).set(stall_obj)
2019-02-09 09:05:07 +00:00
2019-02-09 07:59:14 +00:00
2019-02-09 09:50:39 +00:00
start_time = time.time()
2019-02-09 09:05:07 +00:00
2019-02-09 09:50:39 +00:00
while True:
poll()
poll_time = float(os.getenv('POLL_FREQUENCY'))
time.sleep(poll_time - ((time.time() - start_time) % poll_time))