Skip to content

Commit 944ed3f

Browse files
committed
Make status page return useful information
The flask app is now multithreaded. Only one request will handle merch at a time through /vend, and the /status endpoint will return 200 if the machine is available to vend, and 503 if it is currently vending
1 parent c624e4d commit 944ed3f

File tree

2 files changed

+33
-4
lines changed

2 files changed

+33
-4
lines changed

machine_controller/app.py

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ def vend():
5151

5252

5353
statuses = []
54+
merch.acquire()
5455
for i, item in enumerate(items):
5556
try:
5657
merch.vend(item[0], int(item[1]))
@@ -62,11 +63,25 @@ def vend():
6263
# goes wrong, we still need to let the client know instead of
6364
# throwing a 500
6465
statuses.append({'error': str(e), 'location': item})
66+
merch.release()
6567

6668
return jsonify(transaction_id=transaction_id, items=statuses)
6769

68-
if __name__ == '__main__':
69-
# Make sure flask runs in a single thread. Otherwise concurrent requests
70-
# may cause problems with vending
71-
app.run(debug=True, host='0.0.0.0', threaded=False)
70+
@app.route('/status', methods=['GET'])
71+
def status():
72+
if request.headers.get('Authorization', '') != token_value:
73+
abort(401)
74+
75+
ready = merch.inUse()
76+
77+
if(ready):
78+
# 200 to indicate success
79+
return ('', 200)
7280

81+
else:
82+
return ('', 503)
83+
84+
85+
86+
if __name__ == '__main__':
87+
app.run(debug=True, host='0.0.0.0', threaded=True)

machine_controller/vend.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
# THE SOFTWARE.
3535
import RPi.GPIO as GPIO
3636
import time
37+
from threading import Condition, Lock
3738

3839

3940
class Merch:
@@ -56,9 +57,22 @@ def __init__(self, debug=False):
5657
self.__low()
5758
self.__commit()
5859

60+
self.lock = Lock()
61+
5962
def __del__(self):
6063
self.__cleanup()
6164

65+
def acquire(self):
66+
self.lock.acquire()
67+
68+
def release(self):
69+
self.lock.release()
70+
71+
def inUse(self):
72+
# Trylock
73+
return not self.lock.acquire(False)
74+
75+
6276
def __cleanup(self):
6377
''' Clean up all of the GPIO pins '''
6478
GPIO.cleanup()

0 commit comments

Comments
 (0)