forked from ck9393/fanctrlplus
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfanctrlplus.page
More file actions
1932 lines (1672 loc) · 74.2 KB
/
Copy pathfanctrlplus.page
File metadata and controls
1932 lines (1672 loc) · 74.2 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
Menu="Utilities"
Title="FanCtrl Plus"
Icon="fanctrlplus.png"
---
<?php
echo <<<HTML
<link rel="stylesheet" href="/plugins/fanctrlplus/fonts/style.css">
<link rel="stylesheet" type="text/css" href="/webGui/styles/jquery.switchbutton.css">
<link rel="stylesheet" href="/plugins/fanctrlplus/css/sweetalert2.min.css">
<link rel="stylesheet" href="/plugins/fanctrlplus/css/fcp.base.css?v=1.3.1a">
<script src="/plugins/fanctrlplus/js/sweetalert2.min.js"></script>
<script src="/plugins/fanctrlplus/js/chart.min.js"></script>
<script src="/plugins/fanctrlplus/include/chart-handler.js"></script>
HTML;
?>
<script>
window.addEventListener('DOMContentLoaded', () => {
const titleDiv = document.querySelector('div.title > span.left');
if (titleDiv) {
titleDiv.innerHTML = `
<i class="icon-fanctrlplus" style="font-size:20px; vertical-align:middle;"></i>
<span style="margin-left:8px; vertical-align:middle;">FanCtrl Plus Configuration</span>`;
}
});
</script>
<?PHP
$plugin = "fanctrlplus";
$cfg_dir = "/boot/config/plugins/$plugin";
// 包含公用函数
require_once "$docroot/plugins/$plugin/include/Common.php";
require_once "$docroot/plugins/$plugin/include/FanBlockRender.php";
// 初始化配置目录
if (!is_dir($cfg_dir)) {
mkdir($cfg_dir, 0777, true);
}
// === 第一步:读取所有 fanctrlplus_*.cfg 文件 ===
$cfg_files = glob("$cfg_dir/{$plugin}_*.cfg");
if (empty($cfg_files)) {
$temp_file = "$cfg_dir/{$plugin}_temp_0.cfg";
if (!file_exists($temp_file)) {
file_put_contents($temp_file, <<<INI
custom=""
service="1"
controller=""
pwm="102"
max="255"
low="40"
high="60"
interval="2"
disks=""
syslog="1"
cpu_enable="0"
cpu_sensor=""
cpu_min_temp=""
cpu_max_temp=""
INI
);
}
// 重新加载 cfg_files
$cfg_files = glob("$cfg_dir/{$plugin}_*.cfg");
}
// === 第二步:从 order.cfg 读取左右栏顺序 ===
$order_left = [];
$order_right = [];
$order_file = "$cfg_dir/order.cfg";
if (is_file($order_file)) {
$ini = parse_ini_file($order_file);
foreach ($ini as $k => $v) {
if (strpos($k, 'left') === 0) $order_left[] = $v;
if (strpos($k, 'right') === 0) $order_right[] = $v;
}
}
// === 第三步:已出现在 order.cfg 的 cfg 列表,避免重复加载 ===
$seen = array_flip(array_merge($order_left, $order_right));
// === 第四步:准备 fan block 渲染数组(含左右栏 + 其他)===
$fan_column_left = [];
$fan_column_right = [];
$all_cfg = [];
// 左栏渲染
foreach ($order_left as $file) {
$path = "$cfg_dir/$file";
if (is_file($path)) {
$cfg = parse_ini_file($path);
$cfg['file'] = $file;
$fan_column_left[] = $cfg;
$all_cfg[] = $cfg;
}
}
// 右栏渲染
foreach ($order_right as $file) {
$path = "$cfg_dir/$file";
if (is_file($path)) {
$cfg = parse_ini_file($path);
$cfg['file'] = $file;
$fan_column_right[] = $cfg;
$all_cfg[] = $cfg;
}
}
// === 第五步:加载未在 order.cfg 出现的正式 cfg(默认塞入右栏)===
foreach ($cfg_files as $path) {
$basename = basename($path);
if (!isset($seen[$basename]) && strpos($basename, '_temp_') === false) {
$cfg = parse_ini_file($path);
$cfg['file'] = $basename;
$fan_column_right[] = $cfg;
$all_cfg[] = $cfg;
}
}
// === 第六步:加载所有 temp_x.cfg,默认加入右栏 ===
foreach ($cfg_files as $path) {
$basename = basename($path);
if (strpos($basename, '_temp_') !== false) {
$cfg = parse_ini_file($path);
$cfg['file'] = $basename;
$fan_column_right[] = $cfg;
$all_cfg[] = $cfg;
}
}
$pwms = list_pwm();
$disks = list_valid_disks_by_id();
$width = 300;
$cpu_sensors = detect_cpu_sensors();
$aux_sensors = detect_aux_sensors();
// === 读取 FCP Airflow 开关 ===
function fcp_airflow_enabled(string $cfg_dir): bool {
$labels_file = $cfg_dir.'/pwm_labels.cfg';
if (!is_file($labels_file)) return false;
foreach (file($labels_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $ln) {
$ln = trim($ln);
if ($ln === '' || $ln[0] === '#') continue;
if (preg_match('/^__FCP_AIRFLOW__\s*=\s*([01])\s*$/', $ln, $m)) {
return $m[1] === '1';
}
}
return false;
}
$fcp_airflow_enabled = fcp_airflow_enabled($cfg_dir);
?>
<div class="fanctrl-header">
<div class="fanctrl-indicator-container" id="fanctrl-indicator" title="Fan control status">
<span class="fanctrl-label">Running</span>
<div class="fanctrl-dot"></div>
<div class="fanctrl-dot"></div>
<div class="fanctrl-dot"></div>
</div>
<b id="fanctrlplus-sort-toggle"
class="system icon-u-lock green-text fanctrl-sort-toggle"
title="Unlock to rearrange fans"></b>
</div>
<script>
const DEBUG = false; // ✅ 设置是否开启调试输出
const themeClass = document.documentElement.className;
let cssFile = '/plugins/fanctrlplus/css/fanctrlplus-swal2.css';
if (themeClass.includes('Theme--black') || themeClass.includes('Theme--gray')) {
cssFile = '/plugins/fanctrlplus/css/fanctrlplus-swal2-dark.css';
}
const link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = cssFile;
document.head.appendChild(link);
function updatePwmDropdowns() {
// 统计所有已选PWM(不为空)
const selected = [];
$('.pwm-controller').each(function() {
const val = $(this).val();
if (val) selected.push(val);
});
// 逐个select处理option
$('.pwm-controller').each(function() {
const self = $(this);
const ownVal = self.val();
self.find('option').each(function() {
const optVal = $(this).val();
if (optVal === ownVal || !selected.includes(optVal)) {
$(this).prop('disabled', false);
} else {
$(this).prop('disabled', true);
}
});
});
}
const dropdownChecklistOptions = {
emptyText: '(None)',
width: 300,
explicitClose: '...close',
textFormatFunction: function (options) {
const selected = options.filter(':selected');
const count = selected.length;
const tooltip = selected.map(function () {
return $(this).text();
}).get().join('\n') || '(None)';
setTimeout(() => {
options.closest('td').find('.ui-dropdownchecklist-text').attr('title', tooltip);
}, 10);
return count === 0 ? '(None)' : `Selected ${count} Disk${count > 1 ? 's' : ''}`;
}
};
const auxDropdownChecklistOptions = {
emptyText: '(None)',
width: 300,
explicitClose: '...close',
textFormatFunction: function (options) {
const selected = options.filter(':selected');
const count = selected.length;
const tooltip = selected.map(function () {
return $(this).text();
}).get().join('\n') || '(None)';
setTimeout(() => {
options.closest('td').find('.ui-dropdownchecklist-text').attr('title', tooltip);
}, 10);
return count === 0 ? '(None)' : `Selected ${count} Sensor${count > 1 ? 's' : ''}`;
}
};
$(function() {
// 跳动绿点动画
let dotIndex = 0;
const dotEls = document.querySelectorAll('#fanctrl-indicator .fanctrl-dot');
dotEls.forEach(dot => dot.classList.remove('visible'));
dotEls[dotIndex].classList.add('visible');
function animateDots() {
const container = document.getElementById('fanctrl-indicator');
if (!container || container.classList.contains('fanctrl-stopped')) return;
dotEls.forEach(dot => dot.classList.remove('visible'));
dotIndex = (dotIndex + 1) % dotEls.length;
dotEls[dotIndex].classList.add('visible');
}
setInterval(animateDots, 2000);
// 初始化 SVG 风扇转动
$('.fan-block svg[id^="fan-icon-"]').each(function() {
const id = $(this).attr('id');
updateRotorById(id, true);
});
function updateRotorById(fanId, isRunning = true) {
const fanIcon = document.getElementById(fanId);
if (!fanIcon) return;
const rotor = fanIcon.querySelector('.rotor');
if (rotor) rotor.classList.toggle('rotating', isRunning);
const bg = getComputedStyle(document.body).backgroundColor;
const match = bg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
const brightness = match ? (parseInt(match[1]) + parseInt(match[2]) + parseInt(match[3])) / 3 : 255;
const isDark = brightness < 128;
let frameColor, hubColor;
if (isRunning) {
frameColor = isDark ? '#ffffff' : '#000000';
hubColor = isDark ? '#cccccc' : '#666666';
} else {
frameColor = '#cc0000';
hubColor = '#ff6666';
}
const frame = fanIcon.querySelector('.frame');
const hub = fanIcon.querySelector('.hub');
if (!frame || !hub) {
setTimeout(() => updateRotorById(fanId, isRunning), 100);
return;
}
frame.setAttribute('fill', frameColor);
hub.setAttribute('fill', hubColor);
}
window.updateFanControlStatus = function(isRunning = null) {
if (isRunning === null) {
fetch("/plugins/fanctrlplus/include/FanctrlLogic.php?op=status")
.then(res => res.text())
.then(status => updateFanControlStatus(status.trim() === "running"));
return;
}
const container = document.getElementById('fanctrl-indicator');
const label = container.querySelector('.fanctrl-label');
if (isRunning) {
container.classList.remove('fanctrl-stopped');
label.textContent = 'Running';
} else {
container.classList.add('fanctrl-stopped');
label.textContent = 'Inactive';
}
};
function updateStatusLightAndButton() {
$.get('/plugins/fanctrlplus/include/FanctrlLogic.php', {op: 'status'}, function(statusObj) {
const isRunning = statusObj.status === 'running';
updateFanControlStatus(isRunning);
const btn = $('#toggle-daemon');
btn.text(isRunning ? '⏹️ Stop' : '▶️ Start');
btn.attr('title', isRunning ? 'Stop fan control.' : 'Start fan control.');
btn.prop('disabled', false);
}).fail(function(jqXHR, textStatus, errorThrown) {
});
}
function updateAllFanStatus() {
$.get('/plugins/fanctrlplus/include/FanctrlLogic.php', { op: 'status_all' }, function (statusMap) {
$('.fan-block').each(function () {
const block = $(this);
const cfgFile = block.data('file');
if (!cfgFile) return;
const matchedKey = Object.keys(statusMap).find(k => k.toLowerCase() === cfgFile.toLowerCase());
const status = matchedKey ? statusMap[matchedKey] : 'stopped';
const isRunning = status === 'running';
const fanSvg = block.find('svg')[0];
if (!fanSvg) return;
const rotor = fanSvg.querySelector('.rotor');
const frame = fanSvg.querySelector('.frame');
const hub = fanSvg.querySelector('.hub');
if (rotor) rotor.classList.toggle('rotating', isRunning);
const bg = getComputedStyle(document.body).backgroundColor;
const match = bg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
const brightness = match ? (parseInt(match[1]) + parseInt(match[2]) + parseInt(match[3])) / 3 : 255;
const isDark = brightness < 128;
const frameColor = isRunning ? (isDark ? '#ffffff' : '#000000') : '#cc0000';
const hubColor = isRunning ? (isDark ? '#cccccc' : '#666666') : '#ff6666';
if (frame) frame.setAttribute('fill', frameColor);
if (hub) hub.setAttribute('fill', hubColor);
const cpuEnabled = block.find('select[name^="cpu_enable["]').val() === "1";
const auxEnabled = block.find('select[name^="aux_enable["]').val() === "1";
const hasDisks = block.find('select[name^="disks["] option:selected').length > 0;
const container = fanSvg.closest('.fan-svg-container');
if (container) {
const sources = [];
if (cpuEnabled) sources.push("CPU");
if (hasDisks) sources.push("Disk");
if (auxEnabled) sources.push("Aux");
const sourceText = sources.length
? ` (based on ${sources.join(" and ")} temperature)`
: '';
container.title = `Fan control: ${isRunning
? `Active${sourceText}`
: 'Inactive (not automatically controlled)'}`;
}
});
}).fail(function (jqXHR, textStatus, errorThrown) {
ensureAtLeastOneFanBlock();
});
}
updateStatusLightAndButton();
updateAllFanStatus();
setInterval(function() {
updateStatusLightAndButton();
updateAllFanStatus();
}, 30000);
window.toggleDaemon = function() {
const btn = $('#toggle-daemon');
btn.prop('disabled', true);
const action = btn.text().includes('Stop') ? 'stop' : 'start';
$.get('/plugins/fanctrlplus/include/FanctrlLogic.php', {op: action}, function() {
let tries = 0, maxTries = 10;
const check = () => {
$.get('/plugins/fanctrlplus/include/FanctrlLogic.php', {op: 'status'}, function(data) {
const isRunning = data.status === 'running';
const wantRunning = action === 'start';
if (isRunning === wantRunning || tries >= maxTries) {
updateStatusLightAndButton();
updateAllFanStatus();
btn.prop('disabled', false);
} else {
tries++;
setTimeout(check, 500);
}
});
};
check();
}).fail(function(jqXHR, textStatus, errorThrown) {
btn.prop('disabled', false);
});
};
window.identifyFan = function(pwm, mode, btn) {
if (!pwm) {
alert('Please select a PWM controller.');
return;
}
if (!btn) return;
const $btn = $(btn);
const origText = $btn.data('orig') || $btn.text();
$btn.data('orig', origText);
$btn.prop('disabled', true).text("Identifying...");
$.ajax({
url: '/plugins/fanctrlplus/include/FanctrlLogic.php',
method: 'GET',
data: { op: 'identify', pwm: pwm, mode: mode },
timeout: 1000,
success: function() {
let seconds = (mode === 'pulse') ? 40 : 30;
const interval = setInterval(() => {
if (seconds <= 0) {
clearInterval(interval);
$btn.text($btn.data('orig')).prop('disabled', false);
} else {
// 显示不同模式的倒计时提示
let label = mode === 'pause' ? 'Paused'
: mode === 'max' ? 'Max'
: 'Pulse';
$btn.text(`${label} (${seconds}s)`);
seconds--;
}
}, 1000);
},
error: function() {
$btn.text($btn.data('orig')).prop('disabled', false);
}
});
};
window.ensureAtLeastOneFanBlock = function () {
const realBlocks = $('.fan-block').not('.sortable-placeholder, .ui-sortable-placeholder');
if (realBlocks.length === 0) {
addFan();
}
};
window.addFan = function () {
const index = $('.fan-block').length;
$.post('/plugins/fanctrlplus/include/FanctrlLogic.php', { op: 'newtemp', index: index }, function (html) {
const leftCount = $('#fan-column-left .fan-block').length;
const rightCount = $('#fan-column-right .fan-block').length;
const targetColumn = (leftCount <= rightCount) ? '#fan-column-left' : '#fan-column-right';
const $html = $(html);
$(targetColumn).append($html);
initOriginalForBlock($html);
$html.find('.disk-select').dropdownchecklist(dropdownChecklistOptions);
$html.find('.aux-select').dropdownchecklist(auxDropdownChecklistOptions);
updateAllFanStatus();
ensureColumnDroppable();
applySortableState();
updatePwmDropdowns();
bindPWMChangeHandlers();
setTimeout(() => {
updateAllFanStatus();
bindUnitInputs([
{ selector: 'input[id^="pwm_percent_input_"]', unit: '%', min: 0, max: 100 },
{ selector: 'input[id^="max_percent_input_"]', unit: '%', min: 0, max: 100 },
{ selector: `#idle_percent_input_${index}`, unit: '%', min: 0, max: 100 },
{ selector: 'input[id^="low_temp_input_"]', unit: '°C', min: 1, max: 100 },
{ selector: 'input[id^="high_temp_input_"]', unit: '°C', min: 1, max: 100 },
{ selector: 'input[id^="cpu_low_temp_input_"]', unit: '°C', min: 1, max: 95 },
{ selector: 'input[id^="cpu_high_temp_input_"]', unit: '°C', min: 1, max: 110 },
{ selector: 'input[id^="aux_low_temp_input_"]', unit: '°C', min: 1, max: 110 },
{ selector: 'input[id^="aux_high_temp_input_"]', unit: '°C', min: 1, max: 110 },
{ selector: 'input[id^="interval_input_"]', unit: ' min', min: 1, max: 60 }
]);
$html.find('select[id^="cpu-enable-"]').each(function () {
const index = this.id.replace('cpu-enable-', '');
window.handleCpuEnableChange(this, index);
});
$html.find('select[id^="aux-enable-"]').each(function () {
const index = this.id.replace('aux-enable-', '');
window.handleAuxEnableChange(this, index);
});
bindFanSpeedEvents();
bindIdleEvents();
}, 100);
});
};
$('form').on('change keyup', 'input, select, textarea', function() {
$('form').trigger('ui:changed');
});
$('form').on('ui:changed', function() {
$('input[name="#apply"]').prop('disabled', false);
});
function sanitizePercent(str) {
return parseInt(String(str).replace('%', '').replace(/\D/g, '') || '0', 10);
}
// 在更新 PWM 显示时,连带更新 input 的 title 提示
function updateFanSpeedDisplay(i) {
const $minInput = $(`#pwm_percent_input_${i}`);
const $maxInput = $(`#max_percent_input_${i}`);
let rawMin = stripUnit($minInput.val());
let rawMax = stripUnit($maxInput.val());
if (!rawMin && !rawMax) return;
let minVal = parseInt(rawMin || 0);
let maxVal = parseInt(rawMax || 0);
minVal = Math.min(Math.max(minVal, 0), 100);
maxVal = Math.min(Math.max(maxVal, 0), 100);
if (rawMin) $minInput.val(`${minVal}%`);
if (rawMax) $maxInput.val(`${maxVal}%`);
const pwmMin = Math.round(minVal * 255 / 100);
const pwmMax = Math.round(maxVal * 255 / 100);
$(`#pwm_display_min_${i}`).text(rawMin ? `(${pwmMin} PWM)` : '');
$(`#pwm_display_max_${i}`).text(rawMax ? `(${pwmMax} PWM)` : '');
$minInput.attr('title', rawMin ? `Minimum speed: ${minVal}% = ${pwmMin} PWM` : '');
$maxInput.attr('title', rawMax ? `Maximum speed: ${maxVal}% = ${pwmMax} PWM` : '');
}
function bindFanSpeedEvents() {
$('.fan-block').each(function (i) {
$(`#pwm_percent_input_${i}, #max_percent_input_${i}`).off('input');
updateFanSpeedDisplay(i);
$(`#pwm_percent_input_${i}, #max_percent_input_${i}`).on('input', function () {
updateFanSpeedDisplay(i);
updateIdleDisplay(i);
});
});
}
function updateIdleDisplay(i) {
const $idleInput = $(`#idle_percent_input_${i}`);
const $minInput = $(`#pwm_percent_input_${i}`);
const rawIdle = stripUnit($idleInput.val());
if (!rawIdle) {
$idleInput.attr('title', '');
return;
}
let idleVal = Math.min(100, Math.max(0, parseInt(rawIdle, 10)));
// 软夹到 Min(若 Min 有值)
const rawMin = stripUnit($minInput.val());
if (rawMin) {
const minVal = Math.min(100, Math.max(0, parseInt(rawMin, 10)));
if (!Number.isNaN(minVal)) idleVal = Math.min(idleVal, minVal);
}
$idleInput.val(`${idleVal}%`);
const pwmIdle = Math.round(idleVal * 255 / 100);
$idleInput.attr('title', `Idle speed: ${idleVal}% = ${pwmIdle} PWM`);
}
function bindIdleEvents() {
$('input[id^="idle_percent_input_"]').each(function () {
const i = this.id.split('_').pop();
const $idle = $(`#idle_percent_input_${i}`);
$idle.off('input change').on('input change', function () {
updateIdleDisplay(i);
setApplyAllButtonState();
});
updateIdleDisplay(i);
});
}
$(document).ready(bindFanSpeedEvents);
$(document).ready(bindIdleEvents);
$(document).ready(applySortableState);
function bindUnitInputs(unitConfigs) {
unitConfigs.forEach(({ selector, unit, min = 0, max = 100 }) => {
document.querySelectorAll(selector).forEach(input => {
const enforceUnit = () => {
let val = (input.value ?? '').toString().replace(/\D/g, '');
// 如果转换后是空字符串,就不设置单位
if (!val) {
input.value = '';
return;
}
val = Math.min(Math.max(parseInt(val), min), max);
input.value = val + unit;
// 光标移到单位前
const pos = input.value.indexOf(unit);
input.setSelectionRange(pos, pos);
};
input.addEventListener('input', enforceUnit);
input.addEventListener('click', () => {
setTimeout(() => {
const pos = input.value.indexOf(unit);
input.setSelectionRange(pos, pos);
}, 0);
});
enforceUnit(); // 初始执行一次
});
});
}
$(document).ready(function () {
bindUnitInputs([
{ selector: 'input[id^="pwm_percent_input_"]', unit: '%', min: 0, max: 100 },
{ selector: 'input[id^="max_percent_input_"]', unit: '%', min: 0, max: 100 },
{ selector: 'input[id^="idle_percent_input_"]', unit: '%', min: 0, max: 100 },
{ selector: 'input[id^="low_temp_input_"]', unit: '°C', min: 1, max: 100 },
{ selector: 'input[id^="high_temp_input_"]', unit: '°C', min: 1, max: 100 },
{ selector: 'input[id^="cpu_low_temp_input_"]', unit: '°C', min: 1, max: 95 },
{ selector: 'input[id^="cpu_high_temp_input_"]', unit: '°C', min: 1, max: 110 },
{ selector: 'input[id^="aux_low_temp_input_"]', unit: '°C', min: 1, max: 110 },
{ selector: 'input[id^="aux_high_temp_input_"]', unit: '°C', min: 1, max: 110 },
{ selector: 'input[id^="interval_input_"]', unit: ' min', min: 1, max: 60 }
]);
loadPWMOptions();
bindPWMChangeHandlers();
});
function stripUnit(val) {
return (val ?? '').toString().replace(/\s*(min|°C|%)/gi, '').trim();
}
// Identify 弹窗块
function showIdentifyModal(pwm = '') {
const html = `
<div class="fcp-swal-intro">
You’ve selected a PWM controller that hasn’t been labeled yet.<br>
To help identify which physical fan it controls, first choose an <b>Identify Mode</b> (<b>Pause</b>, <b>Max</b>, or <b>Pulse</b>), then click <b>Identify</b> and observe how the fan reacts.
<br><br>
<em>Note:</em> some fans have a built-in minimum RPM; with <b>Pause</b> they may slow to their minimum instead of fully stopping.
<br><br>
If you don’t need to identify it now, just click <b>Close</b> to continue setting up.<br>
This feature is also available anytime in the <b>Identify PWM Controller</b> section below.
</div>
<table>
<tr>
<td class="fcp-td-right">
<label for="identify-modal-select">Select PWM Controller:</label>
</td>
<td>
<select id="identify-modal-select" class="fcp-field-220"></select>
</td>
</tr>
<tr>
<td class="fcp-td-right fcp-pt-12">
<label for="identify-modal-mode-select">Identify Mode:</label>
</td>
<td class="fcp-pt-12">
<select id="identify-modal-mode-select" class="fcp-field-220">
<option value="pause" selected>Pause (30s)</option>
<option value="max">Max Speed (30s)</option>
<option value="pulse">Pulse (40s)</option>
</select>
</td>
</tr>
<tr>
<td class="fcp-td-right fcp-pt-12">
<label for="identify-modal-label-input">Custom Label:</label>
</td>
<td class="fcp-pt-12">
<input type="text" id="identify-modal-label-input" placeholder="Label (e.g. Rear Fan)" class="fcp-field-220">
</td>
</tr>
</table>
<div class="fcp-swal-actions">
<button type="button" class="btn" id="identify-btn">Identify</button>
<button type="button" class="btn" id="save-label-btn">Save Label</button>
<span id="identify-modal-label-tip" class="save-tip"></span>
</div>`;
Swal.fire({
title: 'Identify PWM Controller',
html,
showCancelButton: true,
showConfirmButton: false,
cancelButtonText: 'Close',
customClass: 'wide-swal',
didOpen: () => {
// 焦点陷阱
const dummy = document.createElement('div');
dummy.tabIndex = -1;
dummy.className = 'fcp-focus-trap';
Swal.getPopup().prepend(dummy);
dummy.focus();
// 加载并选中 pwm
if (pwm) {
loadPWMOptions('identify-modal-select', pwm);
} else {
loadPWMOptions('identify-modal-select');
}
// 事件绑定:Identify
$('#identify-btn').off('click').on('click', function () {
const pwmVal = $('#identify-modal-select').val();
const modeVal = $('#identify-modal-mode-select').val();
identifyFan(pwmVal, modeVal, this); // 使用你已实现的 identifyFan()
});
// 事件绑定:保存标签
$('#save-label-btn').off('click').on('click', function () {
savePWMLabel('identify-modal-select', 'identify-modal-label-input', 'identify-modal-label-tip');
});
}
});
}
window.showIdentifyModal = showIdentifyModal;
window.loadPWMOptionsIntoElement = function(selector) {
$.getJSON('/plugins/fanctrlplus/include/FanctrlLogic.php?op=getpwm', function(pwmList) {
const select = $(selector);
if (!select.length) return;
select.empty();
select.append('<option value="">-- Select PWM Controller --</option>');
pwmList.forEach(pwm => {
let display = pwm.chip + ' - ' + pwm.name;
if (pwm.label) {
display += '(' + pwm.label + ')';
}
select.append(`<option value="${pwm.sensor}">${display}</option>`);
});
}).fail(function(jqXHR, textStatus, errorThrown) {
console.error('Failed to load PWM list into ' + selector, textStatus, errorThrown);
});
};
window.loadPWMOptions = function(selectIds = ['pwm-select', 'identify-pwm-select', 'identify-modal-select'], selectedPWM = '') {
if (!Array.isArray(selectIds)) {
selectIds = [selectIds];
}
$.getJSON('/plugins/fanctrlplus/include/FanctrlLogic.php?op=getpwm', function(pwmList) {
selectIds.forEach(selectId => {
const select = $('#' + selectId);
if (!select.length) return;
select.empty();
select.append('<option value="">-- Select PWM Controller --</option>');
pwmList.forEach(pwm => {
let display = pwm.chip + ' - ' + pwm.name;
if (pwm.label) display += `(${pwm.label})`;
// 判断是否选中
const isSelected = (selectedPWM && pwm.sensor === selectedPWM) ? ' selected' : '';
select.append(`<option value="${pwm.sensor}"${isSelected}>${display}</option>`);
});
// 如果传了 selectedPWM 但找不到匹配选项,强制设置
if (selectedPWM && !select.val()) {
select.val(selectedPWM);
}
});
}).fail(function(jqXHR, textStatus, errorThrown) {
console.error('Failed to load PWM list:', textStatus, errorThrown);
});
};
window.savePWMLabel = function(selectId, inputId, tipId) {
const select = $('#' + selectId);
const input = $('#' + inputId);
const tip = $('#' + tipId);
const pwm = select.val();
const label = input.val().trim();
if (!pwm) {
alert('Please select a PWM controller!');
return;
}
$.post('/plugins/fanctrlplus/include/FanctrlLogic.php', {
op: 'savelabel',
pwm: pwm,
label: label
}, function(data) {
if (data && data.status === 'ok') {
input.val('');
tip.css('color', '#4caf50')
.text(label ? 'Label saved!' : 'Label cleared!').show();
setTimeout(() => {
tip.fadeOut(500, function() {
$(this).text('').show();
});
}, 2500);
loadPWMOptions && loadPWMOptions();
refreshAllFanBlockPWMLabels && refreshAllFanBlockPWMLabels();
} else {
tip.css('color', '#f44336').text('Failed to save');
setTimeout(() => {
tip.fadeOut(500, function() {
$(this).css('color', '#4caf50').text('').show();
});
}, 3500);
}
}, 'json').fail(function() {
alert('Error saving label (network or server error)');
});
}
let pwmLabelMap = {};
function updatePWMLabelMap() {
$.getJSON('/plugins/fanctrlplus/include/FanctrlLogic.php?op=getpwm', function(pwmList) {
pwmLabelMap = {};
pwmList.forEach(pwm => {
pwmLabelMap[pwm.sensor] = pwm.label || '';
});
});
}
function bindPWMChangeHandlers() {
$('.pwm-controller').off('change').on('change', function () {
const selectedPWM = $(this).val();
if (!selectedPWM) return;
// 查询当前 PWM 是否有 label
$.getJSON('/plugins/fanctrlplus/include/FanctrlLogic.php?op=getpwm', function (pwmList) {
const match = pwmList.find(pwm => pwm.sensor === selectedPWM);
if (match && !match.label) {
// 如果该 PWM 没有 label,才弹窗
showIdentifyModal(selectedPWM);
}
});
});
}
function refreshAllFanBlockPWMLabels() {
$.getJSON('/plugins/fanctrlplus/include/FanctrlLogic.php?op=getpwm', function(pwmList) {
// 收集所有 fan block 已选中的 PWM
const usedPWMs = [];
$('.pwm-controller').each(function () {
const val = $(this).val();
if (val) usedPWMs.push(val);
});
$('.pwm-controller').each(function () {
const selected = $(this).val();
$(this).empty().append('<option value="">-- Select PWM Controller --</option>');
pwmList.forEach(pwm => {
let display = pwm.chip + ' - ' + pwm.name;
if (pwm.label) display += `(${pwm.label})`;
const isSelected = pwm.sensor === selected;
const isUsed = usedPWMs.includes(pwm.sensor) && !isSelected;
$(this).append(`<option value="${pwm.sensor}" ${isSelected ? 'selected' : ''} ${isUsed ? 'disabled' : ''}>${display}</option>`);
});
});
updatePWMLabelMap();
bindPWMChangeHandlers();
});
}
function initOriginalForBlock($block) {
const original = {
custom: $block.find('input[name^="custom["]').val(),
service: $block.find('select[name^="service["]').val(),
controller: $block.find('select[name^="controller["]').val(),
pwm_percent: stripUnit($block.find('input[name^="pwm_percent["]').val()),
max_percent: stripUnit($block.find('input[name^="max_percent["]').val()),
idle_percent: stripUnit($block.find('input[name^="idle_percent["]').val() || '0'),
low: stripUnit($block.find('input[name^="low["]').val()),
high: stripUnit($block.find('input[name^="high["]').val()),
interval: stripUnit($block.find('input[name^="interval["]').val()),
disks: $block.find('select[name^="disks["]').val(),
cpu_enable: $block.find('select[name^="cpu_enable["]').val(),
cpu_sensor: $block.find('select[name^="cpu_sensor["]').val(),
cpu_min_temp: stripUnit($block.find('input[name^="cpu_min_temp["]').val()),
cpu_max_temp: stripUnit($block.find('input[name^="cpu_max_temp["]').val()),
aux_enable: $block.find('select[name^="aux_enable["]').val(),
aux_sensor: $block.find('select[name^="aux_sensor["]').val(),
aux_min_temp: stripUnit($block.find('input[name^="aux_min_temp["]').val()),
aux_max_temp: stripUnit($block.find('input[name^="aux_max_temp["]').val())
};
$block.data('original', original);
}
function setApplyAllButtonState() {
let dirty = false;
$('.fan-block').each(function () {
const $block = $(this);
const original = $block.data('original');
const current = {
custom: $block.find('input[name^="custom["]').val(),
service: $block.find('select[name^="service["]').val(),
controller: $block.find('select[name^="controller["]').val(),
pwm_percent: stripUnit($block.find('input[name^="pwm_percent["]').val()),
max_percent: stripUnit($block.find('input[name^="max_percent["]').val()),
idle_percent: stripUnit($block.find('input[name^="idle_percent["]').val() || '0'),
low: stripUnit($block.find('input[name^="low["]').val()),
high: stripUnit($block.find('input[name^="high["]').val()),
interval: stripUnit($block.find('input[name^="interval["]').val()),
disks: $block.find('select[name^="disks["]').val(),
cpu_enable: $block.find('select[name^="cpu_enable["]').val(),
cpu_sensor: $block.find('select[name^="cpu_sensor["]').val(),
cpu_min_temp: stripUnit($block.find('input[name^="cpu_min_temp["]').val()),
cpu_max_temp: stripUnit($block.find('input[name^="cpu_max_temp["]').val()),
aux_enable: $block.find('select[name^="aux_enable["]').val(),
aux_sensor: $block.find('select[name^="aux_sensor["]').val(),
aux_min_temp: stripUnit($block.find('input[name^="aux_min_temp["]').val()),
aux_max_temp: stripUnit($block.find('input[name^="aux_max_temp["]').val())
};
if (JSON.stringify(original) !== JSON.stringify(current)) {
dirty = true;
}
});
$('#apply-btn').prop('disabled', !dirty);
}
function ensureColumnDroppable() {
['#fan-column-left', '#fan-column-right'].forEach(function (selector) {
const $col = $(selector);
if (
$col.children('.fan-block:not(.sortable-placeholder)').length === 0 &&
$col.find('.sortable-placeholder').length === 0
) {
$col.append(`<div class="fan-block sortable-placeholder">Drag Fan Configuration Here</div>`);
}
if ($col.children('.fan-block:not(.sortable-placeholder)').length > 0) {
$col.find('.sortable-placeholder').remove();
}
const blockHeight = $('.fan-block:not(.sortable-placeholder):first').outerHeight();
$('.sortable-placeholder').css('min-height', blockHeight + 'px');
});
}
// 全局:默认上锁
let sortableUnlocked = false;
// 锁 = destroy,解锁 = 重新 sortable(opts)
function applySortableState() {
const $cols = $('#fan-column-left, #fan-column-right');
$cols.each(function () {
const inst = $(this).sortable('instance');
if (inst) $(this).sortable('destroy');
});
if (!sortableUnlocked) {
$cols.removeClass('ui-sortable ui-sortable-disabled');
$cols.find('.fan-block').removeClass('ui-sortable-handle');
return;
}
// 解锁:重建实例
const hasHandle = $cols.find('.fcp-drag-handle').length > 0;
const opts = {
items: '> .fan-block:not(.sortable-placeholder)',
tolerance: 'pointer',
placeholder: 'fan-placeholder',
start: function (e, ui) { ui.placeholder.height(ui.item.outerHeight()); },
over: function () { $(this).find('.sortable-placeholder').remove(); },
out: function () {
const $col = $(this);
const hasReal = $col.children('.fan-block:not(.sortable-placeholder)').length > 0;
if (!hasReal && $col.find('.sortable-placeholder').length === 0) {
const h = $('.fan-block:not(.sortable-placeholder):first').outerHeight() || 100;
$('<div class="fan-block sortable-placeholder">Drag Fan Configuration Here</div>')
.css('min-height', h + 'px').appendTo($col);
}
},