-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresmgmt.py
More file actions
400 lines (328 loc) · 14 KB
/
resmgmt.py
File metadata and controls
400 lines (328 loc) · 14 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
from fastapi import FastAPI, HTTPException, Depends, WebSocket, WebSocketDisconnect
from fastapi.responses import JSONResponse
from fastapi.requests import Request
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Enum, Date, text, Float, DateTime
from sqlalchemy.orm import sessionmaker, declarative_base, relationship, Session
import enum
import datetime
from pydantic import BaseModel
from typing import List, Optional, Dict
from sqlalchemy import Enum as SqlEnum
from fastapi.exceptions import RequestValidationError
# ---------- FASTAPI APP ----------
app = FastAPI()
# ---------- ENUMS & SCHEMAS ----------
class TrainLocationUpdate(BaseModel):
train_no: str
latitude: float
longitude: float
timestamp: datetime.datetime
class TrainType(str, enum.Enum):
EXPRESS = "Express"
PASSENGER = "Passenger"
FREIGHT = "Freight"
class TrainAllocationRequest(BaseModel):
train_no: str
engine_id: int
pilot_id: Optional[int] = None
carriage_ids: List[int]
route: str
start_date: datetime.date
end_date: datetime.date
train_type: TrainType = TrainType.EXPRESS
class EngineStatus(str, enum.Enum):
AVAILABLE = "Available"
IN_USE = "In Use"
MAINTENANCE = "Maintenance"
RESERVED = "Reserved"
class CarriageStatus(str, enum.Enum):
AVAILABLE = "Available"
IN_USE = "In Use"
MAINTENANCE = "Maintenance"
RESERVED = "Reserved"
class PilotStatus(str, enum.Enum):
AVAILABLE = "Available"
ASSIGNED = "Assigned"
ON_LEAVE = "On Leave"
TRAINING = "Training"
RETIRED = "Retired"
class TrainStatus(str, enum.Enum):
RUNNING = "Running"
DELAYED = "Delayed"
RESERVED = "Reserved"
MAINTENANCE = "Maintenance"
COMPLETED = "Completed"
# ---------- DATABASE CONFIG ----------
DATABASE_URL = "mysql+pymysql://root:mysql19t02r06@localhost:3306/resource_mgmt"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)
Base = declarative_base()
# ---------- TABLE MODELS ----------
class TrainLocation(Base):
__tablename__ = "train_location"
id = Column(Integer, primary_key=True, index=True)
train_no = Column(String(20), ForeignKey("train_allocation.train_no"))
latitude = Column(Float)
longitude = Column(Float)
timestamp = Column(DateTime, default=datetime.datetime.utcnow)
train = relationship("TrainAllocation", back_populates="locations")
class Engine(Base):
__tablename__ = "engine"
engine_id = Column(Integer, primary_key=True, index=True)
engine_type = Column(String(50))
status = Column(Enum(EngineStatus, native_enum=False), default=EngineStatus.AVAILABLE)
last_maintenance = Column(Date, nullable=True)
next_maintenance = Column(Date, nullable=True)
class Carriage(Base):
__tablename__ = "carriage"
carriage_id = Column(Integer, primary_key=True, index=True)
carriage_type = Column(String(50))
station_id = Column(String(50))
status = Column(Enum(CarriageStatus, native_enum=False), default=CarriageStatus.AVAILABLE)
last_maintenance = Column(Date, nullable=True)
next_maintenance = Column(Date, nullable=True)
class LocoPilot(Base):
__tablename__ = "locopilot"
pilot_id = Column(Integer, primary_key=True, index=True)
name = Column(String(100))
experience_years = Column(Integer)
status = Column(Enum(PilotStatus, native_enum=False, validate_strings=True), default=PilotStatus.AVAILABLE)
last_trip_date = Column(Date, default=None)
resting_period_days = Column(Integer, default=1)
class TrainAllocation(Base):
__tablename__ = "train_allocation"
train_no = Column(String(20), primary_key=True, index=True)
engine_id = Column(Integer, ForeignKey("engine.engine_id"))
pilot_id = Column(Integer, ForeignKey("locopilot.pilot_id"))
route = Column(String(100))
status = Column(Enum(TrainStatus, native_enum=False), default=TrainStatus.RESERVED)
trip_start_date = Column(Date, default=None)
trip_end_date = Column(Date, default=None)
train_type = Column(SqlEnum(TrainType, native_enum=False), default=TrainType.EXPRESS)
engine = relationship("Engine")
pilot = relationship("LocoPilot")
carriages = relationship("TrainCarriageMapping", back_populates="train")
locations = relationship("TrainLocation", back_populates="train")
class TrainCarriageMapping(Base):
__tablename__ = "train_carriage_mapping"
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
train_no = Column(String(20), ForeignKey("train_allocation.train_no"))
carriage_id = Column(Integer, ForeignKey("carriage.carriage_id"))
train = relationship("TrainAllocation", back_populates="carriages")
carriage = relationship("Carriage")
def calculate_pilot_score(pilot: LocoPilot, start_date: datetime.date) -> int:
if pilot.status != PilotStatus.AVAILABLE:
return -1
if pilot.last_trip_date:
if start_date < pilot.last_trip_date:
return -1 # cannot start before last trip
days_since_trip = (start_date - pilot.last_trip_date).days
if days_since_trip < pilot.resting_period_days:
return -1
score = days_since_trip
else:
score = 5 # bonus for fresh availability
score += pilot.experience_years * 2
return score
# Dependency to get DB session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
#---------web socket manager-----
class ConnectionManager:
def __init__(self):
self.active_connections: Dict[str, List[WebSocket]] = {}
async def connect(self, train_no: str, websocket: WebSocket):
await websocket.accept()
if train_no not in self.active_connections:
self.active_connections[train_no] = []
self.active_connections[train_no].append(websocket)
def disconnect(self, train_no: str, websocket: WebSocket):
if train_no in self.active_connections:
self.active_connections[train_no].remove(websocket)
if not self.active_connections[train_no]:
del self.active_connections[train_no]
async def broadcast(self, message: Dict):
for train_no, connections in self.active_connections.items():
for connection in connections:
try:
await connection.send_json(message)
except WebSocketDisconnect:
self.disconnect(train_no, connection)
manager = ConnectionManager()
# ---------- API ENDPOINTS ----------
@app.get("/")
def root():
return {"message": "Resource Management API (WCR Hackathon)"}
@app.get("/engines/")
def get_engines(db: Session = Depends(get_db)):
return db.query(Engine).all()
@app.get("/carriages/")
def get_carriages(db: Session = Depends(get_db)):
return db.query(Carriage).all()
@app.get("/pilots/")
def get_pilots(db: Session = Depends(get_db)):
return db.query(LocoPilot).all()
# WebSocket endpoint for real-time tracking
@app.websocket("/ws/train-tracking/{train_no}")
async def websocket_endpoint(websocket: WebSocket, train_no: str):
await manager.connect(train_no, websocket)
try:
while True:
# We can receive messages here if the client needs to send data back
# For now, we'll just keep the connection open.
await websocket.receive_text()
except WebSocketDisconnect:
manager.disconnect(train_no)
# API endpoint to receive location updates from a train's GPS/IoT device
@app.post("/api/update-location/")
async def update_train_location(location: TrainLocationUpdate, db: Session = Depends(get_db)):
# 1. Save the location to the database
new_location = TrainLocation(
train_no=location.train_no,
latitude=location.latitude,
longitude=location.longitude,
timestamp=location.timestamp
)
db.add(new_location)
db.commit()
db.refresh(new_location)
# 2. Broadcast the location to all connected dashboard clients
await manager.broadcast(location.dict())
return {"message": "Location updated and broadcasted successfully"}
# Allocate train with conflict + rest + maintenance check
@app.post("/allocate-train/")
def allocate_train(request: TrainAllocationRequest, db: Session = Depends(get_db)):
train_no = request.train_no
engine_id = request.engine_id
pilot_id = request.pilot_id
carriage_ids = request.carriage_ids
route = request.route
start_date = request.start_date
end_date = request.end_date
# Check engine availability + maintenance
engine = db.query(Engine).filter_by(engine_id=engine_id).first()
if not engine or engine.status != EngineStatus.AVAILABLE:
raise HTTPException(status_code=400, detail="Engine not available")
if engine.next_maintenance and engine.next_maintenance < start_date:
raise HTTPException(status_code=400, detail=f"Engine {engine.engine_id} requires maintenance before this trip")
# Handle pilot selection
if request.pilot_id:
pilot = db.query(LocoPilot).filter_by(pilot_id=request.pilot_id).first()
if not pilot:
raise HTTPException(status_code=400, detail="Pilot not found")
if pilot.status != PilotStatus.AVAILABLE:
raise HTTPException(status_code=400, detail="Pilot not available")
if pilot.last_trip_date:
days_since_trip = (request.start_date - pilot.last_trip_date).days
if days_since_trip < pilot.resting_period_days:
raise HTTPException(
status_code=400,
detail=f"Pilot needs rest. Available after {pilot.last_trip_date + datetime.timedelta(days=pilot.resting_period_days)}"
)
else:
# Auto-select best pilot
candidates = db.query(LocoPilot).filter_by(status=PilotStatus.AVAILABLE).all()
scored = [(p, calculate_pilot_score(p, request.start_date)) for p in candidates]
scored = [p for p in scored if p[1] >= 0]
if not scored:
raise HTTPException(status_code=400, detail="No eligible pilots available")
pilot = max(scored, key=lambda x: x[1])[0]
# Check carriage availability + maintenance + overlap
for cid in carriage_ids:
carriage = db.query(Carriage).filter_by(carriage_id=cid).first()
if not carriage or carriage.status != CarriageStatus.AVAILABLE:
raise HTTPException(status_code=400, detail=f"Carriage {cid} not available")
if carriage.next_maintenance and carriage.next_maintenance < start_date:
raise HTTPException(status_code=400, detail=f"Carriage {cid} requires maintenance before this trip")
overlap = db.query(TrainCarriageMapping).join(TrainAllocation).filter(
TrainCarriageMapping.carriage_id == cid,
TrainAllocation.trip_start_date <= end_date,
TrainAllocation.trip_end_date >= start_date
).first()
if overlap:
raise HTTPException(status_code=400, detail=f"Carriage {cid} is already assigned in this period")
# Create train allocation
train = TrainAllocation(
train_no=train_no,
engine_id=engine_id,
pilot_id=pilot.pilot_id,
route=route,
status=TrainStatus.RUNNING,
trip_start_date=start_date,
trip_end_date=end_date,
train_type=request.train_type
)
db.add(train)
db.flush()
# Assign carriages
for cid in carriage_ids:
mapping = TrainCarriageMapping(train_no=train_no, carriage_id=cid)
db.add(mapping)
# Update resource statuses
engine.status = EngineStatus.IN_USE
pilot.status = PilotStatus.ASSIGNED
pilot.last_trip_date = start_date
for cid in carriage_ids:
carriage = db.query(Carriage).filter_by(carriage_id=cid).first()
carriage.status = CarriageStatus.IN_USE
db.commit()
return {
"message": "Train allocated successfully",
"train_no": train_no,
"train_type": request.train_type.value,
"engine_id": engine_id,
"pilot_id": pilot.pilot_id,
"pilot_name": pilot.name,
"carriage_ids": carriage_ids,
"route": route,
"start_date": str(start_date),
"end_date": str(end_date)
}
# Reset resources after train completes journey
@app.post("/reset-train/{train_no}")
def reset_train(train_no: str, db: Session = Depends(get_db)):
train = db.query(TrainAllocation).filter_by(train_no=train_no).first()
if not train:
raise HTTPException(404, "Train not found")
train.status = TrainStatus.COMPLETED
# Reset engine
if train.engine:
train.engine.status = EngineStatus.AVAILABLE
# update maintenance
train.engine.last_maintenance = train.trip_end_date
train.engine.next_maintenance = train.trip_end_date + datetime.timedelta(days=30) # example rule: every 30 days
# Reset pilot (respecting rest days)
if train.pilot:
train.pilot.last_trip_date = train.trip_end_date
train.pilot.status = PilotStatus.AVAILABLE
# Reset carriages
for mapping in train.carriages:
mapping.carriage.status = CarriageStatus.AVAILABLE
# update maintenance
mapping.carriage.last_maintenance = train.trip_end_date
mapping.carriage.next_maintenance = train.trip_end_date + datetime.timedelta(days=45) # example: every 45 days
db.commit()
return {"message": f"Train {train_no} reset successfully"}
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
if isinstance(exc, HTTPException):
return JSONResponse(
status_code=exc.status_code,
content={"message": exc.detail},
)
return JSONResponse(
status_code=500,
content={"message": f"Unexpected error: {str(exc)}"}
)
# ---------- HEALTH CHECK ----------
@app.get("/health")
def health_check(db: Session = Depends(get_db)):
try:
db.execute(text("SELECT 1"))
return {"status": "ok"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))