python-backend/index.py

52 lines
1.8 KiB
Python
Raw Permalink 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-09 21:33:44 +00:00
def poll():
doc_ref_lot = db.collection('lots').document(os.getenv('LOT_NAME'))
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()
urllib.request.urlretrieve('http://localhost:8000/img/references/'+lot_info['refImage'], './ref-img.jpg')
reference = Image.open('./ref-img.jpg').load()
2019-02-09 09:50:39 +00:00
# Take the picture
2019-02-09 22:43:19 +00:00
img = Image.open(camera.capture(os.getenv('CAMERA_DEVICE'))).load()
#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-09 09:50:39 +00:00
stall_occupied = image_tools.threshold(image_tools.differences(color_reference, color_compare), float(os.getenv('E_HAT_TRIGGER_LEVEL')))
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))