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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
| #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #include <ESP8266Ping.h> #include <ArduinoJson.h> #include <time.h>
const char* ssid = "zhou"; const char* password = "123456"; const char* computerIP = "1.1.1.45"; String localGatewayIP = "192.168.31.1"; String targetNetworkGatewayIP = "1.1.1.1";
ESP8266WebServer server(80); const int relayPin = 0; const int ledPin = 2; bool computerStatus = false; bool lastKnownComputerStatus = false; bool isRestarting = false; bool wifiConnected = false; bool failSafeMode = false; bool statusValidBeforeFailure = false;
unsigned long lastPingTime = 0; const unsigned long pingInterval = 8000; unsigned long lastWiFiCheck = 0; const unsigned long wifiCheckInterval = 15000; unsigned long networkFailureTime = 0; const unsigned long failSafeTimeout = 10000; const unsigned long routerStartupTimeout = 20000; unsigned long lastComputerOnlineTime = 0; unsigned long lastSuccessfulPingTime = 0; unsigned long continuousFailureStartTime = 0; unsigned long systemStartTime = 0; unsigned long totalOperations = 0; bool hasEverPingedSuccessfully = false; bool isRouterStartupPhase = true; unsigned long lastUserOperationTime = 0; const unsigned long userOperationGracePeriod = 120000;
enum FailSafePolicy { FAILSAFE_ALWAYS_ON, FAILSAFE_PRESERVE_STATE, FAILSAFE_SMART }; FailSafePolicy failSafePolicy = FAILSAFE_SMART; bool localNetworkConnectivity = false; bool targetNetworkConnectivity = false; unsigned long lastGatewayPingTime = 0;
enum TaskType { TASK_ON, TASK_OFF, TASK_TOGGLE };
struct Task { TaskType type; unsigned long executeMillis; String desc; };
const int MAX_TASKS = 5; Task tasks[MAX_TASKS]; int taskCount = 0;
void handleRoot() { String html = F(R"=====( <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>远程电源控制</title> <style> *{box-sizing:border-box} body{margin:0;padding:10px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);min-height:100vh;color:#333} .container{background:rgba(255,255,255,0.95);backdrop-filter:blur(10px);padding:20px;border-radius:12px;box-shadow:0 8px 32px rgba(0,0,0,0.1);max-width:800px;width:100%;margin:0 auto;border:1px solid rgba(255,255,255,0.2)} h1{margin:0 0 20px 0;color:#2c3e50;font-size:24px;text-align:center} h3{margin:15px 0 10px 0;color:#34495e;font-size:16px} .status{margin:15px 0;padding:12px;border-radius:8px;font-weight:bold;text-align:center;font-size:16px;border:2px solid transparent} .online{background:#d4edda;color:#155724;border-color:#c3e6cb} .offline{background:#f8d7da;color:#721c24;border-color:#f5c6cb} .info{font-size:13px;color:#6c757d;margin:5px 0;text-align:center} .button{padding:12px 20px;font-size:16px;color:white;background:#007bff;border:none;border-radius:8px;cursor:pointer;margin:5px;transition:all 0.3s ease;font-weight:500;min-height:48px;display:flex;align-items:center;justify-content:center} .button:hover{background:#0056b3;transform:translateY(-1px);box-shadow:0 4px 12px rgba(0,123,255,0.3)} .button:active{transform:translateY(0)} .button:disabled{background:#6c757d;cursor:not-allowed;transform:none;box-shadow:none} .button.on{background:#28a745} .button.on:hover{background:#218838;box-shadow:0 4px 12px rgba(40,167,69,0.3)} .button.off{background:#dc3545} .button.off:hover{background:#c82333;box-shadow:0 4px 12px rgba(220,53,69,0.3)} .section{margin:20px 0;padding:15px;border:1px solid rgba(0,0,0,0.1);border-radius:10px;background:rgba(255,255,255,0.5)} .input-group{margin:10px 0;display:flex;gap:8px;flex-wrap:wrap} .input-group input,.input-group select{padding:10px;border:2px solid #e9ecef;border-radius:6px;font-size:14px;transition:border-color 0.3s ease;min-height:40px} .input-group input:focus,.input-group select:focus{outline:none;border-color:#007bff;box-shadow:0 0 0 3px rgba(0,123,255,0.1)} .task-item{padding:12px;margin:8px 0;background:rgba(248,249,250,0.8);border-radius:8px;display:flex;justify-content:space-between;align-items:center;font-size:14px;border:1px solid rgba(0,0,0,0.05)} .task-item button{padding:6px 12px;font-size:12px;background:#dc3545;color:white;border:none;border-radius:5px;cursor:pointer;transition:background 0.3s ease} .task-item button:hover{background:#c82333} .quick-actions{display:flex;gap:8px;margin:15px 0;flex-wrap:wrap;justify-content:center} .quick{padding:8px 12px;background:#17a2b8;color:white;border-radius:6px;cursor:pointer;font-size:13px;transition:all 0.3s ease;border:none;min-height:36px} .quick:hover{background:#138496;transform:translateY(-1px)} #message{margin:15px 0;padding:12px;background:#d1ecf1;color:#0c5460;border-radius:8px;display:none;border-left:4px solid #17a2b8} .grid{display:grid;gap:15px} @media(min-width:768px){ .container{padding:30px;max-width:900px} h1{font-size:28px} .grid{grid-template-columns:1fr 1fr} .grid .section:first-child{grid-column:1/-1} .input-group{flex-wrap:nowrap} .input-group input,.input-group select{flex:1} .quick-actions{justify-content:flex-start} .button{width:auto;min-width:120px} } @media(max-width:767px){ .container{padding:15px;margin:5px} h1{font-size:20px} .input-group{flex-direction:column} .input-group input,.input-group select{width:100%;margin:3px 0} .button{width:100%;margin:8px 0} .quick{flex:1;text-align:center;margin:3px} .task-item{flex-direction:column;align-items:flex-start;gap:8px} .task-item button{align-self:flex-end} } @media(max-width:480px){ body{padding:5px} .container{padding:12px;border-radius:8px} h1{font-size:18px;margin-bottom:15px} h3{font-size:14px} .status{font-size:14px;padding:10px} .button{font-size:14px;padding:10px 15px;min-height:44px} .info{font-size:12px} } </style> </head> <body> <div class="container"> <h1>💻 电脑远程电源控制</h1>
<!-- 状态信息区域 --> <div id="computerStatus" class="status offline">🔍 状态: 获取中...</div> <div id="wifiStatus" class="info">📶 WiFi: 检测中...</div> <div id="failSafeStatus" class="info" style="display:none;">⚠️ 故障安全模式</div> <div class="info" id="pingInfo">正在检测网络连接...</div> <div class="info" id="nowTime"></div>
<!-- 快速操作 --> <div class="quick-actions"> <button class="quick" onclick="quickShutdown()">⏰ 5分钟后关机</button> <button class="quick" onclick="quickRestart()">🔄 重启电脑</button> <button class="quick" onclick="quickStartup()">🌅 明早8点开机</button> <button class="quick" onclick="triggerFailSafe()" style="background:#ffc107;color:#000;">⚠️ 故障安全开机</button> </div>
<div id="message"></div>
<!-- 网格布局开始 --> <div class="grid"> <!-- 即时控制 --> <div class="section"> <h3>⚡ 即时控制</h3> <button class="button" id="powerButton" onclick="togglePower()">🔄 开/关机</button> </div>
<!-- 定时指令 --> <div class="section"> <h3>⏰ 定时指令</h3> <div class="input-group"> <input type="datetime-local" id="scheduledTime" title="选择具体时间"> <select id="scheduleOp" title="选择操作类型"> <option value="on">🟢 开机</option> <option value="off">🔴 关机</option> </select> </div> <button class="button" onclick="setSchedule()">📅 设置定时任务</button> </div>
<!-- 倒计时指令 --> <div class="section"> <h3>⏱️ 倒计时指令</h3> <div class="input-group"> <input type="number" id="countdownValue" placeholder="输入数值" min="1" max="3600" value="5" title="输入时间数值"> <select id="countdownUnit" title="选择时间单位"> <option value="s">秒</option> <option value="m" selected>分钟</option> <option value="h">小时</option> </select> <select id="countdownOp" title="选择操作类型"> <option value="on">🟢 开机</option> <option value="off">🔴 关机</option> </select> </div> <button class="button" onclick="setCountdown()">⏱️ 设置倒计时</button> </div> </div> <!-- 网格布局结束 -->
<!-- 任务管理 --> <div class="section"> <h3>📋 待执行任务</h3> <div id="pendingTasks"> <div style="text-align:center;color:#6c757d;padding:20px;"> <div style="font-size:48px;margin-bottom:10px;">📝</div> <div>暂无待执行任务</div> </div> </div> </div> </div>
<script> // 页面加载完成后初始化 document.addEventListener('DOMContentLoaded', function() { // 设置默认时间为当前时间+1小时 const now = new Date(); now.setHours(now.getHours() + 1); now.setMinutes(0); document.getElementById('scheduledTime').value = now.toISOString().slice(0, 16);
// 监听倒计时单位变化,动态更新输入框限制 document.getElementById('countdownUnit').addEventListener('change', function() { updateCountdownLimits(); });
// 初始化倒计时限制 updateCountdownLimits();
fetchStatus(); setInterval(fetchStatus, 3000); });
// 更新倒计时输入框的限制和提示 function updateCountdownLimits() { const unit = document.getElementById('countdownUnit').value; const input = document.getElementById('countdownValue');
switch(unit) { case 's': input.max = 3600; input.placeholder = '输入秒数(1-3600)'; input.title = '1-3600秒之间'; break; case 'm': input.max = 1440; input.placeholder = '输入分钟数(1-1440)'; input.title = '1-1440分钟之间'; break; case 'h': input.max = 24; input.placeholder = '输入小时数(1-24)'; input.title = '1-24小时之间'; break; }
// 如果当前值超过新的最大值,重置为默认值 const currentValue = parseInt(input.value) || 0; if (currentValue > parseInt(input.max)) { input.value = unit === 'h' ? 1 : 5; } }
function fetchStatus() { fetch('/status') .then(response => response.json()) .then(data => { const statusDiv = document.getElementById('computerStatus'); const powerButton = document.getElementById('powerButton'); const wifiStatusDiv = document.getElementById('wifiStatus'); const failSafeStatusDiv = document.getElementById('failSafeStatus');
// 更新电脑状态 if(data.online) { statusDiv.innerHTML = '🟢 状态: 电脑在线'; statusDiv.className = 'status online'; powerButton.innerHTML = '🔴 关机'; powerButton.className = 'button off'; } else { statusDiv.innerHTML = '🔴 状态: 电脑离线'; statusDiv.className = 'status offline'; powerButton.innerHTML = '🟢 开机'; powerButton.className = 'button on'; }
// 更新WiFi状态 if(data.wifiConnected) { const rssi = data.wifiRSSI; const signalStrength = rssi > -50 ? '强' : rssi > -70 ? '中' : '弱'; wifiStatusDiv.innerHTML = `📶 WiFi: 已连接 (信号${signalStrength}: ${rssi}dBm)`; wifiStatusDiv.style.color = '#28a745'; } else { wifiStatusDiv.innerHTML = '📶 WiFi: 断开连接'; wifiStatusDiv.style.color = '#dc3545'; }
// 更新故障安全模式状态 if(data.failSafeMode) { const lastKnownStatusText = data.statusValidBeforeFailure ? (data.lastKnownStatus ? '在线' : '离线') : '未知'; failSafeStatusDiv.innerHTML = `⚠️ 故障安全模式: 已激活 (故障前状态: ${lastKnownStatusText})`; failSafeStatusDiv.style.display = 'block'; failSafeStatusDiv.style.color = '#ffc107'; failSafeStatusDiv.style.fontWeight = 'bold'; } else if(data.networkFailureTime > 0) { const countdown = data.failSafeCountdown; const lastKnownStatusText = data.statusValidBeforeFailure ? (data.lastKnownStatus ? '在线' : '离线') : '未知'; failSafeStatusDiv.innerHTML = `⏳ 网络故障: ${Math.floor(countdown/60)}分${countdown%60}秒后进入故障安全模式<br><small>故障前状态: ${lastKnownStatusText}</small>`; failSafeStatusDiv.style.display = 'block'; failSafeStatusDiv.style.color = '#fd7e14'; } else { failSafeStatusDiv.style.display = 'none'; }
const lastCheck = data.lastCheck.substr(11,8); const pingTime = data.pingTime > 0 ? data.pingTime + 'ms' : '无法检测'; document.getElementById('pingInfo').innerHTML = `🌐 最后检测: ${lastCheck} | 延迟: ${pingTime}`; document.getElementById('nowTime').innerHTML = `🕐 当前时间: ${data.now.substr(11,8)}`;
updateTasks(data.pendingTasks); }) .catch(error => { showMessage('❌ 网络连接失败,请检查设备连接', 'error'); document.getElementById('computerStatus').innerHTML = '❓ 状态: 连接失败'; document.getElementById('computerStatus').className = 'status offline'; document.getElementById('wifiStatus').innerHTML = '📶 WiFi: 无法连接到设备'; document.getElementById('wifiStatus').style.color = '#dc3545'; }); }
function updateTasks(tasks) { const div = document.getElementById('pendingTasks'); if (tasks && tasks.length > 0) { div.innerHTML = tasks.map((task, i) => `<div class="task-item"> <span><strong>${task.type}</strong><br><small>${task.time}</small></span> <button onclick="cancelTask(${i})" title="取消任务">❌ 取消</button> </div>` ).join(''); } else { div.innerHTML = ` <div style="text-align:center;color:#6c757d;padding:20px;"> <div style="font-size:48px;margin-bottom:10px;">📝</div> <div>暂无待执行任务</div> <small>设置定时或倒计时任务后会在这里显示</small> </div>`; } }
function cancelTask(index) { if(confirm('确定要取消这个任务吗?')) { fetch(`/cancelTask?index=${index}`) .then(() => { showMessage('✅ 任务已取消', 'success'); fetchStatus(); }) .catch(() => showMessage('❌ 取消失败', 'error')); } } function togglePower() { const button = document.getElementById('powerButton'); button.disabled = true; button.innerHTML = '⏳ 执行中...';
sendCommand('/trigger', '⚡ 正在发送电源信号...', () => { button.disabled = false; setTimeout(fetchStatus, 1000); // 1秒后刷新状态 }); }
function setSchedule() { const time = document.getElementById('scheduledTime').value; const op = document.getElementById('scheduleOp').value;
if (!time) { showMessage('⚠️ 请选择具体的时间', 'warning'); return; }
const selectedTime = new Date(time); const now = new Date();
if (selectedTime <= now) { showMessage('⚠️ 请选择未来的时间', 'warning'); return; }
const opText = op === 'on' ? '开机' : '关机'; const timeText = selectedTime.toLocaleString('zh-CN');
if(confirm(`确定要在 ${timeText} 执行${opText}操作吗?`)) { sendCommand(`/schedule?time=${encodeURIComponent(time)}&op=${op}`, `📅 正在设置定时${opText}任务...`); } }
function setCountdown() { const value = parseInt(document.getElementById('countdownValue').value) || 0; const unit = document.getElementById('countdownUnit').value; const op = document.getElementById('countdownOp').value;
// 根据单位设置不同的最大值限制 let maxValue, unitText; switch(unit) { case 's': maxValue = 3600; // 最大3600秒(1小时) unitText = '秒'; break; case 'm': maxValue = 1440; // 最大1440分钟(24小时) unitText = '分钟'; break; case 'h': maxValue = 24; // 最大24小时 unitText = '小时'; break; default: maxValue = 1440; unitText = '分钟'; }
if (value <= 0 || value > maxValue) { showMessage(`⚠️ 请输入1-${maxValue}${unitText}之间的数值`, 'warning'); return; }
const opText = op === 'on' ? '开机' : '关机';
if(confirm(`确定要在${value}${unitText}后执行${opText}操作吗?`)) { sendCommand(`/countdown?unit=${unit}&value=${value}&op=${op}`, `⏱️ 正在设置${value}${unitText}后${opText}...`); } }
function quickShutdown() { if(confirm('确定要在5分钟后关机吗?')) { // 同时更新界面上的倒计时设置 document.getElementById('countdownValue').value = 5; document.getElementById('countdownUnit').value = 'm'; document.getElementById('countdownOp').value = 'off'; sendCommand('/countdown?unit=m&value=5&op=off', '⏰ 设置5分钟后关机...'); } }
function quickRestart() { if(confirm('确定要重启电脑吗?\n\n重启过程:\n1. 立即关机\n2. 检测电脑状态变化\n3. 检测到关机后自动开机')) { sendCommand('/restart', '🔄 正在重启电脑,检测状态变化中...'); } }
function quickStartup() { const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); tomorrow.setHours(8, 0, 0, 0); const timeStr = tomorrow.toISOString().slice(0, 16);
if(confirm('确定要设置明天早上8点开机吗?')) { sendCommand(`/schedule?time=${encodeURIComponent(timeStr)}&op=on`, '🌅 设置明早8点开机...'); } }
function triggerFailSafe() { if(confirm('确定要手动触发故障安全模式吗?\n\n这将立即发送开机信号,确保电脑处于开机状态。\n通常在网络故障时使用此功能。')) { sendCommand('/failsafe', '⚠️ 正在激活故障安全模式...'); } }
function sendCommand(url, message, callback) { showMessage(message, 'info');
fetch(url) .then(response => response.text()) .then(data => { showMessage('✅ ' + data, 'success'); setTimeout(() => { fetchStatus(); if(callback) callback(); }, 1000); }) .catch(error => { showMessage('❌ 操作失败: ' + error, 'error'); if(callback) callback(); }); }
function showMessage(text, type = 'info') { const msg = document.getElementById('message'); msg.style.display = 'block'; msg.textContent = text;
// 根据消息类型设置样式 msg.style.backgroundColor = type === 'success' ? '#d4edda' : type === 'error' ? '#f8d7da' : type === 'warning' ? '#fff3cd' : '#d1ecf1'; msg.style.color = type === 'success' ? '#155724' : type === 'error' ? '#721c24' : type === 'warning' ? '#856404' : '#0c5460'; msg.style.borderLeftColor = type === 'success' ? '#28a745' : type === 'error' ? '#dc3545' : type === 'warning' ? '#ffc107' : '#17a2b8';
// 自动隐藏消息 setTimeout(() => { msg.style.display = 'none'; }, type === 'error' ? 4000 : 3000); }
// 添加键盘快捷键支持(仅电脑端) document.addEventListener('keydown', function(e) { // 检查是否为移动设备 if(window.innerWidth > 768) { if (e.ctrlKey && e.key === 'p') { e.preventDefault(); togglePower(); } if (e.ctrlKey && e.key === 'r') { e.preventDefault(); location.reload(); } } });
// 添加触摸反馈(移动端) if('ontouchstart' in window) { document.addEventListener('touchstart', function(e) { if(e.target.classList.contains('button') || e.target.classList.contains('quick')) { e.target.style.transform = 'scale(0.95)'; } });
document.addEventListener('touchend', function(e) { if(e.target.classList.contains('button') || e.target.classList.contains('quick')) { setTimeout(() => { e.target.style.transform = ''; }, 150); } }); } </script> </body> </html> )====="); server.send(200, "text/html", html); }
void handleTrigger() { if (isRestarting) { server.send(400, "text/plain", "重启过程进行中,请稍候"); return; }
lastUserOperationTime = millis(); Serial.println("用户手动操作电源,记录操作时间");
digitalWrite(ledPin, LOW); digitalWrite(relayPin, LOW); delay(500); digitalWrite(relayPin, HIGH); digitalWrite(ledPin, HIGH);
totalOperations++; String message = computerStatus ? "已发送关机信号" : "已发送开机信号"; server.send(200, "text/plain", message); }
void handleRestart() { if (computerStatus && !isRestarting) { lastUserOperationTime = millis(); Serial.println("用户手动重启电脑,记录操作时间");
isRestarting = true; Serial.println("开始重启过程");
digitalWrite(ledPin, LOW); digitalWrite(relayPin, LOW); delay(500); digitalWrite(relayPin, HIGH); Serial.println("已发送关机信号");
unsigned long startTime = millis(); const unsigned long maxWaitTime = 300000; bool shutdownDetected = false;
while (millis() - startTime < maxWaitTime) { delay(1000);
bool pingResult = Ping.ping(computerIP, 3);
if (pingResult != computerStatus) { computerStatus = pingResult; Serial.print("重启过程中状态改变: "); Serial.println(computerStatus ? "在线" : "离线"); }
if (!computerStatus) { shutdownDetected = true; Serial.println("检测到电脑已关机"); break; }
server.handleClient(); }
if (shutdownDetected) { Serial.println("等待3秒确保完全关机"); delay(3000);
Serial.println("发送开机信号"); digitalWrite(relayPin, LOW); delay(500); digitalWrite(relayPin, HIGH); digitalWrite(ledPin, HIGH);
Serial.println("等待5秒让开机过程开始"); delay(5000);
totalOperations += 2; isRestarting = false; server.send(200, "text/plain", "重启完成:已检测到关机状态并发送开机信号"); Serial.println("重启过程完成"); } else { digitalWrite(ledPin, HIGH); totalOperations += 1; isRestarting = false; server.send(200, "text/plain", "重启超时:已发送关机信号但未检测到状态变化,请手动检查"); Serial.println("重启过程超时"); } } else if (isRestarting) { server.send(400, "text/plain", "重启过程进行中,请稍候"); } else { server.send(400, "text/plain", "电脑当前离线,无法执行重启操作"); } }
String getTimeString() { unsigned long currentMillis = millis(); unsigned long seconds = currentMillis / 1000; unsigned long minutes = seconds / 60; unsigned long hours = minutes / 60; char timeStr[20]; sprintf(timeStr, "%02d:%02d:%02d", hours % 24, minutes % 60, seconds % 60); return String(timeStr); }
String getDateTimeString() { time_t now = time(nullptr); struct tm *tm_info = localtime(&now); char buffer[32]; strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm_info); return String(buffer); }
void handleStatus() { DynamicJsonDocument doc(768); doc["online"] = computerStatus; doc["wifiConnected"] = wifiConnected; doc["localNetworkConnectivity"] = localNetworkConnectivity; doc["targetNetworkConnectivity"] = targetNetworkConnectivity; doc["failSafeMode"] = failSafeMode; doc["lastCheck"] = getDateTimeString(); doc["pingTime"] = wifiConnected ? Ping.averageTime() : -1; doc["now"] = getDateTimeString();
if (networkFailureTime > 0 || failSafeMode) { doc["lastKnownStatus"] = lastKnownComputerStatus; doc["statusValidBeforeFailure"] = statusValidBeforeFailure; }
if (networkFailureTime > 0) { unsigned long failureTime = millis() - networkFailureTime; unsigned long currentTimeout = hasEverPingedSuccessfully ? failSafeTimeout : routerStartupTimeout; doc["networkFailureTime"] = failureTime / 1000; doc["failSafeCountdown"] = max(0L, (long)(currentTimeout - failureTime) / 1000); doc["isRouterStartupPhase"] = isRouterStartupPhase; doc["hasEverPingedSuccessfully"] = hasEverPingedSuccessfully; }
if (lastUserOperationTime > 0) { unsigned long timeSinceOperation = millis() - lastUserOperationTime; if (timeSinceOperation < userOperationGracePeriod) { doc["userOperationGracePeriod"] = (userOperationGracePeriod - timeSinceOperation) / 1000; } }
if (wifiConnected) { doc["wifiRSSI"] = WiFi.RSSI(); }
if (taskCount > 0) { JsonArray arr = doc.createNestedArray("pendingTasks"); for (int i = 0; i < taskCount; i++) { JsonObject t = arr.createNestedObject(); t["type"] = tasks[i].type == TASK_ON ? "开机" : (tasks[i].type == TASK_OFF ? "关机" : "反转"); t["time"] = tasks[i].desc; } }
String response; serializeJson(doc, response); server.send(200, "application/json", response); }
void checkWiFiStatus() { bool currentWiFiStatus = (WiFi.status() == WL_CONNECTED);
if (currentWiFiStatus != wifiConnected) { wifiConnected = currentWiFiStatus; Serial.print("WiFi状态改变: "); Serial.println(wifiConnected ? "已连接" : "断开连接");
if (!wifiConnected) { if (networkFailureTime == 0) { lastKnownComputerStatus = computerStatus; statusValidBeforeFailure = true; networkFailureTime = millis(); continuousFailureStartTime = millis(); Serial.print("网络故障开始计时,保存故障前电脑状态: "); Serial.println(lastKnownComputerStatus ? "在线" : "离线"); } } else { Serial.println("WiFi重新连接,等待网络稳定确认"); } } }
void checkComputerStatus() { if (!wifiConnected) { return; }
bool localGatewayPing = Ping.ping(localGatewayIP.c_str(), 1); bool previousLocalConnectivity = localNetworkConnectivity; localNetworkConnectivity = localGatewayPing;
bool targetGatewayPing = false; bool previousTargetConnectivity = targetNetworkConnectivity; if (localNetworkConnectivity) { targetGatewayPing = Ping.ping(targetNetworkGatewayIP.c_str(), 1); } targetNetworkConnectivity = targetGatewayPing;
lastGatewayPingTime = millis();
if (localGatewayPing != previousLocalConnectivity) { Serial.print("本地网络状态改变: "); Serial.println(localGatewayPing ? "正常" : "故障"); } if (targetGatewayPing != previousTargetConnectivity) { Serial.print("目标网络连通性改变: "); Serial.println(targetGatewayPing ? "正常" : "故障"); }
bool overallNetworkConnectivity = localNetworkConnectivity && targetNetworkConnectivity;
bool computerPingResult = false; if (overallNetworkConnectivity) { computerPingResult = Ping.ping(computerIP, 2); lastSuccessfulPingTime = millis();
if (isRouterStartupPhase) { isRouterStartupPhase = false; hasEverPingedSuccessfully = true; Serial.println("网络连接已建立,退出路由器启动阶段"); }
if (networkFailureTime > 0) { Serial.println("网络已恢复正常,重置故障计时"); networkFailureTime = 0; continuousFailureStartTime = 0; if (failSafeMode) { failSafeMode = false; Serial.println("退出故障安全模式"); } } } else { if (networkFailureTime == 0) { unsigned long currentTime = millis();
if (isRouterStartupPhase && !hasEverPingedSuccessfully && currentTime < routerStartupTimeout) { Serial.print("路由器启动阶段,网络不通但暂不计入故障 (已等待 "); Serial.print(currentTime / 1000); Serial.println(" 秒)"); return; }
lastKnownComputerStatus = computerStatus; statusValidBeforeFailure = true; networkFailureTime = millis(); continuousFailureStartTime = millis(); isRouterStartupPhase = false;
Serial.print("网络故障检测 - 本地网络: "); Serial.print(localNetworkConnectivity ? "正常" : "故障"); Serial.print(", 目标网络: "); Serial.print(targetNetworkConnectivity ? "正常" : "故障"); Serial.print(", 开始故障计时,保存故障前电脑状态: "); Serial.println(lastKnownComputerStatus ? "在线" : "离线"); } }
if (overallNetworkConnectivity) { if (computerPingResult != computerStatus) { computerStatus = computerPingResult; Serial.print("电脑状态改变: "); Serial.println(computerStatus ? "在线" : "离线");
if (computerStatus) { lastComputerOnlineTime = millis(); } } else if (computerStatus) { lastComputerOnlineTime = millis(); } } }
void checkFailSafeMode() { if (networkFailureTime > 0 && !failSafeMode) { unsigned long failureTime = millis() - networkFailureTime; unsigned long currentTimeout = failSafeTimeout;
if (!hasEverPingedSuccessfully) { currentTimeout = routerStartupTimeout; }
if (failureTime >= currentTimeout) { failSafeMode = true; Serial.print("网络故障超时,进入故障安全模式 (故障时长: "); Serial.print(failureTime / 1000); Serial.print("秒, 超时阈值: "); Serial.print(currentTimeout / 1000); Serial.println("秒)");
bool shouldPowerOn = false; String actionReason = "";
if (statusValidBeforeFailure) { switch (failSafePolicy) { case FAILSAFE_ALWAYS_ON: shouldPowerOn = true; actionReason = "策略:总是开机 - 发送开机信号确保电脑可用"; break;
case FAILSAFE_PRESERVE_STATE: shouldPowerOn = lastKnownComputerStatus; actionReason = lastKnownComputerStatus ? "策略:保持状态 - 故障前在线,发送开机信号保持开机" : "策略:保持状态 - 故障前离线,保持关机状态"; break;
case FAILSAFE_SMART: shouldPowerOn = !lastKnownComputerStatus; actionReason = lastKnownComputerStatus ? "策略:智能模式 - 故障前在线,假设仍在线,不执行操作" : "策略:智能模式 - 故障前离线,发送开机信号确保可用"; break; } } else { shouldPowerOn = true; actionReason = "无故障前状态记录,默认发送开机信号(安全策略)"; }
Serial.println(actionReason);
if (shouldPowerOn) { digitalWrite(ledPin, LOW); digitalWrite(relayPin, LOW); delay(500); digitalWrite(relayPin, HIGH); digitalWrite(ledPin, HIGH); totalOperations++; Serial.println("已执行开机操作"); } else { Serial.println("根据策略,不执行任何操作"); } } } }
void addTask(TaskType type, unsigned long delayMillis, String desc) { if (taskCount < MAX_TASKS) { tasks[taskCount].type = type; tasks[taskCount].executeMillis = millis() + delayMillis; tasks[taskCount].desc = desc; taskCount++; } }
void processTasks() { unsigned long now = millis(); for (int i = 0; i < taskCount; ) { if (now >= tasks[i].executeMillis) { if (tasks[i].type == TASK_ON && computerStatus) { } else if (tasks[i].type == TASK_OFF && !computerStatus) { } else { lastUserOperationTime = millis(); Serial.println("定时任务执行,记录操作时间"); digitalWrite(relayPin, LOW); delay(500); digitalWrite(relayPin, HIGH); } for (int j = i; j < taskCount - 1; j++) tasks[j] = tasks[j + 1]; taskCount--; } else { i++; } } }
void handleCountdown() { String unit = server.hasArg("unit") ? server.arg("unit") : "s"; int value = server.hasArg("value") ? server.arg("value").toInt() : 0; String op = server.hasArg("op") ? server.arg("op") : "toggle"; if (value <= 0) { server.send(400, "text/plain", "倒计时时间无效"); return; } unsigned long delayMillis = 0; if (unit == "s") delayMillis = value * 1000UL; else if (unit == "m") delayMillis = value * 60000UL; else if (unit == "h") delayMillis = value * 3600000UL; else { server.send(400, "text/plain", "单位无效"); return; } TaskType type = TASK_TOGGLE; if (op == "on") type = TASK_ON; else if (op == "off") type = TASK_OFF; addTask(type, delayMillis, "倒计时" + String(value) + unit + "后" + op); server.send(200, "text/plain", "倒计时任务已添加"); }
void handleSchedule() { String timeStr = server.arg("time"); String op = server.hasArg("op") ? server.arg("op") : "toggle"; if (timeStr.length() < 16) { server.send(400, "text/plain", "时间格式无效"); return; } int year = timeStr.substring(0,4).toInt(); int month = timeStr.substring(5,7).toInt(); int day = timeStr.substring(8,10).toInt(); int hour = timeStr.substring(11,13).toInt(); int minute = timeStr.substring(14,16).toInt(); time_t now = time(nullptr); struct tm targetTm = {0}; targetTm.tm_year = year - 1900; targetTm.tm_mon = month - 1; targetTm.tm_mday = day; targetTm.tm_hour = hour; targetTm.tm_min = minute; targetTm.tm_sec = 0; time_t target = mktime(&targetTm); unsigned long delayMillis = 0; if (target > now) { delayMillis = (unsigned long)(target - now) * 1000UL; } else { server.send(400, "text/plain", "定时时间已过"); return; } TaskType type = TASK_TOGGLE; if (op == "on") type = TASK_ON; else if (op == "off") type = TASK_OFF; addTask(type, delayMillis, "定时" + timeStr + op); server.send(200, "text/plain", "定时任务已添加"); }
void setup() { Serial.begin(115200);
pinMode(relayPin, OUTPUT); pinMode(ledPin, OUTPUT); digitalWrite(relayPin, HIGH); digitalWrite(ledPin, HIGH);
systemStartTime = millis();
lastKnownComputerStatus = false; statusValidBeforeFailure = false; WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.print("连接WiFi");
int wifiAttempts = 0; while (WiFi.status() != WL_CONNECTED && wifiAttempts < 60) { delay(500); Serial.print("."); wifiAttempts++; }
if (WiFi.status() == WL_CONNECTED) { wifiConnected = true; Serial.println("\nWiFi已连接"); Serial.print("本机IP地址: "); Serial.println(WiFi.localIP()); Serial.print("子网掩码: "); Serial.println(WiFi.subnetMask()); Serial.print("网关地址: "); Serial.println(WiFi.gatewayIP()); Serial.print("DNS服务器: "); Serial.println(WiFi.dnsIP());
localGatewayIP = WiFi.gatewayIP().toString(); Serial.print("本地网关IP (ESP8266直连): "); Serial.println(localGatewayIP); Serial.print("目标网关IP (电脑网络): "); Serial.println(targetNetworkGatewayIP); Serial.println("将使用分层网络检测:本地网关 + 目标网关"); } else { wifiConnected = false; networkFailureTime = millis(); Serial.println("\nWiFi连接失败,启动AP模式");
WiFi.mode(WIFI_AP_STA); WiFi.softAP("ESP8266-PowerControl", "12345678"); Serial.print("AP模式已启动,IP地址: "); Serial.println(WiFi.softAPIP()); Serial.println("可以连接WiFi: ESP8266-PowerControl, 密码: 12345678"); }
if (wifiConnected) { configTime(8 * 3600, 0, "ntp.aliyun.com", "ntp1.aliyun.com", "pool.ntp.org"); Serial.print("等待NTP时间同步"); time_t now = time(nullptr); int ntpAttempts = 0; while (now < 8 * 3600 * 2 && ntpAttempts < 20) { delay(500); Serial.print("."); now = time(nullptr); ntpAttempts++; } if (now >= 8 * 3600 * 2) { Serial.println(""); Serial.print("当前时间: "); Serial.println(ctime(&now)); } else { Serial.println("\nNTP时间同步超时,使用系统时间"); } } else { Serial.println("WiFi未连接,跳过NTP时间同步"); } server.on("/", handleRoot); server.on("/trigger", handleTrigger); server.on("/restart", handleRestart); server.on("/status", handleStatus); server.on("/countdown", handleCountdown); server.on("/schedule", handleSchedule); server.on("/failsafe", []() { if (!failSafeMode) { failSafeMode = true; Serial.println("手动激活故障安全模式");
bool shouldPowerOn = true; String statusMessage = "";
if (wifiConnected) { if (computerStatus) { statusMessage = "故障安全模式已激活,电脑当前在线,发送开机信号确保保持开机"; } else { statusMessage = "故障安全模式已激活,电脑当前离线,发送开机信号"; } } else { if (statusValidBeforeFailure) { if (lastKnownComputerStatus) { statusMessage = "故障安全模式已激活,故障前电脑在线,发送开机信号确保保持开机"; } else { shouldPowerOn = false; statusMessage = "故障安全模式已激活,故障前电脑离线,保持关机状态"; } } else { statusMessage = "故障安全模式已激活,无故障前状态记录,默认发送开机信号"; } }
if (shouldPowerOn) { digitalWrite(ledPin, LOW); digitalWrite(relayPin, LOW); delay(500); digitalWrite(relayPin, HIGH); digitalWrite(ledPin, HIGH); totalOperations++; }
server.send(200, "text/plain", statusMessage); } else { server.send(200, "text/plain", "故障安全模式已经激活"); } }); server.on("/cancelTask", []() { if (server.hasArg("index")) { int idx = server.arg("index").toInt(); if (idx >= 0 && idx < taskCount) { for (int j = idx; j < taskCount - 1; j++) tasks[j] = tasks[j + 1]; taskCount--; server.send(200, "text/plain", "任务已取消"); return; } } server.send(400, "text/plain", "参数错误"); }); server.begin(); Serial.println("服务器已启动");
if (wifiConnected) { Serial.println("开始初始网络检测..."); checkComputerStatus();
if (networkFailureTime > 0) { Serial.println("检测到网络连接问题:WiFi已连接但无法ping通目标设备"); Serial.println("可能原因:路由器未连接互联网、目标设备离线、或网络配置问题"); Serial.println("将在5分钟后进入故障安全模式"); } }
Serial.println("=== 初始化完成 ==="); Serial.print("运行模式: "); if (wifiConnected) { if (networkFailureTime > 0) { Serial.println("网络故障模式 (WiFi已连接但网络不通)"); } else { Serial.println("正常模式 (WiFi已连接,网络正常)"); } } else { Serial.println("故障安全模式 (WiFi未连接,AP模式已启动)"); } Serial.println("开始主循环..."); }
void loop() { server.handleClient();
if (isRestarting) { return; }
unsigned long currentMillis = millis();
if (currentMillis - lastWiFiCheck >= wifiCheckInterval) { lastWiFiCheck = currentMillis; checkWiFiStatus();
if (!wifiConnected) { Serial.println("尝试重连WiFi..."); WiFi.reconnect(); } }
if (currentMillis - lastPingTime >= pingInterval) { lastPingTime = currentMillis; checkComputerStatus();
static unsigned long lastDebugOutput = 0; if (currentMillis - lastDebugOutput >= 60000) { lastDebugOutput = currentMillis; Serial.print("故障检测状态 - WiFi: "); Serial.print(wifiConnected ? "连接" : "断开"); Serial.print(", 本地网络: "); Serial.print(localNetworkConnectivity ? "正常" : "故障"); Serial.print(", 目标网络: "); Serial.print(targetNetworkConnectivity ? "正常" : "故障"); Serial.print(", 电脑: "); Serial.print(computerStatus ? "在线" : "离线"); Serial.print(", 网络阶段: "); if (isRouterStartupPhase) { Serial.print("路由器启动"); } else if (hasEverPingedSuccessfully) { Serial.print("正常运行"); } else { Serial.print("连接问题"); } Serial.print(", 故障计时: "); if (networkFailureTime > 0) { unsigned long failureTime = (currentMillis - networkFailureTime) / 1000; unsigned long timeoutThreshold = (hasEverPingedSuccessfully ? failSafeTimeout : routerStartupTimeout) / 1000; Serial.print(failureTime); Serial.print("/"); Serial.print(timeoutThreshold); Serial.print("秒"); } else { Serial.print("无"); } Serial.print(", 故障安全模式: "); Serial.print(failSafeMode ? "激活" : "未激活");
if (lastUserOperationTime > 0) { unsigned long timeSinceOperation = (currentMillis - lastUserOperationTime) / 1000; if (timeSinceOperation < userOperationGracePeriod / 1000) { Serial.print(", 用户操作宽限期: "); Serial.print((userOperationGracePeriod / 1000) - timeSinceOperation); Serial.print("秒"); } } Serial.println(); } }
checkFailSafeMode();
updateLEDStatus();
processTasks(); }
void updateLEDStatus() { static unsigned long lastLEDUpdate = 0; static bool ledState = false; static int lastLEDMode = -1; unsigned long currentMillis = millis();
int currentLEDMode = 0;
if (failSafeMode) { currentLEDMode = 3; } else if (!wifiConnected) { currentLEDMode = 2; } else if (computerStatus) { currentLEDMode = 0; } else { currentLEDMode = 1; }
unsigned long interval = 1000; if (currentLEDMode == 3) interval = 200; else if (currentLEDMode == 2) interval = 500; else if (currentLEDMode == 1) interval = 1000;
if (currentMillis - lastLEDUpdate >= interval) { lastLEDUpdate = currentMillis;
if (currentLEDMode == 0) { if (lastLEDMode != 0) { digitalWrite(ledPin, HIGH); } } else { ledState = !ledState; digitalWrite(ledPin, ledState ? LOW : HIGH); }
lastLEDMode = currentLEDMode; } }
|