Compare commits

..

6 Commits

Author SHA1 Message Date
Tanner
02ddc30b60 Add "Standard Membership" package 2025-03-02 12:56:14 -07:00
8230f487f1 Update requests 2023-12-07 19:12:10 +00:00
d43b96db1b Remove invalid packages 2023-12-07 18:51:39 +00:00
acc38ad17f Deploy to RPi 4 2023-09-03 03:07:12 +01:00
743ac56d3a Improve recovery after NFC comms failure 2023-08-30 23:34:33 +01:00
44ece0b3b0 Integrate PN532 reader, handle disconnections 2023-08-30 23:07:59 +01:00
3 changed files with 77 additions and 47 deletions

View File

@@ -1,6 +1,6 @@
# Airlock # Airlock
Door controller for scanning Protospace member cards on the front and back doors. Door controller for scanning Fuse33 member cards on the front and back doors.
## Setup ## Setup
@@ -34,6 +34,13 @@ KERNEL=="watchdog", MODE="0666"
Also ensure `/boot/cmdline.txt` doesn't contain `console=serial0,115200`. Also ensure `/boot/cmdline.txt` doesn't contain `console=serial0,115200`.
On Raspberry Pi 4, you may need to add this to the end of '/boot/config.txt`, after `[all]`:
```
enable_uart=1
dtoverlay=disable-bt
```
Then reboot: Then reboot:
```text ```text
@@ -90,6 +97,8 @@ stdout_logfile=/var/log/airlock.log
stdout_logfile_maxbytes=10MB stdout_logfile_maxbytes=10MB
``` ```
Run `sudo supervisorctl reread; sudo supervisorctl update` to deploy.
Script logs to /var/log/airlock.log. Remove `-u` from the above command when you're done testing. Script logs to /var/log/airlock.log. Remove `-u` from the above command when you're done testing.
## License ## License

103
main.py
View File

@@ -1,4 +1,4 @@
import os import os, sys
import logging import logging
logging.basicConfig( logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
@@ -13,78 +13,89 @@ import json
import requests import requests
import time import time
from signal import * from signal import *
import binascii
if not TEST: if not TEST:
import serial
import RPi.GPIO as GPIO import RPi.GPIO as GPIO
from pn532pi import Pn532, Pn532Hsu, pn532
import secrets import secrets
RELAY_PIN = 17 RELAY_PIN = 18
RFID_EN_PIN = 27
CARDS_FILE = 'card_data.json' CARDS_FILE = 'card_data.json'
OPEN_DURATION = 4 OPEN_DURATION = 4
VALID_PACKAGES = [ VALID_PACKAGES = [
'Maker', 'Maker',
'Maker Plus', 'Maker Plus',
'Maker Pro', 'Maker Pro',
#'Storage bin rental',
#'Backyard Rental Spot',
'IndiCity Laser Space Rental',
#'Shipping container rental',
'Day Pass Holder',
'Access to everything 24/7', 'Access to everything 24/7',
'Barter Membership', 'Standard Membership',
'Loft Member',
] ]
TEST_PIPE = '/tmp/airlock' TEST_PIPE = '/tmp/airlock'
os.remove(TEST_PIPE) try:
os.remove(TEST_PIPE)
except FileNotFoundError:
pass
API_MEMBERS = 'https://fabman.io/api/v1/members?limit=1000&embed=key&embed=activePackages&includeKeyToken=true' API_MEMBERS = 'https://fabman.io/api/v1/members?limit=1000&embed=key&embed=activePackages&includeKeyToken=true'
ser = None nfc = None
def unlock_door(): def unlock_door():
logging.info('Unlocking door...') logging.info('Unlocking door...')
if not TEST: if not TEST:
GPIO.output(RELAY_PIN, GPIO.HIGH) GPIO.output(RELAY_PIN, GPIO.HIGH)
GPIO.output(RFID_EN_PIN, GPIO.HIGH)
time.sleep(OPEN_DURATION) time.sleep(OPEN_DURATION)
GPIO.output(RELAY_PIN, GPIO.LOW) GPIO.output(RELAY_PIN, GPIO.LOW)
GPIO.output(RFID_EN_PIN, GPIO.LOW)
logging.info('Done.')
def lock_door_on_exit(*args): def lock_door_on_exit(*args):
logging.info('Exiting, locking door...') logging.info('Exiting, locking door...')
if not TEST: if not TEST:
GPIO.output(RELAY_PIN, GPIO.LOW) GPIO.output(RELAY_PIN, GPIO.LOW)
GPIO.output(RFID_EN_PIN, GPIO.LOW)
os._exit(0) os._exit(0)
def feed_watchdog():
if DEBUG or TEST:
return
with open('/dev/watchdog', 'w') as wdt:
wdt.write('1')
def init(): def init():
global ser, cards global nfc, cards
if not TEST: if not TEST:
GPIO.setwarnings(False) GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM) GPIO.setmode(GPIO.BCM)
GPIO.setup(RELAY_PIN, GPIO.OUT) GPIO.setup(RELAY_PIN, GPIO.OUT)
GPIO.output(RELAY_PIN, GPIO.LOW) GPIO.output(RELAY_PIN, GPIO.LOW)
GPIO.setup(RFID_EN_PIN, GPIO.OUT)
GPIO.output(RFID_EN_PIN, GPIO.LOW)
logging.info('GPIO initialized') logging.info('GPIO initialized')
if TEST: if TEST:
os.mkfifo(TEST_PIPE) os.mkfifo(TEST_PIPE)
logging.info('Test pipe initialized') logging.info('Test pipe initialized')
else: else:
ser = serial.Serial(port='/dev/ttyAMA0', baudrate=2400, timeout=0.1) PN532_HSU = Pn532Hsu(Pn532Hsu.RPI_MINI_UART)
logging.info('Serial initialized') nfc = Pn532(PN532_HSU)
nfc.begin()
nfc.SAMConfig()
version = nfc.getFirmwareVersion()
logging.info('NFC reader initialized, verion: %s', version)
if not version:
logging.error('Unable to communicate with reader, waiting 10s and exiting...')
time.sleep(10)
os._exit(0)
for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM): for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM):
signal(sig, lock_door_on_exit) signal(sig, lock_door_on_exit)
@@ -105,17 +116,29 @@ def reader_thread(card_data_queue):
if TEST: if TEST:
with open(TEST_PIPE, 'r') as pipe: with open(TEST_PIPE, 'r') as pipe:
card = pipe.readline() success, card = (True, pipe.readline())
else: else:
card = ser.readline() nfc.SAMConfig()
success, card = nfc.readPassiveTargetID(pn532.PN532_MIFARE_ISO14443A_106KBPS)
if not card: continue if not TEST:
try:
# ensure we have communication with the reader
if nfc.getFirmwareVersion():
feed_watchdog()
else:
raise
except:
logging.error('Problem communicating with NFC reader!')
time.sleep(1)
continue
try: try:
card = card.decode().strip() card = binascii.hexlify(card).decode().strip()
except AttributeError: except TypeError:
card = card.strip() card = card.strip()
except UnicodeDecodeError: except:
logging.info('Unable to decode card: %s', str(card))
continue continue
if len(card) != 14: continue if len(card) != 14: continue
@@ -125,6 +148,7 @@ def reader_thread(card_data_queue):
if card in recent_scans: if card in recent_scans:
if now - recent_scans[card] < 5.0: if now - recent_scans[card] < 5.0:
logging.info('Debounce skipping card scan') logging.info('Debounce skipping card scan')
time.sleep(1)
continue continue
recent_scans[card] = now recent_scans[card] = now
@@ -156,14 +180,10 @@ def reader_thread(card_data_queue):
# continue # continue
def get_cards(card_data_queue): def get_cards(card_data_queue):
try: headers = {'Authorization': 'Bearer ' + secrets.FABMAN_API_KEY}
headers = {'Authorization': 'Bearer ' + secrets.FABMAN_API_KEY} res = requests.get(API_MEMBERS, headers=headers, timeout=10)
res = requests.get(API_MEMBERS, headers=headers, timeout=10) res.raise_for_status()
res.raise_for_status() res = res.json()
res = res.json()
except BaseException as e:
logging.exception('Problem GETting Fabman API: {} - {}'.format(e.__class__.__name__, str(e)))
return
members = res members = res
cards = {} cards = {}
@@ -211,17 +231,15 @@ def update_thread(card_data_queue):
while True: while True:
logging.info('Updating cards...') logging.info('Updating cards...')
get_cards(card_data_queue)
try:
get_cards(card_data_queue)
except BaseException as e:
logging.exception('Problem updating cards: {} - {}'.format(e.__class__.__name__, str(e)))
time.sleep(300) time.sleep(300)
def watchdog_thread():
while True:
with open('/dev/watchdog', 'w') as wdt:
wdt.write('1')
time.sleep(1)
if __name__ == '__main__': if __name__ == '__main__':
logging.info('Initializing...') logging.info('Initializing...')
init() init()
@@ -230,4 +248,3 @@ if __name__ == '__main__':
Process(target=reader_thread, args=(card_data,)).start() Process(target=reader_thread, args=(card_data,)).start()
Process(target=update_thread, args=(card_data,)).start() Process(target=update_thread, args=(card_data,)).start()
if not DEBUG: Process(target=watchdog_thread).start()

View File

@@ -1,7 +1,11 @@
certifi==2019.11.28 certifi==2019.11.28
chardet==3.0.4 chardet==3.0.4
charset-normalizer==3.2.0
idna==2.9 idna==2.9
pyserial==3.4 pn532pi==1.4
requests==2.23.0 pyserial==3.5
RPi.GPIO==0.7.0 requests==2.31.0
RPi.GPIO==0.7.1
spidev==3.6
typing==3.7.4.3
urllib3==1.25.8 urllib3==1.25.8