Compare commits
11 Commits
cbb5a360b9
...
master
Author | SHA1 | Date | |
---|---|---|---|
|
02ddc30b60 | ||
8230f487f1 | |||
d43b96db1b | |||
acc38ad17f | |||
743ac56d3a | |||
44ece0b3b0 | |||
2d74cb11e5 | |||
c4998709a9 | |||
c3e745ec35 | |||
51c21a10b5 | |||
9de94414d0 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -103,3 +103,4 @@ ENV/
|
|||||||
*.swo
|
*.swo
|
||||||
|
|
||||||
card_data.json
|
card_data.json
|
||||||
|
secrets.py
|
||||||
|
40
README.md
40
README.md
@@ -1,16 +1,14 @@
|
|||||||
# 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
|
||||||
|
|
||||||
Ensure Pi user has read permissions to /dev/ttyACM0 (Pi user needs to be part of the dialout group).
|
|
||||||
|
|
||||||
Install dependencies:
|
Install dependencies:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
$ sudo apt update
|
$ sudo apt update
|
||||||
$ sudo apt install python3 python3-pip python-virtualenv python3-virtualenv supervisor
|
$ sudo apt install python3 python3-pip python3-virtualenv supervisor git
|
||||||
```
|
```
|
||||||
|
|
||||||
Clone this repo:
|
Clone this repo:
|
||||||
@@ -21,16 +19,34 @@ $ sudo mv airlock/ /opt/
|
|||||||
$ cd /opt/airlock
|
$ cd /opt/airlock
|
||||||
```
|
```
|
||||||
|
|
||||||
### Watchdog
|
### Hardware Access
|
||||||
|
|
||||||
For the watchdog to work, we need write access to `/dev/watchdog/`.
|
Ensure Pi user has read permissions to `/dev/ttyACA0` and `/dev/watchdog`.
|
||||||
|
|
||||||
Configure `/etc/udev/rules.d/60-watchdog.rules`:
|
Configure `/etc/udev/rules.d/local.rules`:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
|
ACTION=="add", KERNEL=="dialout", MODE="0666"
|
||||||
|
ACTION=="add", KERNEL=="ttyACM0", MODE="0666"
|
||||||
|
ACTION=="add", KERNEL=="ttyAMA0", MODE="0666"
|
||||||
KERNEL=="watchdog", MODE="0666"
|
KERNEL=="watchdog", MODE="0666"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
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:
|
||||||
|
|
||||||
|
```text
|
||||||
|
$ sudo reboot
|
||||||
|
```
|
||||||
|
|
||||||
### Main Script
|
### Main Script
|
||||||
|
|
||||||
Create a venv, activate it, and install:
|
Create a venv, activate it, and install:
|
||||||
@@ -53,6 +69,13 @@ Now you can run the script to test:
|
|||||||
(env) $ DEBUG=true python main.py
|
(env) $ DEBUG=true python main.py
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Copy and edit the settings file:
|
||||||
|
|
||||||
|
```text
|
||||||
|
(env) $ cp secrets.py.example secrets.py
|
||||||
|
(env) $ vim secrets.py
|
||||||
|
```
|
||||||
|
|
||||||
## Process management
|
## Process management
|
||||||
|
|
||||||
The script is kept alive with [supervisor](https://pypi.org/project/supervisor/).
|
The script is kept alive with [supervisor](https://pypi.org/project/supervisor/).
|
||||||
@@ -64,6 +87,7 @@ Configure `/etc/supervisor/conf.d/airlock.conf`:
|
|||||||
user=pi
|
user=pi
|
||||||
directory=/opt/airlock
|
directory=/opt/airlock
|
||||||
command=/opt/airlock/env/bin/python -u main.py
|
command=/opt/airlock/env/bin/python -u main.py
|
||||||
|
stopasgroup=true
|
||||||
stopsignal=INT
|
stopsignal=INT
|
||||||
autostart=true
|
autostart=true
|
||||||
autorestart=true
|
autorestart=true
|
||||||
@@ -73,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
|
||||||
|
232
main.py
232
main.py
@@ -1,59 +1,101 @@
|
|||||||
|
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',
|
||||||
level=logging.INFO)
|
level=logging.INFO)
|
||||||
|
|
||||||
from multiprocessing import Process, Queue
|
TEST = os.environ.get('TEST', False)
|
||||||
from queue import Empty
|
|
||||||
import RPi.GPIO as GPIO
|
|
||||||
import os
|
|
||||||
import json
|
|
||||||
import requests
|
|
||||||
import serial
|
|
||||||
import time
|
|
||||||
from signal import *
|
|
||||||
|
|
||||||
DEBUG = os.environ.get('DEBUG', False)
|
DEBUG = os.environ.get('DEBUG', False)
|
||||||
|
|
||||||
RELAY_PIN = 17
|
from multiprocessing import Process, Queue
|
||||||
RFID_EN_PIN = 27
|
from queue import Empty
|
||||||
|
import json
|
||||||
|
import requests
|
||||||
|
import time
|
||||||
|
from signal import *
|
||||||
|
import binascii
|
||||||
|
|
||||||
|
if not TEST:
|
||||||
|
import RPi.GPIO as GPIO
|
||||||
|
from pn532pi import Pn532, Pn532Hsu, pn532
|
||||||
|
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
|
||||||
|
RELAY_PIN = 18
|
||||||
CARDS_FILE = 'card_data.json'
|
CARDS_FILE = 'card_data.json'
|
||||||
OPEN_DURATION = 4
|
OPEN_DURATION = 4
|
||||||
|
VALID_PACKAGES = [
|
||||||
|
'Maker',
|
||||||
|
'Maker Plus',
|
||||||
|
'Maker Pro',
|
||||||
|
'Access to everything 24/7',
|
||||||
|
'Standard Membership',
|
||||||
|
]
|
||||||
|
|
||||||
API_STATS = 'https://api.my.protospace.ca/stats/'
|
TEST_PIPE = '/tmp/airlock'
|
||||||
API_DOOR = 'https://api.my.protospace.ca/door/'
|
try:
|
||||||
API_SEEN = lambda x: 'https://api.my.protospace.ca/door/{}/seen/'.format(x)
|
os.remove(TEST_PIPE)
|
||||||
|
except FileNotFoundError:
|
||||||
|
pass
|
||||||
|
|
||||||
ser = None
|
API_MEMBERS = 'https://fabman.io/api/v1/members?limit=1000&embed=key&embed=activePackages&includeKeyToken=true'
|
||||||
|
|
||||||
|
nfc = None
|
||||||
|
|
||||||
def unlock_door():
|
def unlock_door():
|
||||||
|
logging.info('Unlocking door...')
|
||||||
|
|
||||||
|
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:
|
||||||
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 init():
|
def feed_watchdog():
|
||||||
global ser, cards
|
if DEBUG or TEST:
|
||||||
|
return
|
||||||
|
|
||||||
|
with open('/dev/watchdog', 'w') as wdt:
|
||||||
|
wdt.write('1')
|
||||||
|
|
||||||
|
def init():
|
||||||
|
global nfc, cards
|
||||||
|
|
||||||
|
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')
|
||||||
|
|
||||||
ser = serial.Serial(port='/dev/ttyAMA0', baudrate=2400, timeout=0.1)
|
if TEST:
|
||||||
logging.info('Serial initialized')
|
os.mkfifo(TEST_PIPE)
|
||||||
|
logging.info('Test pipe initialized')
|
||||||
|
else:
|
||||||
|
PN532_HSU = Pn532Hsu(Pn532Hsu.RPI_MINI_UART)
|
||||||
|
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)
|
||||||
@@ -63,89 +105,140 @@ def reader_thread(card_data_queue):
|
|||||||
recent_scans = {}
|
recent_scans = {}
|
||||||
|
|
||||||
with open(CARDS_FILE, 'r') as f:
|
with open(CARDS_FILE, 'r') as f:
|
||||||
card_data = json.load(f)
|
cards = json.load(f)
|
||||||
logging.info('Read {} card numbers from disk'.format(str(len(card_data))))
|
logging.info('Read {} cards from disk'.format(len(cards)))
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
card_data = card_data_queue.get_nowait()
|
cards = card_data_queue.get_nowait()
|
||||||
except Empty:
|
except Empty:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
card = ser.readline()
|
if TEST:
|
||||||
if not card: continue
|
with open(TEST_PIPE, 'r') as pipe:
|
||||||
|
success, card = (True, pipe.readline())
|
||||||
|
else:
|
||||||
|
nfc.SAMConfig()
|
||||||
|
success, card = nfc.readPassiveTargetID(pn532.PN532_MIFARE_ISO14443A_106KBPS)
|
||||||
|
|
||||||
card = card.decode().strip()
|
if not TEST:
|
||||||
if len(card) != 10: continue
|
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:
|
||||||
|
card = binascii.hexlify(card).decode().strip()
|
||||||
|
except TypeError:
|
||||||
|
card = card.strip()
|
||||||
|
except:
|
||||||
|
logging.info('Unable to decode card: %s', str(card))
|
||||||
|
continue
|
||||||
|
|
||||||
|
if len(card) != 14: continue
|
||||||
|
|
||||||
# debounce card scans
|
# debounce card scans
|
||||||
now = time.time()
|
now = time.time()
|
||||||
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')
|
||||||
|
time.sleep(1)
|
||||||
continue
|
continue
|
||||||
recent_scans[card] = now
|
recent_scans[card] = now
|
||||||
|
|
||||||
logging.info('Read card: ' + card)
|
logging.info('Read card: ' + card)
|
||||||
|
|
||||||
if card in card_data:
|
if card in cards:
|
||||||
logging.info('Card recognized')
|
logging.info('Card recognized')
|
||||||
else:
|
else:
|
||||||
logging.info('Card not recognized, denying access')
|
logging.info('Card not recognized, denying access')
|
||||||
continue
|
continue
|
||||||
|
|
||||||
logging.info('DOOR ACCESS - Card: {} | Name: {}'.format(
|
card_data = cards[card]
|
||||||
card, card_data[card],
|
|
||||||
))
|
logging.info('Card belongs to: %s', card_data['name'])
|
||||||
|
|
||||||
|
if not any(package in card_data['packages'] for package in VALID_PACKAGES):
|
||||||
|
logging.info('No valid packages found: %s', str(card_data['packages']))
|
||||||
|
continue
|
||||||
|
|
||||||
|
logging.info('DOOR ACCESS GRANTED - Card: %s | Name: %s', card, card_data['name'])
|
||||||
|
|
||||||
unlock_door()
|
unlock_door()
|
||||||
|
|
||||||
try:
|
#try:
|
||||||
res = requests.post(API_SEEN(card), timeout=2)
|
# res = requests.post(API_SEEN(card), timeout=2)
|
||||||
res.raise_for_status()
|
# res.raise_for_status()
|
||||||
except BaseException as e:
|
#except BaseException as e:
|
||||||
logging.error('Problem POSTing seen: {} - {}'.format(e.__class__.__name__, str(e)))
|
# logging.error('Problem POSTing seen: {} - {}'.format(e.__class__.__name__, str(e)))
|
||||||
continue
|
# continue
|
||||||
|
|
||||||
def update_thread(card_data_queue):
|
def get_cards(card_data_queue):
|
||||||
last_card_change = None
|
headers = {'Authorization': 'Bearer ' + secrets.FABMAN_API_KEY}
|
||||||
|
res = requests.get(API_MEMBERS, headers=headers, timeout=10)
|
||||||
while True:
|
|
||||||
time.sleep(5)
|
|
||||||
|
|
||||||
try:
|
|
||||||
res = requests.get(API_STATS, timeout=5)
|
|
||||||
res.raise_for_status()
|
res.raise_for_status()
|
||||||
res = res.json()
|
res = res.json()
|
||||||
except BaseException as e:
|
|
||||||
logging.error('Problem GETting stats: {} - {}'.format(e.__class__.__name__, str(e)))
|
members = res
|
||||||
|
cards = {}
|
||||||
|
|
||||||
|
logging.info('Got {} members from API'.format(str(len(res))))
|
||||||
|
|
||||||
|
for member in members:
|
||||||
|
if member['state'] != 'active':
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if res['last_card_change'] == last_card_change:
|
packages = []
|
||||||
continue
|
|
||||||
last_card_change = res['last_card_change']
|
|
||||||
|
|
||||||
logging.info('Cards changed, pulling update from API')
|
for member_packages in member['_embedded']['memberPackages']:
|
||||||
|
package = member_packages['_embedded']['package']
|
||||||
|
|
||||||
try:
|
if package['state'] != 'active':
|
||||||
res = requests.get(API_DOOR, timeout=5)
|
|
||||||
res.raise_for_status()
|
|
||||||
res = res.json()
|
|
||||||
except BaseException as e:
|
|
||||||
logging.error('Problem GETting door: {} - {}'.format(e.__class__.__name__, str(e)))
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
logging.info('Got {} cards from API'.format(str(len(res))))
|
packages.append(package['name'])
|
||||||
card_data_queue.put(res)
|
|
||||||
|
key = member['_embedded']['key']
|
||||||
|
|
||||||
|
if not key:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if key['state'] != 'active':
|
||||||
|
continue
|
||||||
|
|
||||||
|
token = key['token']
|
||||||
|
name = '{} {} ({})'.format(member['firstName'], member['lastName'], member['memberNumber'])
|
||||||
|
|
||||||
|
cards[token] = dict(name=name, packages=packages)
|
||||||
|
|
||||||
|
|
||||||
|
logging.info('Processed {} cards'.format(len(cards)))
|
||||||
|
|
||||||
|
card_data_queue.put(cards)
|
||||||
|
|
||||||
logging.info('Writing data to file')
|
logging.info('Writing data to file')
|
||||||
with open(CARDS_FILE, 'w') as f:
|
with open(CARDS_FILE, 'w') as f:
|
||||||
json.dump(res, f)
|
json.dump(cards, f, indent=4)
|
||||||
|
|
||||||
|
def update_thread(card_data_queue):
|
||||||
|
if not DEBUG: time.sleep(10)
|
||||||
|
|
||||||
def watchdog_thread():
|
|
||||||
while True:
|
while True:
|
||||||
with open('/dev/watchdog', 'w') as wdt:
|
logging.info('Updating cards...')
|
||||||
wdt.write('1')
|
|
||||||
time.sleep(1)
|
try:
|
||||||
|
get_cards(card_data_queue)
|
||||||
|
except BaseException as e:
|
||||||
|
logging.exception('Problem updating cards: {} - {}'.format(e.__class__.__name__, str(e)))
|
||||||
|
|
||||||
|
time.sleep(300)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
logging.info('Initializing...')
|
logging.info('Initializing...')
|
||||||
@@ -155,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()
|
|
||||||
|
@@ -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
|
||||||
|
2
secrets.py.example
Normal file
2
secrets.py.example
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
# Fabman API key
|
||||||
|
FABMAN_API_KEY = ''
|
Reference in New Issue
Block a user