-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmt40_controller.py
More file actions
executable file
·1540 lines (1352 loc) · 51.8 KB
/
mt40_controller.py
File metadata and controls
executable file
·1540 lines (1352 loc) · 51.8 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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
MT40 Power Controller Application
- Receives webhooks from MT30 button presses
- Controls MT40 power state via Meraki API
- Runs scheduled power on/off based on cron-style schedule
"""
import meraki
import os
import json
import logging
import gzip
import shutil
from datetime import datetime
from functools import wraps
from collections import deque
from flask import Flask, request, jsonify, Response, render_template_string
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from dotenv import load_dotenv, set_key
# Load environment variables
load_dotenv()
# Configuration
API_KEY = os.getenv('MERAKI_API_KEY')
ORG_ID = os.getenv('MERAKI_ORG_ID')
NETWORK_NAME = os.getenv('MERAKI_NETWORK_NAME')
MT40_SERIAL = os.getenv('MT40_SERIAL')
WEBHOOK_PORT = int(os.getenv('WEBHOOK_PORT', 3001))
WEBHOOK_HOST = os.getenv('WEBHOOK_HOST', '0.0.0.0')
CONFIG_FILE = 'schedules.json'
DEBUG_MODE = os.getenv('DEBUG_MODE', '').lower() # Options: 'webhook', 'schedule', 'all', or empty for no debug
UI_USERNAME = os.getenv('UI_USERNAME', 'admin')
UI_PASSWORD = os.getenv('UI_PASSWORD', 'admin')
LONG_PRESS_TIMEOUT = int(os.getenv('LONG_PRESS_TIMEOUT', 20)) # Seconds to wait for second press
MISFIRE_GRACE_TIME = int(os.getenv('MISFIRE_GRACE_TIME', 600))
ENV_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env')
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('mt40_controller.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# Initialize Flask app
app = Flask(__name__)
# Initialize Meraki Dashboard API
dashboard = meraki.DashboardAPI(API_KEY, suppress_logging=True)
# Initialize scheduler with explicit timezone and generous misfire grace time
# misfire_grace_time: if a job fires late (e.g., after reboot + NTP sync delay), still run it
scheduler = BackgroundScheduler(
timezone='America/New_York',
job_defaults={'misfire_grace_time': MISFIRE_GRACE_TIME}
)
scheduler.start()
# Event history (keep last 100 events)
event_history = deque(maxlen=100)
# Runtime debug mode control (can be changed via API)
# Each action type can be independently set to debug mode
def parse_debug_mode(mode_str):
"""Parse DEBUG_MODE env var to individual toggles"""
mode = mode_str.lower() if mode_str else ''
return {
'webhook': mode in ('webhook', 'all'),
'schedule': mode in ('schedule', 'all'),
'manual': mode in ('manual', 'all')
}
debug_mode_state = parse_debug_mode(DEBUG_MODE)
# Long press confirmation tracking (for double press to turn off)
long_press_pending = {'timestamp': None, 'timeout_seconds': LONG_PRESS_TIMEOUT}
def require_auth(f):
"""Decorator for routes that require HTTP Basic Authentication"""
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or auth.username != UI_USERNAME or auth.password != UI_PASSWORD:
return Response(
'Authentication required',
401,
{'WWW-Authenticate': 'Basic realm="MT40 Controller"'}
)
return f(*args, **kwargs)
return decorated
def get_network_id():
"""Get the network ID for the configured network name"""
try:
networks = dashboard.organizations.getOrganizationNetworks(ORG_ID)
for network in networks:
if network['name'] == NETWORK_NAME:
return network['id']
logger.error(f"Network '{NETWORK_NAME}' not found")
return None
except Exception as e:
logger.error(f"Error getting network ID: {e}")
return None
def control_mt40_power(action, source='unknown'):
"""
Control MT40 downstream power state
Args:
action: 'on' or 'off'
source: 'webhook', 'schedule', 'manual', or 'unknown'
Returns:
bool: True if successful, False otherwise
"""
# Map friendly names to MT40 API operations
operation_map = {
'on': 'enableDownstreamPower',
'off': 'disableDownstreamPower'
}
operation = operation_map.get(action)
if not operation:
logger.error(f"Invalid action: {action}. Must be 'on' or 'off'")
return False
# Check if this action should be skipped due to debug mode
skip_action = debug_mode_state.get(source, False)
if skip_action:
logger.info(f"[DEBUG MODE - {source.upper()}] Would send {operation} command to MT40 ({MT40_SERIAL}), but skipping due to debug enabled for {source}")
logger.info(f"[DEBUG MODE] MT40 power {action.upper()} - ACTION SKIPPED")
# Log event
event_history.append({
'timestamp': datetime.now().isoformat(),
'action': action,
'source': source,
'status': 'debug_skipped'
})
return True # Return True to indicate "successful" debug execution
try:
logger.info(f"Sending {operation} command to MT40 ({MT40_SERIAL})...")
response = dashboard.sensor.createDeviceSensorCommand(
MT40_SERIAL,
operation=operation
)
command_id = response.get('commandId', 'unknown')
status = response.get('status', 'unknown')
logger.info(f"✓ MT40 power {action.upper()} command sent successfully (ID: {command_id}, Status: {status})")
logger.debug(f"Full response: {response}")
# Log if there are immediate errors
if response.get('errors'):
logger.warning(f"Command queued but has errors: {response.get('errors')}")
# Log event
event_history.append({
'timestamp': datetime.now().isoformat(),
'action': action,
'source': source,
'status': 'success'
})
return True
except meraki.exceptions.APIError as e:
logger.error(f"Meraki API Error controlling MT40: {e}")
# Log event
event_history.append({
'timestamp': datetime.now().isoformat(),
'action': action,
'source': source,
'status': 'failed',
'error': str(e)
})
return False
except Exception as e:
logger.error(f"Error controlling MT40: {e}")
# Log event
event_history.append({
'timestamp': datetime.now().isoformat(),
'action': action,
'source': source,
'status': 'failed',
'error': str(e)
})
return False
def rotate_log():
"""Rotate the log file - compress and keep one backup"""
log_file = 'mt40_controller.log'
backup_file = 'mt40_controller.log.1.gz'
try:
if not os.path.exists(log_file):
logger.info("Log rotation skipped - no log file exists")
return
logger.info("Starting monthly log rotation...")
# Close the file handler
for handler in logging.root.handlers:
if isinstance(handler, logging.FileHandler):
handler.close()
# Compress log to backup (overwrites previous backup)
with open(log_file, 'rb') as f_in:
with gzip.open(backup_file, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
# Delete the original
os.remove(log_file)
# Reopen the handler (creates new empty file)
for handler in logging.root.handlers:
if isinstance(handler, logging.FileHandler):
handler.stream = open(log_file, 'a')
logger.info("Log rotation complete")
except Exception as e:
logger.error(f"Error during log rotation: {e}")
def power_on():
"""Turn MT40 power ON - scheduled function"""
logger.info("⚡ Scheduled power ON triggered")
control_mt40_power('on', source='schedule')
def power_off():
"""Turn MT40 power OFF - scheduled function"""
logger.info("⏻ Scheduled power OFF triggered")
control_mt40_power('off', source='schedule')
def load_schedules():
"""Load schedules from JSON config file and setup cron jobs"""
try:
if not os.path.exists(CONFIG_FILE):
logger.warning(f"Config file '{CONFIG_FILE}' not found. No schedules loaded.")
return
with open(CONFIG_FILE, 'r') as f:
config = json.load(f)
schedules = config.get('schedules', [])
# Clear existing jobs
scheduler.remove_all_jobs()
# Add new jobs
for schedule in schedules:
if not schedule.get('enabled', True):
logger.info(f"Skipping disabled schedule: {schedule.get('name', 'Unnamed')}")
continue
name = schedule.get('name', 'Unnamed Schedule')
action = schedule.get('action') # 'on' or 'off'
time_str = schedule.get('time') # HH:MM format
days = schedule.get('days', 'mon-fri') # e.g., 'mon-fri', 'mon,wed,fri', 'daily'
if not action or not time_str:
logger.warning(f"Invalid schedule: {schedule}")
continue
# Parse time
hour, minute = map(int, time_str.split(':'))
# Parse days
if days == 'daily':
day_of_week = '*'
elif days == 'mon-fri':
day_of_week = 'mon-fri'
elif days == 'weekends':
day_of_week = 'sat,sun'
else:
day_of_week = days
# Choose function based on action
if action == 'on':
func = power_on
action_name = "Power ON"
else:
func = power_off
action_name = "Power OFF"
# Add cron job
trigger = CronTrigger(
day_of_week=day_of_week,
hour=hour,
minute=minute
)
scheduler.add_job(
func=func,
trigger=trigger,
id=f"schedule_{name}",
name=f"{name} - {action_name}",
replace_existing=True
)
logger.info(f"✓ Loaded schedule: '{name}' - {action_name} at {time_str} on {days}")
logger.info(f"Total schedules loaded: {len(scheduler.get_jobs())}")
except json.JSONDecodeError as e:
logger.error(f"Error parsing JSON config: {e}")
except Exception as e:
logger.error(f"Error loading schedules: {e}")
# Add log rotation job (1st of each month at midnight)
scheduler.add_job(
func=rotate_log,
trigger=CronTrigger(day=1, hour=0, minute=0),
id='log_rotation',
name='Monthly Log Rotation',
replace_existing=True
)
logger.info("Log rotation scheduled for 1st of each month at midnight")
@app.route('/webhook', methods=['POST', 'GET'])
def webhook_handler():
"""Handle incoming webhooks from MT30 button"""
# Handle GET requests (Meraki validation)
if request.method == 'GET':
logger.info("Webhook GET validation received")
return "Webhook GET Received", 200
try:
# Check if body is empty
if not request.data:
logger.warning("Empty webhook body received")
return "Webhook POST Received", 200
data = request.get_json(force=True)
# Extract trigger data (sensor automation structure)
# Check both top-level and inside alertData for Meraki compatibility
trigger = data.get('trigger', {})
alert_data = data.get('alertData', {})
# If trigger not at top level, check inside alertData
if not trigger and alert_data:
trigger = alert_data.get('trigger', {})
metric = trigger.get('metric', '')
button_data = trigger.get('button', {})
press_type = button_data.get('pressType', '')
# Also check alternative payload structures for compatibility
alert_type = data.get('alertType', '')
# Fallback: check automation message
automation_message = alert_data.get('message', '').lower() if alert_data else ''
if not automation_message:
automation_message = data.get('automationMessage', '').lower()
# Check if this is a button press event
if metric == 'button' or 'button' in alert_type.lower():
# Determine press type from multiple possible sources
if press_type == 'short' or 'short' in automation_message:
logger.info("🔘 SHORT PRESS detected - Turning MT40 ON")
control_mt40_power('on', source='webhook')
return "Webhook POST Received", 200
elif press_type == 'long' or 'long' in automation_message:
# Double long press confirmation for turning off
now = datetime.now()
last_press = long_press_pending['timestamp']
timeout = long_press_pending['timeout_seconds']
if last_press and (now - last_press).total_seconds() <= timeout:
# Second press within timeout - execute OFF
logger.info("🔘 SECOND LONG PRESS detected - Turning MT40 OFF")
long_press_pending['timestamp'] = None # Clear pending
control_mt40_power('off', source='webhook')
return "Webhook POST Received", 200
else:
# First press or timeout expired - wait for confirmation
logger.info(f"🔘 FIRST LONG PRESS detected - Press again within {timeout}s to turn OFF")
long_press_pending['timestamp'] = now
# Log this as a pending confirmation event
event_history.append({
'timestamp': now.isoformat(),
'action': 'off',
'source': 'webhook',
'status': 'pending_confirmation'
})
return "Webhook POST Received", 200
else:
logger.warning(f"Unknown button press type. Payload: {json.dumps(data, indent=2)}")
return "Webhook POST Received", 200
else:
logger.info(f"Non-button event received. Alert type: {alert_type}, Metric: {metric}")
return "Webhook POST Received", 200
except Exception as e:
logger.error(f"Error handling webhook: {e}", exc_info=True)
return "No data received", 400
@app.route('/health', methods=['GET'])
def health_check():
"""Health check endpoint"""
return jsonify({
'status': 'running',
'timestamp': datetime.now().isoformat(),
'schedules_active': len(scheduler.get_jobs())
}), 200
@app.route('/schedules', methods=['GET'])
def list_schedules():
"""List all active schedules"""
jobs = scheduler.get_jobs()
schedule_list = []
for job in jobs:
schedule_list.append({
'id': job.id,
'name': job.name,
'next_run': job.next_run_time.isoformat() if job.next_run_time else None
})
return jsonify({
'schedules': schedule_list,
'count': len(schedule_list)
}), 200
@app.route('/control/<action>', methods=['POST'])
@require_auth
def manual_control(action):
"""Manual control endpoint for testing"""
if action == 'on':
result = control_mt40_power('on', source='manual')
return jsonify({'status': 'success' if result else 'failed', 'action': 'power_on'}), 200
elif action == 'off':
result = control_mt40_power('off', source='manual')
return jsonify({'status': 'success' if result else 'failed', 'action': 'power_off'}), 200
else:
return jsonify({'status': 'error', 'message': 'Invalid action. Use "on" or "off"'}), 400
@app.route('/admin', methods=['GET'])
@require_auth
def admin_ui():
"""Serve the schedule management UI"""
# Get server timezone
server_tz = datetime.now().astimezone().tzname()
html_template = '''
<!DOCTYPE html>
<html>
<head>
<title>MT40 Schedule Manager</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background: #f5f5f5;
padding: 20px;
line-height: 1.6;
}
.container {
max-width: 1000px;
margin: 0 auto;
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
position: relative;
}
.header-section {
position: relative;
margin-bottom: 30px;
}
.clock {
position: absolute;
top: 0;
right: 0;
font-size: 18px;
font-weight: 600;
color: #333;
background: #f8f9fa;
padding: 10px 20px;
border-radius: 6px;
border: 1px solid #ddd;
}
h1 {
color: #333;
margin-bottom: 10px;
}
.subtitle {
color: #666;
margin-bottom: 0;
}
.toast {
position: fixed;
bottom: 20px;
right: 20px;
padding: 12px 20px;
border-radius: 6px;
display: none;
z-index: 1000;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
max-width: 350px;
animation: slideIn 0.3s ease;
}
@keyframes slideIn {
from { transform: translateX(100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
.toast.success {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.toast.error {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.version {
font-size: 12px;
color: #999;
margin-top: 5px;
}
.form-section {
background: #f8f9fa;
padding: 20px;
border-radius: 6px;
margin-bottom: 30px;
}
.form-section h2 {
margin-bottom: 15px;
font-size: 18px;
color: #333;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: 500;
color: #333;
}
input[type="text"],
input[type="time"],
select {
width: 100%;
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
input[type="checkbox"] {
margin-right: 8px;
}
.form-row {
display: grid;
grid-template-columns: 2fr 1fr 1fr 1.5fr 0.5fr;
gap: 10px;
align-items: end;
}
button {
padding: 10px 20px;
border: none;
border-radius: 4px;
font-size: 14px;
cursor: pointer;
font-weight: 500;
}
.btn-primary {
background: #007bff;
color: white;
}
.btn-primary:hover {
background: #0056b3;
}
.btn-danger {
background: #dc3545;
color: white;
padding: 6px 12px;
font-size: 12px;
}
.btn-danger:hover {
background: #c82333;
}
.btn-secondary {
background: #6c757d;
color: white;
padding: 6px 12px;
font-size: 12px;
}
.btn-secondary:hover {
background: #545b62;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 10px;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background: #f8f9fa;
font-weight: 600;
color: #333;
}
tr:hover {
background: #f8f9fa;
}
.status-badge {
display: inline-block;
padding: 4px 8px;
border-radius: 3px;
font-size: 12px;
font-weight: 500;
}
.status-enabled {
background: #d4edda;
color: #155724;
}
.status-disabled {
background: #f8d7da;
color: #721c24;
}
.status-pending {
background: #fff3cd;
color: #856404;
}
.action-badge {
display: inline-block;
padding: 4px 8px;
border-radius: 3px;
font-size: 12px;
font-weight: 500;
}
.action-on {
background: #d1ecf1;
color: #0c5460;
}
.action-off {
background: #f8d7da;
color: #721c24;
}
.actions {
display: flex;
gap: 8px;
}
.power-control-bar {
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
margin-bottom: 25px;
padding: 12px 20px;
background: #f8f9fa;
border-radius: 6px;
}
.power-control-row {
display: flex;
align-items: center;
justify-content: center;
gap: 15px;
}
.power-control-bar .label {
font-weight: 500;
color: #555;
}
.debug-status-line {
font-size: 13px;
color: #856404;
background: rgba(255, 193, 7, 0.2);
padding: 4px 12px;
border-radius: 4px;
}
.power-status {
display: inline-block;
padding: 6px 16px;
border-radius: 16px;
font-weight: 600;
font-size: 14px;
min-width: 70px;
text-align: center;
}
.power-status.on {
background: #28a745;
color: white;
}
.power-status.off {
background: #dc3545;
color: white;
}
.power-status.unknown {
background: #6c757d;
color: white;
}
.btn-control {
padding: 8px 20px;
font-size: 14px;
font-weight: 500;
border: none;
border-radius: 4px;
cursor: pointer;
transition: all 0.2s;
}
.btn-control:hover {
transform: translateY(-1px);
box-shadow: 0 2px 6px rgba(0,0,0,0.15);
}
.btn-power-on {
background: #28a745;
color: white;
}
.btn-power-on:hover {
background: #218838;
}
.btn-power-off {
background: #dc3545;
color: white;
}
.btn-power-off:hover {
background: #c82333;
}
#debugSection {
border: 2px solid #ffc107;
background: #fff3cd;
}
.debug-toggle-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 16px;
background: white;
border-radius: 6px;
margin-bottom: 10px;
border: 1px solid #ddd;
}
.debug-toggle-row:last-child {
margin-bottom: 0;
}
.debug-toggle-label {
font-weight: 500;
color: #333;
}
.toggle-switch {
position: relative;
width: 50px;
height: 26px;
}
.toggle-switch input {
opacity: 0;
width: 0;
height: 0;
}
.toggle-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: 0.3s;
border-radius: 26px;
}
.toggle-slider:before {
position: absolute;
content: "";
height: 20px;
width: 20px;
left: 3px;
bottom: 3px;
background-color: white;
transition: 0.3s;
border-radius: 50%;
}
.toggle-switch input:checked + .toggle-slider {
background-color: #ffc107;
}
.toggle-switch input:checked + .toggle-slider:before {
transform: translateX(24px);
}
.debug-note {
color: #856404;
font-size: 0.9em;
margin-top: 15px;
padding: 10px 12px;
background: rgba(255, 193, 7, 0.2);
border-radius: 4px;
border-left: 3px solid #ffc107;
}
</style>
</head>
<body>
<div class="container">
<div class="header-section">
<div id="clock" class="clock">--:--:--</div>
<h1>MT40 Schedule Manager</h1>
<p class="subtitle">Manage power on/off schedules</p>
<p class="version">v1.2.2</p>
</div>
<div id="toast" class="toast"></div>
<div class="power-control-bar">
<div class="power-control-row">
<span class="label">Power Status:</span>
<span id="powerStatus" class="power-status unknown">...</span>
<span class="label" style="margin-left: 10px;">Set Power:</span>
<button class="btn-control btn-power-on" onclick="manualPowerControl('on')">ON</button>
<button class="btn-control btn-power-off" onclick="manualPowerControl('off')">OFF</button>
</div>
<div class="power-control-row" style="margin-top: 8px;">
<span class="label">Misfire Grace:</span>
<input type="number" id="misfireGraceTime" min="30" max="3600" style="width:70px; padding:4px 8px; border:1px solid #ccc; border-radius:4px; font-size:14px;">
<span class="label">sec</span>
<button class="btn-control" style="background:#6c757d; color:white;" onclick="saveMisfireGraceTime()">Save</button>
</div>
<div id="debugStatusLine" class="debug-status-line">Debugging: None</div>
</div>
<div class="form-section">
<h2>Current Schedules</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Action</th>
<th>Time</th>
<th>Days</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="scheduleTable">
<tr>
<td colspan="6" style="text-align: center; color: #999;">Loading...</td>
</tr>
</tbody>
</table>
</div>
<div class="form-section">
<h2>Add New Schedule</h2>
<form id="addForm">
<div class="form-row">
<div class="form-group">
<label>Name</label>
<input type="text" id="name" required placeholder="e.g., Morning ON">
</div>
<div class="form-group">
<label>Action</label>
<select id="action" required>
<option value="on">Power ON</option>
<option value="off">Power OFF</option>
</select>
</div>
<div class="form-group">
<label>Time</label>
<input type="time" id="time" required>
</div>
<div class="form-group">
<label>Days</label>
<select id="days" required>
<option value="daily">Daily</option>
<option value="mon-fri">Weekdays (Mon-Fri)</option>
<option value="weekends">Weekends (Sat-Sun)</option>
<option value="mon">Monday</option>
<option value="tue">Tuesday</option>
<option value="wed">Wednesday</option>
<option value="thu">Thursday</option>
<option value="fri">Friday</option>
<option value="sat">Saturday</option>
<option value="sun">Sunday</option>
</select>
</div>
<div class="form-group">
<button type="submit" class="btn-primary">Add</button>
</div>
</div>
</form>
</div>
<div class="form-section">
<h2>Recent Events</h2>
<table>
<thead>
<tr>
<th>Timestamp</th>
<th>Action</th>
<th>Source</th>
<th>Status</th>
</tr>
</thead>
<tbody id="eventsTable">
<tr>
<td colspan="4" style="text-align: center; color: #999;">Loading...</td>
</tr>
</tbody>
</table>
</div>
<div class="form-section" id="debugSection">
<h2>Debug Mode</h2>
<p style="color: #666; margin-bottom: 15px;">Test power commands without affecting the actual device</p>
<div class="debug-toggle-row">
<span class="debug-toggle-label">Manual (UI Buttons)</span>
<label class="toggle-switch">
<input type="checkbox" id="debugManual" onchange="updateDebugMode('manual', this.checked)">
<span class="toggle-slider"></span>
</label>
</div>
<div class="debug-toggle-row">
<span class="debug-toggle-label">Webhook (MT30 Button)</span>
<label class="toggle-switch">
<input type="checkbox" id="debugWebhook" onchange="updateDebugMode('webhook', this.checked)">
<span class="toggle-slider"></span>
</label>
</div>
<div class="debug-toggle-row">
<span class="debug-toggle-label">Schedule (Automated)</span>
<label class="toggle-switch">
<input type="checkbox" id="debugSchedule" onchange="updateDebugMode('schedule', this.checked)">
<span class="toggle-slider"></span>
</label>
</div>
<div class="debug-note">
Enabling debug for an action prevents it from changing the power status.
</div>
</div>
</div>
<script>
let schedules = [];
function showMessage(text, type) {
const toast = document.getElementById('toast');
toast.textContent = text;
toast.className = 'toast ' + type;
toast.style.display = 'block';
setTimeout(() => {
toast.style.display = 'none';
}, 3000);
}
async function manualPowerControl(action) {
try {
const response = await fetch(`/control/${action}`, {
method: 'POST'
});
if (!response.ok) throw new Error(`Failed to ${action} power`);
const data = await response.json();
if (data.status === 'success') {
showMessage(`Power ${action.toUpperCase()} command sent successfully`, 'success');
// Refresh events and status to show the new action
setTimeout(() => {
loadEvents();
loadPowerStatus();
}, 1000);
} else {
showMessage(`Failed to ${action} power`, 'error');
}
} catch (error) {
showMessage(`Error: ${error.message}`, 'error');
}
}