-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_wrapper.py
More file actions
202 lines (167 loc) · 6.4 KB
/
api_wrapper.py
File metadata and controls
202 lines (167 loc) · 6.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import datetime
import requests
from analytics.entries import FuncEntry
from django.conf import settings
from django.utils import timezone
from requests.exceptions import HTTPError
from laundry.models import LaundryRoom, LaundrySnapshot
from pennmobile.analytics import LabsAnalytics
def get_room_url(room_id: int):
return f"{settings.LAUNDRY_URL}/rooms/{room_id}/machines?raw=true"
def get_validated(url):
"""
Makes a request to the given URL and returns the JSON response if the request is successful.
Uses headers specific to the laundry API and should not be used for other requests.
@param url: The URL to make the request to.
@return: The JSON response if the request is successful, otherwise None.
"""
try:
request = requests.get(url, timeout=60, headers=settings.LAUNDRY_HEADERS)
request.raise_for_status()
return request.json()
except HTTPError as e:
print(f"Error: {e}")
return None
def update_machine_object(machine, machine_type_data):
"""
Updates Machine status and time remaining
"""
# TODO: Early stage in update 9/29/2024, known status codes are
# TODO: "IN_USE", "AVAILABLE", "COMPLETE";
# TODO: need to update if we identify other codes, especially error
status = machine["currentStatus"]["statusId"]
if status == "IN_USE":
time_remaining = machine["currentStatus"]["remainingSeconds"]
machine_type_data["running"] += 1
try:
machine_type_data["time_remaining"].append(int(time_remaining) // 60)
machine_type_data["time_remaining_seconds"].append(int(time_remaining))
except ValueError:
pass
elif status in ["AVAILABLE", "COMPLETE"]:
machine_type_data["open"] += 1
# TODO: Verify there are no other statuses
else:
machine_type_data["offline"] += 1
# edge case that handles machine not sending time data
# TODO: I don't think we need this?
diff = int(machine_type_data["running"]) - len(machine_type_data["time_remaining"])
while diff > 0:
machine_type_data["time_remaining"].append(-1)
diff = diff - 1
return machine_type_data
def parse_a_room(room_request_link):
"""
Return names, hall numbers, and the washers/dryers available for a certain room_id
"""
washers = {
"open": 0,
"running": 0,
"out_of_order": 0,
"offline": 0,
"time_remaining": [],
"time_remaining_seconds": [],
}
dryers = {
"open": 0,
"running": 0,
"out_of_order": 0,
"offline": 0,
"time_remaining": [],
"time_remaining_seconds": [],
}
detailed = []
request_json = get_validated(room_request_link)
if request_json is None:
return {"washers": washers, "dryers": dryers, "details": detailed}
for machine in request_json:
if machine["isWasher"]:
update_machine_object(machine, washers)
elif machine["isDryer"]:
update_machine_object(machine, dryers)
detailed = [
{
"id": machine["id"],
"type": "washer" if machine["isWasher"] else "dryer",
"status": machine["currentStatus"]["statusId"],
"time_remaining": (
int(machine["currentStatus"]["remainingSeconds"]) // 60
if machine["currentStatus"]["statusId"] == "IN_USE"
else 0
),
"time_remaining_seconds": (
int(machine["currentStatus"]["remainingSeconds"])
if machine["currentStatus"]["statusId"] == "IN_USE"
else 0
),
"finishes_at": (
(
datetime.datetime.fromisoformat(machine["currentStatus"]["receivedAt"])
+ datetime.timedelta(seconds=int(machine["currentStatus"]["remainingSeconds"]))
)
if machine["currentStatus"]["statusId"] == "IN_USE"
else None
),
"selected_cycle": machine["currentStatus"]["selectedCycle"].get("name", None),
"selected_modifier": machine["currentStatus"]["selectedModifier"].get("name", None),
"display_status": (machine["currentStatus"]["displayStatus"].get("values", [])),
}
for machine in request_json
if machine["isWasher"] or machine["isDryer"]
]
return {"washers": washers, "dryers": dryers, "details": detailed}
def check_is_working():
"""
Returns True if the wash alert web interface seems to be working properly, or False otherwise.
"""
all_rooms_request = get_validated(f"{settings.LAUNDRY_URL}/geoBoundaries/5610?raw=true")
return all_rooms_request is not None
def all_status():
"""
Return names, hall numbers, and the washers/dryers available for all rooms in the system
"""
return {
room.name: parse_a_room(get_room_url(room.room_id)) for room in LaundryRoom.objects.all()
}
def room_status(room):
"""
Return the status of each specific washer/dryer in a particular hall_id
"""
machines = parse_a_room(get_room_url(room.room_id))
return {"machines": machines, "hall_name": room.name, "location": room.location}
def is_room_full(room_data: dict) -> bool:
"""
Retruns whether a room is full or not meaning no washers or dryers are available
"""
return (
room_data.get("washers", {}).get("open", 0) == 0
and room_data.get("dryers", {}).get("open", 0) == 0
)
@LabsAnalytics.record_function(
FuncEntry(
name="cron.full_laundry_room",
get_value=lambda args, res: sum(1 for room_data in res.values() if is_room_full(room_data)),
),
FuncEntry(
name="cron.full_laundry_rooms_list",
get_value=lambda args, res: [
name for name, room_data in res.items() if is_room_full(room_data)
],
),
)
def save_data():
"""
Retrieves current laundry info and saves it into the database.
"""
now = timezone.localtime()
if LaundrySnapshot.objects.filter(date=now).count() == 0:
data = all_status()
for name, room in data.items():
laundry_room = LaundryRoom.objects.get(name=name)
LaundrySnapshot.objects.create(
room=laundry_room,
date=now,
available_washers=room["washers"]["open"],
available_dryers=room["dryers"]["open"],
)
return data