chenhaozhe
2026-10-30 d8339cc4a46e87f5d6b0c6ee18084da7c6525bed
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
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
[
    {
        "id": "cee834492540f06e",
        "type": "tab",
        "label": "MSSQL 数据同步",
        "disabled": false,
        "info": "",
        "env": []
    },
    {
        "id": "tab_collector_mqtt",
        "type": "tab",
        "label": "采集器 MQTT 接入",
        "disabled": false,
        "info": "采集器对接:/cmd 指令下发与回执确认。\n\n注意:MQTT 采集与写库已拆分到独立页签「MQTT · 采集入库(独立)」——本页签不再把 signal_msg 转发到主流程,也不再参与写库。"
    },
    {
        "id": "yy_multi_collect",
        "type": "tab",
        "label": "用友 · 多表采集整合",
        "disabled": false,
        "info": "用友多表采集:分表清单缓存5分钟,集合分页查询;保留(time,SourceTable,id)增量水位。字段映射经虚拟链接进入MSSQL数据同步页sync_rows内存缓冲,5秒/最多5000行共用Bulk写入HX_LMESsys.dbo.Sb_EquipMentCollectionTechParam_Temp。只有整批插入/防重跳过全部确认后才提交水位。暂停不清空缓冲,失败原批回填。",
        "env": []
    },
    {
        "id": "tab_mqtt_pipeline",
        "type": "tab",
        "label": "MQTT · 采集入库(独立)",
        "disabled": false,
        "info": "## MQTT · 采集入库(独立)\n\n链路:/report/# → mp_gate_in(启停闸门)→ 解析 → mp_fn_mqtt_ad → mp_fn_buffer → mp_inject_flush(5s) → mp_gate_flush → mp_fn_flush → Bulk 写 dbo.Sb_EquipMentCollectionTechParam_Temp。\n\n**独立启停(测试用)**:点「▶ 启动本页签」= 只影响本页签;「⏸ 停止本页签」= 丢弃新报文、缓冲保留不写库。\n- 本页签开关优先:mqtt_pipeline_paused=false 运行 / true 停止。\n- 本页签开关未动过(undefined)时,回落到总开关 collection_paused(页面上的「暂停/恢复全部采集」)。\n- 重启 Node-RED 后本页签回到「未启动」,需要点一次启动。"
    },
    {
        "id": "d082727f8d89ba41",
        "type": "MSSQL-CN",
        "tdsVersion": "7_4",
        "name": "WuYangSync",
        "server": "192.168.0.62",
        "port": "49855",
        "encyption": false,
        "trustServerCertificate": true,
        "database": "JYPM_wuyang",
        "useUTC": true,
        "connectTimeout": "",
        "requestTimeout": "",
        "cancelTimeout": "",
        "pool": "",
        "parseJSON": false,
        "enableArithAbort": true,
        "readOnlyIntent": false
    },
    {
        "id": "9bb47eb9867c4772",
        "type": "MSSQL-CN",
        "tdsVersion": "7_4",
        "name": "ZyMesSync",
        "server": "192.168.0.62",
        "port": "49855",
        "encyption": false,
        "trustServerCertificate": true,
        "database": "HX_LMESsys",
        "useUTC": true,
        "connectTimeout": "",
        "requestTimeout": "",
        "cancelTimeout": "",
        "pool": "",
        "parseJSON": false,
        "enableArithAbort": true,
        "readOnlyIntent": false
    },
    {
        "id": "04dfbd6bd2067336",
        "type": "MSSQL-CN",
        "tdsVersion": "7_4",
        "name": "yongyouSync",
        "server": "192.168.0.62",
        "port": "49855",
        "encyption": false,
        "trustServerCertificate": true,
        "database": "StandBussDB",
        "useUTC": true,
        "connectTimeout": "",
        "requestTimeout": "",
        "cancelTimeout": "",
        "pool": "",
        "parseJSON": false,
        "enableArithAbort": true,
        "readOnlyIntent": false
    },
    {
        "id": "mqtt_broker_local",
        "type": "mqtt-broker",
        "name": "自有设备 MQTT Broker",
        "broker": "127.0.0.1",
        "port": "1883",
        "clientid": "",
        "autoConnect": true,
        "usetls": false,
        "verifyservercert": true,
        "protocolVersion": "4",
        "keepalive": "60",
        "cleansession": true,
        "autoUnsubscribe": true,
        "birthTopic": "",
        "birthQos": "0",
        "birthRetain": "false",
        "birthPayload": "",
        "birthMsg": {},
        "closeTopic": "",
        "closeQos": "0",
        "closeRetain": "false",
        "closePayload": "",
        "closeMsg": {},
        "willTopic": "",
        "willQos": "0",
        "willRetain": "false",
        "willPayload": "",
        "willMsg": {},
        "userProps": "",
        "sessionExpiry": ""
    },
    {
        "id": "4e0d058caa7afc4e",
        "type": "MSSQL",
        "z": "cee834492540f06e",
        "mssqlCN": "d082727f8d89ba41",
        "name": "五洋 数据库",
        "outField": "payload",
        "returnType": "0",
        "throwErrors": "1",
        "query": "",
        "modeOpt": "",
        "modeOptType": "query",
        "queryOpt": "query",
        "queryOptType": "msg",
        "paramsOpt": "queryParams",
        "paramsOptType": "msg",
        "rows": "rows",
        "rowsType": "msg",
        "parseMustache": false,
        "params": [],
        "x": 620,
        "y": 320,
        "wires": [
            [
                "c53aa63e531b7e6d"
            ]
        ]
    },
    {
        "id": "e20ef8063f6ae7d6",
        "type": "debug",
        "z": "cee834492540f06e",
        "name": "同步 · 标准化结果",
        "active": false,
        "tosidebar": true,
        "console": true,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 1420,
        "y": 420,
        "wires": []
    },
    {
        "id": "c48718bed4c3dfa7",
        "type": "inject",
        "z": "cee834492540f06e",
        "name": "五洋 · 每1s实时快照 → 缓冲",
        "props": [],
        "repeat": "1",
        "crontab": "",
        "once": true,
        "onceDelay": 1,
        "topic": "",
        "x": 160,
        "y": 320,
        "wires": [
            [
                "fn_wy_q"
            ]
        ]
    },
    {
        "id": "c53aa63e531b7e6d",
        "type": "function",
        "z": "cee834492540f06e",
        "name": "五洋 · 标准化为数据库字段",
        "func": "/**\n * 五洋实时快照标准化\n * 输入:msg.payload=BaseMachine记录,msg.wySampleTime=本次采样毫秒\n * 输出:msg.collectionRows=数据库字段数组;payload同数组\n * 上下文:wy_snapshot_stats;wy_poll_inflight\n */\nfunction canonicalParameterName(parameterName) {\n  const aliases = {\n    '转速': '机器转速',\n    '班次平均车速': '班次平均转速',\n    '本班产量': '班次产量(源单位)',\n    '本班效率': '班次效率(%)',\n    '本班停机次数': '班次停机次数',\n    '本班停机时间(秒)': '班次停机时间(秒)',\n    '本匹产量': '本匹产量(源单位)'\n  };\n  const name = String(parameterName);\n  // 用友事件里的本班产量附有实际单位,沿用同一班次产量名称。\n  const withUnit = /^本班产量\\((.+)\\)$/.exec(name);\n  if (withUnit) return '班次产量(' + withUnit[1] + ')';\n  return aliases[name] || name;\n}\nfunction createCollectionRow(source, deviceCode, parameterName, value, collectedAt, createdAt) {\n  const amount = Math.round(Number(value) * 100) / 100;\n  return {\n    HItemID: null,\n    // SQL Server 自增,Bulk 不传此列\n    HDate: new Date(collectedAt),\n    // 采样时间/源设备时间\n    HSourceCode: String(deviceCode).slice(0, 50),\n    HTechParamID: 0,\n    // 沿用现有目标表约定\n    HTechParamName: canonicalParameterName(parameterName).slice(0, 500),\n    HCount: amount,\n    // SQL decimal(18,2)\n    HCreateTime: new Date(createdAt),\n    // 标准化创建时间;重试保持不变\n    HResult: String(amount).slice(0, 50),\n    HProcNumber: String(source).slice(0, 50),\n    // WY / YY / MQTT\n    HFlag: 0\n  };\n}\nfunction normalizeWuyangSnapshot(msg, flow, global, node) {\n  // 每秒全量快照:相同数值也入队,HDate用本次采样时间。\n  flow.set('wy_poll_inflight', false);\n  if (global.get('collection_paused') !== false) {\n    node.status({\n      fill: 'yellow',\n      shape: 'ring',\n      text: '采集已暂停'\n    });\n    return null;\n  }\n  const sourceRows = Array.isArray(msg.payload) ? msg.payload : [];\n  if (!sourceRows.length) {\n    node.status({\n      fill: 'grey',\n      shape: 'ring',\n      text: 'BaseMachine 0台设备'\n    });\n    return null;\n  }\n  const sampleTimestamp = Number(msg.wySampleTime);\n  if (!Number.isFinite(sampleTimestamp)) {\n    node.error('缺少五洋采样时间,拒绝合并到旧时间点', msg);\n    return null;\n  }\n\n  // 字段名称直接使用五洋BaseMachine字典;状态转换为统一数值编码。\n  const stateCodes = {\n    '运行': 1,\n    '待机': 2,\n    '停机': 3,\n    '报警': 4,\n    '离线': 5\n  };\n  const parameterNames = ['机器转速', '生产速度', '累计产量', '订单匹数', '已生产匹数', '当前匹已生产长度'];\n  for (let axisNumber = 1; axisNumber <= 8; axisNumber++) parameterNames.push('经轴送经量' + axisNumber);\n  const collectedAt = new Date(sampleTimestamp);\n  const createdAt = new Date();\n  const collectionRows = [];\n  const sourceTimes = [];\n  let deviceCount = 0;\n  let latestSourceTime = null;\n  for (const sourceRow of sourceRows) {\n    const machineCode = String(sourceRow.MachineNo || sourceRow.BaseMachineID || '').trim();\n    if (!machineCode) continue;\n    const deviceCode = ('WY-' + machineCode).slice(0, 50);\n    const firstRowIndex = collectionRows.length;\n    for (const parameterName of parameterNames) {\n      const rawValue = sourceRow[parameterName];\n      if (rawValue === null || rawValue === undefined || String(rawValue).trim() === '') continue;\n      // 五洋有些varchar值带单位;保留原流程去单位的数值解析规则。\n      const value = parseFloat(String(rawValue).replace(/[^0-9.\\-]/g, ''));\n      if (Number.isFinite(value)) {\n        collectionRows.push(createCollectionRow('WY', deviceCode, parameterName, value, collectedAt, createdAt));\n      }\n    }\n    const stateCode = stateCodes[String(sourceRow['状态'] || '').trim()];\n    if (stateCode !== undefined) {\n      collectionRows.push(createCollectionRow('WY', deviceCode, '运行状态', stateCode, collectedAt, createdAt));\n    }\n    if (collectionRows.length === firstRowIndex) continue;\n    deviceCount += 1;\n    const sourceTime = sourceRow.MachineCollectionTime ? new Date(sourceRow.MachineCollectionTime) : null;\n    if (sourceTime && Number.isFinite(sourceTime.getTime())) {\n      sourceTimes.push({\n        HSourceCode: deviceCode,\n        sourceCollectionTime: sourceTime\n      });\n      if (!latestSourceTime || sourceTime > latestSourceTime) latestSourceTime = sourceTime;\n    }\n  }\n  if (!collectionRows.length) {\n    node.status({\n      fill: 'grey',\n      shape: 'ring',\n      text: '无有效设备参数'\n    });\n    return null;\n  }\n  const previousStats = flow.get('wy_snapshot_stats') || {};\n  const snapshotStats = {\n    polls: (previousStats.polls || 0) + 1,\n    snapshots: (previousStats.snapshots || 0) + deviceCount,\n    parameters: (previousStats.parameters || 0) + collectionRows.length,\n    devices: deviceCount,\n    lastSampleTime: collectedAt.toISOString(),\n    latestSourceTime: latestSourceTime ? latestSourceTime.toISOString() : null\n  };\n  flow.set('wy_snapshot_stats', snapshotStats);\n  delete msg.collect;\n  msg.collectionRows = collectionRows;\n  msg.collectionSourceTimes = sourceTimes; // 审计信息,与目标表列分开保存\n  msg.collectionSummary = {\n    source: 'WY',\n    devices: deviceCount,\n    parameters: collectionRows.length,\n    sampleTime: snapshotStats.lastSampleTime\n  };\n  msg.payload = collectionRows;\n  node.status({\n    fill: 'green',\n    shape: 'dot',\n    text: deviceCount + '台 / ' + collectionRows.length + '项 / 每秒完整快照'\n  });\n  return msg;\n}\nreturn normalizeWuyangSnapshot(msg, flow, global, node);\n",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 860,
        "y": 320,
        "wires": [
            []
        ]
    },
    {
        "id": "fe88ac9fe19141be",
        "type": "MSSQL",
        "z": "cee834492540f06e",
        "mssqlCN": "9bb47eb9867c4772",
        "name": "目标库 · bulk 写缓存临时表",
        "outField": "payload",
        "returnType": "0",
        "throwErrors": "1",
        "query": "dbo.Sb_EquipMentCollectionTechParam_Temp",
        "modeOpt": "bulk",
        "modeOptType": "bulk",
        "queryOpt": "",
        "queryOptType": "editor",
        "paramsOpt": "queryParams",
        "paramsOptType": "msg",
        "rows": "rows",
        "rowsType": "msg",
        "parseMustache": false,
        "params": [],
        "x": 1020,
        "y": 500,
        "wires": [
            [
                "fn_sync_success"
            ]
        ]
    },
    {
        "id": "08c95ee2bd3a9073",
        "type": "function",
        "z": "cee834492540f06e",
        "name": "数据库标准行 → 公共缓冲",
        "func": "/**\n * 统一数据库行入缓冲\n * 输入:msg.collectionRows;用友另带msg.yySync\n * 输出:输出1=入队摘要/数据库字段预览;输出2=用友回执\n * 上下文:sync_rows;sync_yy_batches;sync_yy_completed\n */\nfunction collectionRowKey(row) {\n  // 保留原有自然键编码,兼容旧待确认批次的 doneKeys。\n  return row.HProcNumber + '|' + row.HSourceCode + '|' + row.HTechParamName + '|' + new Date(row.HDate).getTime();\n}\nfunction convertLegacyBufferRow(row, createdAt) {\n  if (row.HDate !== undefined && row.HSourceCode !== undefined) {\n    // 已是新格式:保留既有字段和批次引用,只恢复 Date 类型。\n    return {\n      ...row,\n      HDate: new Date(row.HDate),\n      HCreateTime: row.HCreateTime ? new Date(row.HCreateTime) : new Date(createdAt)\n    };\n  }\n  // 部署兼容:旧 sync_rows 使用 s/d/p/v/t,原批语义及原参数名保持不变。\n  const converted = {\n    HItemID: null,\n    HDate: new Date(row.t),\n    HSourceCode: row.d,\n    HTechParamID: 0,\n    HTechParamName: row.p,\n    HCount: row.v,\n    HCreateTime: new Date(createdAt),\n    HResult: String(row.v).slice(0, 50),\n    HProcNumber: row.s,\n    HFlag: 0\n  };\n  if (row.yyRefs?.length) converted._sync = {\n    yyBatchIds: [...row.yyRefs]\n  };\n  return converted;\n}\nfunction legacyCollectToRows(collect, createdAt) {\n  // 只用于升级前缓存的 pending.write;三路新消息都直接输出 collectionRows。\n  const rows = [];\n  for (const item of collect || []) {\n    const collectedAt = new Date(item.ts);\n    if (!Number.isFinite(collectedAt.getTime())) continue;\n    for (const [parameterName, value] of Object.entries(item.data || {})) {\n      if (value === null || value === undefined || value === '') continue;\n      if (!Number.isFinite(Number(value))) continue;\n      // 已等待确认的旧批不改名,保证与之前已落库部分的防重键一致。\n      rows.push({\n        HItemID: null,\n        HDate: collectedAt,\n        HSourceCode: String(item.device).slice(0, 50),\n        HTechParamID: 0,\n        HTechParamName: parameterName.slice(0, 500),\n        HCount: Math.round(Number(value) * 100) / 100,\n        HCreateTime: new Date(createdAt),\n        HResult: String(Math.round(Number(value) * 100) / 100).slice(0, 50),\n        HProcNumber: item.src,\n        HFlag: 0\n      });\n    }\n  }\n  return rows;\n}\nfunction enqueueCollectionRows(msg, flow, global, node) {\n  const batchMeta = msg.yySync;\n  const isYouyangBatch = Boolean(batchMeta?.batchId && batchMeta?.stream);\n  const makeAck = (kind, details = {}) => ({\n    yySync: batchMeta,\n    yyAck: {\n      kind,\n      ...details\n    },\n    payload: {\n      stream: batchMeta?.stream,\n      ...details\n    }\n  });\n\n  // 1. 暂停只停止新增,不清空原缓冲,也不提交用友水位。\n  if (global.get('collection_paused') !== false) {\n    node.status({\n      fill: 'yellow',\n      shape: 'ring',\n      text: '采集已暂停,缓冲保留'\n    });\n    return isYouyangBatch ? [null, makeAck('deferred', {\n      reason: '采集已暂停'\n    })] : null;\n  }\n  const completedBatches = flow.get('sync_yy_completed') || {};\n  const pendingBatches = flow.get('sync_yy_batches') || {};\n  if (isYouyangBatch && completedBatches[batchMeta.batchId]) {\n    return [null, completedBatches[batchMeta.batchId]];\n  }\n  if (isYouyangBatch && pendingBatches[batchMeta.batchId]) {\n    return [null, makeAck('queued', {\n      expected: pendingBatches[batchMeta.batchId].expected,\n      duplicateRequest: true\n    })];\n  }\n\n  // 2. 三路新输入均为数据库字段对象。collect 仅兼容部署前的待确认消息。\n  const createdAt = new Date();\n  const inputRows = Array.isArray(msg.collectionRows) ? msg.collectionRows : legacyCollectToRows(msg.collect, createdAt);\n  const validRows = [];\n  const uniqueYouyangRows = new Map();\n  for (const input of inputRows) {\n    const row = convertLegacyBufferRow(input, createdAt);\n    const valid = row.HSourceCode && row.HTechParamName && Number.isFinite(row.HDate.getTime()) && Number.isFinite(row.HCreateTime.getTime()) && typeof row.HCount === 'number' && Number.isFinite(row.HCount);\n    if (!valid) {\n      // 不把“格式错误”伪装成写库成功;用友必须保留原批和水位。\n      if (isYouyangBatch) return [null, makeAck('deferred', {\n        reason: '标准行无效,检查数据库字段'\n      })];\n      node.warn('忽略无效采集参数行');\n      continue;\n    }\n    if (isYouyangBatch) {\n      if (row.HProcNumber !== 'YY') return [null, makeAck('deferred', {\n        reason: '用友批次来源必须为YY'\n      })];\n      row._sync = {\n        yyBatchIds: [batchMeta.batchId]\n      }; // 仅用于确认,不是数据库列\n      uniqueYouyangRows.set(collectionRowKey(row), row);\n    } else {\n      validRows.push(row);\n    }\n  }\n  if (isYouyangBatch) validRows.push(...uniqueYouyangRows.values());\n  const bufferRows = flow.get('sync_rows') || [];\n  if (isYouyangBatch && bufferRows.length + validRows.length > 20000) {\n    node.status({\n      fill: 'yellow',\n      shape: 'ring',\n      text: '缓冲积压,用友原批等待'\n    });\n    return [null, makeAck('deferred', {\n      reason: '缓冲达到20000行限流'\n    })];\n  }\n  if (!validRows.length) {\n    return isYouyangBatch ? [null, makeAck('committed', {\n      inserted: 0,\n      skipped: 0,\n      expected: 0\n    })] : null;\n  }\n\n  // 3. 入队回执仅表示已接收。整批写入/跳过完成后,才会发送 committed。\n  if (isYouyangBatch) {\n    pendingBatches[batchMeta.batchId] = {\n      meta: {\n        ...batchMeta,\n        phase: 'buffer'\n      },\n      expected: validRows.length,\n      done: 0,\n      inserted: 0,\n      skipped: 0,\n      doneKeys: {},\n      queuedAt: new Date().toISOString()\n    };\n  }\n  bufferRows.push(...validRows);\n  flow.set('sync_rows', bufferRows);\n  flow.set('sync_yy_batches', pendingBatches);\n  node.status({\n    fill: 'blue',\n    shape: 'dot',\n    text: '+' + validRows.length + ' / 缓冲 ' + bufferRows.length\n  });\n\n  // 调试只预览前3行,便于对照数据库字段,也避免每秒打印大量参数。\n  const preview = validRows.slice(0, 3).map(row => {\n    const {\n      _sync,\n      ...databaseFields\n    } = row;\n    return databaseFields;\n  });\n  const diagnostic = {\n    payload: {\n      source: validRows[0].HProcNumber,\n      buffered: validRows.length,\n      pending: bufferRows.length,\n      records: preview\n    }\n  };\n  const ack = isYouyangBatch ? makeAck('queued', {\n    expected: validRows.length,\n    pending: bufferRows.length\n  }) : null;\n  return [diagnostic, ack];\n}\nreturn enqueueCollectionRows(msg, flow, global, node);\n",
        "outputs": 2,
        "timeout": 0,
        "noerr": 0,
        "initialize": "function convertLegacyBufferRow(row, createdAt) {\n  if (row.HDate !== undefined && row.HSourceCode !== undefined) {\n    // 已是新格式:保留既有字段和批次引用,只恢复 Date 类型。\n    return {\n      ...row,\n      HDate: new Date(row.HDate),\n      HCreateTime: row.HCreateTime ? new Date(row.HCreateTime) : new Date(createdAt)\n    };\n  }\n  // 部署兼容:旧 sync_rows 使用 s/d/p/v/t,原批语义及原参数名保持不变。\n  const converted = {\n    HItemID: null,\n    HDate: new Date(row.t),\n    HSourceCode: row.d,\n    HTechParamID: 0,\n    HTechParamName: row.p,\n    HCount: row.v,\n    HCreateTime: new Date(createdAt),\n    HResult: String(row.v).slice(0, 50),\n    HProcNumber: row.s,\n    HFlag: 0\n  };\n  if (row.yyRefs?.length) converted._sync = {\n    yyBatchIds: [...row.yyRefs]\n  };\n  return converted;\n}\nconst oldRows = flow.get('sync_rows');\nif (Array.isArray(oldRows) && oldRows.length) {\n  const migratedRows = oldRows.map(row => convertLegacyBufferRow(row, new Date()));\n  if (migratedRows.some(row => !Number.isFinite(row.HDate.getTime()) || !Number.isFinite(row.HCreateTime.getTime()))) throw new Error('旧缓冲时间无效,未覆盖原缓冲');\n  flow.set('sync_rows', migratedRows);\n}\n",
        "finalize": "",
        "libs": [],
        "x": 1150,
        "y": 420,
        "wires": [
            [
                "e20ef8063f6ae7d6"
            ],
            [
                "yy_ack_out"
            ]
        ]
    },
    {
        "id": "fn_wy_q",
        "type": "function",
        "z": "cee834492540f06e",
        "name": "五洋 · 读取全部实时设备",
        "func": "/**\n * 五洋实时查询\n * 输入:每秒定时触发\n * 输出:msg.query/queryParams;msg.wySampleTime\n * 上下文:wy_poll_inflight;wy_last_scheduled_second;sync_rows背压\n */\nfunction readWuyangDevices(msg, flow, global, node) {\n  if (global.get('collection_paused') !== false) {\n    node.status({\n      fill: 'yellow',\n      shape: 'ring',\n      text: '采集已暂停'\n    });\n    return null;\n  }\n  if ((flow.get('sync_rows') || []).length >= 20000) {\n    node.status({\n      fill: 'yellow',\n      shape: 'ring',\n      text: '写库积压,暂停快照采样'\n    });\n    return null;\n  }\n  if (flow.get('wy_poll_inflight')) {\n    node.status({\n      fill: 'yellow',\n      shape: 'ring',\n      text: '等待上次查询完成'\n    });\n    return null;\n  }\n  const sampleTimestamp = Math.floor(Date.now() / 1000) * 1000;\n  if (flow.get('wy_last_scheduled_second') === sampleTimestamp) return null;\n  flow.set('wy_last_scheduled_second', sampleTimestamp);\n  flow.set('wy_poll_inflight', true);\n  const parameterNames = ['机器转速', '生产速度', '累计产量', '订单匹数', '已生产匹数', '当前匹已生产长度'];\n  for (let axisNumber = 1; axisNumber <= 8; axisNumber++) parameterNames.push('经轴送经量' + axisNumber);\n  msg.wySampleTime = sampleTimestamp;\n  msg.query = `SELECT BaseMachineID, MachineNo, MachineName, 状态, MachineCollectionTime,\n       ${parameterNames.map(name => '[' + name + ']').join(', ')}\nFROM JYPM_wuyang.dbo.BaseMachine\nORDER BY BaseMachineID;`;\n  msg.queryParams = [];\n  delete msg.wmFrom;\n  node.status({\n    fill: 'blue',\n    shape: 'dot',\n    text: '每秒全设备快照'\n  });\n  return msg;\n}\nreturn readWuyangDevices(msg, flow, global, node);\n",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "flow.set('wy_poll_inflight', false);\n",
        "finalize": "",
        "libs": [],
        "x": 410,
        "y": 320,
        "wires": [
            [
                "4e0d058caa7afc4e"
            ]
        ]
    },
    {
        "id": "fn_sync_flush",
        "type": "function",
        "z": "cee834492540f06e",
        "name": "缓冲数据库行 → Bulk列数组",
        "func": "/**\n * 缓冲转Bulk请求\n * 输入:每5秒触发\n * 输出:msg.rows=按列定义排列的二维数组;retryBuf=原数据库行\n * 上下文:sync_rows;sync_inflight\n */\nfunction collectionRowKey(row) {\n  // 保留原有自然键编码,兼容旧待确认批次的 doneKeys。\n  return row.HProcNumber + '|' + row.HSourceCode + '|' + row.HTechParamName + '|' + new Date(row.HDate).getTime();\n}\nfunction convertLegacyBufferRow(row, createdAt) {\n  if (row.HDate !== undefined && row.HSourceCode !== undefined) {\n    // 已是新格式:保留既有字段和批次引用,只恢复 Date 类型。\n    return {\n      ...row,\n      HDate: new Date(row.HDate),\n      HCreateTime: row.HCreateTime ? new Date(row.HCreateTime) : new Date(createdAt)\n    };\n  }\n  // 部署兼容:旧 sync_rows 使用 s/d/p/v/t,原批语义及原参数名保持不变。\n  const converted = {\n    HItemID: null,\n    HDate: new Date(row.t),\n    HSourceCode: row.d,\n    HTechParamID: 0,\n    HTechParamName: row.p,\n    HCount: row.v,\n    HCreateTime: new Date(createdAt),\n    HResult: String(row.v).slice(0, 50),\n    HProcNumber: row.s,\n    HFlag: 0\n  };\n  if (row.yyRefs?.length) converted._sync = {\n    yyBatchIds: [...row.yyRefs]\n  };\n  return converted;\n}\nfunction flushCollectionBuffer(msg, flow, global, node) {\n  if (global.get('collection_paused') !== false) {\n    node.status({\n      fill: 'yellow',\n      shape: 'ring',\n      text: '采集已暂停'\n    });\n    return null;\n  }\n  if (flow.get('sync_inflight')) return null;\n  const bufferRows = flow.get('sync_rows') || [];\n  if (!bufferRows.length) return null;\n\n  // 1. 最多取5000行。同键只写一次,但合并所有用友批次引用。\n  const selectedRows = bufferRows.slice(0, 5000);\n  const uniqueRows = new Map();\n  const createdAt = new Date();\n  for (const input of selectedRows) {\n    const row = convertLegacyBufferRow(input, createdAt);\n    const key = collectionRowKey(row);\n    const previous = uniqueRows.get(key);\n    const batchIds = new Set([...(previous?._sync?.yyBatchIds || []), ...(row._sync?.yyBatchIds || [])]);\n    if (batchIds.size) row._sync = {\n      yyBatchIds: Array.from(batchIds)\n    };\n    uniqueRows.set(key, row);\n  }\n  const selectedRecords = Array.from(uniqueRows.values());\n\n  // 2. 只有Bulk边界需要二维数组,列顺序集中定义,不再使用r.s/r.d/r.p等缩写。\n  const bulkColumns = [{\n    name: 'HDate',\n    type: 'datetime'\n  }, {\n    name: 'HSourceCode',\n    type: 'varchar(50)'\n  }, {\n    name: 'HTechParamID',\n    type: 'int'\n  }, {\n    name: 'HTechParamName',\n    type: 'varchar(500)'\n  }, {\n    name: 'HCount',\n    type: 'decimal(18,2)'\n  }, {\n    name: 'HCreateTime',\n    type: 'datetime'\n  }, {\n    name: 'HResult',\n    type: 'varchar(50)'\n  }, {\n    name: 'HProcNumber',\n    type: 'varchar(50)'\n  }, {\n    name: 'HFlag',\n    type: 'bit'\n  }].map(column => ({\n    ...column,\n    options: {\n      nullable: false\n    }\n  }));\n  flow.set('sync_rows', bufferRows.slice(selectedRows.length));\n  flow.set('sync_inflight', true);\n  msg.retryBuf = selectedRecords;\n  msg.bulkColumns = bulkColumns;\n  msg.rows = selectedRecords.map(record => bulkColumns.map(column => record[column.name]));\n  msg.queryParams = bulkColumns.map(column => ({\n    ...column\n  }));\n  msg.query = 'dbo.Sb_EquipMentCollectionTechParam_Temp';\n  msg.queryMode = 'bulk';\n  msg.syncWrittenRows = selectedRecords;\n  msg.syncSkippedRows = [];\n  msg.payload = {\n    table: msg.query,\n    rows: selectedRecords.length\n  };\n  return msg;\n}\nreturn flushCollectionBuffer(msg, flow, global, node);\n",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 380,
        "y": 500,
        "wires": [
            [
                "sync_bulk_prepare"
            ]
        ]
    },
    {
        "id": "fn_sync_retry",
        "type": "function",
        "z": "cee834492540f06e",
        "name": "失败回填缓冲",
        "func": "/**\n * 失败原批回填\n * 输入:失败请求,msg.retryBuf和msg.error\n * 输出:输出1=错误摘要;输出2=用友重试通知\n * 上下文:sync_rows;sync_inflight\n */\nfunction requeueFailedBulk(msg, flow, global, node) {\n  const retryRecords = Array.isArray(msg.retryBuf) ? msg.retryBuf : [];\n  if (retryRecords.length) flow.set('sync_rows', retryRecords.concat(flow.get('sync_rows') || []));\n  flow.set('sync_inflight', false);\n  const errorMessage = typeof msg.error === 'string' ? msg.error : msg.error?.details || msg.error?.message || 'Bulk或防重预查失败';\n  const pendingBatches = flow.get('sync_yy_batches') || {};\n  const affectedBatchIds = new Set(retryRecords.flatMap(row => row._sync?.yyBatchIds || []));\n  const acknowledgements = Array.from(affectedBatchIds).filter(batchId => pendingBatches[batchId]).map(batchId => ({\n    yySync: pendingBatches[batchId].meta,\n    yyAck: {\n      kind: 'retrying',\n      reason: errorMessage\n    }\n  }));\n  node.status({\n    fill: 'red',\n    shape: 'ring',\n    text: '失败回填 ' + retryRecords.length + ' 行,水位未推进'\n  });\n  return [{\n    payload: {\n      error: errorMessage,\n      requeued: retryRecords.length\n    }\n  }, acknowledgements];\n}\nreturn requeueFailedBulk(msg, flow, global, node);\n",
        "outputs": 2,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 330,
        "y": 560,
        "wires": [
            [
                "sync_err_dbg"
            ],
            [
                "yy_ack_out"
            ]
        ]
    },
    {
        "id": "sync_flush",
        "type": "inject",
        "z": "cee834492540f06e",
        "name": "每 5s 批量入库",
        "props": [],
        "repeat": "5",
        "crontab": "",
        "once": true,
        "onceDelay": "8",
        "topic": "",
        "payload": "",
        "payloadType": "date",
        "x": 140,
        "y": 500,
        "wires": [
            [
                "fn_sync_flush"
            ]
        ]
    },
    {
        "id": "sync_out_dbg",
        "type": "debug",
        "z": "cee834492540f06e",
        "name": "入库结果",
        "active": false,
        "tosidebar": true,
        "console": true,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 1650,
        "y": 500,
        "wires": []
    },
    {
        "id": "sync_catch",
        "type": "catch",
        "z": "cee834492540f06e",
        "name": "同步异常",
        "scope": [
            "fe88ac9fe19141be",
            "yy_idempotent_write",
            "sync_bulk_prepare",
            "sync_bulk_filter"
        ],
        "uncaught": false,
        "x": 100,
        "y": 560,
        "wires": [
            [
                "fn_sync_retry"
            ]
        ]
    },
    {
        "id": "sync_err_dbg",
        "type": "debug",
        "z": "cee834492540f06e",
        "name": "异常详情",
        "active": true,
        "tosidebar": true,
        "console": true,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 630,
        "y": 560,
        "wires": []
    },
    {
        "id": "fn_reset_wm",
        "type": "function",
        "z": "cee834492540f06e",
        "name": "重置水位 → 当前时刻",
        "func": "/**\n * 设置回补起点\n * 输入:payload=天数/日期/空\n * 输出:输出1=维护日志;输出2=用友回补控制\n * 上下文:旧水位兼容键;MQTT变化缓存\n */\nfunction localTime(date) {\n  const d = new Date(date);\n  if (!Number.isFinite(d.getTime())) return null;\n  const p = n => String(n).padStart(2, '0');\n  return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes()) + ':' + p(d.getSeconds()) + '.' + String(d.getMilliseconds()).padStart(3, '0');\n}\nfunction resetCollectionWatermark(msg, flow, global, node) {\n  const input = msg.payload;\n  let fromTime = localTime(new Date()).slice(0, 19);\n  let description = '当前时刻';\n  const numericDays = typeof input === 'number' || typeof input === 'string' && /^\\d+$/.test(input.trim());\n  if (numericDays && Number.isFinite(Number(input))) {\n    fromTime = localTime(new Date(Date.now() - Number(input) * 86400000)).slice(0, 19);\n    description = '回补 ' + Number(input) + ' 天';\n  } else if (typeof input === 'string' && /^\\d{4}-\\d{2}-\\d{2}/.test(input.trim())) {\n    fromTime = input.trim();\n    description = '指定 ' + fromTime;\n  }\n  flow.set('wy_wm', fromTime);\n  flow.set('yy_wm', fromTime);\n  flow.set('wy_seen', {});\n  flow.set('mqtt_seen', {});\n  flow.set('mqtt_seen_n', 0);\n  msg.payload = '水位 → ' + fromTime + '(' + description + ')';\n  return [msg, {\n    yyControl: {\n      from: fromTime\n    }\n  }];\n}\nreturn resetCollectionWatermark(msg, flow, global, node);\n",
        "outputs": 2,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 400,
        "y": 700,
        "wires": [
            [
                "reset_dbg"
            ],
            [
                "yy_control_out"
            ]
        ]
    },
    {
        "id": "reset_btn",
        "type": "inject",
        "z": "cee834492540f06e",
        "name": "重置水位(维护)",
        "props": [],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "x": 150,
        "y": 700,
        "wires": [
            [
                "fn_reset_wm"
            ]
        ]
    },
    {
        "id": "reset_dbg",
        "type": "debug",
        "z": "cee834492540f06e",
        "name": "水位日志",
        "active": false,
        "tosidebar": true,
        "console": true,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 630,
        "y": 700,
        "wires": []
    },
    {
        "id": "bf10",
        "type": "inject",
        "z": "cee834492540f06e",
        "name": "回补最近 10 天",
        "props": [
            {
                "p": "payload",
                "v": "10",
                "vt": "num"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "",
        "payloadType": "date",
        "x": 140,
        "y": 780,
        "wires": [
            [
                "fn_reset_wm"
            ]
        ]
    },
    {
        "id": "bf30",
        "type": "inject",
        "z": "cee834492540f06e",
        "name": "回补最近 30 天",
        "props": [
            {
                "p": "payload",
                "v": "30",
                "vt": "num"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "",
        "payloadType": "date",
        "x": 140,
        "y": 860,
        "wires": [
            [
                "fn_reset_wm"
            ]
        ]
    },
    {
        "id": "fn_sync_success",
        "type": "function",
        "z": "cee834492540f06e",
        "name": "写库成功 → 确认批次",
        "func": "/**\n * Bulk成功及批次确认\n * 输入:retryBuf;syncWrittenRows;syncSkippedRows\n * 输出:输出1=写库统计;输出2=整批完成回执\n * 上下文:sync_inflight;sync_yy_batches;sync_written\n */\nfunction collectionRowKey(row) {\n  // 保留原有自然键编码,兼容旧待确认批次的 doneKeys。\n  return row.HProcNumber + '|' + row.HSourceCode + '|' + row.HTechParamName + '|' + new Date(row.HDate).getTime();\n}\nfunction confirmBulkSuccess(msg, flow, global, node) {\n  flow.set('sync_inflight', false);\n  const originalRecords = Array.isArray(msg.retryBuf) ? msg.retryBuf : [];\n  const writtenRecords = Array.isArray(msg.syncWrittenRows) ? msg.syncWrittenRows : originalRecords;\n  const skippedRecords = Array.isArray(msg.syncSkippedRows) ? msg.syncSkippedRows : [];\n  const skippedKeys = new Set(skippedRecords.map(collectionRowKey));\n  const pendingBatches = flow.get('sync_yy_batches') || {};\n  const completedBatches = flow.get('sync_yy_completed') || {};\n  const acknowledgements = [];\n\n  // 一个Bulk可以包含多个源批次,也可以只是一个源批次的一部分。\n  for (const record of originalRecords) {\n    const rowKey = collectionRowKey(record);\n    for (const batchId of new Set(record._sync?.yyBatchIds || [])) {\n      const batch = pendingBatches[batchId];\n      if (!batch || batch.doneKeys[rowKey]) continue;\n      batch.doneKeys[rowKey] = true;\n      batch.done += 1;\n      if (skippedKeys.has(rowKey)) batch.skipped += 1;else batch.inserted += 1;\n    }\n  }\n  for (const [batchId, batch] of Object.entries(pendingBatches)) {\n    if (batch.done < batch.expected) continue;\n    const ack = {\n      yySync: batch.meta,\n      yyAck: {\n        kind: 'committed',\n        expected: batch.expected,\n        inserted: batch.inserted,\n        skipped: batch.skipped\n      },\n      payload: {\n        stream: batch.meta.stream,\n        inserted: batch.inserted,\n        skipped: batch.skipped\n      }\n    };\n    acknowledgements.push(ack);\n    completedBatches[batchId] = ack;\n    delete pendingBatches[batchId];\n  }\n  const completedIds = Object.keys(completedBatches);\n  for (const batchId of completedIds.slice(0, Math.max(0, completedIds.length - 256))) delete completedBatches[batchId];\n  flow.set('sync_yy_batches', pendingBatches);\n  flow.set('sync_yy_completed', completedBatches);\n  const totalWritten = (flow.get('sync_written') || 0) + writtenRecords.length;\n  flow.set('sync_written', totalWritten);\n  flow.set('sync_last_success', new Date().toISOString());\n  node.status({\n    fill: 'green',\n    shape: 'dot',\n    text: 'Bulk写入 ' + writtenRecords.length + ' / 已有 ' + skippedRecords.length\n  });\n  return [{\n    payload: {\n      written: writtenRecords.length,\n      skipped: skippedRecords.length,\n      total: totalWritten,\n      pending: (flow.get('sync_rows') || []).length,\n      yyPendingBatches: Object.keys(pendingBatches).length\n    }\n  }, acknowledgements];\n}\nreturn confirmBulkSuccess(msg, flow, global, node);\n",
        "outputs": 2,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 1390,
        "y": 500,
        "wires": [
            [
                "sync_out_dbg"
            ],
            [
                "yy_ack_out"
            ]
        ]
    },
    {
        "id": "sync_source_catch",
        "type": "catch",
        "z": "cee834492540f06e",
        "name": "五洋实时查询/映射异常",
        "scope": [
            "fn_wy_q",
            "4e0d058caa7afc4e",
            "c53aa63e531b7e6d"
        ],
        "uncaught": false,
        "x": 110,
        "y": 620,
        "wires": [
            [
                "wy_read_error"
            ]
        ]
    },
    {
        "id": "yy_write_in",
        "type": "link in",
        "z": "cee834492540f06e",
        "name": "用友 → 共用缓冲",
        "links": [
            "yy_data_out"
        ],
        "x": 645,
        "y": 380,
        "wires": [
            []
        ]
    },
    {
        "id": "yy_idempotent_write",
        "type": "MSSQL",
        "z": "cee834492540f06e",
        "mssqlCN": "9bb47eb9867c4772",
        "name": "用友 · Bulk前集合防重预查",
        "outField": "payload",
        "returnType": "0",
        "throwErrors": "1",
        "query": "",
        "modeOpt": "",
        "modeOptType": "query",
        "queryOpt": "query",
        "queryOptType": "msg",
        "paramsOpt": "queryParams",
        "paramsOptType": "msg",
        "rows": "rows",
        "rowsType": "msg",
        "parseMustache": false,
        "params": [],
        "x": 900,
        "y": 720,
        "wires": [
            [
                "sync_bulk_filter"
            ]
        ]
    },
    {
        "id": "yy_ack_out",
        "type": "link out",
        "z": "cee834492540f06e",
        "name": "缓冲/Bulk回执 → 用友水位",
        "mode": "link",
        "links": [
            "yy_ack_in"
        ],
        "x": 1575,
        "y": 600,
        "wires": []
    },
    {
        "id": "yy_control_out",
        "type": "link out",
        "z": "cee834492540f06e",
        "name": "→ 悠扬回补起点控制",
        "mode": "link",
        "links": [
            "yy_control_in"
        ],
        "x": 585,
        "y": 740,
        "wires": []
    },
    {
        "id": "wy_read_error",
        "type": "function",
        "z": "cee834492540f06e",
        "name": "五洋 · 解除查询锁/下秒重试",
        "func": "/**\n * 五洋查询错误恢复\n * 输入:msg.error\n * 输出:错误摘要,下秒可重试\n * 上下文:wy_poll_inflight;wy_last_read_error\n */\nfunction handleWuyangReadError(msg, flow, global, node) {\n  flow.set('wy_poll_inflight', false);\n  const errorMessage = typeof msg.error === 'string' ? msg.error : msg.error?.message || '五洋查询失败';\n  flow.set('wy_last_read_error', {\n    time: new Date().toISOString(),\n    error: errorMessage\n  });\n  node.status({\n    fill: 'red',\n    shape: 'ring',\n    text: '查询失败,下秒重试'\n  });\n  msg.payload = {\n    source: 'WY',\n    error: errorMessage\n  };\n  return msg;\n}\nreturn handleWuyangReadError(msg, flow, global, node);\n",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 360,
        "y": 620,
        "wires": [
            [
                "sync_err_dbg"
            ]
        ]
    },
    {
        "id": "collection_control",
        "type": "function",
        "z": "cee834492540f06e",
        "name": "采集总开关 · 暂停/恢复",
        "func": "/**\n * 采集暂停/恢复\n * 输入:payload=true暂停;false恢复\n * 输出:输出1=状态;输出2=恢复时触发采集/写库\n * 上下文:global.collection_paused;MQTT变化缓存\n */\nfunction controlCollection(msg, flow, global, node) {\n  if (typeof msg.payload !== 'boolean') {\n    node.error('采集开关参数必须是 true(暂停)或 false(恢复)', msg);\n    return null;\n  }\n  const paused = msg.payload;\n  global.set('collection_paused', paused);\n  global.set('collection_control_state', {\n    paused,\n    changedAt: new Date().toISOString()\n  });\n  if (!paused) {\n    flow.set('mqtt_seen', {});\n    flow.set('mqtt_seen_n', 0);\n  }\n  node.status({\n    fill: paused ? 'yellow' : 'green',\n    shape: paused ? 'ring' : 'dot',\n    text: paused ? '已暂停采集和写库' : '正在采集和写库'\n  });\n  msg.payload = {\n    paused,\n    message: paused ? '已暂停新采集和后续写库;已提交的数据库请求会完成,缓冲保留' : '已恢复采集和写库',\n    buffered: (flow.get('sync_rows') || []).length\n  };\n  return [msg, paused ? null : {}];\n}\nreturn controlCollection(msg, flow, global, node);\n",
        "outputs": 2,
        "timeout": 0,
        "noerr": 0,
        "initialize": "// 重启或重新部署总开关节点时默认暂停,避免测试环境自动持续写库。\nglobal.set('collection_paused', true);\nglobal.set('collection_control_state', {\n  paused: true,\n  changedAt: new Date().toISOString()\n});\nnode.status({\n  fill: 'yellow',\n  shape: 'ring',\n  text: '已暂停采集和写库'\n});\n",
        "finalize": "",
        "libs": [],
        "x": 460,
        "y": 60,
        "wires": [
            [
                "collection_control_debug"
            ],
            [
                "fn_sync_flush",
                "fn_wy_q"
            ]
        ]
    },
    {
        "id": "collection_pause",
        "type": "inject",
        "z": "cee834492540f06e",
        "name": "⏸ 暂停全部采集/写库",
        "props": [
            {
                "p": "payload"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "true",
        "payloadType": "bool",
        "x": 170,
        "y": 60,
        "wires": [
            [
                "collection_control"
            ]
        ]
    },
    {
        "id": "collection_resume",
        "type": "inject",
        "z": "cee834492540f06e",
        "name": "▶ 恢复全部采集/写库",
        "props": [
            {
                "p": "payload",
                "v": "false",
                "vt": "bool"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "x": 170,
        "y": 110,
        "wires": [
            [
                "collection_control"
            ]
        ]
    },
    {
        "id": "collection_control_debug",
        "type": "debug",
        "z": "cee834492540f06e",
        "name": "采集总开关状态",
        "active": false,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "x": 740,
        "y": 60,
        "wires": []
    },
    {
        "id": "collection_pause_note",
        "type": "comment",
        "z": "cee834492540f06e",
        "name": "总开关控制五洋、用友、MQTT采集和后续写库;启动默认暂停,缓冲保留",
        "info": "点击左侧注入按钮暂停/恢复。不清空缓冲,不丢弃悠扬待确认批次;已提交的数据库请求允许完成。MQTT连接和业务确认回执继续响应,采集数据在暂停期间不入缓冲、不写库。",
        "x": 300,
        "y": 20,
        "wires": []
    },
    {
        "id": "collection_control_link_in",
        "type": "link in",
        "z": "cee834492540f06e",
        "name": "← 其他页签采集总开关",
        "links": [
            "collection_yy_control_out",
            "collection_mqtt_control_out"
        ],
        "x": 255,
        "y": 160,
        "wires": [
            [
                "collection_control"
            ]
        ]
    },
    {
        "id": "fn_clear_buffer",
        "type": "function",
        "z": "cee834492540f06e",
        "name": "⚠️ 强制清空失败缓冲",
        "func": "/**\n * 人工清空缓冲\n * 输入:手动触发\n * 输出:清理结果;存在在途/用友批次时拒绝\n * 上下文:sync_rows;sync_inflight;维护日志\n */\nfunction canMaintainBuffer(flow) {\n  return !flow.get('sync_inflight') && Object.keys(flow.get('sync_yy_batches') || {}).length === 0;\n}\nfunction clearCollectionBuffer(msg, flow, global, node) {\n  if (!canMaintainBuffer(flow)) {\n    msg.payload = {\n      action: 'blocked',\n      reason: '存在Bulk在途请求或用友待确认批次,暂不清理'\n    };\n    node.status({\n      fill: 'yellow',\n      shape: 'ring',\n      text: '未清理:在途/用友待确认'\n    });\n    return msg;\n  }\n  const clearedCount = (flow.get('sync_rows') || []).length;\n  flow.set('sync_rows', []);\n  flow.set('sync_inflight', false);\n  flow.set('wy_poll_inflight', false);\n  const result = {\n    cleared: clearedCount,\n    clearedAt: new Date().toISOString(),\n    reason: '手动清空失败缓冲'\n  };\n  flow.set('buffer_emergency_clear', result);\n  msg.payload = result;\n  node.status({\n    fill: 'orange',\n    shape: 'ring',\n    text: '已清空 ' + clearedCount + ' 行缓冲'\n  });\n  return msg;\n}\nreturn clearCollectionBuffer(msg, flow, global, node);\n",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 370,
        "y": 940,
        "wires": [
            [
                "buffer_control_debug"
            ]
        ]
    },
    {
        "id": "fn_view_buffer",
        "type": "function",
        "z": "cee834492540f06e",
        "name": "查看当前缓冲状态",
        "func": "/**\n * 查看缓冲\n * 输入:手动触发\n * 输出:完整来源统计、数据库字段预览、用友确认进度\n * 上下文:只读sync_rows及相关统计\n */\nfunction convertLegacyBufferRow(row, createdAt) {\n  if (row.HDate !== undefined && row.HSourceCode !== undefined) {\n    // 已是新格式:保留既有字段和批次引用,只恢复 Date 类型。\n    return {\n      ...row,\n      HDate: new Date(row.HDate),\n      HCreateTime: row.HCreateTime ? new Date(row.HCreateTime) : new Date(createdAt)\n    };\n  }\n  // 部署兼容:旧 sync_rows 使用 s/d/p/v/t,原批语义及原参数名保持不变。\n  const converted = {\n    HItemID: null,\n    HDate: new Date(row.t),\n    HSourceCode: row.d,\n    HTechParamID: 0,\n    HTechParamName: row.p,\n    HCount: row.v,\n    HCreateTime: new Date(createdAt),\n    HResult: String(row.v).slice(0, 50),\n    HProcNumber: row.s,\n    HFlag: 0\n  };\n  if (row.yyRefs?.length) converted._sync = {\n    yyBatchIds: [...row.yyRefs]\n  };\n  return converted;\n}\nfunction viewCollectionBuffer(msg, flow, global, node) {\n  const bufferRows = flow.get('sync_rows') || [];\n  const sourceCounts = {};\n  const deviceCodes = new Set();\n  let oldestTimestamp = null;\n  let newestTimestamp = null;\n  for (const input of bufferRows) {\n    const row = convertLegacyBufferRow(input, new Date());\n    const source = row.HProcNumber || 'UNKNOWN';\n    sourceCounts[source] = (sourceCounts[source] || 0) + 1;\n    if (row.HSourceCode) deviceCodes.add(row.HSourceCode);\n    const timestamp = row.HDate.getTime();\n    if (!Number.isFinite(timestamp)) continue;\n    if (oldestTimestamp === null || timestamp < oldestTimestamp) oldestTimestamp = timestamp;\n    if (newestTimestamp === null || timestamp > newestTimestamp) newestTimestamp = timestamp;\n  }\n  const preview = bufferRows.slice(0, 3).map(input => {\n    const {\n      _sync,\n      ...databaseFields\n    } = convertLegacyBufferRow(input, new Date());\n    return databaseFields;\n  });\n  msg.payload = {\n    bufferSize: bufferRows.length,\n    inflight: Boolean(flow.get('sync_inflight')),\n    wyPolling: Boolean(flow.get('wy_poll_inflight')),\n    paused: global.get('collection_paused') !== false,\n    totalWritten: flow.get('sync_written') || 0,\n    lastSuccess: flow.get('sync_last_success'),\n    sources: sourceCounts,\n    uniqueDevices: deviceCodes.size,\n    oldestData: oldestTimestamp === null ? null : new Date(oldestTimestamp).toISOString(),\n    newestData: newestTimestamp === null ? null : new Date(newestTimestamp).toISOString(),\n    records: preview,\n    youyangPendingBatches: Object.values(flow.get('sync_yy_batches') || {}).map(batch => ({\n      stream: batch.meta.stream,\n      expected: batch.expected,\n      confirmed: batch.done,\n      inserted: batch.inserted,\n      skipped: batch.skipped,\n      queuedAt: batch.queuedAt\n    })),\n    timestamp: new Date().toISOString()\n  };\n  node.status({\n    fill: bufferRows.length >= 20000 ? 'red' : 'blue',\n    shape: 'dot',\n    text: bufferRows.length + ' 行'\n  });\n  return msg;\n}\nreturn viewCollectionBuffer(msg, flow, global, node);\n",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 370,
        "y": 1020,
        "wires": [
            [
                "buffer_control_debug"
            ]
        ]
    },
    {
        "id": "fn_trim_buffer",
        "type": "function",
        "z": "cee834492540f06e",
        "name": "保留最新 5000 条",
        "func": "/**\n * 人工裁剪缓冲\n * 输入:手动触发\n * 输出:按HDate保留最新5000行;未完成批次期间拒绝\n * 上下文:sync_rows;buffer_trim_history\n */\nfunction canMaintainBuffer(flow) {\n  return !flow.get('sync_inflight') && Object.keys(flow.get('sync_yy_batches') || {}).length === 0;\n}\nfunction trimCollectionBuffer(msg, flow, global, node) {\n  if (!canMaintainBuffer(flow)) {\n    msg.payload = {\n      action: 'blocked',\n      reason: '存在Bulk在途请求或用友待确认批次,暂不裁剪'\n    };\n    node.status({\n      fill: 'yellow',\n      shape: 'ring',\n      text: '未清理:在途/用友待确认'\n    });\n    return msg;\n  }\n  const bufferRows = flow.get('sync_rows') || [];\n  const keepCount = 5000;\n  if (bufferRows.length <= keepCount) {\n    msg.payload = {\n      action: 'skip',\n      current: bufferRows.length,\n      message: '缓冲未超过限制'\n    };\n    node.status({\n      fill: 'green',\n      shape: 'dot',\n      text: '缓冲正常,无需裁剪'\n    });\n    return msg;\n  }\n  const timestampOf = row => new Date(row.HDate !== undefined ? row.HDate : row.t).getTime();\n  const keptRows = [...bufferRows].sort((left, right) => timestampOf(right) - timestampOf(left)).slice(0, keepCount);\n  flow.set('sync_rows', keptRows);\n  const result = {\n    action: 'trim',\n    before: bufferRows.length,\n    kept: keptRows.length,\n    dropped: bufferRows.length - keptRows.length,\n    trimmedAt: new Date().toISOString()\n  };\n  flow.set('buffer_trim_history', result);\n  msg.payload = result;\n  node.status({\n    fill: 'yellow',\n    shape: 'dot',\n    text: '保留 ' + result.kept + ' / 丢弃 ' + result.dropped\n  });\n  return msg;\n}\nreturn trimCollectionBuffer(msg, flow, global, node);\n",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 360,
        "y": 1100,
        "wires": [
            [
                "buffer_control_debug"
            ]
        ]
    },
    {
        "id": "btn_clear_buffer",
        "type": "inject",
        "z": "cee834492540f06e",
        "name": "🚨 紧急清空缓冲",
        "props": [],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "x": 140,
        "y": 940,
        "wires": [
            [
                "fn_clear_buffer"
            ]
        ]
    },
    {
        "id": "btn_view_buffer",
        "type": "inject",
        "z": "cee834492540f06e",
        "name": "📊 查看缓冲状态",
        "props": [],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "x": 140,
        "y": 1020,
        "wires": [
            [
                "fn_view_buffer"
            ]
        ]
    },
    {
        "id": "btn_trim_buffer",
        "type": "inject",
        "z": "cee834492540f06e",
        "name": "✂️ 裁剪缓冲",
        "props": [],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "x": 130,
        "y": 1100,
        "wires": [
            [
                "fn_trim_buffer"
            ]
        ]
    },
    {
        "id": "buffer_control_debug",
        "type": "debug",
        "z": "cee834492540f06e",
        "name": "缓冲控制日志",
        "active": false,
        "tosidebar": true,
        "console": true,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 640,
        "y": 1020,
        "wires": []
    },
    {
        "id": "buffer_control_note",
        "type": "comment",
        "z": "cee834492540f06e",
        "name": "缓冲维护:在途/Bulk待确认期间禁止清空和裁剪",
        "info": "当写库持续失败导致缓冲堆积时使用这些控制:\n1. 📊 查看缓冲状态 - 了解当前缓冲大小、数据来源分布\n2. ✂️ 裁剪缓冲 - 保留最新5000条,丢弃旧数据(推荐)\n3. 🚨 紧急清空缓冲 - 完全清空缓冲队列(慎用,会丢失所有待写入数据)\n\n使用场景:\n- 缓冲超过 20000 条导致新数据无法进入\n- 数据库连接长期异常需要清理积压\n- 测试环境需要重置状态\n2026-10-25:存在Bulk在途请求或用友待确认批次时,清空/裁剪自动拒绝,防止丢失待确认行。先恢复写库让批次完成,再执行维护。",
        "x": 220,
        "y": 900,
        "wires": []
    },
    {
        "id": "sync_bulk_prepare",
        "type": "function",
        "z": "cee834492540f06e",
        "name": "Bulk分流 · 用友集合防重",
        "func": "/**\n * Bulk前集合防重分流\n * 输入:msg.retryBuf=数据库行\n * 输出:输出1=直接Bulk;输出2=用友防重SELECT请求\n * 上下文:无新增状态;最多1900个SQL参数\n */\nfunction canonicalParameterName(parameterName) {\n  const aliases = {\n    '转速': '机器转速',\n    '班次平均车速': '班次平均转速',\n    '本班产量': '班次产量(源单位)',\n    '本班效率': '班次效率(%)',\n    '本班停机次数': '班次停机次数',\n    '本班停机时间(秒)': '班次停机时间(秒)',\n    '本匹产量': '本匹产量(源单位)'\n  };\n  const name = String(parameterName);\n  // 用友事件里的本班产量附有实际单位,沿用同一班次产量名称。\n  const withUnit = /^本班产量\\((.+)\\)$/.exec(name);\n  if (withUnit) return '班次产量(' + withUnit[1] + ')';\n  return aliases[name] || name;\n}\nfunction equivalentParameterNames(parameterName) {\n  const canonicalName = canonicalParameterName(parameterName);\n  const historicalNames = ['转速', '班次平均车速', '本班产量', '本班效率', '本班停机次数', '本班停机时间(秒)', '本匹产量'];\n  const names = new Set([parameterName, canonicalName]);\n  for (const historicalName of historicalNames) {\n    if (canonicalParameterName(historicalName) === canonicalName) names.add(historicalName);\n  }\n  const withUnit = /^班次产量\\((.+)\\)$/.exec(canonicalName);\n  if (withUnit) names.add('本班产量(' + withUnit[1] + ')');\n  return Array.from(names);\n}\nfunction prepareYouyangDuplicateCheck(msg, flow, global, node) {\n  const youyangRows = (msg.retryBuf || []).filter(row => row.HProcNumber === 'YY');\n  if (!youyangRows.length) return [msg, null];\n\n  // 按源批次收窄时间、设备和参数范围,一次查询整个Bulk批次。\n  const groupsByBatch = new Map();\n  for (const row of youyangRows) {\n    const batchId = row._sync?.yyBatchIds?.[0] || 'untracked';\n    const timestamp = new Date(row.HDate).getTime();\n    if (!groupsByBatch.has(batchId)) {\n      groupsByBatch.set(batchId, {\n        minTime: timestamp,\n        maxTime: timestamp,\n        devices: new Set(),\n        parameters: new Set()\n      });\n    }\n    const group = groupsByBatch.get(batchId);\n    group.minTime = Math.min(group.minTime, timestamp);\n    group.maxTime = Math.max(group.maxTime, timestamp);\n    group.devices.add(row.HSourceCode);\n    for (const name of equivalentParameterNames(row.HTechParamName)) group.parameters.add(name);\n  }\n  let groups = Array.from(groupsByBatch.values());\n  if (groups.length > 128) {\n    const times = youyangRows.map(row => new Date(row.HDate).getTime());\n    groups = [{\n      minTime: Math.min(...times),\n      maxTime: Math.max(...times),\n      devices: new Set(youyangRows.map(row => row.HSourceCode)),\n      parameters: new Set(youyangRows.flatMap(row => equivalentParameterNames(row.HTechParamName)))\n    }];\n  }\n\n  // SQL Server最多2100个参数;预留余量。条件收缩只会多查,不会漏查。\n  const queryParams = [];\n  const predicates = [];\n  const groupBudget = Math.floor(1900 / groups.length) - 2;\n  groups.forEach((group, index) => {\n    const prefix = 'group' + index;\n    queryParams.push({\n      name: prefix + 'MinTime',\n      type: 'datetime',\n      value: new Date(group.minTime)\n    }, {\n      name: prefix + 'MaxTime',\n      type: 'datetime',\n      value: new Date(group.maxTime)\n    });\n    const filters = ['HDate >= @' + prefix + 'MinTime', 'HDate <= @' + prefix + 'MaxTime'];\n    let remainingBudget = groupBudget;\n    for (const filter of [{\n      values: group.parameters,\n      column: 'HTechParamName',\n      type: 'varchar(500)'\n    }, {\n      values: group.devices,\n      column: 'HSourceCode',\n      type: 'varchar(50)'\n    }]) {\n      if (filter.values.size > remainingBudget) continue;\n      const names = Array.from(filter.values).map((value, valueIndex) => {\n        const name = prefix + filter.column + valueIndex;\n        queryParams.push({\n          name,\n          type: filter.type,\n          value\n        });\n        return '@' + name;\n      });\n      filters.push(filter.column + ' IN (' + names.join(', ') + ')');\n      remainingBudget -= filter.values.size;\n    }\n    predicates.push('(' + filters.join(' AND ') + ')');\n  });\n  msg.query = `SET NOCOUNT ON;\nSELECT HDate, HSourceCode, HTechParamName\nFROM dbo.Sb_EquipMentCollectionTechParam_Temp\nWHERE HProcNumber = 'YY'\n  AND (${predicates.join('\\n    OR ')});`;\n  msg.queryParams = queryParams;\n  msg.queryMode = 'query';\n  msg.payload = null;\n  return [null, msg];\n}\nreturn prepareYouyangDuplicateCheck(msg, flow, global, node);\n",
        "outputs": 2,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 650,
        "y": 500,
        "wires": [
            [
                "fe88ac9fe19141be"
            ],
            [
                "yy_idempotent_write"
            ]
        ]
    },
    {
        "id": "sync_bulk_filter",
        "type": "function",
        "z": "cee834492540f06e",
        "name": "已有跳过 → Bulk待写行",
        "func": "/**\n * 过滤已有用友记录\n * 输入:payload=目标已有键;retryBuf/rows保留原批\n * 输出:输出1=剩余行Bulk;输出2=全跳过直接确认\n * 上下文:不修改源水位\n */\nfunction canonicalParameterName(parameterName) {\n  const aliases = {\n    '转速': '机器转速',\n    '班次平均车速': '班次平均转速',\n    '本班产量': '班次产量(源单位)',\n    '本班效率': '班次效率(%)',\n    '本班停机次数': '班次停机次数',\n    '本班停机时间(秒)': '班次停机时间(秒)',\n    '本匹产量': '本匹产量(源单位)'\n  };\n  const name = String(parameterName);\n  // 用友事件里的本班产量附有实际单位,沿用同一班次产量名称。\n  const withUnit = /^本班产量\\((.+)\\)$/.exec(name);\n  if (withUnit) return '班次产量(' + withUnit[1] + ')';\n  return aliases[name] || name;\n}\nfunction collectionRowKey(row) {\n  // 保留原有自然键编码,兼容旧待确认批次的 doneKeys。\n  return row.HProcNumber + '|' + row.HSourceCode + '|' + row.HTechParamName + '|' + new Date(row.HDate).getTime();\n}\nfunction canonicalRowKey(row) {\n  // 防重可识别历史同义参数;原批确认仍使用原键,避免升级破坏doneKeys。\n  return collectionRowKey({\n    ...row,\n    HTechParamName: canonicalParameterName(row.HTechParamName)\n  });\n}\nfunction filterExistingYouyangRows(msg, flow, global, node) {\n  if (!Array.isArray(msg.retryBuf) || !Array.isArray(msg.rows) || !Array.isArray(msg.bulkColumns)) {\n    node.error('Bulk预查缺少原批数据', msg);\n    return null;\n  }\n  const existingRows = Array.isArray(msg.payload) ? msg.payload : [];\n  const existingKeys = new Set(existingRows.map(row => canonicalRowKey({\n    ...row,\n    HProcNumber: 'YY'\n  })));\n  const rowsToWrite = [];\n  const writtenRecords = [];\n  const skippedRecords = [];\n  msg.retryBuf.forEach((record, index) => {\n    if (record.HProcNumber === 'YY' && existingKeys.has(canonicalRowKey(record))) {\n      skippedRecords.push(record);\n    } else {\n      writtenRecords.push(record);\n      rowsToWrite.push(msg.rows[index]);\n    }\n  });\n  msg.rows = rowsToWrite;\n  msg.syncWrittenRows = writtenRecords;\n  msg.syncSkippedRows = skippedRecords;\n  // MSSQL预查会改变queryParams的type对象,重新使用原Bulk列定义。\n  msg.queryParams = msg.bulkColumns.map(column => ({\n    ...column\n  }));\n  msg.query = 'dbo.Sb_EquipMentCollectionTechParam_Temp';\n  msg.queryMode = 'bulk';\n  msg.payload = {\n    table: msg.query,\n    rows: rowsToWrite.length,\n    skipped: skippedRecords.length\n  };\n  return rowsToWrite.length ? [msg, null] : [null, msg];\n}\nreturn filterExistingYouyangRows(msg, flow, global, node);\n",
        "outputs": 2,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 1190,
        "y": 720,
        "wires": [
            [
                "fe88ac9fe19141be"
            ],
            [
                "fn_sync_success"
            ]
        ]
    },
    {
        "id": "c06152e6ab227d0b",
        "type": "link in",
        "z": "cee834492540f06e",
        "name": "link in 1",
        "links": [
            "223b29559f4a36ae"
        ],
        "x": 645,
        "y": 420,
        "wires": [
            [
                "91f3df9e5a0d8a92"
            ]
        ]
    },
    {
        "id": "91f3df9e5a0d8a92",
        "type": "function",
        "z": "cee834492540f06e",
        "name": "MQTT · 标准化为数据库字段",
        "func": "/**\n * MQTT采集标准化\n * 输入:msg.dev或原始JSON/Buffer\n * 输出:输出1=msg.collectionRows;输出2=诊断/暂停预览\n * 上下文:mqtt_seen;mqtt_seen_n;mqtt_adapter_stats\n */\nfunction canonicalParameterName(parameterName) {\n    const aliases = {\n        '转速': '机器转速',\n        '班次平均车速': '班次平均转速',\n        '本班产量': '班次产量(源单位)',\n        '本班效率': '班次效率(%)',\n        '本班停机次数': '班次停机次数',\n        '本班停机时间(秒)': '班次停机时间(秒)',\n        '本匹产量': '本匹产量(源单位)'\n    };\n    const name = String(parameterName);\n    // 用友事件里的本班产量附有实际单位,沿用同一班次产量名称。\n    const withUnit = /^本班产量\\((.+)\\)$/.exec(name);\n    if (withUnit) return '班次产量(' + withUnit[1] + ')';\n    return aliases[name] || name;\n}\nfunction createCollectionRow(source, deviceCode, parameterName, value, collectedAt, createdAt) {\n    // 采集值按文本保存;HCount只作固定占位。\n    return {\n        HItemID: null,\n        // SQL Server 自增,Bulk 不传此列\n        HDate: new Date(collectedAt),\n        // 采样时间/源设备时间\n        HSourceCode: String(deviceCode).slice(0, 50),\n        HTechParamID: 0,\n        // 沿用现有目标表约定\n        HTechParamName: canonicalParameterName(parameterName).slice(0, 500),\n        HCount: 1,\n        // SQL decimal(18,2)\n        HCreateTime: new Date(createdAt),\n        // 标准化创建时间;重试保持不变\n        HResult: String(value).slice(0, 50),\n        HProcNumber: String(source).slice(0, 50),\n        // WY / YY / MQTT\n        HFlag: 0\n    };\n}\nfunction normalizeMqttReport(msg, flow, global, node) {\n    // 1. MQTT原字段 -> 统一参数名。无明确单位/统计周期的字段不强行冒充累计或班次值。\n    const fieldMappings = [{\n        sourceField: 'rpm',\n        parameterName: '机器转速'\n    }, {\n        sourceField: 'rpm_avr',\n        parameterName: '班次平均转速'\n    }, {\n        sourceField: 'produce',\n        parameterName: '班次产量(源单位)'\n    }, {\n        sourceField: 'effect',\n        parameterName: '班次效率(%)'\n    }, {\n        sourceField: 'beat',\n        parameterName: '打纬数'\n    }, {\n        sourceField: 'boot_time',\n        parameterName: '开机时间(秒)'\n    }, {\n        sourceField: 'run_time',\n        parameterName: '运行时间(秒)'\n    }, {\n        sourceField: 'stop_count',\n        parameterName: '班次停机次数'\n    }, {\n        sourceField: 'stop_time',\n        parameterName: '班次停机时间(秒)'\n    }, {\n        sourceField: 'stop_times',\n        parameterName: '累计停机次数'\n    }, {\n        sourceField: 'remain_length',\n        parameterName: '剩余经长'\n    }, {\n        sourceField: 'remain_length2',\n        parameterName: '剩余经长2'\n    }, {\n        sourceField: 'cloth_length_cap',\n        parameterName: '本匹产量(源单位)'\n    }, {\n        sourceField: 'worker_id',\n        parameterName: '职员id'\n    },\n    {\n        sourceField: 'worker_name',\n        parameterName: '职员名称'\n    },\n    {\n        sourceField: \"variety_id\",\n        parameterName: \"品号\"\n    },\n    {\n        sourceField: \"mach_id\",\n        parameterName: \"机台号\"\n    }\n    ];\n    function collectedValue(value) {\n        if (value === null || value === undefined) return null;\n        if (!['string', 'number', 'boolean'].includes(typeof value)) return null;\n        if (typeof value === 'number' && !Number.isFinite(value)) return null;\n        // 字符串原样保留,包括前导零、空字符串和小数精度。\n        return String(value);\n    }\n    function numericValue(value) {\n        if (value === null || value === undefined || typeof value === 'boolean' || typeof value === 'object') return null;\n        if (typeof value === 'string' && !value.trim()) return null;\n        const parsed = Number(value);\n        return Number.isFinite(parsed) ? Math.round(parsed * 100) / 100 : null;\n    }\n    function parseDeviceTime(value) {\n        if (value === null || value === undefined || value === '') return null;\n        if (value instanceof Date) return Number.isFinite(value.getTime()) ? value : null;\n        const text = String(value).trim();\n        const match = /^(\\d{4})-(\\d{1,2})-(\\d{1,2})(?:[ T](\\d{1,2}):(\\d{1,2})(?::(\\d{1,2})(?:\\.(\\d{1,3}))?)?)?$/.exec(text);\n        if (match) {\n            const year = Number(match[1]);\n            const monthIndex = Number(match[2]) - 1;\n            const day = Number(match[3]);\n            const hour = Number(match[4] || 0);\n            const minute = Number(match[5] || 0);\n            const second = Number(match[6] || 0);\n            const millisecond = Number((match[7] || '').padEnd(3, '0') || 0);\n            // 显式7个参数,避免展开不定长数组触发编辑器TS2556。\n            const date = new Date(year, monthIndex, day, hour, minute, second, millisecond);\n            const matchesInput = date.getFullYear() === year && date.getMonth() === monthIndex && date.getDate() === day && date.getHours() === hour && date.getMinutes() === minute && date.getSeconds() === second;\n            return matchesInput ? date : null;\n        }\n        if (/T.*(?:Z|[+-]\\d{2}:?\\d{2})$/i.test(text)) {\n            const date = new Date(text);\n            return Number.isFinite(date.getTime()) ? date : null;\n        }\n        return null;\n    }\n    function diagnostic(status, message, details = {}) {\n        const previousStats = flow.get('mqtt_adapter_stats') || {};\n        flow.set('mqtt_adapter_stats', {\n            ...previousStats,\n            received: (previousStats.received || 0) + 1,\n            [status]: (previousStats[status] || 0) + 1,\n            lastStatus: status,\n            lastMessage: message,\n            lastAt: new Date().toISOString()\n        });\n        const statusColors = {\n            buffered: 'green',\n            invalid: 'red',\n            paused: 'yellow',\n            unchanged: 'grey'\n        };\n        node.status({\n            fill: statusColors[status],\n            shape: status === 'buffered' ? 'dot' : 'ring',\n            text: message\n        });\n        return {\n            payload: {\n                source: 'MQTT',\n                status,\n                message,\n                ...details\n            },\n            _msgid: msg._msgid\n        };\n    }\n\n    // 2. 优先接收解析节点msg.dev,也支持直接传入JSON/Buffer。\n    let deviceReport = msg.dev;\n    if (!deviceReport || !deviceReport.items) {\n        let body = msg.payload;\n        if (Buffer.isBuffer(body)) body = body.toString('utf8');\n        if (typeof body === 'string') {\n            try {\n                body = JSON.parse(body);\n            } catch {\n                body = null;\n            }\n        }\n        if (body && typeof body === 'object' && !Array.isArray(body)) {\n            const topicParts = String(msg.topic || '').split('/').filter(Boolean);\n            deviceReport = {\n                cmd: body.cmd,\n                sn: body.sn || topicParts[2] || '',\n                cmdId: body.cmd_id,\n                items: body.items,\n                receivedAt: new Date(),\n                topic: msg.topic || ''\n            };\n            msg.dev = deviceReport;\n        }\n    }\n    for (const field of ['queryParams', 'query', 'queryMode', 'rows', 'retryBuf', 'collect', 'collectionRows', 'signalRecord']) delete msg[field];\n    const fields = deviceReport?.items;\n    if (deviceReport?.cmd !== 'signal_msg' || !fields || typeof fields !== 'object' || Array.isArray(fields)) {\n        const result = diagnostic('invalid', '不是有效 signal_msg 报文');\n        node.warn(result.payload.message);\n        return [null, result];\n    }\n    const machineId = fields.mach_id === null || fields.mach_id === undefined ? '' : String(fields.mach_id).trim();\n    if (!machineId) {\n        const result = diagnostic('invalid', '缺少 mach_id,未送入缓冲');\n        node.warn(result.payload.message);\n        return [null, result];\n    }\n    // const deviceCode = ((deviceReport.sn ? String(deviceReport.sn).trim() + '-' : '') + machineId).slice(0, 50);\n    const deviceCode = deviceReport.sn ? String(deviceReport.sn).trim() : ''\n    const sourceTime = parseDeviceTime(fields.time);\n    const receivedTime = new Date(deviceReport.receivedAt || Date.now());\n    const collectedAt = sourceTime || (Number.isFinite(receivedTime.getTime()) ? receivedTime : new Date());\n    const createdAt = new Date();\n    const parameterValues = {};\n    for (const mapping of fieldMappings) {\n        const value = collectedValue(fields[mapping.sourceField]);\n        if (value !== null) parameterValues[mapping.parameterName] = value;\n    }\n    const signal = numericValue(fields.signal);\n    if (signal !== null) {\n        parameterValues['信号值'] = collectedValue(fields.signal);\n        parameterValues['运行状态'] = (signal & 3) === 3 ? 1 : 3;\n    }\n\n    // 原报文保留作诊断;数值和文本采集参数统一写入HResult。\n    msg.signalRecord = {\n        设备编码: deviceCode,\n        机台号: machineId,\n        设备时间: fields.time || '',\n        采样时间: collectedAt.toISOString(),\n        时间来源: sourceTime ? '设备时间' : '接收时间',\n        信号: signal,\n        转速: numericValue(fields.rpm),\n        产量: numericValue(fields.produce),\n        效率: numericValue(fields.effect),\n        批号: fields.batch_number ?? null,\n        剩余经长: numericValue(fields.remain_length),\n        停机次数: numericValue(fields.stop_count),\n        停机时间: numericValue(fields.stop_time),\n        开机时间: numericValue(fields.boot_time),\n        运行时间: numericValue(fields.run_time),\n        轴号: fields.axis_id ?? null,\n        职员id: fields.worker_id ?? null,\n        职员名称: fields.worker_name ?? null,\n        品号: fields.variety_id ?? null\n    };\n    const collectionRows = Object.entries(parameterValues).map(([name, value]) => createCollectionRow('MQTT', deviceCode, name, value, collectedAt, createdAt));\n    const fieldCount = collectionRows.length;\n    if (!fieldCount) return [null, diagnostic('invalid', '无有效采集字段,未送入缓冲', {\n        device: deviceCode,\n        record: msg.signalRecord\n    })];\n\n    // 3. 暂停仍输出数据库字段预览,既不更新去重缓存,也不入队。\n    if (global.get('collection_paused') !== false) {\n        return [null, diagnostic('paused', '采集已暂停:已解析 ' + fieldCount + ' 项,未送入缓冲', {\n            device: deviceCode,\n            fields: fieldCount,\n            values: parameterValues,\n            record: msg.signalRecord,\n            collectionRows\n        })];\n    }\n\n    // 4. 按HResult判断变化;任一字段变化时送出本次报文的全部有效映射字段。\n    let previousValues = flow.get('mqtt_seen') || {};\n    let previousCount = flow.get('mqtt_seen_n') || 0;\n    if (previousCount > 50000) {\n        previousValues = {};\n        previousCount = 0;\n    }\n    const changedRows = [];\n    for (const row of collectionRows) {\n        const cacheKey = row.HSourceCode + '|' + row.HTechParamName;\n        if (previousValues[cacheKey] === row.HResult) continue;\n        if (!Object.prototype.hasOwnProperty.call(previousValues, cacheKey)) previousCount += 1;\n        previousValues[cacheKey] = row.HResult;\n        changedRows.push(row);\n    }\n    flow.set('mqtt_seen', previousValues);\n    flow.set('mqtt_seen_n', previousCount);\n    if (!changedRows.length) return [null, diagnostic('unchanged', '采集值无变化,未重复入缓冲', {\n        device: deviceCode,\n        fields: fieldCount,\n        record: msg.signalRecord\n    })];\n    msg.collectionRows = collectionRows;\n    msg.payload = collectionRows;\n    const result = diagnostic('buffered', '变化 ' + changedRows.length + ' 项 / 全量入缓冲 ' + fieldCount + ' 项', {\n        device: deviceCode,\n        fields: fieldCount,\n        changed: changedRows.length,\n        values: Object.fromEntries(collectionRows.map(row => [row.HTechParamName, row.HResult])),\n        record: msg.signalRecord,\n        collectionRows\n    });\n    return [msg, result];\n}\nreturn normalizeMqttReport(msg, flow, global, node);\n",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 860,
        "y": 420,
        "wires": [
            [
                "08c95ee2bd3a9073",
                "90d43ad76fa8926f"
            ]
        ]
    },
    {
        "id": "90d43ad76fa8926f",
        "type": "debug",
        "z": "cee834492540f06e",
        "name": "MQTT 标准化结果",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 1150,
        "y": 320,
        "wires": []
    },
    {
        "id": "cm_collector_note",
        "type": "comment",
        "z": "tab_collector_mqtt",
        "name": "采集写库已迁至「MQTT · 采集入库(独立)」页签",
        "info": "本页签职责:\n1) /cmd 指令 → 指令分类 → 开班/停机/结班 HTTP 请求;\n2) 设备业务动作(员工上班/落布/了机…)→ 确认回执。\n\n采集与写库:/report 上报的 signal_msg 已由独立页签「MQTT · 采集入库(独立)」完整接管(解析 → 标准化 → 独立缓冲 → 每5s Bulk 写 dbo.Sb_EquipMentCollectionTechParam_Temp)。\n\n若需彻底停用本页签的 /report 订阅,可删除节点「设备上报 /report/#」,回执走 /cmd 不受影响。",
        "x": 280,
        "y": 60,
        "wires": []
    },
    {
        "id": "in_report",
        "type": "mqtt in",
        "z": "tab_collector_mqtt",
        "name": "设备上报 /report/#",
        "topic": "/report/#",
        "qos": "1",
        "datatype": "json",
        "broker": "mqtt_broker_local",
        "nl": false,
        "rap": true,
        "rh": 0,
        "inputs": 0,
        "x": 190,
        "y": 120,
        "wires": [
            [
                "fn_parse"
            ]
        ]
    },
    {
        "id": "in_cmd",
        "type": "mqtt in",
        "z": "tab_collector_mqtt",
        "name": "兼容 /cmd/#  确认是否是文档笔误",
        "topic": "/cmd/#",
        "qos": "1",
        "datatype": "json",
        "broker": "mqtt_broker_local",
        "nl": false,
        "rap": true,
        "rh": 0,
        "inputs": 0,
        "x": 150,
        "y": 200,
        "wires": [
            [
                "fn_parse"
            ]
        ]
    },
    {
        "id": "fn_parse",
        "type": "function",
        "z": "tab_collector_mqtt",
        "name": "解析设备报文",
        "func": "/**\n * MQTT协议解析\n * 输入:原始msg.payload和msg.topic\n * 输出:msg.dev;msg.flowType供Switch分流\n * 上下文:不写数据库/缓冲\n */\n// 采集器报文解析:/report/**(设备上报)与 /cmd/**(文档里把 了机/机修/采集数据 误写成 /cmd,两条都订阅)\nconst RECEIPT = {\n  worker_register_msg: '员工上班',\n  worker_report_msg: '员工下班',\n  axis_start_msg: '上轴',\n  variety_change_msg: '改品',\n  fall_cloth_msg: '落布',\n  axis_end_msg: '了机',\n  repair_msg: '机修'\n};\nconst SIGNAL_CMD = 'signal_msg';\nlet body = msg.payload;\nif (Buffer.isBuffer(body)) {\n  body = body.toString('utf8');\n}\nif (typeof body === 'string') {\n  try {\n    body = JSON.parse(body);\n  } catch (e) {\n    node.warn('非 JSON 报文,已丢弃:' + msg.topic);\n    return null;\n  }\n}\nif (!body || typeof body !== 'object') {\n  node.warn('空报文,已丢弃:' + msg.topic);\n  return null;\n}\nconst topic = msg.topic || '';\nconst seg = topic.split('/').filter(function (s) {\n  return s !== '';\n});\nconst dir = seg[0] || ''; // report | cmd\nconst kind = seg[1] || ''; // woven 梭织 | round 圆机\nconst sn = String(body.sn || seg[2] || '');\nconst cmd = String(body.cmd || '');\nconst cmdId = body.cmd_id === undefined || body.cmd_id === null ? '' : String(body.cmd_id);\nconst items = body.items && typeof body.items === 'object' ? body.items : {};\n\n// 丢弃本机发出的确认回执(订阅 /cmd/# 时 MQTT 会把我们自己的回执回显回来)\n// 回执只有 mach_id(落布再加 cloth_id),没有 time;设备上报必然带 time\nif (dir === 'cmd' && (items.time === undefined || Object.keys(items).length < 2)) {\n  node.status({\n    fill: 'grey',\n    shape: 'ring',\n    text: '回执回显,忽略'\n  });\n  return null;\n}\nmsg.flowType = RECEIPT[cmd] ? 'confirm' : cmd === SIGNAL_CMD ? 'signal' : 'unknown';\nmsg.dev = {\n  dir: dir,\n  kind: kind || 'woven',\n  sn: sn,\n  cmd: cmd,\n  cmdId: cmdId,\n  items: items,\n  label: RECEIPT[cmd] || (cmd === SIGNAL_CMD ? '采集数据上报' : cmd || '(缺少 cmd)'),\n  topic: topic,\n  receivedAt: new Date()\n};\nnode.status({\n  fill: 'blue',\n  shape: 'dot',\n  text: msg.dev.label\n});\n\nmsg.cmd = cmd\nreturn msg;\n",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 400,
        "y": 160,
        "wires": [
            [
                "sw_type",
                "8a19a552dffdf1e1"
            ]
        ]
    },
    {
        "id": "sw_type",
        "type": "switch",
        "z": "tab_collector_mqtt",
        "name": "按消息类型分流",
        "property": "flowType",
        "propertyType": "msg",
        "rules": [
            {
                "t": "eq",
                "v": "confirm",
                "vt": "str"
            },
            {
                "t": "eq",
                "v": "signal",
                "vt": "str"
            },
            {
                "t": "else"
            }
        ],
        "checkall": "true",
        "repair": false,
        "outputs": 3,
        "x": 610,
        "y": 160,
        "wires": [
            [
                "fn_confirm"
            ],
            [
                "dbg_signal",
                "223b29559f4a36ae"
            ],
            [
                "dbg_unknown"
            ]
        ]
    },
    {
        "id": "fn_confirm",
        "type": "function",
        "z": "tab_collector_mqtt",
        "name": "生成确认回执",
        "func": "/**\n * MQTT业务确认回执\n * 输入:msg.dev=已解析业务报文\n * 输出:输出1=诊断;输出2=MQTT确认消息\n * 上下文:不写采集缓冲;signal_msg不走此节点\n */\n// 七类需要回执的消息:输出 1 = 调试窗口记录,输出 2 = 回执报文\nconst d = msg.dev || {};\nconst it = d.items || {};\n\n// 落布要给服务器生成(这里给设备)的布匹号,纯数字\nfunction clothIdOf() {\n  const dev = it.cloth_id_dev;\n  if (dev !== undefined && dev !== null && /^\\d+$/.test(String(dev).trim())) {\n    return String(dev).trim();\n  }\n  // 兜底:用毫秒时间戳后 9 位,保证纯数字且基本不重复;正式环境建议换成数据库序列\n  return String(Date.now()).slice(-9);\n}\nconst ackItems = {\n  mach_id: it.mach_id === undefined ? '' : String(it.mach_id)\n};\nlet clothId = null;\nif (d.cmd === 'fall_cloth_msg') {\n  clothId = clothIdOf();\n  ackItems.cloth_id = clothId;\n}\nconst record = {\n  '消息': d.label,\n  'cmd': d.cmd,\n  'cmd_id': d.cmdId,\n  '设备SN': d.sn,\n  '机台号': ackItems.mach_id,\n  '时间': it.time || '',\n  '主题': d.topic,\n  '字段': it\n};\nif (clothId) {\n  record['回执cloth_id'] = clothId;\n}\nconst ack = {\n  cmd: d.cmd,\n  sn: d.sn,\n  cmd_id: d.cmdId,\n  items: ackItems\n};\nconst ackMsg = {\n  topic: '/cmd/' + (d.kind || 'woven') + '/' + d.sn,\n  payload: JSON.stringify(ack),\n  qos: 1,\n  retain: false\n};\nnode.status({\n  fill: 'green',\n  shape: 'dot',\n  text: d.label + ' 已确认'\n});\nreturn [{\n  payload: record,\n  _msgid: msg._msgid\n}, ackMsg];\n",
        "outputs": 2,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 830,
        "y": 120,
        "wires": [
            [
                "dbg_record"
            ],
            [
                "mqtt_out_ack"
            ]
        ]
    },
    {
        "id": "dbg_record",
        "type": "debug",
        "z": "tab_collector_mqtt",
        "name": "设备消息(调试窗口)",
        "active": false,
        "tosidebar": true,
        "console": true,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 1090,
        "y": 80,
        "wires": []
    },
    {
        "id": "mqtt_out_ack",
        "type": "mqtt out",
        "z": "tab_collector_mqtt",
        "name": "回复确认消息",
        "topic": "",
        "qos": "1",
        "retain": "false",
        "respTopic": "",
        "contentType": "",
        "userProps": "",
        "correl": "",
        "expiry": "",
        "broker": "mqtt_broker_local",
        "x": 1060,
        "y": 120,
        "wires": []
    },
    {
        "id": "dbg_unknown",
        "type": "debug",
        "z": "tab_collector_mqtt",
        "name": "未识别消息(调试窗口)",
        "active": false,
        "tosidebar": true,
        "console": true,
        "tostatus": false,
        "complete": "true",
        "targetType": "full",
        "statusVal": "",
        "statusType": "auto",
        "x": 860,
        "y": 320,
        "wires": []
    },
    {
        "id": "dbg_error",
        "type": "debug",
        "z": "tab_collector_mqtt",
        "name": "异常(调试窗口)",
        "active": false,
        "tosidebar": true,
        "console": true,
        "tostatus": false,
        "complete": "true",
        "targetType": "full",
        "statusVal": "",
        "statusType": "auto",
        "x": 880,
        "y": 380,
        "wires": []
    },
    {
        "id": "dbg_signal",
        "type": "debug",
        "z": "tab_collector_mqtt",
        "name": "采集原始字段(调试窗口)",
        "active": false,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "dev.items",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 1100,
        "y": 180,
        "wires": []
    },
    {
        "id": "coll_catch",
        "type": "catch",
        "z": "tab_collector_mqtt",
        "name": "采集器 · 异常",
        "scope": null,
        "uncaught": false,
        "x": 650,
        "y": 380,
        "wires": [
            [
                "dbg_error"
            ]
        ]
    },
    {
        "id": "collection_mqtt_control_out",
        "type": "link out",
        "z": "tab_collector_mqtt",
        "name": "→ 采集总开关(全部流程)",
        "mode": "link",
        "links": [
            "collection_control_link_in"
        ],
        "x": 490,
        "y": 310,
        "wires": []
    },
    {
        "id": "collection_mqtt_pause",
        "type": "inject",
        "z": "tab_collector_mqtt",
        "name": "⏸ 暂停全部采集/写库",
        "props": [
            {
                "p": "payload",
                "v": "true",
                "vt": "bool"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "x": 180,
        "y": 280,
        "wires": [
            [
                "collection_mqtt_control_out"
            ]
        ]
    },
    {
        "id": "collection_mqtt_resume",
        "type": "inject",
        "z": "tab_collector_mqtt",
        "name": "▶ 恢复全部采集/写库",
        "props": [
            {
                "p": "payload",
                "v": "false",
                "vt": "bool"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "x": 180,
        "y": 340,
        "wires": [
            [
                "collection_mqtt_control_out"
            ]
        ]
    },
    {
        "id": "2a9b70e492406c99",
        "type": "switch",
        "z": "tab_collector_mqtt",
        "name": "按照指令类型分流",
        "property": "cmdType",
        "propertyType": "msg",
        "rules": [
            {
                "t": "eq",
                "v": "workbegin",
                "vt": "str"
            },
            {
                "t": "eq",
                "v": "workstop",
                "vt": "str"
            },
            {
                "t": "eq",
                "v": "workend",
                "vt": "str"
            },
            {
                "t": "eq",
                "v": "unknow",
                "vt": "str"
            }
        ],
        "checkall": "true",
        "repair": false,
        "outputs": 4,
        "x": 790,
        "y": 500,
        "wires": [
            [
                "746212d2b24dee79"
            ],
            [
                "0d55791095dd9798"
            ],
            [
                "b1f55cf02a6874d6"
            ],
            [
                "969b330c32c6d99b"
            ]
        ]
    },
    {
        "id": "129964fd2e838f95",
        "type": "http request",
        "z": "tab_collector_mqtt",
        "name": "指令 生成开班单",
        "method": "POST",
        "ret": "obj",
        "paytoqs": "ignore",
        "url": "http://localhost:81/API/Sc_MESBeginWorkBill/SaveGetMESBeginWorkFrom",
        "tls": "",
        "persist": false,
        "proxy": "",
        "insecureHTTPParser": false,
        "authType": "",
        "senderr": false,
        "headers": [],
        "x": 1260,
        "y": 420,
        "wires": [
            [
                "b95821d0ecf31b06"
            ]
        ]
    },
    {
        "id": "b95821d0ecf31b06",
        "type": "debug",
        "z": "tab_collector_mqtt",
        "name": "开班单 返回结果",
        "active": true,
        "tosidebar": true,
        "console": true,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 1450,
        "y": 420,
        "wires": []
    },
    {
        "id": "8a19a552dffdf1e1",
        "type": "function",
        "z": "tab_collector_mqtt",
        "name": "指令分类",
        "func": "let msgType = 'unknow';\nlet cmd = flow.get(\"cmd\")\n// 根据命令传输的类型区分需要生成单据的类型\n\nif (cmd == 'worker_register_msg') {\n    // 员工上班 生成开班单(暂定)\n    msg.msgType = 'workbegin'\n}\nelse if(cmd == 'axis_start_msg'\n|| cmd =='fall_cloth_msg'\n|| cmd == 'axis_end_msg'\n|| cmd == 'repair_msg'\n|| cmd == 'variety_change_msg') {\n  // 设备停机操作 需生成停机单\n  msg.msgType = 'workstop'\n}\nelse if (cmd == 'worker_report_msg') {\n  // 员工下班,生成结班单\n  msg.msgType = 'workend'\n}\nelse {\n  msg.msgType = 'unknow'\n}\n\nreturn msg;",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 600,
        "y": 500,
        "wires": [
            [
                "2a9b70e492406c99"
            ]
        ]
    },
    {
        "id": "969b330c32c6d99b",
        "type": "debug",
        "z": "tab_collector_mqtt",
        "name": "异常指令",
        "active": true,
        "tosidebar": true,
        "console": true,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 1370,
        "y": 540,
        "wires": []
    },
    {
        "id": "22db5d23f5f3b117",
        "type": "http request",
        "z": "tab_collector_mqtt",
        "name": "指令生成 异常反馈请求单",
        "method": "GET",
        "ret": "obj",
        "paytoqs": "ignore",
        "url": "",
        "tls": "",
        "persist": false,
        "proxy": "",
        "insecureHTTPParser": false,
        "authType": "",
        "senderr": false,
        "headers": [],
        "x": 1290,
        "y": 460,
        "wires": [
            [
                "89d8213271967cf2"
            ]
        ]
    },
    {
        "id": "89d8213271967cf2",
        "type": "debug",
        "z": "tab_collector_mqtt",
        "name": "异常反馈 返回结果",
        "active": true,
        "tosidebar": true,
        "console": true,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 1520,
        "y": 460,
        "wires": []
    },
    {
        "id": "5b954fff423a59e1",
        "type": "http request",
        "z": "tab_collector_mqtt",
        "name": "指令 生成结班单",
        "method": "GET",
        "ret": "txt",
        "paytoqs": "ignore",
        "url": "",
        "tls": "",
        "persist": false,
        "proxy": "",
        "insecureHTTPParser": false,
        "authType": "",
        "senderr": false,
        "headers": [],
        "x": 1260,
        "y": 500,
        "wires": [
            [
                "6593cb6999b49bf4"
            ]
        ]
    },
    {
        "id": "6593cb6999b49bf4",
        "type": "debug",
        "z": "tab_collector_mqtt",
        "name": "结班单 返回状态",
        "active": true,
        "tosidebar": true,
        "console": true,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 1450,
        "y": 500,
        "wires": []
    },
    {
        "id": "223b29559f4a36ae",
        "type": "link out",
        "z": "tab_collector_mqtt",
        "name": "→ 原始采集报文(主流程统一转换)",
        "mode": "link",
        "links": [
            "c06152e6ab227d0b"
        ],
        "x": 995,
        "y": 220,
        "wires": []
    },
    {
        "id": "746212d2b24dee79",
        "type": "function",
        "z": "tab_collector_mqtt",
        "name": "生成开班单负载",
        "func": "// 开班单标准结构\n//{\"HInterID\":0,\"HBillNo\":\"SCKG000000001334\",\"HDate\":\"{{ 填写 当前时间 年-月-日 时:分:秒 }}\",\"HMainSourceBillNo\":\"\",\n//\"HMainSourceInterID\":0,\"HMainSourceEntryID\":1,\"HProcExchBillNo\":\"\",\"HProcExchInterID\":0,\n//\"HProcExchEntryID\":1,\"HMainSourceBillType\":\"-1\",\"HICMOBillNo\":\"\",\"HICMOInterID\":0,\"HICMOEntryID\":1,\n//\"HSourceName\":\"\",\"HSourceID\":{{ 填写mach_id }},\"HProcName\":\"\",\"HProcID\":0,\"HMaterNumber\":\"\",\n//\"HMaterCode\":\"\",\"HMaterName\":\"\",\"HMaterSpec\":\"\",\"HMaterID\":0,\n//\"HBeginWorkTime\":\"{{ 填写 当前时间 年-月-日 时:分:秒 }}\",\"HGroupName\":\"\",\"HGroupID\":0,\"HEmpName\":\"{{ 填写worker_name }}\",\n//\"HEmpID\":{{ 填写worker_id }},\"HDeptName\":\"\",\"HDeptID\":0,\"HWorkShiftName\":\"\",\"HWorkShiftID\":0,\n//\"SourceType\":\"1\",\"HPeopleSum\":1,\"HMaker\":\"admin\",\"HMakeDate\":\"{{ 填写 当前时间 年-月-日 时:分:秒 }}\",\n//\"HUpDater\":\"\",\"HUpDateDate\":\"\",\"HChecker\":\"\",\"HCheckDate\":\"\",\"HCloseMan\":\"\",\"HDeleteMan\":\"\",\n//\"HCloseDate\":\"\",\"HDeleteDate\":\"\"};[{\"HMaterID\":\"0\",\"HMaterName\":\"\",\"HProcID\":\"0\",\"HProcName\":\"\",\n//\"HRelationBillInterID\":\"0\",\"HRelationBillEntryID\":\"0\",\"HRelationBillType\":\"\",\"HRelationBillNo\":\"\",\n//\"HICMOInterID\":\"0\",\"HICMOEntryID\":\"0\",\"HICMOBillNo\":\"\",\"HProcExchInterID\":\"0\",\"HProcExchEntryID\":\"0\",\n//\"HProcExchBillNo\":\"\",\"HRemark\":\"\",\"HSourceInterID\":\"0\",\"HSourceEntryID\":\"0\",\"HSourceBillNo\":\"\",\"HSourceBillType\":\"\",\n//\"LAY_TABLE_INDEX\":0}];admin;Add\n\n\nreturn msg;",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 1020,
        "y": 420,
        "wires": [
            [
                "129964fd2e838f95",
                "4f16c5c0b639cbda"
            ]
        ]
    },
    {
        "id": "0d55791095dd9798",
        "type": "function",
        "z": "tab_collector_mqtt",
        "name": "生成异常反馈单负载",
        "func": "\nreturn msg;",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 1040,
        "y": 460,
        "wires": [
            [
                "22db5d23f5f3b117",
                "4f16c5c0b639cbda"
            ]
        ]
    },
    {
        "id": "b1f55cf02a6874d6",
        "type": "function",
        "z": "tab_collector_mqtt",
        "name": "生成结班单负载",
        "func": "\nreturn msg;",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 1020,
        "y": 500,
        "wires": [
            [
                "5b954fff423a59e1",
                "4f16c5c0b639cbda"
            ]
        ]
    },
    {
        "id": "4f16c5c0b639cbda",
        "type": "debug",
        "z": "tab_collector_mqtt",
        "name": "查看 生成单据负载",
        "active": true,
        "tosidebar": true,
        "console": true,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 1400,
        "y": 600,
        "wires": []
    },
    {
        "id": "e9a1290762230e06",
        "type": "inject",
        "z": "yy_multi_collect",
        "name": "每10s · 六路采集/失败重试",
        "props": [],
        "repeat": "10",
        "crontab": "",
        "once": true,
        "onceDelay": 3,
        "topic": "",
        "x": 170,
        "y": 140,
        "wires": [
            [
                "fn_yy_q"
            ]
        ]
    },
    {
        "id": "c3e4894ab572dc51",
        "type": "MSSQL",
        "z": "yy_multi_collect",
        "mssqlCN": "04dfbd6bd2067336",
        "name": "用友 · 集合分表/字典查询",
        "outField": "payload",
        "returnType": "0",
        "throwErrors": "1",
        "query": "",
        "modeOpt": "",
        "modeOptType": "query",
        "queryOpt": "query",
        "queryOptType": "msg",
        "paramsOpt": "queryParams",
        "paramsOptType": "msg",
        "rows": "rows",
        "rowsType": "msg",
        "parseMustache": false,
        "params": [],
        "x": 770,
        "y": 100,
        "wires": [
            [
                "ff402f329edcf253"
            ]
        ]
    },
    {
        "id": "ff402f329edcf253",
        "type": "function",
        "z": "yy_multi_collect",
        "name": "用友 · 字典映射为数据库字段",
        "func": "/**\n * 用友字典映射标准化\n * 输入:SQL结果;msg.yySync\n * 输出:输出1=msg.collectionRows;输出2=继续调度\n * 上下文:yy_multi.pending/seen/stats;此处不提前提交写库水位\n */\n// 可维护字典:源字段、目标参数、倍率、单位。分钟转秒的倍率为60。\nconst config = {\n  \"stateMap\": {\n    \"1\": 5,\n    \"2\": 1,\n    \"3\": 3,\n    \"4\": 3,\n    \"5\": 3,\n    \"6\": 3\n  },\n  \"production\": [{\n    \"sourceField\": \"WorkNums\",\n    \"parameterName\": \"班次产量\",\n    \"scale\": 1,\n    \"unit\": \"output\"\n  }, {\n    \"sourceField\": \"ClothWorkNums\",\n    \"parameterName\": \"当前匹已生产长度\",\n    \"scale\": 1,\n    \"unit\": \"metres\"\n  }, {\n    \"sourceField\": \"ProductNums\",\n    \"parameterName\": \"班次生产计数\",\n    \"scale\": 1\n  }, {\n    \"sourceField\": \"StopNums\",\n    \"parameterName\": \"班次停机次数\",\n    \"scale\": 1\n  }, {\n    \"sourceField\": \"OpenLong\",\n    \"parameterName\": \"班次开机时间(秒)\",\n    \"scale\": 60\n  }, {\n    \"sourceField\": \"WorkLong\",\n    \"parameterName\": \"班次运行时间(秒)\",\n    \"scale\": 60\n  }, {\n    \"sourceField\": \"StopLong\",\n    \"parameterName\": \"班次停机时间(秒)\",\n    \"scale\": 60\n  }, {\n    \"sourceField\": \"OffLong\",\n    \"parameterName\": \"班次离线时间(秒)\",\n    \"scale\": 60\n  }, {\n    \"sourceField\": \"ZhouTimeLong\",\n    \"parameterName\": \"班次上轴时间(秒)\",\n    \"scale\": 60\n  }, {\n    \"sourceField\": \"ShaTimeLong\",\n    \"parameterName\": \"班次穿纱时间(秒)\",\n    \"scale\": 60\n  }, {\n    \"sourceField\": \"RepairTimeLong\",\n    \"parameterName\": \"班次机修时间(秒)\",\n    \"scale\": 60\n  }],\n  \"event\": [{\n    \"sourceField\": \"ClassOutPut\",\n    \"parameterName\": \"本班产量\",\n    \"scale\": 1,\n    \"unit\": \"output\"\n  }, {\n    \"sourceField\": \"ClothOutPut\",\n    \"parameterName\": \"当前匹已生产长度\",\n    \"scale\": 1,\n    \"unit\": \"metres\"\n  }],\n  \"plan\": [{\n    \"sourceField\": \"NeedClothNums\",\n    \"parameterName\": \"订单匹数\",\n    \"scale\": 1\n  }, {\n    \"sourceField\": \"FinishCloth\",\n    \"parameterName\": \"已生产匹数\",\n    \"scale\": 1\n  }, {\n    \"sourceField\": \"RealNums\",\n    \"parameterName\": \"计划累计产量\",\n    \"scale\": 1,\n    \"unit\": \"output\"\n  }, {\n    \"sourceField\": \"FinishNums\",\n    \"parameterName\": \"计划目标产量\",\n    \"scale\": 1,\n    \"unit\": \"output\"\n  }]\n};\nfunction localTime(date) {\n  const d = new Date(date);\n  if (!Number.isFinite(d.getTime())) return null;\n  const p = n => String(n).padStart(2, '0');\n  return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes()) + ':' + p(d.getSeconds()) + '.' + String(d.getMilliseconds()).padStart(3, '0');\n}\nfunction parseTableCatalog(rows) {\n  const roots = {\n      speed: 'MachineSpeedInfo',\n      state: 'MachineTimeLine',\n      production: 'PWorkRecordDetail'\n    },\n    tables = {\n      speed: [],\n      state: [],\n      production: []\n    };\n  let bootstrap = null;\n  for (const r of rows) {\n    if (r.BootstrapSpeed) bootstrap = localTime(r.BootstrapSpeed);\n    for (const [k, root] of Object.entries(roots)) {\n      if (typeof r.TableName === 'string' && new RegExp('^' + root + '[12]\\\\d{3}(0[1-9]|1[0-2])$').test(r.TableName)) tables[k].push(r.TableName);\n    }\n  }\n  for (const k of Object.keys(tables)) tables[k] = [...new Set(tables[k])].sort();\n  return {\n    tables,\n    bootstrap\n  };\n}\nfunction canonicalParameterName(parameterName) {\n  const aliases = {\n    '转速': '机器转速',\n    '班次平均车速': '班次平均转速',\n    '本班产量': '班次产量(源单位)',\n    '本班效率': '班次效率(%)',\n    '本班停机次数': '班次停机次数',\n    '本班停机时间(秒)': '班次停机时间(秒)',\n    '本匹产量': '本匹产量(源单位)'\n  };\n  const name = String(parameterName);\n  // 用友事件里的本班产量附有实际单位,沿用同一班次产量名称。\n  const withUnit = /^本班产量\\((.+)\\)$/.exec(name);\n  if (withUnit) return '班次产量(' + withUnit[1] + ')';\n  return aliases[name] || name;\n}\nfunction createCollectionRow(source, deviceCode, parameterName, value, collectedAt, createdAt) {\n  const amount = Math.round(Number(value) * 100) / 100;\n  return {\n    HItemID: null,\n    // SQL Server 自增,Bulk 不传此列\n    HDate: new Date(collectedAt),\n    // 采样时间/源设备时间\n    HSourceCode: String(deviceCode).slice(0, 50),\n    HTechParamID: 0,\n    // 沿用现有目标表约定\n    HTechParamName: canonicalParameterName(parameterName).slice(0, 500),\n    HCount: amount,\n    // SQL decimal(18,2)\n    HCreateTime: new Date(createdAt),\n    // 标准化创建时间;重试保持不变\n    HResult: String(amount).slice(0, 50),\n    HProcNumber: String(source).slice(0, 50),\n    // WY / YY / MQTT\n    HFlag: 0\n  };\n}\nfunction collectionRowKey(row) {\n  // 保留原有自然键编码,兼容旧待确认批次的 doneKeys。\n  return row.HProcNumber + '|' + row.HSourceCode + '|' + row.HTechParamName + '|' + new Date(row.HDate).getTime();\n}\nfunction mapYouyangSourceRows(stream, sourceRows, previousSignatures) {\n  const collectionRows = [];\n  const nextSeen = {};\n  const createdAt = new Date();\n  let cursor = null;\n  let unknownStates = 0;\n  function addParameter(sourceRow, parameterName, value, collectedAt = sourceRow.RowTime) {\n    if (value === null || value === undefined || value === '' || !Number.isFinite(Number(value))) return;\n    const date = new Date(collectedAt);\n    if (!Number.isFinite(date.getTime())) return;\n    const deviceCode = 'YY-' + String(sourceRow.MachineID).padStart(2, '0');\n    collectionRows.push(createCollectionRow('YY', deviceCode, parameterName, value, date, createdAt));\n  }\n  function addMappedParameters(sourceRow, fieldMappings, namePrefix = '') {\n    const outputUnit = String(sourceRow.OutPutUnit || '').trim();\n    for (const mapping of fieldMappings) {\n      // 五洋“当前匹已生产长度”口径为米;源单位不明或为公斤时不强行映射。\n      if (mapping.unit === 'metres' && !/^(米|m|M|meter|metre)$/.test(outputUnit)) continue;\n      let parameterName = namePrefix + mapping.parameterName;\n      if (mapping.unit === 'output') parameterName += '(' + (outputUnit || '源单位') + ')';\n      const sourceValue = sourceRow[mapping.sourceField];\n      const value = sourceValue === null || sourceValue === undefined ? null : Number(sourceValue) * mapping.scale;\n      addParameter(sourceRow, parameterName, value);\n    }\n  }\n  for (const sourceRow of sourceRows) {\n    const collectedAt = localTime(sourceRow.RowTime);\n    if (!collectedAt || sourceRow.MachineID === null || sourceRow.MachineID === undefined) {\n      throw new Error('无效设备或采集时间,停止推进增量水位');\n    }\n    cursor = {\n      time: collectedAt,\n      table: sourceRow.SourceTable,\n      id: sourceRow.id\n    };\n    if (stream === 'speed') {\n      addParameter(sourceRow, '机器转速', sourceRow.SpeedValue);\n    } else if (stream === 'state') {\n      const stateCode = config.stateMap[String(sourceRow.MainType)];\n      if (stateCode === undefined) {\n        unknownStates += 1;\n        addParameter(sourceRow, '悠扬原始状态码', sourceRow.MainType);\n      } else addParameter(sourceRow, '运行状态', stateCode);\n    } else if (stream === 'production') {\n      addMappedParameters(sourceRow, config.production);\n      if (Number(sourceRow.OpenLong) > 0 && sourceRow.WorkLong !== null && sourceRow.WorkLong !== undefined) {\n        addParameter(sourceRow, '班次运行效率(%)', Number(sourceRow.WorkLong) / Number(sourceRow.OpenLong) * 100);\n      }\n    } else if (stream === 'event') {\n      addMappedParameters(sourceRow, config.event);\n    } else if (stream === 'snapshot' || stream === 'plan') {\n      const signatureKey = stream + '|' + sourceRow.FactoryID + '|' + sourceRow.MachineID + '|' + (sourceRow.PlanID || sourceRow.id);\n      const stableFields = Object.fromEntries(Object.entries(sourceRow).filter(([name]) => name !== 'RowTime'));\n      const signature = JSON.stringify(stableFields);\n      nextSeen[signatureKey] = signature;\n      if (previousSignatures[signatureKey] === signature) continue;\n      if (stream === 'snapshot') {\n        const currentMappings = config.production.filter(mapping => !['ProductNums', 'ClothWorkNums'].includes(mapping.sourceField));\n        addMappedParameters(sourceRow, currentMappings, '当前');\n        addMappedParameters(sourceRow, config.production.filter(mapping => mapping.sourceField === 'ClothWorkNums'));\n        const stateCode = config.stateMap[String(sourceRow.WorkState)];\n        if (stateCode !== undefined && sourceRow.StateLastUpdate) {\n          addParameter(sourceRow, '运行状态', stateCode, sourceRow.StateLastUpdate);\n        }\n      } else addMappedParameters(sourceRow, config.plan);\n    }\n  }\n  const uniqueRows = new Map();\n  for (const row of collectionRows) uniqueRows.set(collectionRowKey(row), row);\n  return {\n    collectionRows: Array.from(uniqueRows.values()),\n    cursor,\n    nextSeen,\n    unknownStates\n  };\n}\nfunction normalizeYouyangQueryResult(msg, flow, global, node) {\n  const state = flow.get('yy_multi');\n  const batchMeta = msg.yySync;\n  if (!state || !batchMeta) return null;\n  if (batchMeta.stream === 'catalog') {\n    if (state.sourceBusy?.batchId !== batchMeta.batchId) return null;\n    const catalog = parseTableCatalog(Array.isArray(msg.payload) ? msg.payload : []);\n    state.catalog = {\n      ...catalog,\n      at: Date.now(),\n      month: localTime(new Date()).slice(0, 7),\n      from: state.from\n    };\n    if (!state.manualBackfill && !state.cursors.speed && catalog.bootstrap && catalog.bootstrap > state.from) {\n      state.cursors.speed = {\n        time: catalog.bootstrap,\n        table: '',\n        id: 0\n      };\n    }\n    delete state.sourceBusy;\n    flow.set('yy_multi', state);\n    return [null, {\n      yyDrain: true\n    }];\n  }\n  const pending = state.pending[batchMeta.stream];\n  if (pending?.batchId !== batchMeta.batchId) return null;\n  const sourceRows = Array.isArray(msg.payload) ? msg.payload : [];\n  const result = mapYouyangSourceRows(batchMeta.stream, sourceRows, state.seen[batchMeta.stream] || {});\n  pending.cursor = result.cursor;\n  pending.nextSeen = result.nextSeen;\n  delete state.sourceBusy;\n  state.stats[batchMeta.stream] = {\n    ...(state.stats[batchMeta.stream] || {}),\n    read: sourceRows.length,\n    candidates: result.collectionRows.length,\n    lastQuery: new Date().toISOString()\n  };\n  if (result.unknownStates) node.warn(batchMeta.stream + ' 含未识别状态,保留原始状态码');\n  if (!result.collectionRows.length) {\n    if (result.cursor && !['snapshot', 'plan'].includes(batchMeta.stream)) state.cursors[batchMeta.stream] = result.cursor;\n    if (['snapshot', 'plan'].includes(batchMeta.stream)) state.seen[batchMeta.stream] = result.nextSeen;\n    delete state.pending[batchMeta.stream];\n    flow.set('yy_multi', state);\n    return [null, {\n      yyDrain: true\n    }];\n  }\n  const output = {\n    collectionRows: result.collectionRows,\n    payload: result.collectionRows,\n    yySync: {\n      ...batchMeta,\n      phase: 'buffer',\n      count: result.collectionRows.length\n    }\n  };\n  pending.write = output;\n  pending.stage = 'buffer';\n  pending.count = result.collectionRows.length;\n  pending.retryAt = Date.now() + 10000;\n  flow.set('yy_multi', state);\n  node.status({\n    fill: 'blue',\n    shape: 'dot',\n    text: batchMeta.stream + ' ' + sourceRows.length + '行 → 缓冲 ' + result.collectionRows.length + '项'\n  });\n  return [output, null];\n}\nreturn normalizeYouyangQueryResult(msg, flow, global, node);\n",
        "outputs": 2,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 1060,
        "y": 120,
        "wires": [
            [
                "yy_data_out"
            ],
            [
                "fn_yy_q"
            ]
        ]
    },
    {
        "id": "fn_yy_q",
        "type": "function",
        "z": "yy_multi_collect",
        "name": "集合查询调度 · 分表缓存/增量水位",
        "func": "/**\n * 用友分路调度\n * 输入:10秒触发或msg.yyDrain;旧待确认批次兼容\n * 输出:输出1=串行源查询;输出2=尚未入队原批重投\n * 上下文:yy_multi:from/catalog/cursors/pending/sourceBusy/queue\n */\n// 调度配置;字段映射集中在下游“用友 · 字典映射为数据库字段”节点。\nconst config = {\n  \"lookbackDays\": 30,\n  \"batchRows\": 400,\n  \"pollSeconds\": 10\n};\nfunction localTime(date) {\n  const d = new Date(date);\n  if (!Number.isFinite(d.getTime())) return null;\n  const p = n => String(n).padStart(2, '0');\n  return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes()) + ':' + p(d.getSeconds()) + '.' + String(d.getMilliseconds()).padStart(3, '0');\n}\nfunction buildCatalogQuery(from, bootstrap) {\n  return {\n    query: `SET NOCOUNT ON;\nDECLARE @from datetime=CONVERT(datetime,@fromText,121),@speed datetime;\nIF @bootstrap=1 SELECT @speed=MAX(HDate) FROM HX_LMESsys.dbo.Sb_EquipMentCollectionTechParam_Temp WHERE HProcNumber='YY' AND HTechParamName='机器转速' AND HDate>=@from;\nSELECT t.name AS TableName,@speed AS BootstrapSpeed FROM sys.tables t JOIN sys.schemas s ON s.schema_id=t.schema_id\nWHERE s.name='dbo' AND (t.name LIKE 'MachineSpeedInfo[12][0-9][0-9][0-9][01][0-9]' OR t.name LIKE 'MachineTimeLine[12][0-9][0-9][0-9][01][0-9]' OR t.name LIKE 'PWorkRecordDetail[12][0-9][0-9][0-9][01][0-9]')\nAND RIGHT(t.name,2) BETWEEN '01' AND '12'\nAND RIGHT(t.name,6)>=CONVERT(char(6),DATEADD(month,-1,@from),112) AND RIGHT(t.name,6)<=CONVERT(char(6),GETDATE(),112)\nUNION ALL SELECT NULL,@speed;`,\n    queryParams: [{\n      name: 'fromText',\n      type: 'varchar(23)',\n      value: from\n    }, {\n      name: 'bootstrap',\n      type: 'bit',\n      value: bootstrap ? 1 : 0\n    }]\n  };\n}\nfunction buildSourceQuery(stream, watermark, from, catalog, config) {\n  const monthly = {\n    speed: {\n      root: 'MachineSpeedInfo',\n      time: 's.SpeedTime',\n      fields: 's.SpeedValue'\n    },\n    state: {\n      root: 'MachineTimeLine',\n      time: 'COALESCE(s.LastUpDate,s.BeginTime)',\n      fields: 's.MainType,s.DetailType,s.StateName'\n    },\n    production: {\n      root: 'PWorkRecordDetail',\n      time: 'COALESCE(s.LastUpDate,s.WorkEndTime,s.WorkBeginTime)',\n      fields: 's.WorkNums,s.ClothWorkNums,s.ProductNums,s.OpenLong,s.StopNums,s.StopLong,s.OffLong,s.WorkLong,s.ZhouTimeLong,s.ShaTimeLong,s.RepairTimeLong'\n    }\n  };\n  let query;\n  const header = 'SET NOCOUNT ON; DECLARE @from datetime=CONVERT(datetime,@fromText,121),@wm datetime=CONVERT(datetime,@cursorText,121); IF @wm IS NULL SET @wm=@from;\\n';\n  if (monthly[stream]) {\n    const def = monthly[stream];\n    let tables = (catalog.tables[stream] || []).filter(name => new RegExp('^' + def.root + '[12]\\\\d{3}(0[1-9]|1[0-2])$').test(name));\n    // 速度采样时间归属该月份,已读完的旧月无需再次扫描。可变状态/班次仍扫描窗口内的前月表。\n    if (stream === 'speed' && watermark?.time) {\n      const ym = watermark.time.slice(0, 7).replace('-', '');\n      tables = tables.filter(t => t.slice(-6) >= ym);\n    }\n    const parts = tables.map((name, i) => `SELECT * FROM (SELECT TOP (@take) s.id,s.MachineID,s.FactoryID,CAST(N'${name}' AS nvarchar(128)) AS SourceTable,${def.fields},${def.time} AS RowTime FROM dbo.[${name}] s WHERE ${def.time}>=@from AND (${def.time}>@wm OR (${def.time}=@wm AND (N'${name}'>@cursorTable OR (N'${name}'=@cursorTable AND s.id>@cursorId)))) ORDER BY ${def.time},s.id) p${i}`);\n    query = header + (parts.length ? `WITH candidates AS (${parts.join('\\nUNION ALL\\n')}), page AS (SELECT TOP (@take) * FROM candidates ORDER BY RowTime,SourceTable,id)\nSELECT p.*,m.MachineNo,mt.OutPutUnit,mt.SpeedUnitName FROM page p\nLEFT JOIN StandPublicDB.dbo.PMachineNo m ON m.FactoryID=p.FactoryID AND m.MachineID=p.MachineID\nLEFT JOIN StandPublicDB.dbo.MachineType mt ON mt.TypeID=m.MachineType\nORDER BY p.RowTime,p.SourceTable,p.id;` : 'SELECT CAST(NULL AS int) AS id,CAST(NULL AS datetime) AS RowTime WHERE 1=0;');\n  } else if (stream === 'event') {\n    query = header + `WITH page AS (SELECT TOP (@take) s.id,s.MachineID,CAST(N'EventInfo' AS nvarchar(128)) AS SourceTable,COALESCE(s.SaveTime,s.DoTime) AS RowTime,s.DoTime,s.EventName,s.ClassOutPut,s.ClothOutPut,s.OpState\nFROM dbo.EventInfo s WHERE COALESCE(s.SaveTime,s.DoTime)>=@from AND (COALESCE(s.SaveTime,s.DoTime)>@wm OR (COALESCE(s.SaveTime,s.DoTime)=@wm AND s.id>@cursorId)) ORDER BY COALESCE(s.SaveTime,s.DoTime),s.id)\nSELECT p.*,m.MachineNo,mt.OutPutUnit,mt.SpeedUnitName FROM page p\nLEFT JOIN StandPublicDB.dbo.PMachineNo m ON m.MachineID=p.MachineID\nLEFT JOIN StandPublicDB.dbo.MachineType mt ON mt.TypeID=m.MachineType ORDER BY p.RowTime,p.id;`;\n  } else if (stream === 'snapshot') {\n    query = header + `SELECT s.id,s.MachineID,s.FactoryID,CAST(N'A_PWorkRecordDetail' AS nvarchar(128)) AS SourceTable,GETDATE() AS RowTime,s.WorkBeginTime,s.WorkEndTime,s.WorkNums,s.ClothWorkNums,s.ProductNums,s.OpenLong,s.StopNums,s.StopLong,s.OffLong,s.WorkLong,s.ZhouTimeLong,s.ShaTimeLong,s.RepairTimeLong,m.MachineNo,mt.OutPutUnit,mt.SpeedUnitName,st.WorkState,st.StateLastUpdate\nFROM dbo.A_PWorkRecordDetail s LEFT JOIN StandPublicDB.dbo.PMachineNo m ON m.FactoryID=s.FactoryID AND m.MachineID=s.MachineID\nLEFT JOIN StandPublicDB.dbo.MachineType mt ON mt.TypeID=m.MachineType LEFT JOIN StandPublicDB.dbo.MachineState st ON st.FactoryID=s.FactoryID AND st.MachineID=s.MachineID\nWHERE s.WorkBeginTime>=@from AND s.WorkEndTime IS NULL ORDER BY s.FactoryID,s.MachineID,s.id;`;\n  } else if (stream === 'plan') {\n    query = header + `SELECT pc.id,pc.MachineID,pc.FactoryID,CAST(N'ProductPlanPC' AS nvarchar(128)) AS SourceTable,GETDATE() AS RowTime,pc.PlanID,pc.DoDate,pc.RealNums,pc.FinishNums,pc.FinishCloth,b.NeedClothNums,b.Unit AS OutPutUnit,m.MachineNo\nFROM dbo.ProductPlanPC pc JOIN dbo.ProductPlanBill b ON b.FactoryID=pc.FactoryID AND b.PlanID=pc.PlanID LEFT JOIN StandPublicDB.dbo.PMachineNo m ON m.FactoryID=pc.FactoryID AND m.MachineID=pc.MachineID\nWHERE pc.FinishDate IS NULL AND COALESCE(pc.StartDate,pc.DoDate)>=@from ORDER BY pc.FactoryID,pc.MachineID,pc.PlanID;`;\n  } else throw Error('Unknown stream ' + stream);\n  return {\n    query,\n    queryParams: [{\n      name: 'fromText',\n      type: 'varchar(23)',\n      value: from\n    }, {\n      name: 'cursorText',\n      type: 'varchar(23)',\n      value: watermark?.time || null\n    }, {\n      name: 'cursorTable',\n      type: 'nvarchar(128)',\n      value: watermark?.table || ''\n    }, {\n      name: 'cursorId',\n      type: 'int',\n      value: watermark?.id || 0\n    }, {\n      name: 'take',\n      type: 'int',\n      value: config.batchRows\n    }]\n  };\n}\nfunction collectItems(items) {\n  const groups = new Map();\n  for (const it of items) {\n    const key = it.device + '|' + it.time;\n    let group = groups.get(key);\n    if (!group) {\n      group = {\n        src: 'YY',\n        device: it.device,\n        ts: new Date(it.time.replace(' ', 'T')),\n        u: 'loc',\n        data: {}\n      };\n      groups.set(key, group);\n    }\n    group.data[it.name] = it.value;\n  }\n  return [...groups.values()];\n}\nfunction readLegacyCollect(write) {\n  if (Array.isArray(write?.collect)) return write.collect;\n  const xml = write?.queryParams?.find(p => p.name === 'rowsXml')?.value;\n  if (typeof xml !== 'string') return null;\n  const decode = s => s.replace(/&quot;/g, '\"').replace(/&apos;/g, \"'\").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');\n  const rows = [];\n  for (const match of xml.matchAll(/<r\\s+d=\"([^\"]*)\"\\s+p=\"([^\"]*)\"\\s+v=\"([^\"]*)\"\\s+t=\"([^\"]*)\"\\s*\\/>/g)) rows.push({\n    device: decode(match[1]),\n    name: decode(match[2]),\n    value: Number(decode(match[3])),\n    time: decode(match[4])\n  });\n  return rows.length ? collectItems(rows) : null;\n}\nfunction legacyCollectToRows(collect, createdAt) {\n  // 只用于升级前缓存的 pending.write;三路新消息都直接输出 collectionRows。\n  const rows = [];\n  for (const item of collect || []) {\n    const collectedAt = new Date(item.ts);\n    if (!Number.isFinite(collectedAt.getTime())) continue;\n    for (const [parameterName, value] of Object.entries(item.data || {})) {\n      if (value === null || value === undefined || value === '') continue;\n      if (!Number.isFinite(Number(value))) continue;\n      // 已等待确认的旧批不改名,保证与之前已落库部分的防重键一致。\n      rows.push({\n        HItemID: null,\n        HDate: collectedAt,\n        HSourceCode: String(item.device).slice(0, 50),\n        HTechParamID: 0,\n        HTechParamName: parameterName.slice(0, 500),\n        HCount: Math.round(Number(value) * 100) / 100,\n        HCreateTime: new Date(createdAt),\n        HResult: String(Math.round(Number(value) * 100) / 100).slice(0, 50),\n        HProcNumber: item.src,\n        HFlag: 0\n      });\n    }\n  }\n  return rows;\n}\nfunction scheduleYouyangQueries(msg, flow, global, node) {\n  if (global.get('collection_paused') !== false) {\n    node.status({\n      fill: 'yellow',\n      shape: 'ring',\n      text: '采集已暂停'\n    });\n    return null;\n  }\n  const now = Date.now();\n  const state = flow.get('yy_multi') || {\n    from: localTime(new Date(now - config.lookbackDays * 86400000))\n  };\n  for (const name of ['cursors', 'pending', 'seen', 'stats']) state[name] = state[name] || {};\n  state.queue = state.queue || [];\n  const retryMessages = [];\n\n  // 1. 重投“尚未入队”的原批;已入队的批次由公共Bulk重试,不重复入队。\n  for (const pending of Object.values(state.pending)) {\n    if (pending.write && !pending.stage) {\n      const legacyCollect = readLegacyCollect(pending.write);\n      if (!legacyCollect) {\n        node.error('旧待确认批次无法迁移,请保留原批检查');\n        return null;\n      }\n      pending.write = {\n        collectionRows: legacyCollectToRows(legacyCollect, new Date()),\n        yySync: {\n          ...pending.write.yySync,\n          phase: 'buffer'\n        }\n      };\n      pending.stage = 'buffer';\n      pending.retryAt = now;\n    }\n    if (pending.stage === 'buffer' && (!pending.retryAt || now >= pending.retryAt) && pending.write) {\n      pending.retryAt = now + 10000;\n      retryMessages.push(pending.write);\n    }\n  }\n\n  // 2. 每轮六路各读一次;数据库查询串行,入队后的批次可同时等待Bulk确认。\n  if (!msg.yyDrain && !state.queue.length) {\n    state.queue = ['speed', 'state', 'production', 'event', 'snapshot', 'plan'].filter(stream => !state.pending[stream]);\n  }\n  const bufferedCount = Object.values(state.pending).filter(pending => pending.stage === 'queued').reduce((total, pending) => total + (pending.count || 0), 0);\n  if (state.sourceBusy || bufferedCount >= 20000) {\n    flow.set('yy_multi', state);\n    return [[], retryMessages];\n  }\n\n  // 3. 先刷新过期的分表清单;跨月和改变回补起点也会失效。\n  const currentMonth = localTime(new Date(now)).slice(0, 7);\n  const catalog = state.catalog;\n  const catalogExpired = !catalog || catalog.from !== state.from || catalog.month !== currentMonth || now - catalog.at > 300000;\n  if (state.queue.length && catalogExpired) {\n    const batchMeta = {\n      stream: 'catalog',\n      batchId: 'catalog-' + now,\n      phase: 'query'\n    };\n    const allowBootstrap = !state.manualBackfill && !state.cursors.speed;\n    state.sourceBusy = batchMeta;\n    flow.set('yy_multi', state);\n    return [[{\n      ...buildCatalogQuery(state.from, allowBootstrap),\n      yySync: batchMeta\n    }], retryMessages];\n  }\n  let nextStream;\n  while (state.queue.length) {\n    const candidate = state.queue.shift();\n    if (!state.pending[candidate]) {\n      nextStream = candidate;\n      break;\n    }\n  }\n  const queryMessages = [];\n  if (nextStream) {\n    const batchMeta = {\n      stream: nextStream,\n      batchId: nextStream + '-' + now + '-' + Math.random().toString(16).slice(2),\n      phase: 'query'\n    };\n    state.pending[nextStream] = {\n      batchId: batchMeta.batchId,\n      startedAt: now,\n      stage: 'query'\n    };\n    state.sourceBusy = batchMeta;\n    queryMessages.push({\n      ...buildSourceQuery(nextStream, state.cursors[nextStream], state.from, state.catalog, config),\n      yySync: batchMeta\n    });\n  }\n  flow.set('yy_multi', state);\n  node.status({\n    fill: 'blue',\n    shape: 'dot',\n    text: '集合查询 ' + (nextStream || '等待Bulk确认') + ' / 重试 ' + retryMessages.length\n  });\n  return [queryMessages, retryMessages];\n}\nreturn scheduleYouyangQueries(msg, flow, global, node);\n",
        "outputs": 2,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 520,
        "y": 220,
        "wires": [
            [
                "c3e4894ab572dc51"
            ],
            [
                "yy_data_out"
            ]
        ]
    },
    {
        "id": "yy_data_out",
        "type": "link out",
        "z": "yy_multi_collect",
        "name": "用友标准数据 → 共用缓冲",
        "mode": "link",
        "links": [
            "yy_write_in"
        ],
        "x": 1305,
        "y": 160,
        "wires": []
    },
    {
        "id": "yy_ack_in",
        "type": "link in",
        "z": "yy_multi_collect",
        "name": "共用Bulk完整批次确认",
        "links": [
            "yy_ack_out"
        ],
        "x": 165,
        "y": 340,
        "wires": [
            [
                "yy_commit"
            ]
        ]
    },
    {
        "id": "yy_commit",
        "type": "function",
        "z": "yy_multi_collect",
        "name": "Bulk全部确认 → 提交增量水位",
        "func": "/**\n * 用友完整批次确认\n * 输入:msg.yySync;msg.yyAck或查询错误\n * 输出:输出1=统计;输出2=调度继续信号\n * 上下文:yy_multi.cursors/seen仅在整批committed时推进\n */\nfunction commitYouyangWatermark(msg, flow, global, node) {\n  const state = flow.get('yy_multi');\n  const batchMeta = msg.yySync;\n  if (!state || !batchMeta) return null;\n\n  // 查询错误只释放源查询锁,不能更改已确认水位。\n  if (msg.error) {\n    if (state.sourceBusy?.batchId !== batchMeta.batchId) return null;\n    if (batchMeta.stream !== 'catalog' && state.pending[batchMeta.stream]?.batchId === batchMeta.batchId) delete state.pending[batchMeta.stream];\n    delete state.sourceBusy;\n    delete state.catalog;\n    flow.set('yy_multi', state);\n    return [{\n      payload: {\n        stream: batchMeta.stream,\n        error: msg.error.message || msg.error,\n        retry: true\n      }\n    }, {\n      yyDrain: true\n    }];\n  }\n  const pending = state.pending[batchMeta.stream];\n  if (pending?.batchId !== batchMeta.batchId) return null;\n  const acknowledgement = msg.yyAck;\n  if (!acknowledgement) return null;\n  if (acknowledgement.kind === 'queued' || acknowledgement.kind === 'retrying') {\n    pending.stage = 'queued';\n    pending.retryAt = null;\n    flow.set('yy_multi', state);\n    node.status({\n      fill: acknowledgement.kind === 'retrying' ? 'yellow' : 'blue',\n      shape: 'ring',\n      text: batchMeta.stream + ' 缓冲待Bulk确认'\n    });\n    return [null, {\n      yyDrain: true\n    }];\n  }\n  if (acknowledgement.kind === 'deferred') {\n    pending.stage = 'buffer';\n    pending.retryAt = Date.now() + 10000;\n    flow.set('yy_multi', state);\n    return [{\n      payload: {\n        stream: batchMeta.stream,\n        deferred: acknowledgement.reason\n      }\n    }, {\n      yyDrain: true\n    }];\n  }\n  if (acknowledgement.kind !== 'committed' || !Number.isFinite(acknowledgement.inserted) || !Number.isFinite(acknowledgement.skipped)) return null;\n\n  // 只有整批committed回执才能推进时间/表/ID水位,或提交快照指纹。\n  if (pending.cursor && !['snapshot', 'plan'].includes(batchMeta.stream)) state.cursors[batchMeta.stream] = pending.cursor;\n  if (['snapshot', 'plan'].includes(batchMeta.stream)) state.seen[batchMeta.stream] = pending.nextSeen || {};\n  const previousStats = state.stats[batchMeta.stream] || {};\n  state.stats[batchMeta.stream] = {\n    ...previousStats,\n    written: (previousStats.written || 0) + acknowledgement.inserted,\n    skipped: (previousStats.skipped || 0) + acknowledgement.skipped,\n    lastSuccess: new Date().toISOString()\n  };\n  delete state.pending[batchMeta.stream];\n  flow.set('yy_multi', state);\n  node.status({\n    fill: 'green',\n    shape: 'dot',\n    text: batchMeta.stream + ' 写入 ' + acknowledgement.inserted + ' / 已有 ' + acknowledgement.skipped\n  });\n  return [{\n    payload: {\n      stream: batchMeta.stream,\n      inserted: acknowledgement.inserted,\n      skipped: acknowledgement.skipped,\n      cursor: state.cursors[batchMeta.stream] || null\n    }\n  }, {\n    yyDrain: true\n  }];\n}\nreturn commitYouyangWatermark(msg, flow, global, node);\n",
        "outputs": 2,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 510,
        "y": 340,
        "wires": [
            [
                "yy_result_debug"
            ],
            [
                "fn_yy_q"
            ]
        ]
    },
    {
        "id": "yy_result_debug",
        "type": "debug",
        "z": "yy_multi_collect",
        "name": "用友 · 整合入库结果",
        "active": false,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 840,
        "y": 340,
        "wires": []
    },
    {
        "id": "yy_query_catch",
        "type": "catch",
        "z": "yy_multi_collect",
        "name": "查询/映射异常",
        "scope": [
            "fn_yy_q",
            "c3e4894ab572dc51",
            "ff402f329edcf253"
        ],
        "uncaught": false,
        "x": 190,
        "y": 420,
        "wires": [
            [
                "yy_commit"
            ]
        ]
    },
    {
        "id": "yy_note",
        "type": "comment",
        "z": "yy_multi_collect",
        "name": "集合查询 → 虚拟链接 → 共用缓冲/Bulk → 全批确认后推进水位",
        "info": "用友多表采集:分表清单缓存5分钟,集合分页查询;保留(time,SourceTable,id)增量水位。字段映射经虚拟链接进入MSSQL数据同步页sync_rows内存缓冲,5秒/最多5000行共用Bulk写入HX_LMESsys.dbo.Sb_EquipMentCollectionTechParam_Temp。只有整批插入/防重跳过全部确认后才提交水位。暂停不清空缓冲,失败原批回填。 字段字典和分钟转秒规则保持原配置;兼容SQL Server级别100,不需要OPENJSON/STRING_AGG。\n2026-10-25字段版:三路统一msg.collectionRows,使用目标表完整列名。HItemID为自增占位null,Bulk不传。用友批次引用放在缓冲行_sync.yyBatchIds中,不作为数据库列。",
        "x": 260,
        "y": 80,
        "wires": []
    },
    {
        "id": "yy_manual_poll",
        "type": "inject",
        "z": "yy_multi_collect",
        "name": "立即采集/重试",
        "props": [],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": "",
        "topic": "",
        "x": 130,
        "y": 200,
        "wires": [
            [
                "fn_yy_q"
            ]
        ]
    },
    {
        "id": "yy_control_in",
        "type": "link in",
        "z": "yy_multi_collect",
        "name": "← 原页签水位/回补维护",
        "links": [
            "yy_control_out"
        ],
        "x": 165,
        "y": 530,
        "wires": [
            [
                "yy_control_apply"
            ]
        ]
    },
    {
        "id": "yy_control_apply",
        "type": "function",
        "z": "yy_multi_collect",
        "name": "应用回补起点 · 保留未完成批次",
        "func": "/**\n * 应用用友回补起点\n * 输入:msg.yyControl.from=本地日期时间\n * 输出:控制日志;有未完成批次时拒绝重置\n * 上下文:yy_multi重置,manualBackfill=true\n */\nfunction applyYouyangBackfill(msg, flow, global, node) {\n  const state = flow.get('yy_multi');\n  if (state && Object.keys(state.pending || {}).length) {\n    msg.payload = '用友尚有未完成批次,未重置;待入库完成后重新点击回补';\n    node.warn(msg.payload);\n    return msg;\n  }\n  const fromTime = msg.yyControl?.from;\n  if (!fromTime || !/^\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}:\\d{2}/.test(fromTime)) {\n    node.error('无效回补时间', msg);\n    return null;\n  }\n  flow.set('yy_multi', {\n    from: fromTime,\n    cursors: {},\n    pending: {},\n    seen: {},\n    stats: {},\n    manualBackfill: true\n  });\n  msg.payload = '用友回补起点已设置为 ' + fromTime + ';已有记录将跳过';\n  return msg;\n}\nreturn applyYouyangBackfill(msg, flow, global, node);\n",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 490,
        "y": 530,
        "wires": [
            [
                "yy_result_debug"
            ]
        ]
    },
    {
        "id": "collection_yy_control_out",
        "type": "link out",
        "z": "yy_multi_collect",
        "name": "→ 采集总开关(全部流程)",
        "mode": "link",
        "links": [
            "collection_control_link_in"
        ],
        "x": 470,
        "y": 650,
        "wires": []
    },
    {
        "id": "collection_yy_pause",
        "type": "inject",
        "z": "yy_multi_collect",
        "name": "⏸ 暂停全部采集/写库",
        "props": [
            {
                "p": "payload",
                "v": "true",
                "vt": "bool"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "x": 160,
        "y": 620,
        "wires": [
            [
                "collection_yy_control_out"
            ]
        ]
    },
    {
        "id": "collection_yy_resume",
        "type": "inject",
        "z": "yy_multi_collect",
        "name": "▶ 恢复全部采集/写库",
        "props": [
            {
                "p": "payload",
                "v": "false",
                "vt": "bool"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "x": 160,
        "y": 680,
        "wires": [
            [
                "collection_yy_control_out"
            ]
        ]
    },
    {
        "id": "mp_note",
        "type": "comment",
        "z": "tab_mqtt_pipeline",
        "name": "说明 · 独立 MQTT 采集写库",
        "info": "独立页签:MQTT 采集 + 写库(与五洋/用友/采集器页签互不影响)。\n开关:⏸ 停止本页签 / ▶ 启动本页签(global.mqtt_pipeline_paused);未设置时跟随总开关 collection_paused。停止时缓冲保留。",
        "x": 140,
        "y": 40,
        "wires": []
    },
    {
        "id": "mp_in_report",
        "type": "mqtt in",
        "z": "tab_mqtt_pipeline",
        "name": "设备上报 /report/#(独立)",
        "topic": "/report/#",
        "qos": "1",
        "datatype": "json",
        "broker": "mqtt_broker_local",
        "nl": false,
        "rap": true,
        "rh": 0,
        "inputs": 0,
        "x": 110,
        "y": 240,
        "wires": [
            [
                "mp_gate_in"
            ]
        ]
    },
    {
        "id": "mp_fn_parse",
        "type": "function",
        "z": "tab_mqtt_pipeline",
        "name": "MQTT协议解析(独立)",
        "func": "/**\n * MQTT协议解析\n * 输入:原始msg.payload和msg.topic\n * 输出:msg.dev;msg.flowType供Switch分流\n * 上下文:不写数据库/缓冲\n */\n// 采集器报文解析:/report/**(设备上报)与 /cmd/**(文档里把 了机/机修/采集数据 误写成 /cmd,两条都订阅)\nconst RECEIPT = {\n  worker_register_msg: '员工上班',\n  worker_report_msg: '员工下班',\n  axis_start_msg: '上轴',\n  variety_change_msg: '改品',\n  fall_cloth_msg: '落布',\n  axis_end_msg: '了机',\n  repair_msg: '机修'\n};\nconst SIGNAL_CMD = 'signal_msg';\nlet body = msg.payload;\nif (Buffer.isBuffer(body)) {\n  body = body.toString('utf8');\n}\nif (typeof body === 'string') {\n  try {\n    body = JSON.parse(body);\n  } catch (e) {\n    node.warn('非 JSON 报文,已丢弃:' + msg.topic);\n    return null;\n  }\n}\nif (!body || typeof body !== 'object') {\n  node.warn('空报文,已丢弃:' + msg.topic);\n  return null;\n}\nconst topic = msg.topic || '';\nconst seg = topic.split('/').filter(function (s) {\n  return s !== '';\n});\nconst dir = seg[0] || ''; // report | cmd\nconst kind = seg[1] || ''; // woven 梭织 | round 圆机\nconst sn = String(body.sn || seg[2] || '');\nconst cmd = String(body.cmd || '');\nconst cmdId = body.cmd_id === undefined || body.cmd_id === null ? '' : String(body.cmd_id);\nconst items = body.items && typeof body.items === 'object' ? body.items : {};\n\n// 丢弃本机发出的确认回执(订阅 /cmd/# 时 MQTT 会把我们自己的回执回显回来)\n// 回执只有 mach_id(落布再加 cloth_id),没有 time;设备上报必然带 time\nif (dir === 'cmd' && (items.time === undefined || Object.keys(items).length < 2)) {\n  node.status({\n    fill: 'grey',\n    shape: 'ring',\n    text: '回执回显,忽略'\n  });\n  return null;\n}\nmsg.flowType = RECEIPT[cmd] ? 'confirm' : cmd === SIGNAL_CMD ? 'signal' : 'unknown';\nmsg.dev = {\n  dir: dir,\n  kind: kind || 'woven',\n  sn: sn,\n  cmd: cmd,\n  cmdId: cmdId,\n  items: items,\n  label: RECEIPT[cmd] || (cmd === SIGNAL_CMD ? '采集数据上报' : cmd || '(缺少 cmd)'),\n  topic: topic,\n  receivedAt: new Date()\n};\nnode.status({\n  fill: 'blue',\n  shape: 'dot',\n  text: msg.dev.label\n});\n\nmsg.cmd = cmd\nreturn msg;\n",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 370,
        "y": 140,
        "wires": [
            [
                "mp_fn_mqtt_ad"
            ]
        ]
    },
    {
        "id": "mp_fn_mqtt_ad",
        "type": "function",
        "z": "tab_mqtt_pipeline",
        "name": "MQTT · 标准化为数据库字段(独立)",
        "func": "/**\n * MQTT采集标准化\n * 输入:msg.dev或原始JSON/Buffer\n * 输出:输出1=msg.collectionRows;输出2=诊断/暂停预览\n * 上下文:mqtt_seen;mqtt_seen_n;mqtt_adapter_stats\n */\nfunction canonicalParameterName(parameterName) {\n  const aliases = {\n    '转速': '机器转速',\n    '班次平均车速': '班次平均转速',\n    '本班产量': '班次产量(源单位)',\n    '本班效率': '班次效率(%)',\n    '本班停机次数': '班次停机次数',\n    '本班停机时间(秒)': '班次停机时间(秒)',\n    '本匹产量': '本匹产量(源单位)'\n  };\n  const name = String(parameterName);\n  // 用友事件里的本班产量附有实际单位,沿用同一班次产量名称。\n  const withUnit = /^本班产量\\((.+)\\)$/.exec(name);\n  if (withUnit) return '班次产量(' + withUnit[1] + ')';\n  return aliases[name] || name;\n}\nfunction createCollectionRow(source, deviceCode, parameterName, value, collectedAt, createdAt) {\n  const amount = Math.round(Number(value) * 100) / 100;\n  return {\n    HItemID: null,\n    // SQL Server 自增,Bulk 不传此列\n    HDate: new Date(collectedAt),\n    // 采样时间/源设备时间\n    HSourceCode: String(deviceCode).slice(0, 50),\n    HTechParamID: 0,\n    // 沿用现有目标表约定\n    HTechParamName: canonicalParameterName(parameterName).slice(0, 500),\n    HCount: amount,\n    // SQL decimal(18,2)\n    HCreateTime: new Date(createdAt),\n    // 标准化创建时间;重试保持不变\n    HResult: String(amount).slice(0, 50),\n    HProcNumber: String(source).slice(0, 50),\n    // WY / YY / MQTT\n    HFlag: 0\n  };\n}\nfunction normalizeMqttReport(msg, flow, global, node) {\n  // 1. MQTT原字段 -> 统一参数名。无明确单位/统计周期的字段不强行冒充累计或班次值。\n  const fieldMappings = [{\n    sourceField: 'rpm',\n    parameterName: '机器转速'\n  }, {\n    sourceField: 'rpm_avr',\n    parameterName: '班次平均转速'\n  }, {\n    sourceField: 'produce',\n    parameterName: '班次产量(源单位)'\n  }, {\n    sourceField: 'effect',\n    parameterName: '班次效率(%)'\n  }, {\n    sourceField: 'beat',\n    parameterName: '打纬数'\n  }, {\n    sourceField: 'boot_time',\n    parameterName: '开机时间(秒)'\n  }, {\n    sourceField: 'run_time',\n    parameterName: '运行时间(秒)'\n  }, {\n    sourceField: 'stop_count',\n    parameterName: '班次停机次数'\n  }, {\n    sourceField: 'stop_time',\n    parameterName: '班次停机时间(秒)'\n  }, {\n    sourceField: 'stop_times',\n    parameterName: '累计停机次数'\n  }, {\n    sourceField: 'remain_length',\n    parameterName: '剩余经长'\n  }, {\n    sourceField: 'remain_length2',\n    parameterName: '剩余经长2'\n  }, {\n    sourceField: 'cloth_length_cap',\n    parameterName: '本匹产量(源单位)'\n  }];\n  function numericValue(value) {\n    if (value === null || value === undefined || typeof value === 'boolean' || typeof value === 'object') return null;\n    if (typeof value === 'string' && !value.trim()) return null;\n    const parsed = Number(value);\n    return Number.isFinite(parsed) ? Math.round(parsed * 100) / 100 : null;\n  }\n  function parseDeviceTime(value) {\n    if (value === null || value === undefined || value === '') return null;\n    if (value instanceof Date) return Number.isFinite(value.getTime()) ? value : null;\n    const text = String(value).trim();\n    const match = /^(\\d{4})-(\\d{1,2})-(\\d{1,2})(?:[ T](\\d{1,2}):(\\d{1,2})(?::(\\d{1,2})(?:\\.(\\d{1,3}))?)?)?$/.exec(text);\n    if (match) {\n      const year = Number(match[1]);\n      const monthIndex = Number(match[2]) - 1;\n      const day = Number(match[3]);\n      const hour = Number(match[4] || 0);\n      const minute = Number(match[5] || 0);\n      const second = Number(match[6] || 0);\n      const millisecond = Number((match[7] || '').padEnd(3, '0') || 0);\n      // 显式7个参数,避免展开不定长数组触发编辑器TS2556。\n      const date = new Date(year, monthIndex, day, hour, minute, second, millisecond);\n      const matchesInput = date.getFullYear() === year && date.getMonth() === monthIndex && date.getDate() === day && date.getHours() === hour && date.getMinutes() === minute && date.getSeconds() === second;\n      return matchesInput ? date : null;\n    }\n    if (/T.*(?:Z|[+-]\\d{2}:?\\d{2})$/i.test(text)) {\n      const date = new Date(text);\n      return Number.isFinite(date.getTime()) ? date : null;\n    }\n    return null;\n  }\n  function diagnostic(status, message, details = {}) {\n    const previousStats = flow.get('mqtt_adapter_stats') || {};\n    flow.set('mqtt_adapter_stats', {\n      ...previousStats,\n      received: (previousStats.received || 0) + 1,\n      [status]: (previousStats[status] || 0) + 1,\n      lastStatus: status,\n      lastMessage: message,\n      lastAt: new Date().toISOString()\n    });\n    const statusColors = {\n      buffered: 'green',\n      invalid: 'red',\n      paused: 'yellow',\n      unchanged: 'grey'\n    };\n    node.status({\n      fill: statusColors[status],\n      shape: status === 'buffered' ? 'dot' : 'ring',\n      text: message\n    });\n    return {\n      payload: {\n        source: 'MQTT',\n        status,\n        message,\n        ...details\n      },\n      _msgid: msg._msgid\n    };\n  }\n\n  // 2. 优先接收解析节点msg.dev,也支持直接传入JSON/Buffer。\n  let deviceReport = msg.dev;\n  if (!deviceReport || !deviceReport.items) {\n    let body = msg.payload;\n    if (Buffer.isBuffer(body)) body = body.toString('utf8');\n    if (typeof body === 'string') {\n      try {\n        body = JSON.parse(body);\n      } catch {\n        body = null;\n      }\n    }\n    if (body && typeof body === 'object' && !Array.isArray(body)) {\n      const topicParts = String(msg.topic || '').split('/').filter(Boolean);\n      deviceReport = {\n        cmd: body.cmd,\n        sn: body.sn || topicParts[2] || '',\n        cmdId: body.cmd_id,\n        items: body.items,\n        receivedAt: new Date(),\n        topic: msg.topic || ''\n      };\n      msg.dev = deviceReport;\n    }\n  }\n  for (const field of ['queryParams', 'query', 'queryMode', 'rows', 'retryBuf', 'collect', 'collectionRows', 'signalRecord']) delete msg[field];\n  const fields = deviceReport?.items;\n  if (deviceReport?.cmd !== 'signal_msg' || !fields || typeof fields !== 'object' || Array.isArray(fields)) {\n    const result = diagnostic('invalid', '不是有效 signal_msg 报文');\n    node.warn(result.payload.message);\n    return [null, result];\n  }\n  const machineId = fields.mach_id === null || fields.mach_id === undefined ? '' : String(fields.mach_id).trim();\n  if (!machineId) {\n    const result = diagnostic('invalid', '缺少 mach_id,未送入缓冲');\n    node.warn(result.payload.message);\n    return [null, result];\n  }\n  const deviceCode = ((deviceReport.sn ? String(deviceReport.sn).trim() + '-' : '') + machineId).slice(0, 50);\n  const sourceTime = parseDeviceTime(fields.time);\n  const receivedTime = new Date(deviceReport.receivedAt || Date.now());\n  const collectedAt = sourceTime || (Number.isFinite(receivedTime.getTime()) ? receivedTime : new Date());\n  const createdAt = new Date();\n  const parameterValues = {};\n  for (const mapping of fieldMappings) {\n    const value = numericValue(fields[mapping.sourceField]);\n    if (value !== null) parameterValues[mapping.parameterName] = value;\n  }\n  const signal = numericValue(fields.signal);\n  if (signal !== null) {\n    parameterValues['信号值'] = signal;\n    parameterValues['运行状态'] = (signal & 3) === 3 ? 1 : 3;\n  }\n\n  // 原报文文本保留作诊断;写库行只存数值采集参数。\n  msg.signalRecord = {\n    设备编码: deviceCode,\n    机台号: machineId,\n    设备时间: fields.time || '',\n    采样时间: collectedAt.toISOString(),\n    时间来源: sourceTime ? '设备时间' : '接收时间',\n    信号: signal,\n    转速: numericValue(fields.rpm),\n    产量: numericValue(fields.produce),\n    效率: numericValue(fields.effect),\n    批号: fields.batch_number ?? null,\n    剩余经长: numericValue(fields.remain_length),\n    停机次数: numericValue(fields.stop_count),\n    停机时间: numericValue(fields.stop_time),\n    开机时间: numericValue(fields.boot_time),\n    运行时间: numericValue(fields.run_time),\n    轴号: fields.axis_id ?? null\n  };\n  const collectionRows = Object.entries(parameterValues).map(([name, value]) => createCollectionRow('MQTT', deviceCode, name, value, collectedAt, createdAt));\n  const fieldCount = collectionRows.length;\n  if (!fieldCount) return [null, diagnostic('invalid', '无有效数值字段,未送入缓冲', {\n    device: deviceCode,\n    record: msg.signalRecord\n  })];\n\n  // 3. 暂停仍输出数据库字段预览,既不更新去重缓存,也不入队。\nconst __local = global.get('mqtt_pipeline_paused');\nconst __master = global.get('collection_paused');\nconst __running = (__local === false) ? true : (__local === true) ? false : (__master === false);\n  if (!__running) {\n    return [null, diagnostic('paused', '采集已暂停:已解析 ' + fieldCount + ' 项,未送入缓冲', {\n      device: deviceCode,\n      fields: fieldCount,\n      values: parameterValues,\n      record: msg.signalRecord,\n      collectionRows\n    })];\n  }\n\n  // 4. MQTT保持“只送变化值”,五洋的全量快照规则不在此处混用。\n  let previousValues = flow.get('mqtt_seen') || {};\n  let previousCount = flow.get('mqtt_seen_n') || 0;\n  if (previousCount > 50000) {\n    previousValues = {};\n    previousCount = 0;\n  }\n  const changedRows = [];\n  for (const row of collectionRows) {\n    const cacheKey = row.HSourceCode + '|' + row.HTechParamName;\n    if (previousValues[cacheKey] === row.HCount) continue;\n    if (!Object.prototype.hasOwnProperty.call(previousValues, cacheKey)) previousCount += 1;\n    previousValues[cacheKey] = row.HCount;\n    changedRows.push(row);\n  }\n  flow.set('mqtt_seen', previousValues);\n  flow.set('mqtt_seen_n', previousCount);\n  if (!changedRows.length) return [null, diagnostic('unchanged', '数值无变化,未重复入缓冲', {\n    device: deviceCode,\n    fields: fieldCount,\n    record: msg.signalRecord\n  })];\n  msg.collectionRows = changedRows;\n  msg.payload = changedRows;\n  const result = diagnostic('buffered', '已送入缓冲链路 ' + changedRows.length + ' 项', {\n    device: deviceCode,\n    fields: fieldCount,\n    changed: changedRows.length,\n    values: Object.fromEntries(changedRows.map(row => [row.HTechParamName, row.HCount])),\n    record: msg.signalRecord,\n    collectionRows: changedRows\n  });\n  return [msg, result];\n}\nreturn normalizeMqttReport(msg, flow, global, node);\n",
        "outputs": 2,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 610,
        "y": 60,
        "wires": [
            [
                "mp_fn_buffer"
            ],
            [
                "mp_dbg_adapter"
            ]
        ]
    },
    {
        "id": "mp_dbg_adapter",
        "type": "debug",
        "z": "tab_mqtt_pipeline",
        "name": "MQTT · 转换结果与过滤原因(独立)",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 850,
        "y": 240,
        "wires": []
    },
    {
        "id": "mp_fn_buffer",
        "type": "function",
        "z": "tab_mqtt_pipeline",
        "name": "MQTT标准行 → 独立缓冲",
        "func": "/**\n * 统一数据库行入缓冲\n * 输入:msg.collectionRows;用友另带msg.yySync\n * 输出:输出1=入队摘要/数据库字段预览;输出2=用友回执\n * 上下文:sync_rows;sync_yy_batches;sync_yy_completed\n */\nfunction collectionRowKey(row) {\n  // 保留原有自然键编码,兼容旧待确认批次的 doneKeys。\n  return row.HProcNumber + '|' + row.HSourceCode + '|' + row.HTechParamName + '|' + new Date(row.HDate).getTime();\n}\nfunction convertLegacyBufferRow(row, createdAt) {\n  if (row.HDate !== undefined && row.HSourceCode !== undefined) {\n    // 已是新格式:保留既有字段和批次引用,只恢复 Date 类型。\n    return {\n      ...row,\n      HDate: new Date(row.HDate),\n      HCreateTime: row.HCreateTime ? new Date(row.HCreateTime) : new Date(createdAt)\n    };\n  }\n  // 部署兼容:旧 sync_rows 使用 s/d/p/v/t,原批语义及原参数名保持不变。\n  const converted = {\n    HItemID: null,\n    HDate: new Date(row.t),\n    HSourceCode: row.d,\n    HTechParamID: 0,\n    HTechParamName: row.p,\n    HCount: row.v,\n    HCreateTime: new Date(createdAt),\n    HResult: String(row.v).slice(0, 50),\n    HProcNumber: row.s,\n    HFlag: 0\n  };\n  if (row.yyRefs?.length) converted._sync = {\n    yyBatchIds: [...row.yyRefs]\n  };\n  return converted;\n}\nfunction legacyCollectToRows(collect, createdAt) {\n  // 只用于升级前缓存的 pending.write;三路新消息都直接输出 collectionRows。\n  const rows = [];\n  for (const item of collect || []) {\n    const collectedAt = new Date(item.ts);\n    if (!Number.isFinite(collectedAt.getTime())) continue;\n    for (const [parameterName, value] of Object.entries(item.data || {})) {\n      if (value === null || value === undefined || value === '') continue;\n      if (!Number.isFinite(Number(value))) continue;\n      // 已等待确认的旧批不改名,保证与之前已落库部分的防重键一致。\n      rows.push({\n        HItemID: null,\n        HDate: collectedAt,\n        HSourceCode: String(item.device).slice(0, 50),\n        HTechParamID: 0,\n        HTechParamName: parameterName.slice(0, 500),\n        HCount: Math.round(Number(value) * 100) / 100,\n        HCreateTime: new Date(createdAt),\n        HResult: String(Math.round(Number(value) * 100) / 100).slice(0, 50),\n        HProcNumber: item.src,\n        HFlag: 0\n      });\n    }\n  }\n  return rows;\n}\nfunction enqueueCollectionRows(msg, flow, global, node) {\n  const batchMeta = msg.yySync;\n  const isYouyangBatch = Boolean(batchMeta?.batchId && batchMeta?.stream);\n  const makeAck = (kind, details = {}) => ({\n    yySync: batchMeta,\n    yyAck: {\n      kind,\n      ...details\n    },\n    payload: {\n      stream: batchMeta?.stream,\n      ...details\n    }\n  });\n\n  // 1. 暂停只停止新增,不清空原缓冲,也不提交用友水位。\nconst __local = global.get('mqtt_pipeline_paused');\nconst __master = global.get('collection_paused');\nconst __running = (__local === false) ? true : (__local === true) ? false : (__master === false);\n  if (!__running) {\n    node.status({\n      fill: 'yellow',\n      shape: 'ring',\n      text: '采集已暂停,缓冲保留'\n    });\n    return isYouyangBatch ? [null, makeAck('deferred', {\n      reason: '采集已暂停'\n    })] : null;\n  }\n  const completedBatches = flow.get('sync_yy_completed') || {};\n  const pendingBatches = flow.get('sync_yy_batches') || {};\n  if (isYouyangBatch && completedBatches[batchMeta.batchId]) {\n    return [null, completedBatches[batchMeta.batchId]];\n  }\n  if (isYouyangBatch && pendingBatches[batchMeta.batchId]) {\n    return [null, makeAck('queued', {\n      expected: pendingBatches[batchMeta.batchId].expected,\n      duplicateRequest: true\n    })];\n  }\n\n  // 2. 三路新输入均为数据库字段对象。collect 仅兼容部署前的待确认消息。\n  const createdAt = new Date();\n  const inputRows = Array.isArray(msg.collectionRows) ? msg.collectionRows : legacyCollectToRows(msg.collect, createdAt);\n  const validRows = [];\n  const uniqueYouyangRows = new Map();\n  for (const input of inputRows) {\n    const row = convertLegacyBufferRow(input, createdAt);\n    const valid = row.HSourceCode && row.HTechParamName && Number.isFinite(row.HDate.getTime()) && Number.isFinite(row.HCreateTime.getTime()) && typeof row.HCount === 'number' && Number.isFinite(row.HCount);\n    if (!valid) {\n      // 不把“格式错误”伪装成写库成功;用友必须保留原批和水位。\n      if (isYouyangBatch) return [null, makeAck('deferred', {\n        reason: '标准行无效,检查数据库字段'\n      })];\n      node.warn('忽略无效采集参数行');\n      continue;\n    }\n    if (isYouyangBatch) {\n      if (row.HProcNumber !== 'YY') return [null, makeAck('deferred', {\n        reason: '用友批次来源必须为YY'\n      })];\n      row._sync = {\n        yyBatchIds: [batchMeta.batchId]\n      }; // 仅用于确认,不是数据库列\n      uniqueYouyangRows.set(collectionRowKey(row), row);\n    } else {\n      validRows.push(row);\n    }\n  }\n  if (isYouyangBatch) validRows.push(...uniqueYouyangRows.values());\n  const bufferRows = flow.get('mqtt_sync_rows') || [];\n  if (isYouyangBatch && bufferRows.length + validRows.length > 20000) {\n    node.status({\n      fill: 'yellow',\n      shape: 'ring',\n      text: '缓冲积压,用友原批等待'\n    });\n    return [null, makeAck('deferred', {\n      reason: '缓冲达到20000行限流'\n    })];\n  }\n  if (!validRows.length) {\n    return isYouyangBatch ? [null, makeAck('committed', {\n      inserted: 0,\n      skipped: 0,\n      expected: 0\n    })] : null;\n  }\n\n  // 3. 入队回执仅表示已接收。整批写入/跳过完成后,才会发送 committed。\n  if (isYouyangBatch) {\n    pendingBatches[batchMeta.batchId] = {\n      meta: {\n        ...batchMeta,\n        phase: 'buffer'\n      },\n      expected: validRows.length,\n      done: 0,\n      inserted: 0,\n      skipped: 0,\n      doneKeys: {},\n      queuedAt: new Date().toISOString()\n    };\n  }\n  bufferRows.push(...validRows);\n  flow.set('mqtt_sync_rows', bufferRows);\n  flow.set('sync_yy_batches', pendingBatches);\n  node.status({\n    fill: 'blue',\n    shape: 'dot',\n    text: '+' + validRows.length + ' / 缓冲 ' + bufferRows.length\n  });\n\n  // 调试只预览前3行,便于对照数据库字段,也避免每秒打印大量参数。\n  const preview = validRows.slice(0, 3).map(row => {\n    const {\n      _sync,\n      ...databaseFields\n    } = row;\n    return databaseFields;\n  });\n  const diagnostic = {\n    payload: {\n      source: validRows[0].HProcNumber,\n      buffered: validRows.length,\n      pending: bufferRows.length,\n      records: preview\n    }\n  };\n  const ack = isYouyangBatch ? makeAck('queued', {\n    expected: validRows.length,\n    pending: bufferRows.length\n  }) : null;\n  return [diagnostic, ack];\n}\nreturn enqueueCollectionRows(msg, flow, global, node);\n",
        "outputs": 2,
        "timeout": 0,
        "noerr": 0,
        "initialize": "function convertLegacyBufferRow(row, createdAt) {\n  if (row.HDate !== undefined && row.HSourceCode !== undefined) {\n    // 已是新格式:保留既有字段和批次引用,只恢复 Date 类型。\n    return {\n      ...row,\n      HDate: new Date(row.HDate),\n      HCreateTime: row.HCreateTime ? new Date(row.HCreateTime) : new Date(createdAt)\n    };\n  }\n  // 部署兼容:旧 sync_rows 使用 s/d/p/v/t,原批语义及原参数名保持不变。\n  const converted = {\n    HItemID: null,\n    HDate: new Date(row.t),\n    HSourceCode: row.d,\n    HTechParamID: 0,\n    HTechParamName: row.p,\n    HCount: row.v,\n    HCreateTime: new Date(createdAt),\n    HResult: String(row.v).slice(0, 50),\n    HProcNumber: row.s,\n    HFlag: 0\n  };\n  if (row.yyRefs?.length) converted._sync = {\n    yyBatchIds: [...row.yyRefs]\n  };\n  return converted;\n}\nconst oldRows = flow.get('sync_rows');\nif (Array.isArray(oldRows) && oldRows.length) {\n  const migratedRows = oldRows.map(row => convertLegacyBufferRow(row, new Date()));\n  if (migratedRows.some(row => !Number.isFinite(row.HDate.getTime()) || !Number.isFinite(row.HCreateTime.getTime()))) throw new Error('旧缓冲时间无效,未覆盖原缓冲');\n  flow.set('sync_rows', migratedRows);\n}\n",
        "finalize": "",
        "libs": [],
        "x": 930,
        "y": 60,
        "wires": [
            [
                "mp_dbg_buffer"
            ],
            []
        ]
    },
    {
        "id": "mp_dbg_buffer",
        "type": "debug",
        "z": "tab_mqtt_pipeline",
        "name": "MQTT 入缓冲摘要",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 910,
        "y": 180,
        "wires": []
    },
    {
        "id": "mp_inject_flush",
        "type": "inject",
        "z": "tab_mqtt_pipeline",
        "name": "MQTT · 每 5s 写库",
        "props": [],
        "repeat": "5",
        "crontab": "",
        "once": true,
        "onceDelay": "8",
        "topic": "",
        "payload": "",
        "payloadType": "date",
        "x": 140,
        "y": 340,
        "wires": [
            [
                "mp_gate_flush"
            ]
        ]
    },
    {
        "id": "mp_fn_flush",
        "type": "function",
        "z": "tab_mqtt_pipeline",
        "name": "MQTT缓冲 → Bulk列数组",
        "func": "/**\n * 缓冲转Bulk请求\n * 输入:每5秒触发\n * 输出:msg.rows=按列定义排列的二维数组;retryBuf=原数据库行\n * 上下文:sync_rows;sync_inflight\n */\nfunction collectionRowKey(row) {\n  // 保留原有自然键编码,兼容旧待确认批次的 doneKeys。\n  return row.HProcNumber + '|' + row.HSourceCode + '|' + row.HTechParamName + '|' + new Date(row.HDate).getTime();\n}\nfunction convertLegacyBufferRow(row, createdAt) {\n  if (row.HDate !== undefined && row.HSourceCode !== undefined) {\n    // 已是新格式:保留既有字段和批次引用,只恢复 Date 类型。\n    return {\n      ...row,\n      HDate: new Date(row.HDate),\n      HCreateTime: row.HCreateTime ? new Date(row.HCreateTime) : new Date(createdAt)\n    };\n  }\n  // 部署兼容:旧 sync_rows 使用 s/d/p/v/t,原批语义及原参数名保持不变。\n  const converted = {\n    HItemID: null,\n    HDate: new Date(row.t),\n    HSourceCode: row.d,\n    HTechParamID: 0,\n    HTechParamName: row.p,\n    HCount: row.v,\n    HCreateTime: new Date(createdAt),\n    HResult: String(row.v).slice(0, 50),\n    HProcNumber: row.s,\n    HFlag: 0\n  };\n  if (row.yyRefs?.length) converted._sync = {\n    yyBatchIds: [...row.yyRefs]\n  };\n  return converted;\n}\nfunction flushCollectionBuffer(msg, flow, global, node) {\nconst __local = global.get('mqtt_pipeline_paused');\nconst __master = global.get('collection_paused');\nconst __running = (__local === false) ? true : (__local === true) ? false : (__master === false);\n  if (!__running) {\n    node.status({\n      fill: 'yellow',\n      shape: 'ring',\n      text: '采集已暂停'\n    });\n    return null;\n  }\n  if (flow.get('mqtt_sync_inflight')) return null;\n  const bufferRows = flow.get('mqtt_sync_rows') || [];\n  if (!bufferRows.length) return null;\n\n  // 1. 最多取5000行。同键只写一次,但合并所有用友批次引用。\n  const selectedRows = bufferRows.slice(0, 5000);\n  const uniqueRows = new Map();\n  const createdAt = new Date();\n  for (const input of selectedRows) {\n    const row = convertLegacyBufferRow(input, createdAt);\n    const key = collectionRowKey(row);\n    const previous = uniqueRows.get(key);\n    const batchIds = new Set([...(previous?._sync?.yyBatchIds || []), ...(row._sync?.yyBatchIds || [])]);\n    if (batchIds.size) row._sync = {\n      yyBatchIds: Array.from(batchIds)\n    };\n    uniqueRows.set(key, row);\n  }\n  const selectedRecords = Array.from(uniqueRows.values());\n\n  // 2. 只有Bulk边界需要二维数组,列顺序集中定义,不再使用r.s/r.d/r.p等缩写。\n  const bulkColumns = [{\n    name: 'HDate',\n    type: 'datetime'\n  }, {\n    name: 'HSourceCode',\n    type: 'varchar(50)'\n  }, {\n    name: 'HTechParamID',\n    type: 'int'\n  }, {\n    name: 'HTechParamName',\n    type: 'varchar(500)'\n  }, {\n    name: 'HCount',\n    type: 'decimal(18,2)'\n  }, {\n    name: 'HCreateTime',\n    type: 'datetime'\n  }, {\n    name: 'HResult',\n    type: 'varchar(50)'\n  }, {\n    name: 'HProcNumber',\n    type: 'varchar(50)'\n  }, {\n    name: 'HFlag',\n    type: 'bit'\n  }].map(column => ({\n    ...column,\n    options: {\n      nullable: false\n    }\n  }));\n  flow.set('mqtt_sync_rows', bufferRows.slice(selectedRows.length));\n  flow.set('mqtt_sync_inflight', true);\n  msg.retryBuf = selectedRecords;\n  msg.bulkColumns = bulkColumns;\n  msg.rows = selectedRecords.map(record => bulkColumns.map(column => record[column.name]));\n  msg.queryParams = bulkColumns.map(column => ({\n    ...column\n  }));\n  msg.query = 'dbo.Sb_EquipMentCollectionTechParam_Temp';\n  msg.queryMode = 'bulk';\n  msg.syncWrittenRows = selectedRecords;\n  msg.syncSkippedRows = [];\n  msg.payload = {\n    table: msg.query,\n    rows: selectedRecords.length\n  };\n  return msg;\n}\nreturn flushCollectionBuffer(msg, flow, global, node);\n",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 470,
        "y": 320,
        "wires": [
            [
                "mp_fn_prepare_bulk"
            ]
        ]
    },
    {
        "id": "mp_fn_prepare_bulk",
        "type": "function",
        "z": "tab_mqtt_pipeline",
        "name": "Bulk分流(MQTT 无用友防重)",
        "func": "/**\n * Bulk前集合防重分流\n * 输入:msg.retryBuf=数据库行\n * 输出:输出1=直接Bulk;输出2=用友防重SELECT请求\n * 上下文:无新增状态;最多1900个SQL参数\n */\nfunction canonicalParameterName(parameterName) {\n  const aliases = {\n    '转速': '机器转速',\n    '班次平均车速': '班次平均转速',\n    '本班产量': '班次产量(源单位)',\n    '本班效率': '班次效率(%)',\n    '本班停机次数': '班次停机次数',\n    '本班停机时间(秒)': '班次停机时间(秒)',\n    '本匹产量': '本匹产量(源单位)'\n  };\n  const name = String(parameterName);\n  // 用友事件里的本班产量附有实际单位,沿用同一班次产量名称。\n  const withUnit = /^本班产量\\((.+)\\)$/.exec(name);\n  if (withUnit) return '班次产量(' + withUnit[1] + ')';\n  return aliases[name] || name;\n}\nfunction equivalentParameterNames(parameterName) {\n  const canonicalName = canonicalParameterName(parameterName);\n  const historicalNames = ['转速', '班次平均车速', '本班产量', '本班效率', '本班停机次数', '本班停机时间(秒)', '本匹产量'];\n  const names = new Set([parameterName, canonicalName]);\n  for (const historicalName of historicalNames) {\n    if (canonicalParameterName(historicalName) === canonicalName) names.add(historicalName);\n  }\n  const withUnit = /^班次产量\\((.+)\\)$/.exec(canonicalName);\n  if (withUnit) names.add('本班产量(' + withUnit[1] + ')');\n  return Array.from(names);\n}\nfunction prepareYouyangDuplicateCheck(msg, flow, global, node) {\n  const youyangRows = (msg.retryBuf || []).filter(row => row.HProcNumber === 'YY');\n  if (!youyangRows.length) return [msg, null];\n\n  // 按源批次收窄时间、设备和参数范围,一次查询整个Bulk批次。\n  const groupsByBatch = new Map();\n  for (const row of youyangRows) {\n    const batchId = row._sync?.yyBatchIds?.[0] || 'untracked';\n    const timestamp = new Date(row.HDate).getTime();\n    if (!groupsByBatch.has(batchId)) {\n      groupsByBatch.set(batchId, {\n        minTime: timestamp,\n        maxTime: timestamp,\n        devices: new Set(),\n        parameters: new Set()\n      });\n    }\n    const group = groupsByBatch.get(batchId);\n    group.minTime = Math.min(group.minTime, timestamp);\n    group.maxTime = Math.max(group.maxTime, timestamp);\n    group.devices.add(row.HSourceCode);\n    for (const name of equivalentParameterNames(row.HTechParamName)) group.parameters.add(name);\n  }\n  let groups = Array.from(groupsByBatch.values());\n  if (groups.length > 128) {\n    const times = youyangRows.map(row => new Date(row.HDate).getTime());\n    groups = [{\n      minTime: Math.min(...times),\n      maxTime: Math.max(...times),\n      devices: new Set(youyangRows.map(row => row.HSourceCode)),\n      parameters: new Set(youyangRows.flatMap(row => equivalentParameterNames(row.HTechParamName)))\n    }];\n  }\n\n  // SQL Server最多2100个参数;预留余量。条件收缩只会多查,不会漏查。\n  const queryParams = [];\n  const predicates = [];\n  const groupBudget = Math.floor(1900 / groups.length) - 2;\n  groups.forEach((group, index) => {\n    const prefix = 'group' + index;\n    queryParams.push({\n      name: prefix + 'MinTime',\n      type: 'datetime',\n      value: new Date(group.minTime)\n    }, {\n      name: prefix + 'MaxTime',\n      type: 'datetime',\n      value: new Date(group.maxTime)\n    });\n    const filters = ['HDate >= @' + prefix + 'MinTime', 'HDate <= @' + prefix + 'MaxTime'];\n    let remainingBudget = groupBudget;\n    for (const filter of [{\n      values: group.parameters,\n      column: 'HTechParamName',\n      type: 'varchar(500)'\n    }, {\n      values: group.devices,\n      column: 'HSourceCode',\n      type: 'varchar(50)'\n    }]) {\n      if (filter.values.size > remainingBudget) continue;\n      const names = Array.from(filter.values).map((value, valueIndex) => {\n        const name = prefix + filter.column + valueIndex;\n        queryParams.push({\n          name,\n          type: filter.type,\n          value\n        });\n        return '@' + name;\n      });\n      filters.push(filter.column + ' IN (' + names.join(', ') + ')');\n      remainingBudget -= filter.values.size;\n    }\n    predicates.push('(' + filters.join(' AND ') + ')');\n  });\n  msg.query = `SET NOCOUNT ON;\nSELECT HDate, HSourceCode, HTechParamName\nFROM dbo.Sb_EquipMentCollectionTechParam_Temp\nWHERE HProcNumber = 'YY'\n  AND (${predicates.join('\\n    OR ')});`;\n  msg.queryParams = queryParams;\n  msg.queryMode = 'query';\n  msg.payload = null;\n  return [null, msg];\n}\nreturn prepareYouyangDuplicateCheck(msg, flow, global, node);\n",
        "outputs": 2,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 750,
        "y": 320,
        "wires": [
            [
                "mp_db_bulk"
            ],
            []
        ]
    },
    {
        "id": "mp_db_bulk",
        "type": "MSSQL",
        "z": "tab_mqtt_pipeline",
        "mssqlCN": "9bb47eb9867c4772",
        "name": "目标库 · bulk 写缓存临时表(MQTT)",
        "outField": "payload",
        "returnType": "0",
        "throwErrors": "1",
        "query": "dbo.Sb_EquipMentCollectionTechParam_Temp",
        "modeOpt": "bulk",
        "modeOptType": "bulk",
        "queryOpt": "",
        "queryOptType": "editor",
        "paramsOpt": "queryParams",
        "paramsOptType": "msg",
        "rows": "rows",
        "rowsType": "msg",
        "parseMustache": false,
        "params": [],
        "x": 870,
        "y": 400,
        "wires": [
            [
                "mp_fn_success"
            ]
        ]
    },
    {
        "id": "mp_fn_success",
        "type": "function",
        "z": "tab_mqtt_pipeline",
        "name": "写库成功 → 统计(MQTT)",
        "func": "/**\n * Bulk成功及批次确认\n * 输入:retryBuf;syncWrittenRows;syncSkippedRows\n * 输出:输出1=写库统计;输出2=整批完成回执\n * 上下文:sync_inflight;sync_yy_batches;sync_written\n */\nfunction collectionRowKey(row) {\n  // 保留原有自然键编码,兼容旧待确认批次的 doneKeys。\n  return row.HProcNumber + '|' + row.HSourceCode + '|' + row.HTechParamName + '|' + new Date(row.HDate).getTime();\n}\nfunction confirmBulkSuccess(msg, flow, global, node) {\n  flow.set('mqtt_sync_inflight', false);\n  const originalRecords = Array.isArray(msg.retryBuf) ? msg.retryBuf : [];\n  const writtenRecords = Array.isArray(msg.syncWrittenRows) ? msg.syncWrittenRows : originalRecords;\n  const skippedRecords = Array.isArray(msg.syncSkippedRows) ? msg.syncSkippedRows : [];\n  const skippedKeys = new Set(skippedRecords.map(collectionRowKey));\n  const pendingBatches = flow.get('sync_yy_batches') || {};\n  const completedBatches = flow.get('sync_yy_completed') || {};\n  const acknowledgements = [];\n\n  // 一个Bulk可以包含多个源批次,也可以只是一个源批次的一部分。\n  for (const record of originalRecords) {\n    const rowKey = collectionRowKey(record);\n    for (const batchId of new Set(record._sync?.yyBatchIds || [])) {\n      const batch = pendingBatches[batchId];\n      if (!batch || batch.doneKeys[rowKey]) continue;\n      batch.doneKeys[rowKey] = true;\n      batch.done += 1;\n      if (skippedKeys.has(rowKey)) batch.skipped += 1;else batch.inserted += 1;\n    }\n  }\n  for (const [batchId, batch] of Object.entries(pendingBatches)) {\n    if (batch.done < batch.expected) continue;\n    const ack = {\n      yySync: batch.meta,\n      yyAck: {\n        kind: 'committed',\n        expected: batch.expected,\n        inserted: batch.inserted,\n        skipped: batch.skipped\n      },\n      payload: {\n        stream: batch.meta.stream,\n        inserted: batch.inserted,\n        skipped: batch.skipped\n      }\n    };\n    acknowledgements.push(ack);\n    completedBatches[batchId] = ack;\n    delete pendingBatches[batchId];\n  }\n  const completedIds = Object.keys(completedBatches);\n  for (const batchId of completedIds.slice(0, Math.max(0, completedIds.length - 256))) delete completedBatches[batchId];\n  flow.set('sync_yy_batches', pendingBatches);\n  flow.set('sync_yy_completed', completedBatches);\n  const totalWritten = (flow.get('mqtt_sync_written') || 0) + writtenRecords.length;\n  flow.set('mqtt_sync_written', totalWritten);\n  flow.set('mqtt_sync_last_success', new Date().toISOString());\n  node.status({\n    fill: 'green',\n    shape: 'dot',\n    text: 'Bulk写入 ' + writtenRecords.length + ' / 已有 ' + skippedRecords.length\n  });\n  return [{\n    payload: {\n      written: writtenRecords.length,\n      skipped: skippedRecords.length,\n      total: totalWritten,\n      pending: (flow.get('mqtt_sync_rows') || []).length,\n      yyPendingBatches: Object.keys(pendingBatches).length\n    }\n  }, acknowledgements];\n}\nreturn confirmBulkSuccess(msg, flow, global, node);\n",
        "outputs": 2,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 1100,
        "y": 320,
        "wires": [
            [
                "mp_dbg_success"
            ],
            []
        ]
    },
    {
        "id": "mp_dbg_success",
        "type": "debug",
        "z": "tab_mqtt_pipeline",
        "name": "MQTT 入库结果",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 1240,
        "y": 400,
        "wires": []
    },
    {
        "id": "mp_catch",
        "type": "catch",
        "z": "tab_mqtt_pipeline",
        "name": "MQTT 采集写库异常",
        "scope": [
            "mp_db_bulk",
            "mp_fn_prepare_bulk",
            "mp_fn_flush",
            "mp_fn_buffer"
        ],
        "uncaught": false,
        "x": 120,
        "y": 460,
        "wires": [
            [
                "mp_fn_retry"
            ]
        ]
    },
    {
        "id": "mp_fn_retry",
        "type": "function",
        "z": "tab_mqtt_pipeline",
        "name": "失败回填缓冲(MQTT)",
        "func": "/**\n * 失败原批回填\n * 输入:失败请求,msg.retryBuf和msg.error\n * 输出:输出1=错误摘要;输出2=用友重试通知\n * 上下文:sync_rows;sync_inflight\n */\nfunction requeueFailedBulk(msg, flow, global, node) {\n  const retryRecords = Array.isArray(msg.retryBuf) ? msg.retryBuf : [];\n  if (retryRecords.length) flow.set('mqtt_sync_rows', retryRecords.concat(flow.get('mqtt_sync_rows') || []));\n  flow.set('mqtt_sync_inflight', false);\n  const errorMessage = typeof msg.error === 'string' ? msg.error : msg.error?.details || msg.error?.message || 'Bulk或防重预查失败';\n  const pendingBatches = flow.get('sync_yy_batches') || {};\n  const affectedBatchIds = new Set(retryRecords.flatMap(row => row._sync?.yyBatchIds || []));\n  const acknowledgements = Array.from(affectedBatchIds).filter(batchId => pendingBatches[batchId]).map(batchId => ({\n    yySync: pendingBatches[batchId].meta,\n    yyAck: {\n      kind: 'retrying',\n      reason: errorMessage\n    }\n  }));\n  node.status({\n    fill: 'red',\n    shape: 'ring',\n    text: '失败回填 ' + retryRecords.length + ' 行,水位未推进'\n  });\n  return [{\n    payload: {\n      error: errorMessage,\n      requeued: retryRecords.length\n    }\n  }, acknowledgements];\n}\nreturn requeueFailedBulk(msg, flow, global, node);\n",
        "outputs": 2,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 360,
        "y": 460,
        "wires": [
            [
                "mp_dbg_error"
            ],
            []
        ]
    },
    {
        "id": "mp_dbg_error",
        "type": "debug",
        "z": "tab_mqtt_pipeline",
        "name": "MQTT 异常详情",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 620,
        "y": 460,
        "wires": []
    },
    {
        "id": "mp_gate_in",
        "type": "function",
        "z": "tab_mqtt_pipeline",
        "name": "启停闸门 · 入口(本页签)",
        "func": "/**\n * 本页签独立启停闸门(入口)\n * 优先本页签开关 mqtt_pipeline_paused:true=停止,false=运行\n * 未设置(undefined)时回落到总开关 collection_paused\n */\nconst local = global.get('mqtt_pipeline_paused');\nconst master = global.get('collection_paused');\nconst running = (local === false) ? true : (local === true) ? false : (master === false);\nif (!running) {\n  node.status({ fill: 'grey', shape: 'ring', text: local === true ? '本页签已停止' : '未启动/总开关暂停' });\n  return null;\n}\nnode.status({ fill: 'green', shape: 'dot', text: '采集中' });\nreturn msg;",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 360,
        "y": 240,
        "wires": [
            [
                "mp_fn_parse"
            ]
        ]
    },
    {
        "id": "mp_gate_flush",
        "type": "function",
        "z": "tab_mqtt_pipeline",
        "name": "启停闸门 · 写库(本页签)",
        "func": "/**\n * 本页签独立启停闸门(写库)\n * 规则同入口闸门;停止时缓冲保留、不写库\n */\nconst local = global.get('mqtt_pipeline_paused');\nconst master = global.get('collection_paused');\nconst running = (local === false) ? true : (local === true) ? false : (master === false);\nif (!running) {\n  node.status({ fill: 'grey', shape: 'ring', text: '本页签已停止,缓冲保留' });\n  return null;\n}\nnode.status({ fill: 'green', shape: 'dot', text: '写库中' });\nreturn msg;",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 340,
        "y": 400,
        "wires": [
            [
                "mp_fn_flush"
            ]
        ]
    },
    {
        "id": "mp_ctl_pause",
        "type": "inject",
        "z": "tab_mqtt_pipeline",
        "name": "⏸ 停止本页签(测试)",
        "props": [
            {
                "p": "payload"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "pause",
        "payloadType": "str",
        "x": 160,
        "y": 560,
        "wires": [
            [
                "mp_ctl_fn"
            ]
        ]
    },
    {
        "id": "mp_ctl_resume",
        "type": "inject",
        "z": "tab_mqtt_pipeline",
        "name": "▶ 启动本页签(测试)",
        "props": [
            {
                "p": "payload"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "resume",
        "payloadType": "str",
        "x": 160,
        "y": 620,
        "wires": [
            [
                "mp_ctl_fn"
            ]
        ]
    },
    {
        "id": "mp_ctl_fn",
        "type": "function",
        "z": "tab_mqtt_pipeline",
        "name": "独立启停开关",
        "func": "/**\n * 本页签独立启停开关(测试用)\n * 输入:msg.payload = 'pause' | 'resume'\n * 输出:开关状态\n * 上下文:global mqtt_pipeline_paused;global mqtt_pipeline_state\n */\nconst action = String(msg.payload || '').trim().toLowerCase();\nif (action !== 'pause' && action !== 'resume') {\n  node.warn('未知开关指令:' + action + '(只接受 pause / resume)');\n  return null;\n}\nconst paused = action === 'pause';\nglobal.set('mqtt_pipeline_paused', paused);\nconst state = {\n  paused: paused,\n  changedAt: new Date().toISOString(),\n  note: paused ? '本页签停止:丢弃新报文,缓冲保留不写库' : '本页签运行:正常采集并写库(仍受总开关约束)'\n};\nglobal.set('mqtt_pipeline_state', state);\nnode.status({ fill: paused ? 'grey' : 'green', shape: paused ? 'ring' : 'dot', text: paused ? '已停止' : '运行中' });\nreturn { payload: state };",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 440,
        "y": 590,
        "wires": [
            [
                "mp_ctl_dbg"
            ]
        ]
    },
    {
        "id": "mp_ctl_dbg",
        "type": "debug",
        "z": "tab_mqtt_pipeline",
        "name": "启停状态",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 620,
        "y": 590,
        "wires": []
    },
    {
        "id": "3177176df4850606",
        "type": "global-config",
        "env": [],
        "modules": {
            "node-red-contrib-mssql-plus": "0.13.1"
        }
    }
]