yeg
2026-08-29 14ac9c2a2384f1e55b4c01eb7a104033b589d1e0
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
package com.ruoyi.device.bts;
 
import java.io.IOException;
import java.io.StringReader;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import com.ruoyi.device.model.DeviceWorkStatus;
import com.ruoyi.device.simulator.BtsSimulatorStateStore;
import com.ruoyi.device.simulator.BtsSimulatorStateStore.ChannelState;
import com.ruoyi.device.simulator.BtsSimulatorStateStore.ChannelTombstone;
import com.ruoyi.device.simulator.BtsSimulatorStateStore.CollectorChannelState;
import com.ruoyi.device.simulator.BtsSimulatorStateStore.CollectorHistoryAppend;
import com.ruoyi.device.simulator.BtsSimulatorStateStore.CollectorHistoryFaults;
import com.ruoyi.device.simulator.BtsSimulatorStateStore.CollectorMeasurementRecord;
import com.ruoyi.device.simulator.BtsSimulatorStateStore.CollectorMetricState;
import com.ruoyi.device.simulator.BtsSimulatorStateStore.CollectorRealtimeMeasurement;
import com.ruoyi.device.simulator.BtsSimulatorStateStore.CollectorState;
import com.ruoyi.device.simulator.BtsSimulatorStateStore.DeviceState;
import com.ruoyi.device.simulator.BtsSimulatorStateStore.RecentRequest;
import com.ruoyi.device.simulator.BtsSimulatorStateStore.SimulatorState;
import com.ruoyi.device.simulator.InMemoryBtsSimulatorStateStore;
import com.ruoyi.device.simulator.DevelopmentCollectorSimulation;
import com.ruoyi.device.simulator.DevelopmentCollectorSimulation.CollectorAdvance;
import com.ruoyi.device.simulator.DevelopmentCollectorSimulation.CollectorHistoryPage;
import com.ruoyi.device.simulator.DevelopmentCollectorSimulation.CollectorRealtimeSnapshot;
 
/** 提供由开发后端托管的临时只读 BTS 模拟端点。 */
public final class BtsDevelopmentSimulator implements AutoCloseable
{
    public static final String HOST = "127.0.0.1";
    public static final int DEFAULT_PORT = 15020;
    public static final String ADAPTER_CODE = "dev-sim";
    public static final String ADAPTER_NAME = "dev-sim BTS 模拟器";
    public static final int POLL_INTERVAL_MS = 5000;
 
    private static final int DEVICE_TYPE = 22;
    private static final int SUB_DEVICE_ID = 1;
    private static final int MAX_CHANNEL_COUNT = 99;
    private static final int MAX_RECENT_REQUESTS = 20;
    private static final int TOMBSTONE_DISCOVERY_COUNT = 3;
 
    private final ScriptedBtsTcpSimulator simulator;
    private final BtsSimulatorStateStore stateStore;
    private SimulatorState state;
    private boolean running = true;
 
    /** 启动仅监听 IPv4 本机回环地址的开发模拟器;传入 0 时由系统分配测试端口。 */
    public BtsDevelopmentSimulator(int port) throws IOException
    {
        this(port, new InMemoryBtsSimulatorStateStore());
    }
 
    /** 从长期状态恢复后再启动 TCP 服务,避免服务先暴露默认拓扑。 */
    public BtsDevelopmentSimulator(int port, BtsSimulatorStateStore stateStore) throws IOException
    {
        this.stateStore = stateStore;
        state = stateStore.loadOrInitialize(defaultState());
        validateRestoredState();
        stateStore.completeValidatedRestore(state);
        simulator = ScriptedBtsTcpSimulator.responding(port, this::respond);
    }
 
    public int port()
    {
        return simulator.port();
    }
 
    /** 新增一台具有独立虚拟 IP 和通道数的开发设备。 */
    public synchronized int addDevice(String ip, int channelCount)
    {
        validateDeviceConfiguration(ip, channelCount, null);
        int deviceId = state.nextDeviceId();
        List<DeviceState> devices = new ArrayList<>(state.devices());
        devices.add(newDevice(deviceId, ip, channelCount));
        persist(new SimulatorState(BtsSimulatorStateStore.CURRENT_VERSION, devices, state.collectors(),
                deviceId + 1, state.nextCollectorId(), state.tombstones()));
        return deviceId;
    }
 
    /** 修改开发设备的虚拟地址、通道数和在线状态。 */
    public synchronized void updateDevice(int deviceId, String ip, int channelCount, boolean online)
    {
        DeviceState current = requireDevice(deviceId);
        validateDeviceConfiguration(ip, channelCount, deviceId);
        List<ChannelState> channels = new ArrayList<>(channelCount);
        for (int channelId = 1; channelId <= channelCount; channelId++)
        {
            channels.add(channelId <= current.channels().size()
                    ? current.channels().get(channelId - 1)
                    : new ChannelState(channelId, true, DeviceWorkStatus.STOPPED));
        }
        List<DeviceState> devices = replaceDevice(new DeviceState(deviceId, ip.trim(), online, channels));
        List<ChannelTombstone> tombstones = new ArrayList<>(state.tombstones());
        for (int channelId = channelCount + 1; channelId <= current.channels().size(); channelId++)
            upsertTombstone(tombstones, current.deviceId(), current.ip(), channelId);
        tombstones.removeIf(item -> item.deviceId() == deviceId && item.channelId() <= channelCount);
        persist(new SimulatorState(state.version(), devices, state.collectors(), state.nextDeviceId(),
                state.nextCollectorId(), tombstones));
    }
 
    /** 删除指定开发设备;后续发现响应不再返回它。 */
    public synchronized void deleteDevice(int deviceId)
    {
        DeviceState removed = requireDevice(deviceId);
        List<DeviceState> devices = new ArrayList<>(state.devices());
        devices.removeIf(item -> item.deviceId() == deviceId);
        List<ChannelTombstone> tombstones = new ArrayList<>(state.tombstones());
        for (ChannelState channel : removed.channels())
            upsertTombstone(tombstones, removed.deviceId(), removed.ip(), channel.channelId());
        persist(new SimulatorState(state.version(), devices, state.collectors(), state.nextDeviceId(),
                state.nextCollectorId(), tombstones));
    }
 
    /** 修改指定开发设备的单个通道状态。 */
    public synchronized void updateChannel(int deviceId, int channelId, boolean online,
            DeviceWorkStatus workStatus)
    {
        requireControllableStatus(workStatus);
        DeviceState device = requireDevice(deviceId);
        if (channelId < 1 || channelId > device.channels().size())
            throw new IllegalArgumentException("channelId must be between 1 and " + device.channels().size());
        List<ChannelState> channels = new ArrayList<>(device.channels());
        channels.set(channelId - 1, new ChannelState(channelId, online, workStatus));
        persist(new SimulatorState(state.version(),
                replaceDevice(new DeviceState(deviceId, device.ip(), device.online(), channels)), state.collectors(),
                state.nextDeviceId(), state.nextCollectorId(), state.tombstones()));
    }
 
    /** 新增一台与 BTS 检测柜拓扑隔离的开发采集器。 */
    public synchronized int addCollector(String ip, int channelCount)
    {
        validateCollectorConfiguration(ip, channelCount, null);
        int collectorId = state.nextCollectorId();
        List<CollectorState> collectors = new ArrayList<>(state.collectors());
        collectors.add(newCollector(collectorId, ip, channelCount));
        persist(new SimulatorState(state.version(), state.devices(), collectors, state.nextDeviceId(),
                collectorId + 1, state.tombstones()));
        return collectorId;
    }
 
    /** 修改开发采集器的虚拟地址、通道数和在线状态。 */
    public synchronized void updateCollector(int collectorId, String ip, int channelCount, boolean online)
    {
        validateCollectorConfiguration(ip, channelCount, collectorId);
        CollectorState current = requireCollector(collectorId);
        List<CollectorState> collectors = new ArrayList<>(state.collectors());
        collectors.replaceAll(item -> item.collectorId() == collectorId
                ? DevelopmentCollectorSimulation.resize(current, ip, channelCount, online, Instant.now())
                : item);
        persist(new SimulatorState(state.version(), state.devices(), collectors, state.nextDeviceId(),
                state.nextCollectorId(), state.tombstones()));
    }
 
    /** 删除指定开发采集器,不影响检测柜 TCP 发现结果。 */
    public synchronized void deleteCollector(int collectorId)
    {
        CollectorState collector = requireCollector(collectorId);
        List<CollectorState> collectors = new ArrayList<>(state.collectors());
        collectors.removeIf(item -> item.collectorId() == collectorId);
        SimulatorState next = new SimulatorState(state.version(), state.devices(), collectors, state.nextDeviceId(),
                state.nextCollectorId(), state.tombstones());
        stateStore.saveAndDeleteCollectorHistory(next, collector.deviceCode());
        this.state = next;
    }
 
    /** 配置采集器独立采样频率和历史下载故障场景。 */
    public synchronized void configureCollectorSampling(int collectorId, int sampleIntervalMs,
            CollectorHistoryFaults historyFaults)
    {
        CollectorState current = requireCollector(collectorId);
        replaceCollector(DevelopmentCollectorSimulation.configureSampling(current, sampleIntervalMs, historyFaults));
    }
 
    /** 配置一个稳定 S 通道的固定或动态演示指标。 */
    public synchronized void configureCollectorChannel(int collectorId, String channelCode,
            List<CollectorMetricState> metrics)
    {
        CollectorState current = requireCollector(collectorId);
        replaceCollector(DevelopmentCollectorSimulation.configureChannel(current, channelCode, metrics));
    }
 
    /** 模拟现场人工统一开关机;只改变模拟设备事实,不代表系统具备真实设备控制能力。 */
    public synchronized void setAllDevicesPoweredOn(boolean poweredOn)
    {
        List<DeviceState> devices = state.devices().stream()
                .map(device -> new DeviceState(device.deviceId(), device.ip(), poweredOn,
                        device.channels().stream()
                                .map(channel -> new ChannelState(channel.channelId(), poweredOn,
                                        DeviceWorkStatus.STOPPED))
                                .toList()))
                .toList();
        Instant changedAt = Instant.now();
        List<CollectorState> collectors = state.collectors().stream()
                .map(collector -> DevelopmentCollectorSimulation.resize(collector, collector.ip(),
                        collector.channelCount(), poweredOn, changedAt))
                .toList();
        persist(new SimulatorState(state.version(), devices, collectors, state.nextDeviceId(),
                state.nextCollectorId(), state.tombstones()));
    }
 
    /** 按每台采集器自己的频率推进实时和历史采样。 */
    public synchronized void advanceCollectors(Instant now)
    {
        boolean hasOnlineCollector = false;
        for (CollectorState collector : state.collectors())
        {
            if (!collector.online()) continue;
            hasOnlineCollector = true;
            break;
        }
        if (!hasOnlineCollector) return;
        List<CollectorState> collectors = new ArrayList<>(state.collectors().size());
        List<CollectorHistoryAppend> historyAppends = new ArrayList<>();
        for (CollectorState collector : state.collectors())
        {
            CollectorAdvance advance = DevelopmentCollectorSimulation.advance(collector, now);
            collectors.add(advance.state());
            if (!advance.appendedRecords().isEmpty())
                historyAppends.add(new CollectorHistoryAppend(collector.deviceCode(), advance.appendedRecords()));
        }
        if (!historyAppends.isEmpty())
            persist(new SimulatorState(state.version(), state.devices(), collectors, state.nextDeviceId(),
                    state.nextCollectorId(), state.tombstones()), historyAppends);
    }
 
    /** 返回采集器最新实时快照;快照与分页历史保持不同读取路径。 */
    public synchronized CollectorRealtimeSnapshot collectorRealtime(int collectorId)
    {
        return DevelopmentCollectorSimulation.realtime(requireCollector(collectorId));
    }
 
    /** 分页下载采集器模拟历史,并应用已配置的重复、冲突、乱序或缺失场景。 */
    public synchronized CollectorHistoryPage collectorHistory(int collectorId, long offset, int limit)
    {
        CollectorState collector = requireCollector(collectorId);
        return DevelopmentCollectorSimulation.history(collector, stateStore, offset, limit);
    }
 
    /** 返回控制页需要的运行状态快照。 */
    public synchronized StateSnapshot snapshot()
    {
        List<DeviceSnapshot> deviceSnapshots = state.devices().stream()
                .map(device -> new DeviceSnapshot(device.deviceId(), device.ip(), device.online(),
                        device.channels().stream()
                                .map(channel -> new ChannelSnapshot(channel.channelId(), channel.online(),
                                        channel.workStatus()))
                                .toList()))
                .toList();
        List<CollectorSnapshot> collectorSnapshots = state.collectors().stream()
                .map(collector -> new CollectorSnapshot(collector.collectorId(), collector.deviceCode(),
                        collector.ip(), collector.mac(), collector.name(), collector.manufacturer(),
                        collector.model(), collector.channelCount(), collector.online(), collector.sampleIntervalMs(),
                        collector.channels(), collector.historyFaults(), collector.historyRecordCount(),
                        DevelopmentCollectorSimulation.realtime(collector).measurements()))
                .toList();
        return new StateSnapshot(running, HOST + ":" + port(), deviceSnapshots, collectorSnapshots,
                stateStore.loadRecentRequests());
    }
 
    /** 人工恢复默认拓扑;这是正常运行中唯一清空长期模拟状态的入口。 */
    public synchronized void reset()
    {
        SimulatorState defaultState = defaultState();
        stateStore.reset(defaultState);
        state = defaultState;
    }
 
    private SimulatorState defaultState()
    {
        return new SimulatorState(BtsSimulatorStateStore.CURRENT_VERSION,
                List.of(newDevice(1, "127.0.0.2", 4)),
                List.of(newCollector(1, "127.0.1.2", 4)), 2, 2, List.of());
    }
 
    private DeviceState newDevice(int deviceId, String ip, int channelCount)
    {
        List<ChannelState> channels = new ArrayList<>(channelCount);
        for (int channelId = 1; channelId <= channelCount; channelId++)
            channels.add(new ChannelState(channelId, true, DeviceWorkStatus.STOPPED));
        return new DeviceState(deviceId, ip.trim(), true, channels);
    }
 
    private CollectorState newCollector(int collectorId, String ip, int channelCount)
    {
        return new CollectorState(collectorId, "dev-sim-collector-" + collectorId,
                ip.trim(), simulatorCollectorMac(collectorId), "dev-sim 采集器 " + collectorId,
                "开发模拟器", "Virtual Collector", channelCount, true);
    }
 
    private void replaceCollector(CollectorState replacement)
    {
        List<CollectorState> collectors = new ArrayList<>(state.collectors());
        collectors.replaceAll(item -> item.collectorId() == replacement.collectorId() ? replacement : item);
        persist(new SimulatorState(state.version(), state.devices(), collectors, state.nextDeviceId(),
                state.nextCollectorId(), state.tombstones()));
    }
 
    private String respond(String request)
    {
        String command = readCommand(request);
        recordRequest(command, request);
        return switch (command)
        {
            case "getdevinfo" -> deviceInfoResponse();
            case "inquire" -> observationResponse();
            default -> "<bts version=\"1.0\"><cmd>error</cmd></bts>";
        };
    }
 
    private synchronized void recordRequest(String command, String request)
    {
        List<RecentRequest> recentRequests = new ArrayList<>(stateStore.loadRecentRequests());
        recentRequests.add(0, new RecentRequest(Instant.now(), command, request));
        if (recentRequests.size() > MAX_RECENT_REQUESTS)
            recentRequests = new ArrayList<>(recentRequests.subList(0, MAX_RECENT_REQUESTS));
        stateStore.saveRecentRequests(recentRequests);
    }
 
    private String readCommand(String request)
    {
        try
        {
            XMLInputFactory factory = XMLInputFactory.newFactory();
            factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
            factory.setProperty("javax.xml.stream.isSupportingExternalEntities", false);
            XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(request));
            while (reader.hasNext())
            {
                if (reader.next() == XMLStreamConstants.START_ELEMENT && "cmd".equals(reader.getLocalName()))
                    return reader.getElementText().trim();
            }
        }
        catch (Exception exception)
        {
            throw new IllegalArgumentException("Invalid BTS request XML", exception);
        }
        throw new IllegalArgumentException("BTS request does not contain cmd");
    }
 
    private synchronized String deviceInfoResponse()
    {
        int channelCount = state.devices().stream().mapToInt(device -> device.channels().size()).sum()
                + state.tombstones().size();
        StringBuilder response = new StringBuilder("<bts version=\"1.0\"><cmd>getdevinfo_resp</cmd>")
                .append("<serverip count=\"0\"/><middle count=\"").append(channelCount).append("\">");
        for (DeviceState device : state.devices())
        {
            for (ChannelState channel : device.channels())
            {
                boolean available = device.online() && channel.online();
                appendDiscoveredChannel(response, device.deviceId(), device.ip(), channel.channelId(), available);
            }
        }
        List<ChannelTombstone> remaining = new ArrayList<>();
        for (ChannelTombstone tombstone : state.tombstones())
        {
            appendDiscoveredChannel(response, tombstone.deviceId(), tombstone.ip(), tombstone.channelId(), false);
            if (tombstone.remainingDiscoveries() > 1)
                remaining.add(new ChannelTombstone(tombstone.deviceId(), tombstone.ip(), tombstone.channelId(),
                        tombstone.remainingDiscoveries() - 1));
        }
        if (!remaining.equals(state.tombstones()))
            persist(new SimulatorState(state.version(), state.devices(), state.collectors(), state.nextDeviceId(),
                    state.nextCollectorId(), remaining));
        return response.append("</middle></bts>").toString();
    }
 
    private void appendDiscoveredChannel(StringBuilder response, int deviceId, String ip, int channelId,
            boolean available)
    {
        // 展示元数据是开发模拟器扩展,不代表真实 BTS 协议必然提供这些属性。
        response.append("<channel ip=\"").append(ip).append("\" devtype=\"").append(DEVICE_TYPE)
                .append("\" devid=\"").append(deviceId).append("\" subdevid=\"").append(SUB_DEVICE_ID)
                .append("\" Channelid=\"").append(channelId).append("\" name=\"dev-sim 设备 ")
                .append(deviceId).append("\" manufacturer=\"开发模拟器\" model=\"BTS Virtual Cabinet\" mac=\"")
                .append(simulatorMac(DEVICE_TYPE, deviceId)).append("\">")
                .append(available).append("</channel>");
    }
 
    private synchronized String observationResponse()
    {
        List<ObservedChannel> available = new ArrayList<>();
        for (DeviceState device : state.devices())
            for (ChannelState channel : device.channels())
                if (device.online() && channel.online()) available.add(new ObservedChannel(device.deviceId(), channel));
 
        StringBuilder response = new StringBuilder("<bts version=\"1.0\"><cmd>inquire_resp</cmd><list count=\"")
                .append(available.size()).append("\">");
        for (ObservedChannel observed : available)
        {
            ChannelState channel = observed.channel();
            response.append("<inquire dev=\"").append(DEVICE_TYPE).append('-').append(observed.deviceId())
                    .append('-').append(SUB_DEVICE_ID).append('-').append(channel.channelId())
                    .append("-0\" cycle_id=\"1\" step_id=\"1\" step_type=\"cc\" workstatus=\"")
                    .append(toBtsWorkStatus(channel.workStatus()))
                    .append("\" current=\"0\" voltage=\"3.700\" capacity=\"0\" energy=\"0\" ")
                    .append("totaltime=\"0\" relativetime=\"0\" open_or_close=\"0\" log_code=\"0\"/>");
        }
        return response.append("</list></bts>").toString();
    }
 
    private String toBtsWorkStatus(DeviceWorkStatus status)
    {
        return switch (status)
        {
            case STOPPED -> "stop";
            case WORKING -> "working";
            case PAUSED -> "pause";
            case FINISHED -> "finish";
            default -> throw new IllegalArgumentException("Unsupported simulator work status: " + status);
        };
    }
 
    private void validateDeviceConfiguration(String ip, int channelCount, Integer currentDeviceId)
    {
        if (!isIpv4(ip)) throw new IllegalArgumentException("Simulator device IP must be a valid IPv4 address");
        if (channelCount < 1 || channelCount > MAX_CHANNEL_COUNT)
            throw new IllegalArgumentException("channelCount must be between 1 and " + MAX_CHANNEL_COUNT);
        boolean duplicate = state.devices().stream()
                .anyMatch(device -> device.ip().equals(ip.trim())
                        && device.deviceId() != (currentDeviceId == null ? -1 : currentDeviceId));
        duplicate = duplicate || state.collectors().stream().anyMatch(collector -> collector.ip().equals(ip.trim()));
        if (duplicate) throw new IllegalArgumentException("Simulator device IP must be unique");
    }
 
    private void validateCollectorConfiguration(String ip, int channelCount, Integer currentCollectorId)
    {
        if (!isIpv4(ip)) throw new IllegalArgumentException("Simulator collector IP must be a valid IPv4 address");
        if (channelCount < 1 || channelCount > MAX_CHANNEL_COUNT)
            throw new IllegalArgumentException("channelCount must be between 1 and " + MAX_CHANNEL_COUNT);
        boolean duplicate = state.collectors().stream()
                .anyMatch(collector -> collector.ip().equals(ip.trim())
                        && collector.collectorId() != (currentCollectorId == null ? -1 : currentCollectorId));
        duplicate = duplicate || state.devices().stream().anyMatch(device -> device.ip().equals(ip.trim()));
        if (duplicate) throw new IllegalArgumentException("Simulator collector IP must be unique");
    }
 
    private boolean isIpv4(String ip)
    {
        if (ip == null) return false;
        String[] parts = ip.trim().split("\\.", -1);
        if (parts.length != 4) return false;
        for (String part : parts)
        {
            try
            {
                int value = Integer.parseInt(part);
                if (part.isEmpty() || value < 0 || value > 255) return false;
            }
            catch (NumberFormatException exception)
            {
                return false;
            }
        }
        return true;
    }
 
    private DeviceState requireDevice(int deviceId)
    {
        return state.devices().stream().filter(item -> item.deviceId() == deviceId).findFirst()
                .orElseThrow(() -> new IllegalArgumentException("Unknown simulator device: " + deviceId));
    }
 
    private CollectorState requireCollector(int collectorId)
    {
        return state.collectors().stream().filter(item -> item.collectorId() == collectorId).findFirst()
                .orElseThrow(() -> new IllegalArgumentException("Unknown simulator collector: " + collectorId));
    }
 
    private List<DeviceState> replaceDevice(DeviceState replacement)
    {
        List<DeviceState> devices = new ArrayList<>(state.devices());
        devices.replaceAll(item -> item.deviceId() == replacement.deviceId() ? replacement : item);
        return devices;
    }
 
    private void upsertTombstone(List<ChannelTombstone> tombstones, int deviceId, String ip, int channelId)
    {
        tombstones.removeIf(item -> item.deviceId() == deviceId && item.channelId() == channelId);
        tombstones.add(new ChannelTombstone(deviceId, ip, channelId, TOMBSTONE_DISCOVERY_COUNT));
    }
 
    private void persist(SimulatorState nextState)
    {
        // 写穿失败时保留当前内存副本,避免控制页显示未持久化状态。
        stateStore.save(nextState);
        state = nextState;
    }
 
    private void persist(SimulatorState nextState, List<CollectorHistoryAppend> historyAppends)
    {
        // 主状态与原始历史批次必须一起成功,内存序号才能向前推进。
        stateStore.save(nextState, historyAppends);
        state = nextState;
    }
 
    private String simulatorMac(int devtype, int devid)
    {
        return String.format("02:44:%02X:%02X:%02X:%02X",
                (devtype >>> 8) & 0xFF, devtype & 0xFF, (devid >>> 8) & 0xFF, devid & 0xFF);
    }
 
    private String simulatorCollectorMac(int collectorId)
    {
        return String.format("02:43:00:00:%02X:%02X", (collectorId >>> 8) & 0xFF, collectorId & 0xFF);
    }
 
    private void requireControllableStatus(DeviceWorkStatus status)
    {
        if (status == null || (status != DeviceWorkStatus.STOPPED && status != DeviceWorkStatus.WORKING
                && status != DeviceWorkStatus.PAUSED && status != DeviceWorkStatus.FINISHED))
            throw new IllegalArgumentException("Simulator work status must be STOPPED, WORKING, PAUSED or FINISHED");
    }
 
    private void validateRestoredState()
    {
        java.util.Set<Integer> deviceIds = new java.util.HashSet<>();
        java.util.Set<Integer> collectorIds = new java.util.HashSet<>();
        java.util.Set<String> ips = new java.util.HashSet<>();
        int maximumDeviceId = 0;
        for (DeviceState device : state.devices())
        {
            if (device.deviceId() < 1 || !deviceIds.add(device.deviceId()) || !isIpv4(device.ip())
                    || !ips.add(device.ip()) || device.channels().isEmpty()
                    || device.channels().size() > MAX_CHANNEL_COUNT)
                throw new IllegalStateException("Invalid BTS simulator device state in Redis");
            maximumDeviceId = Math.max(maximumDeviceId, device.deviceId());
            for (int index = 0; index < device.channels().size(); index++)
            {
                ChannelState channel = device.channels().get(index);
                if (channel.channelId() != index + 1)
                    throw new IllegalStateException("Invalid BTS simulator channel state in Redis");
                requireControllableStatus(channel.workStatus());
            }
        }
        int maximumCollectorId = 0;
        for (CollectorState collector : state.collectors())
        {
            if (collector.collectorId() < 1 || !collectorIds.add(collector.collectorId())
                    || !isIpv4(collector.ip()) || !ips.add(collector.ip())
                    || collector.channelCount() < 1 || collector.channelCount() > MAX_CHANNEL_COUNT)
                throw new IllegalStateException("Invalid BTS simulator collector state in Redis");
            DevelopmentCollectorSimulation.validate(collector, stateStore);
            maximumCollectorId = Math.max(maximumCollectorId, collector.collectorId());
        }
        java.util.Set<String> tombstoneIds = new java.util.HashSet<>();
        boolean invalidTombstone = state.tombstones().stream().anyMatch(item -> item.deviceId() < 1
                || !isIpv4(item.ip()) || item.channelId() < 1 || item.channelId() > MAX_CHANNEL_COUNT
                || item.remainingDiscoveries() < 1 || item.remainingDiscoveries() > TOMBSTONE_DISCOVERY_COUNT
                || !tombstoneIds.add(item.deviceId() + ":" + item.channelId()));
        if (state.nextDeviceId() <= maximumDeviceId || state.nextCollectorId() <= maximumCollectorId
                || invalidTombstone)
            throw new IllegalStateException("Invalid BTS simulator numbering or tombstone state in Redis");
    }
 
    @Override
    public synchronized void close() throws Exception
    {
        running = false;
        simulator.close();
    }
 
    private record ObservedChannel(int deviceId, ChannelState channel) { }
 
    public record StateSnapshot(boolean running, String listenAddress, List<DeviceSnapshot> devices,
            List<CollectorSnapshot> collectors, List<RecentRequest> recentRequests) { }
 
    public record DeviceSnapshot(int deviceId, String ip, boolean online, List<ChannelSnapshot> channels) { }
 
    public record ChannelSnapshot(int channelId, boolean online, DeviceWorkStatus workStatus) { }
 
    public record CollectorSnapshot(int collectorId, String deviceCode, String ip, String mac, String name,
            String manufacturer, String model, int channelCount, boolean online, int sampleIntervalMs,
            List<CollectorChannelState> channels, CollectorHistoryFaults historyFaults, long historyRecordCount,
            List<CollectorRealtimeMeasurement> latestMeasurements)
    {
        public CollectorSnapshot
        {
            channels = List.copyOf(channels);
            latestMeasurements = List.copyOf(latestMeasurements);
        }
    }
 
}