Skip to content

Instantly share code, notes, and snippets.

@gholms
Last active October 3, 2021 02:02
Show Gist options
  • Save gholms/760fa4f6621c91001b9f2b449e4e4155 to your computer and use it in GitHub Desktop.
Save gholms/760fa4f6621c91001b9f2b449e4e4155 to your computer and use it in GitHub Desktop.
Unifi wireless voucher generator and requestor button
#!/usr/bin/python3
# Copyright 2017 William Klope
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3 of the License or (at your
# option) any later version accepted by the Santa Barbara Hackerspace (or
# its successor approved by the Santa Barbara Hackerspace), which shall
# act as a proxy as defined in Section 14 of version 3 of the license.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.
import datetime
import time
from escpos imoprt *
import requests
import RPi.GPIO as GPIO
PREAMBLE = 'My Guest Wireless\nPassword: FIXME\nCode: \n'
FEED = '\n\n\n\n\n'
LOGO_PATH = '/srv/voucherprinter/logo.jpg'
VOUCHER_URL = 'http://voucherator.example.com/voucher/new'
BUTTON_CHANNEL = 14
BOUNCE_TIME_MS = 15000
PRINTER = printer.File('/dev/usb/lp0')
PRINTER.flush()
def print_code(_):
now = datetime.datetime.now()
req = requests.post(VOUCHER_URL, data={})
code = req.text
PRINTER.set(text_type='NORMAL')
PRINTER.set(align='LEFT')
PRINTER.image(LOGO_PATH)
PRINTER.set(width=1, height=1)
PRINTER.text(PREAMBLE)
PRINTER.set(width=2, height=4)
PRINTER.text(code)
PRINTER.set(width=1, height=1)
PRINTER.text('\n')
PRINTER.text(now.strftime('%Y-%m-%d %H:%M'))
PRINTER.text('\nValid for 24 hours\n')
PRINTER.text(FEED)
PRINTER.flush()
def main():
GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON_CHANNEL, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(BUTTON_CHANNEL, GPIO.FALLING, callback=print_code,
bouncetime=BOUNCE_TIME_MS)
while True:
time.sleep(1)
if __name__ == '__main__':
main()
[Unit]
Description=Push button, get Unifi code
After=network.target
[Service]
ExecStart=/usr/local/bin/buttond
[Install]
WantedBy=multi-user.target
#!/usr/bin/python -tt
# Copyright 2017 Garrett Holmstrom
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3 of the License or (at your
# option) any later version accepted by the Santa Barbara Hackerspace (or
# its successor approved by the Santa Barbara Hackerspace), which shall
# act as a proxy as defined in Section 14 of version 3 of the license.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.
import argparse
import random
import time
import traceback
import pymongo
try:
import BaseHTTPServer as httpserver
import urlparse
except ImportError:
import http.server as httpserver
import urllib.parse as urlparse
CODE_DURATION_MINUTES = 1440
UNIFI_ADMIN_NAME = 'guestbutton'
UNIFI_SITE = 'FIXME'
UNIFI_NOTE = 'Wireless code button'
__version__ = '0.1.0'
class VoucherHTTPRequestHandler(httpserver.BaseHTTPRequestHandler):
"""
Voucher generator HTTP request handler
"""
protocol_version = 'HTTP/1.0'
server_version = 'voucherator/{}'.format(
'.'.join(__version__.split('.')[:2]))
def do_POST(self):
"""
Handle POST requests, the method for creating vouchers.
"""
try:
if self.path == '/voucher/new':
voucher = gen_voucher()
self.send_voucher(voucher)
else:
self.send_error(404)
except:
traceback.print_exc()
self.send_error(500)
def send_voucher(self, voucher):
code = '{}-{}'.format(voucher['code'][:5], voucher['code'][5:])
self.send_response(200)
self.send_header('Connection', 'close')
self.send_header('Content-Length', len(code))
self.send_header('Content-Type', 'text/plain')
self.end_headers()
self.wfile.write(code)
def gen_voucher():
start = time.time()
end = start + CODE_DURATION_MINUTES * 60
voucher = {
'site_id': UNIFI_SITE,
'create_time': 0,
'code': '{0:0<10}'.format(random.randint(0, 9999999999)),
'for_hotspot': False,
'admin_name': UNIFI_ADMIN_NAME,
'quota': 1,
'duration': CODE_DURATION_MINUTES,
'end_time': int(end),
'used': 0,
'qos_overwrite': False,
'note': UNIFI_NOTE,
}
client = pymongo.MongoClient('127.0.0.1', 27117)
db = client.ace
db.voucher.insert(voucher)
client.close()
return voucher
def main():
parser = argparse.ArgumentParser(
description='Unifi wireless voucher generator')
parser.add_argument('-b', '--bind-addr', default='0.0.0.0')
parser.add_argument('-p', '--port', type=int, default=8080)
args = parser.parse_args()
httpd = httpserver.HTTPServer((args.bind_addr, args.port),
VoucherHTTPRequestHandler)
httpd.serve_forever()
if __name__ == '__main__':
main()
[Unit]
Description=Unifi voucher code generator
After=network.target
[Service]
ExecStart=/usr/local/bin/voucherator
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment