yeg
2026-09-02 c2dd019c1fddaeae412e2b6f44fb86ff0dc635d4
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
package com.ruoyi.config;
 
import java.math.BigDecimal;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.device.simulator.BtsSimulatorStateStore;
import com.ruoyi.device.simulator.BtsSimulatorStateStore.BtsDeviceProfile;
import com.ruoyi.device.simulator.BtsSimulatorStateStore.BtsHistoryBatch;
import com.ruoyi.device.simulator.BtsSimulatorStateStore.BtsHistoryRecord;
import com.ruoyi.device.simulator.BtsSimulatorStateStore.BtsPlaybackState;
import com.ruoyi.device.model.DeviceWorkStatus;
 
/** 将开发模拟器完整状态写入 Redis,主状态不设置普通 TTL。 */
@Component
public class RedisBtsSimulatorStateStore implements BtsSimulatorStateStore
{
    static final String STATE_KEY = "dev:bts-simulator:state:v1";
    static final String RECENT_REQUESTS_KEY = "dev:bts-simulator:recent-requests:v1";
    static final String HISTORY_KEYS_KEY = "dev:bts-simulator:collector-history-keys:v1";
    static final String HISTORY_KEY_PREFIX = "dev:bts-simulator:collector-history:v1:";
    // Ticket21 fixture 变更后切换独立 key 版本,避免把旧的 3 循环演示历史恢复到新时间轴。
    static final String BTS_HISTORY_KEYS_KEY = "dev:bts-simulator:bts-history-keys:v2";
    static final String BTS_HISTORY_KEY_PREFIX = "dev:bts-simulator:bts-history:v2:";
    static final String BTS_PLAYBACK_KEY_PREFIX = "dev:bts-simulator:bts-playback:v2:";
    private static final long RECENT_REQUESTS_TTL_HOURS = 1;
 
    private final RedisTemplate<Object, Object> redisTemplate;
    private List<CollectorHistoryAppend> pendingEmbeddedHistory = List.of();
 
    public RedisBtsSimulatorStateStore(RedisTemplate<Object, Object> redisTemplate)
    {
        this.redisTemplate = redisTemplate;
    }
 
    @Override
    public SimulatorState loadOrInitialize(SimulatorState defaultState)
    {
        Object stored = redisTemplate.opsForValue().get(STATE_KEY);
        if (stored != null) return restoreState(stored);
        String initial = JSON.toJSONString(defaultState);
        if (Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(STATE_KEY, initial))) return defaultState;
        stored = redisTemplate.opsForValue().get(STATE_KEY);
        if (stored == null) throw new IllegalStateException("BTS simulator state initialization lost in Redis");
        return restoreState(stored);
    }
 
    @Override
    public SimulatorState resetHistoryForDemoStartup(SimulatorState state)
    {
        if (pendingEmbeddedHistory.isEmpty()) return state;
        java.util.Map<String, Integer> embeddedCounts = new java.util.HashMap<>();
        pendingEmbeddedHistory.forEach(append -> embeddedCounts.put(append.collectorCode(), append.records().size()));
        List<CollectorState> collectors = state.collectors().stream().map(collector -> {
            int embeddedCount = embeddedCounts.getOrDefault(collector.deviceCode(), 0);
            if (embeddedCount == 0) return collector;
            long remaining = Math.max(0L, collector.historyRecordCount() - embeddedCount);
            return new CollectorState(collector.collectorId(), collector.deviceCode(), collector.ip(), collector.mac(),
                    collector.name(), collector.manufacturer(), collector.model(), collector.channelCount(),
                    collector.online(), collector.sampleIntervalMs(), collector.nextSequence(), collector.lastSampledAt(),
                    collector.channels(), collector.latestMeasurements().stream()
                            .filter(item -> collector.deviceCode().equals(item.collectorCode()))
                            .toList(), remaining, collector.historyFaults());
        }).toList();
        // 不删除独立历史 Redis key;这里只阻止旧内嵌数据在本次启动时迁移回来。
        pendingEmbeddedHistory = List.of();
        SimulatorState cleaned = new SimulatorState(state.version(), state.devices(), collectors, state.nextDeviceId(),
                state.nextCollectorId(), state.tombstones());
        save(cleaned);
        return cleaned;
    }
 
    private SimulatorState restoreState(Object stored)
    {
        ParsedSimulatorState parsed = parseState(stored);
        // 旧格式历史先只供恢复校验读取,损坏状态不得被迁移写回覆盖。
        pendingEmbeddedHistory = parsed.embeddedHistory();
        return parsed.state();
    }
 
    @Override
    public void completeValidatedRestore(SimulatorState state)
    {
        if (pendingEmbeddedHistory.isEmpty()) return;
        save(state, pendingEmbeddedHistory);
        pendingEmbeddedHistory = List.of();
    }
 
    @Override
    public void save(SimulatorState state)
    {
        save(state, List.of());
    }
 
    @Override
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void save(SimulatorState state, List<CollectorHistoryAppend> historyAppends)
    {
        List<Object> results = redisTemplate.execute(new SessionCallback<List<Object>>()
        {
            @Override
            public <K, V> List<Object> execute(RedisOperations<K, V> operations)
            {
                RedisOperations<Object, Object> typed = (RedisOperations) operations;
                typed.multi();
                for (CollectorHistoryAppend append : historyAppends)
                {
                    String historyKey = historyKey(append.collectorCode());
                    if (!append.records().isEmpty())
                    {
                        List<Object> records = new ArrayList<>(
                                append.records().stream().map(JSON::toJSONString).toList());
                        typed.opsForList().rightPushAll(historyKey, records);
                        typed.opsForList().trim(historyKey, -MAX_HISTORY_RECORDS, -1);
                        typed.opsForSet().add(HISTORY_KEYS_KEY, historyKey);
                    }
                }
                typed.opsForValue().set(STATE_KEY, JSON.toJSONString(state));
                return typed.exec();
            }
        });
        if (results == null) throw new IllegalStateException("BTS simulator state transaction failed in Redis");
    }
 
    @Override
    public CollectorHistoryBatch loadCollectorHistoryPage(String collectorCode, long offset, int limit,
            boolean reverse)
    {
        if (offset < 0) throw new IllegalArgumentException("offset must not be negative");
        if (limit < 1 || limit > MAX_HISTORY_BATCH_SIZE)
            throw new IllegalArgumentException("limit must be between 1 and " + MAX_HISTORY_BATCH_SIZE);
        String key = historyKey(collectorCode);
        Long storedSize = redisTemplate.opsForList().size(key);
        long redisCount = storedSize == null ? 0 : storedSize;
        List<CollectorMeasurementRecord> embedded = pendingEmbeddedHistory.stream()
                .filter(append -> append.collectorCode().equals(collectorCode))
                .findFirst().map(CollectorHistoryAppend::records).orElse(List.of());
        long total = redisCount + embedded.size();
        long from = Math.min(offset, total);
        int count = (int) Math.min(limit, total - from);
        List<CollectorMeasurementRecord> records = new ArrayList<>(count);
        if (reverse)
        {
            long lower = total - from - count;
            long upper = total - from;
            long embeddedLower = Math.max(lower, redisCount);
            for (long index = upper - 1; index >= embeddedLower; index--)
                records.add(embedded.get((int) (index - redisCount)));
            long redisUpper = Math.min(upper, redisCount);
            if (lower < redisUpper)
            {
                List<Object> stored = redisTemplate.opsForList().range(key, lower, redisUpper - 1);
                if (stored != null)
                    for (int index = stored.size() - 1; index >= 0; index--)
                        records.add(collectorMeasurementRecord(stored.get(index)));
            }
        }
        else
        {
            long upper = from + count;
            long redisUpper = Math.min(upper, redisCount);
            if (from < redisUpper)
            {
                List<Object> stored = redisTemplate.opsForList().range(key, from, redisUpper - 1);
                if (stored != null) stored.forEach(item -> records.add(collectorMeasurementRecord(item)));
            }
            long embeddedFrom = Math.max(from, redisCount);
            if (embeddedFrom < upper)
                records.addAll(embedded.subList((int) (embeddedFrom - redisCount),
                        (int) (upper - redisCount)));
        }
        if (records.size() != count)
            throw new IllegalStateException("Collector history page changed while reading Redis");
        long nextOffset = from + records.size();
        return new CollectorHistoryBatch(offset, nextOffset, nextOffset < total, total, records);
    }
 
    @Override
    public BtsHistoryBatch loadBtsHistoryPage(String historyKey, long offset, int limit)
    {
        if (offset < 0 || limit < 1 || limit > MAX_HISTORY_BATCH_SIZE)
            throw new IllegalArgumentException("invalid BTS history page");
        String key = BTS_HISTORY_KEY_PREFIX + historyKey;
        Long size = redisTemplate.opsForList().size(key);
        long total = size == null ? 0 : size;
        long from = Math.min(offset, total);
        int count = (int) Math.min(limit, total - from);
        List<Object> values = count == 0 ? List.of() : redisTemplate.opsForList().range(key, from, from + count - 1);
        List<BtsHistoryRecord> records = values == null ? List.of() : values.stream()
                .map(item -> JSON.parseObject(item.toString(), BtsHistoryRecord.class)).toList();
        long next = from + records.size();
        return new BtsHistoryBatch(offset, next, next < total, total, records);
    }
 
    @Override
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void appendBtsHistory(String historyKey, BtsHistoryRecord record)
    {
        String key = BTS_HISTORY_KEY_PREFIX + historyKey;
        RedisOperations<Object, Object> operations = redisTemplate;
        operations.opsForList().rightPush(key, JSON.toJSONString(record));
        operations.opsForList().trim(key, -MAX_HISTORY_RECORDS, -1);
        operations.opsForSet().add(BTS_HISTORY_KEYS_KEY, key);
    }
 
    @Override
    public BtsPlaybackState loadBtsPlaybackState(String historyKey)
    {
        Object value = redisTemplate.opsForValue().get(BTS_PLAYBACK_KEY_PREFIX + historyKey);
        return value == null ? null : JSON.parseObject(value.toString(), BtsPlaybackState.class);
    }
 
    @Override
    public void saveBtsPlaybackState(String historyKey, BtsPlaybackState playback)
    {
        redisTemplate.opsForValue().set(BTS_PLAYBACK_KEY_PREFIX + historyKey, JSON.toJSONString(playback));
    }
 
    @Override
    public void deleteBtsPlaybackState(String historyKey)
    {
        redisTemplate.delete(BTS_PLAYBACK_KEY_PREFIX + historyKey);
    }
 
    @Override
    public void deleteBtsHistory(String historyKey)
    {
        String key = BTS_HISTORY_KEY_PREFIX + historyKey;
        redisTemplate.delete(key);
        redisTemplate.opsForSet().remove(BTS_HISTORY_KEYS_KEY, key);
    }
 
    @Override
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void saveBtsPlaybackAndAppendHistory(String historyKey, BtsPlaybackState playback,
            List<BtsHistoryRecord> records)
    {
        List<Object> results = redisTemplate.execute(new SessionCallback<List<Object>>()
        {
            @Override
            public <K, V> List<Object> execute(RedisOperations<K, V> operations)
            {
                RedisOperations<Object, Object> typed = (RedisOperations) operations;
                typed.multi();
                String key = BTS_HISTORY_KEY_PREFIX + historyKey;
                if (!records.isEmpty())
                {
                    typed.opsForList().rightPushAll(key, new ArrayList<>(records.stream()
                            .map(JSON::toJSONString).toList()));
                    typed.opsForList().trim(key, -MAX_HISTORY_RECORDS, -1);
                    typed.opsForSet().add(BTS_HISTORY_KEYS_KEY, key);
                }
                typed.opsForValue().set(BTS_PLAYBACK_KEY_PREFIX + historyKey, JSON.toJSONString(playback));
                return typed.exec();
            }
        });
        if (results == null) throw new IllegalStateException("BTS simulator playback transaction failed in Redis");
    }
 
    @Override
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void saveAndDeleteCollectorHistory(SimulatorState state, String collectorCode)
    {
        String historyKey = historyKey(collectorCode);
        List<Object> results = redisTemplate.execute(new SessionCallback<List<Object>>()
        {
            @Override
            public <K, V> List<Object> execute(RedisOperations<K, V> operations)
            {
                RedisOperations<Object, Object> typed = (RedisOperations) operations;
                typed.multi();
                typed.delete(historyKey);
                typed.opsForSet().remove(HISTORY_KEYS_KEY, historyKey);
                typed.opsForValue().set(STATE_KEY, JSON.toJSONString(state));
                return typed.exec();
            }
        });
        if (results == null) throw new IllegalStateException("BTS simulator collector deletion failed in Redis");
    }
 
    @Override
    public List<RecentRequest> loadRecentRequests()
    {
        Object stored = redisTemplate.opsForValue().get(RECENT_REQUESTS_KEY);
        if (stored == null) return List.of();
        return List.copyOf(JSON.parseArray(stored.toString(), RecentRequest.class));
    }
 
    @Override
    public void saveRecentRequests(List<RecentRequest> requests)
    {
        redisTemplate.opsForValue().set(RECENT_REQUESTS_KEY, JSON.toJSONString(requests),
                RECENT_REQUESTS_TTL_HOURS, TimeUnit.HOURS);
    }
 
    @Override
    public void reset(SimulatorState defaultState)
    {
        pendingEmbeddedHistory = List.of();
        Set<Object> historyKeys = redisTemplate.opsForSet().members(HISTORY_KEYS_KEY);
        if (historyKeys != null && !historyKeys.isEmpty()) redisTemplate.delete(historyKeys);
        redisTemplate.delete(HISTORY_KEYS_KEY);
        Set<Object> btsHistoryKeys = redisTemplate.opsForSet().members(BTS_HISTORY_KEYS_KEY);
        if (btsHistoryKeys != null && !btsHistoryKeys.isEmpty()) redisTemplate.delete(btsHistoryKeys);
        redisTemplate.delete(BTS_HISTORY_KEYS_KEY);
        // 播放状态按通道独立保存,重置演示时必须一并清理。
        Set<Object> playbackKeys = redisTemplate.keys(BTS_PLAYBACK_KEY_PREFIX + "*");
        if (playbackKeys != null && !playbackKeys.isEmpty()) redisTemplate.delete(playbackKeys);
        redisTemplate.delete(RECENT_REQUESTS_KEY);
        save(defaultState);
    }
 
    private ParsedSimulatorState parseState(Object stored)
    {
        try
        {
            // 通用 RedisTemplate 在可执行包中可能将泛型数组恢复为 JSONObject,必须在存储边界逐层重建。
            JSONObject root = jsonObject(stored);
            Integer version = root.getInteger("version");
            if (version == null || version != CURRENT_VERSION)
                throw new IllegalStateException("Unsupported BTS simulator state version: " + version);
            List<DeviceState> devices = new ArrayList<>();
            requiredArray(root, "devices").forEach(item -> devices.add(deviceState(item)));
            List<CollectorState> collectors = new ArrayList<>();
            List<CollectorHistoryAppend> embeddedHistory = new ArrayList<>();
            requiredArray(root, "collectors").forEach(item -> {
                JSONObject collectorObject = jsonObject(item);
                List<CollectorMeasurementRecord> history = embeddedCollectorHistory(collectorObject);
                CollectorState collector = collectorState(collectorObject, history);
                collectors.add(collector);
                if (!history.isEmpty())
                    embeddedHistory.add(new CollectorHistoryAppend(collector.deviceCode(), history));
            });
            List<ChannelTombstone> tombstones = new ArrayList<>();
            requiredArray(root, "tombstones").forEach(item -> tombstones.add(channelTombstone(item)));
            SimulatorState state = new SimulatorState(version, devices, collectors,
                    requiredInteger(root, "nextDeviceId"), requiredInteger(root, "nextCollectorId"), tombstones);
            return new ParsedSimulatorState(state, embeddedHistory);
        }
        catch (IllegalStateException exception)
        {
            throw exception;
        }
        catch (Exception exception)
        {
            throw new IllegalStateException("Invalid BTS simulator state in Redis", exception);
        }
    }
 
    private JSONObject jsonObject(Object value)
    {
        if (value instanceof JSONObject object) return object;
        if (value instanceof String text)
        {
            Object parsed = JSON.parse(text);
            if (parsed instanceof String nested) parsed = JSON.parse(nested);
            if (parsed instanceof JSONObject object) return object;
            return JSON.parseObject(JSON.toJSONString(parsed));
        }
        return JSON.parseObject(JSON.toJSONString(value));
    }
 
    private JSONArray requiredArray(JSONObject object, String field)
    {
        JSONArray array = object.getJSONArray(field);
        if (array == null) throw new IllegalStateException("Missing BTS simulator state field: " + field);
        return array;
    }
 
    private int requiredInteger(JSONObject object, String field)
    {
        Integer value = object.getInteger(field);
        if (value == null) throw new IllegalStateException("Missing BTS simulator state field: " + field);
        return value;
    }
 
    private DeviceState deviceState(Object value)
    {
        JSONObject object = jsonObject(value);
        List<ChannelState> channels = new ArrayList<>();
        requiredArray(object, "channels").forEach(item -> channels.add(channelState(item)));
        BtsDeviceProfile profile = object.containsKey("profile") ? deviceProfile(object.getJSONObject("profile")) : null;
        return new DeviceState(requiredInteger(object, "deviceId"), object.getString("ip"),
                object.getBooleanValue("online"), channels, profile);
    }
 
    private BtsDeviceProfile deviceProfile(JSONObject object)
    {
        if (object == null) throw new IllegalStateException("Invalid BTS simulator device profile");
        return new BtsDeviceProfile(requiredInteger(object, "devtype"), requiredInteger(object, "subDeviceId"),
                object.getString("name"), object.getString("manufacturer"), object.getString("model"),
                object.getString("serialNumber"), object.getString("firmwareVersion"),
                requiredInteger(object, "channelCount"), requiredDecimal(object, "currentMinA"),
                requiredDecimal(object, "currentMaxA"), requiredDecimal(object, "voltageMinV"),
                requiredDecimal(object, "voltageMaxV"), requiredInteger(object, "sampleIntervalMs"));
    }
 
    private List<CollectorMeasurementRecord> embeddedCollectorHistory(JSONObject object)
    {
        JSONArray values = object.getJSONArray("history");
        if (values == null) return List.of();
        List<CollectorMeasurementRecord> history = new ArrayList<>(values.size());
        values.forEach(item -> history.add(collectorMeasurementRecord(item)));
        return List.copyOf(history);
    }
 
    private CollectorState collectorState(JSONObject object, List<CollectorMeasurementRecord> embeddedHistory)
    {
        int collectorId = requiredInteger(object, "collectorId");
        String deviceCode = object.getString("deviceCode");
        String ip = object.getString("ip");
        String mac = object.getString("mac");
        String name = object.getString("name");
        String manufacturer = object.getString("manufacturer");
        String model = object.getString("model");
        int channelCount = requiredInteger(object, "channelCount");
        boolean online = object.getBooleanValue("online");
        // Ticket04 状态只包含发现配置;首次恢复时以演示默认值补齐采样状态。
        if (!object.containsKey("sampleIntervalMs"))
            return new CollectorState(collectorId, deviceCode, ip, mac, name, manufacturer, model,
                    channelCount, online);
 
        List<CollectorChannelState> channels = new ArrayList<>();
        requiredArray(object, "channels").forEach(item -> channels.add(collectorChannelState(item)));
        List<CollectorRealtimeMeasurement> latestMeasurements = new ArrayList<>();
        JSONArray latest = object.getJSONArray("latestMeasurements");
        if (latest != null)
            latest.forEach(item -> latestMeasurements.add(collectorRealtimeMeasurement(item)));
        else
            latestMeasurements.addAll(latestMeasurementsFromLegacyHistory(embeddedHistory, channels));
        long historyRecordCount = object.containsKey("historyRecordCount")
                ? requiredLong(object, "historyRecordCount") : embeddedHistory.size();
        return new CollectorState(collectorId, deviceCode, ip, mac, name, manufacturer, model,
                channelCount, online, requiredInteger(object, "sampleIntervalMs"),
                requiredLong(object, "nextSequence"), optionalInstant(object, "lastSampledAt"),
                channels, latestMeasurements, historyRecordCount,
                collectorHistoryFaults(object.get("historyFaults")));
    }
 
    private CollectorChannelState collectorChannelState(Object value)
    {
        JSONObject object = jsonObject(value);
        List<CollectorMetricState> metrics = new ArrayList<>();
        requiredArray(object, "metrics").forEach(item -> metrics.add(collectorMetricState(item)));
        return new CollectorChannelState(object.getString("channelCode"), metrics);
    }
 
    private CollectorMetricState collectorMetricState(Object value)
    {
        JSONObject object = jsonObject(value);
        BigDecimal measurement = object.getBigDecimal("value");
        if (measurement == null) throw new IllegalStateException("Missing BTS simulator state field: value");
        return new CollectorMetricState(object.getString("metricCode"), measurement, object.getString("unit"));
    }
 
    private CollectorMeasurementRecord collectorMeasurementRecord(Object value)
    {
        JSONObject object = jsonObject(value);
        BigDecimal measurement = object.getBigDecimal("value");
        if (measurement == null) throw new IllegalStateException("Missing BTS simulator state field: value");
        return new CollectorMeasurementRecord(object.getString("adapterCode"), object.getString("collectorCode"),
                object.getString("channelCode"), requiredLong(object, "sequenceId"),
                requiredInstant(object, "deviceTime"), object.getString("deviceTimeRaw"),
                requiredInstant(object, "serverReceivedAt"), object.getString("metricCode"),
                measurement, object.getString("unit"));
    }
 
    private CollectorRealtimeMeasurement collectorRealtimeMeasurement(Object value)
    {
        JSONObject object = jsonObject(value);
        BigDecimal measurement = object.getBigDecimal("value");
        if (measurement == null) throw new IllegalStateException("Missing BTS simulator state field: value");
        return new CollectorRealtimeMeasurement(object.getString("adapterCode"), object.getString("collectorCode"),
                object.getString("channelCode"), requiredLong(object, "sequenceId"),
                requiredInstant(object, "deviceTime"), object.getString("deviceTimeRaw"),
                requiredInstant(object, "serverReceivedAt"), object.getString("metricCode"),
                measurement, object.getString("unit"));
    }
 
    /** 兼容 Ticket06 开发期间已写入但尚未拆分快照模型的状态。 */
    private List<CollectorRealtimeMeasurement> latestMeasurementsFromLegacyHistory(
            List<CollectorMeasurementRecord> history, List<CollectorChannelState> channels)
    {
        java.util.Set<String> configured = new java.util.HashSet<>();
        channels.forEach(channel -> channel.metrics().forEach(metric ->
                configured.add(channel.channelCode() + "\u0000" + metric.metricCode())));
        java.util.Map<String, CollectorRealtimeMeasurement> latest = new java.util.LinkedHashMap<>();
        for (CollectorMeasurementRecord record : history)
        {
            String key = record.channelCode() + "\u0000" + record.metricCode();
            if (configured.contains(key))
                latest.put(key, new CollectorRealtimeMeasurement(record.adapterCode(), record.collectorCode(),
                        record.channelCode(), record.sequenceId(), record.deviceTime(), record.deviceTimeRaw(),
                        record.serverReceivedAt(), record.metricCode(), record.value(), record.unit()));
        }
        return List.copyOf(latest.values());
    }
 
    private CollectorHistoryFaults collectorHistoryFaults(Object value)
    {
        if (value == null) return CollectorHistoryFaults.none();
        JSONObject object = jsonObject(value);
        List<Long> missing = new ArrayList<>();
        JSONArray values = object.getJSONArray("missingSequences");
        if (values != null) values.forEach(item -> missing.add(Long.valueOf(item.toString())));
        return new CollectorHistoryFaults(missing, object.getLong("duplicateSequence"),
                object.getLong("conflictingSequence"), object.getBooleanValue("outOfOrder"));
    }
 
    private ChannelState channelState(Object value)
    {
        JSONObject object = jsonObject(value);
        String workStatus = object.getString("workStatus");
        if (workStatus == null) throw new IllegalStateException("Missing BTS simulator state field: workStatus");
        return new ChannelState(requiredInteger(object, "channelId"), object.getBooleanValue("online"),
                DeviceWorkStatus.valueOf(workStatus));
    }
 
    private ChannelTombstone channelTombstone(Object value)
    {
        JSONObject object = jsonObject(value);
        return new ChannelTombstone(requiredInteger(object, "deviceId"), object.getString("ip"),
                requiredInteger(object, "channelId"), requiredInteger(object, "remainingDiscoveries"));
    }
 
    private long requiredLong(JSONObject object, String field)
    {
        Long value = object.getLong(field);
        if (value == null) throw new IllegalStateException("Missing BTS simulator state field: " + field);
        return value;
    }
 
    private BigDecimal requiredDecimal(JSONObject object, String field)
    {
        BigDecimal value = object.getBigDecimal(field);
        if (value == null) throw new IllegalStateException("Missing BTS simulator state field: " + field);
        return value;
    }
 
    private Instant requiredInstant(JSONObject object, String field)
    {
        Instant value = optionalInstant(object, field);
        if (value == null) throw new IllegalStateException("Missing BTS simulator state field: " + field);
        return value;
    }
 
    private Instant optionalInstant(JSONObject object, String field)
    {
        String value = object.getString(field);
        return value == null ? null : Instant.parse(value);
    }
 
    private String historyKey(String collectorCode)
    {
        return HISTORY_KEY_PREFIX + collectorCode;
    }
 
    private record ParsedSimulatorState(SimulatorState state, List<CollectorHistoryAppend> embeddedHistory)
    {
        private ParsedSimulatorState { embeddedHistory = List.copyOf(embeddedHistory); }
    }
}