This commit is contained in:
2026-06-02 17:31:19 +01:00

16
app.py
View File

@ -12,6 +12,7 @@ import flask
import whspah import whspah
# Used in transmit() to convert the `action` string to a WHSPAH MODE
ACTION_MAP = {'shock': whspah.MODES.SHOCK, ACTION_MAP = {'shock': whspah.MODES.SHOCK,
'vibrate': whspah.MODES.VIBRATE, 'vibrate': whspah.MODES.VIBRATE,
'beep': whspah.MODES.BEEP} 'beep': whspah.MODES.BEEP}
@ -25,9 +26,12 @@ def staticPage(path):
Returns anything requested in the static folder. Returns anything requested in the static folder.
""" """
# Check for an index.html file in the specified path
if os.path.isfile(os.path.join(app.static_folder, path, 'index.html')): if os.path.isfile(os.path.join(app.static_folder, path, 'index.html')):
# If one's found, append it to the path
path = os.path.join(path, 'index.html') path = os.path.join(path, 'index.html')
# Return the file
return flask.send_from_directory(app.static_folder, path) return flask.send_from_directory(app.static_folder, path)
@app.route('/transmit', methods=['POST'], strict_slashes=False) @app.route('/transmit', methods=['POST'], strict_slashes=False)
@ -36,14 +40,17 @@ def transmit():
Transmits the data contained within the POST request through WHSPAH. Transmits the data contained within the POST request through WHSPAH.
""" """
# Get the POST data and load it, assuming it's in a JSON format.
data = json.loads(flask.request.data) data = json.loads(flask.request.data)
# Try to get all required fields
try: try:
txID = int(data['transmitterID']) txID = int(data['transmitterID'])
channel = int(data['channel']) channel = int(data['channel'])
action = ACTION_MAP[data['action']] action = ACTION_MAP[data['action']]
intensity = int(data.get('intensity', 0)) intensity = int(data.get('intensity', 0))
lucal = bool(data.get('lucalEncoded', False)) lucal = bool(data.get('lucalEncoded', False))
# If any of those failed, return an error.
except (ValueError, KeyError): except (ValueError, KeyError):
return {'success': False, 'message': 'Request must contain the following keys:\n'+ return {'success': False, 'message': 'Request must contain the following keys:\n'+
'txID: int,\n'+ 'txID: int,\n'+
@ -52,29 +59,36 @@ def transmit():
'intensity (optional): int\n'+ 'intensity (optional): int\n'+
'lucalEncoded (optional): bool'}, 400 'lucalEncoded (optional): bool'}, 400
# Send the data to WHSPAH
tx: whspah.Transmitter = app.config['transmitter'] tx: whspah.Transmitter = app.config['transmitter']
tx.transmit(txID, channel, action, intensity, lucal) tx.transmit(txID, channel, action, intensity, lucal)
# Return a success message
return {'success': True}, 200 return {'success': True}, 200
if __name__ == '__main__': if __name__ == '__main__':
# Parse console arguments
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('-d', '--debug', action='store_true') parser.add_argument('-d', '--debug', action='store_true')
parser.add_argument('--ip', type=str, default='0.0.0.0') parser.add_argument('--ip', type=str, default='0.0.0.0')
parser.add_argument('--port', type=int, default=8000) parser.add_argument('--port', type=int, default=8000)
args = parser.parse_args() args = parser.parse_args()
# Sets the logging version based on --debug
if args.debug: if args.debug:
logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.DEBUG)
else: else:
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
# Connect to a WHSPAH device
app.config['transmitter'] = whspah.Transmitter() app.config['transmitter'] = whspah.Transmitter()
if args.debug: if args.debug:
# If in debug mode, run Flask's built in server
app.run(host=args.ip, port=args.port, debug=True) app.run(host=args.ip, port=args.port, debug=True)
else: else:
# Otherwise, use Waitress
server = waitress.server.create_server(app, host=args.ip, port=args.port) server = waitress.server.create_server(app, host=args.ip, port=args.port)
print(f'Serving at http://{args.ip}:{args.port}/') print(f'Serving at http://{args.ip}:{args.port}/')
try: try:
@ -82,3 +96,5 @@ if __name__ == '__main__':
except KeyboardInterrupt: except KeyboardInterrupt:
pass pass
server.close() server.close()
app.config['transmitter'].close()