pslockout/doorcontrol/pushcards.py

55 lines
1.7 KiB
Python
Raw Normal View History

import logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.ERROR)
import json
import os
import requests
import sqlite3
import time
CARD_DB_PATH = '/home/pi/production.sqlite3'
CARD_PUSH_DELAY = 10
CARD_UPDATE_URL = 'https://tools-auth.protospace.ca/update-cards/'
settings = json.load(open('settings.json'))
request_headers = {'Authorization': 'Token ' + settings['token']}
last_modified_time = None
card_data = {}
while True:
try:
modified_time = os.path.getmtime(CARD_DB_PATH)
logging.info('modified_time: {}, last_modified_time: {}'.format(modified_time, last_modified_time))
if modified_time != last_modified_time:
logging.info('Card database modified time is different, reading database...')
conn = sqlite3.connect('file:' + CARD_DB_PATH + '?mode=ro', uri=True)
c = conn.cursor()
for row in c.execute('select owner, group_concat(serial) from cards where active=1 group by owner'):
2019-01-21 04:32:22 +00:00
username = row[0].replace(' ', '').lower()
logging.info('Read name: {}, username: {}, cards: {}'.format(row[0], username, row[1]))
card_data[username] = row[1]
conn.close()
last_modified_time = modified_time
logging.info('Uploading card data to server...')
r = requests.put(CARD_UPDATE_URL, headers=request_headers, data=card_data)
if r.status_code == requests.codes.ok:
logging.info('Number of cards updated: {}'.format(r.json()['updated']))
else:
r.raise_for_status()
except BaseException as e:
logging.error(e)
time.sleep(CARD_PUSH_DELAY)