-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_simulation.py
More file actions
174 lines (147 loc) · 5.98 KB
/
Copy pathrun_simulation.py
File metadata and controls
174 lines (147 loc) · 5.98 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
import MySQLdb
import schedule
import time
from datetime import datetime, timedelta
# ----------------------
# Database Configuration
# ----------------------
db_config = {
'host': 'cpsc4910-f25.cobd8enwsupz.us-east-1.rds.amazonaws.com',
'user': 'Team16',
'passwd': 'Tlaw16',
'db': 'Team16_DB',
'charset': 'utf8'
}
# ----------------------
# Helper Functions
# ----------------------
def is_rule_due(schedule_str):
"""Check if a rule schedule matches the current time within ±15 minutes."""
now = datetime.now()
try:
parts = schedule_str.strip().split()
day_part = parts[0].lower()
time_part = parts[1]
# Convert scheduled day to number (0=Monday)
days_map = {
'mon': 0, 'monday': 0,
'tue': 1, 'tuesday': 1,
'wed': 2, 'wednesday': 2,
'thu': 3, 'thursday': 3,
'fri': 4, 'friday': 4,
'sat': 5, 'saturday': 5,
'sun': 6, 'sunday': 6
}
scheduled_day = days_map.get(day_part[:3])
if scheduled_day is None:
print(f"[WARN] Unknown day in schedule: {schedule_str}")
return False
# Parse scheduled time
scheduled_time = datetime.strptime(time_part, "%H:%M").time()
scheduled_datetime = datetime.combine(
now.date() + timedelta(days=(scheduled_day - now.weekday()) % 7),
scheduled_time
)
# Check if current time is within ±15 minutes
window_start = scheduled_datetime - timedelta(minutes=15)
window_end = scheduled_datetime + timedelta(minutes=15)
return window_start <= now <= window_end
except Exception as e:
print(f"[ERROR] Failed to parse schedule '{schedule_str}': {e}")
return False
def run_simulation():
"""Main simulation runner."""
try:
db = MySQLdb.connect(**db_config)
cursor = db.cursor(MySQLdb.cursors.DictCursor)
# Fetch all enabled rules
cursor.execute("SELECT * FROM simulation_rules WHERE enabled=1")
rules = cursor.fetchall()
for rule in rules:
if is_rule_due(rule['schedule']):
execute_rule(rule)
cursor.close()
db.close()
except Exception as e:
print(f"[ERROR] Simulation failed: {e}")
def execute_rule(rule):
"""Perform the action defined by a rule."""
action_type = rule['type']
value = rule['action_value']
try:
db = MySQLdb.connect(**db_config)
cursor = db.cursor()
if action_type == 'add_driver':
username = rule.get('driver_username')
if username:
cursor.execute("INSERT IGNORE INTO drivers (username) VALUES (%s)", (username,))
db.commit()
print(f"[SIM] Added driver '{username}'")
else:
print(f"[WARN] Missing username for add_driver rule {rule['id']}")
elif action_type == 'remove_driver':
username = rule.get('driver_username')
if username:
cursor.execute("DELETE FROM drivers WHERE username=%s", (username,))
db.commit()
print(f"[SIM] Removed driver '{username}'")
else:
print(f"[WARN] Missing username for remove_driver rule {rule['id']}")
elif action_type == 'add_points':
username = rule.get('driver_username')
if username and value is not None:
# Find first sponsor entry for that driver
cursor.execute("""
SELECT sponsor
FROM driver_sponsor_points
WHERE driver_username = %s
ORDER BY sponsor ASC
LIMIT 1
""", (username,))
result = cursor.fetchone()
if result:
sponsor = result[0]
cursor.execute("""
UPDATE driver_sponsor_points
SET points = points + %s
WHERE driver_username = %s AND sponsor = %s
""", (value, username, sponsor))
db.commit()
print(f"[SIM] Added {value} points to {username} under sponsor '{sponsor}'")
else:
print(f"[WARN] No sponsor found for add_points rule {rule['id']}")
else:
print(f"[WARN] Missing username or value for add_points rule {rule['id']}")
elif action_type == 'remove_points':
username = rule.get('driver_username')
if username and value is not None:
cursor.execute("""
SELECT sponsor
FROM driver_sponsor_points
WHERE driver_username = %s
ORDER BY sponsor ASC
LIMIT 1
""", (username,))
result = cursor.fetchone()
if result:
sponsor = result[0]
cursor.execute("""
UPDATE driver_sponsor_points
SET points = GREATEST(points - %s, 0)
WHERE driver_username = %s AND sponsor = %s
""", (value, username, sponsor))
db.commit()
print(f"[SIM] Removed {value} points from {username} under sponsor '{sponsor}'")
else:
print(f"[WARN] No sponsor found for remove_points rule {rule['id']}")
else:
print(f"[WARN] Missing username or value for remove_points rule {rule['id']}")
# ----------------------
# Scheduler
# ----------------------
schedule.every(15).minutes.do(run_simulation)
print("[INFO] Simulation scheduler started. Running every 15 minutes.")
run_simulation() # Optional: run immediately on startup
while True:
schedule.run_pending()
time.sleep(1)