package com.ruoyi.device.simulator;
|
|
import java.math.BigDecimal;
|
import java.time.Duration;
|
import java.time.Instant;
|
import java.time.ZoneId;
|
import java.time.format.DateTimeFormatter;
|
import java.util.ArrayList;
|
import java.util.Comparator;
|
import java.util.LinkedHashMap;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.Set;
|
import com.ruoyi.device.simulator.BtsSimulatorStateStore.CollectorChannelState;
|
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.CollectorState;
|
|
/** 实现第一版开发采集器的独立采样与故障注入合同。 */
|
public final class DevelopmentCollectorSimulation
|
{
|
public static final int DEFAULT_SAMPLE_INTERVAL_MS = 1000;
|
public static final int MIN_SAMPLE_INTERVAL_MS = 100;
|
public static final int MAX_SAMPLE_INTERVAL_MS = 60000;
|
public static final int MAX_HISTORY_PAGE_SIZE = 1000;
|
private static final int MAX_HISTORY_RECORDS = 50000;
|
private static final int MAX_SAMPLES_PER_ADVANCE = 1000;
|
private static final ZoneId DEVICE_ZONE = ZoneId.of("Asia/Hong_Kong");
|
private static final DateTimeFormatter DEVICE_TIME_FORMATTER =
|
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
|
|
private DevelopmentCollectorSimulation() { }
|
|
/** 创建带稳定 S 通道和三项固定演示指标的采集器状态。 */
|
public static List<CollectorChannelState> defaultChannels(int channelCount)
|
{
|
List<CollectorChannelState> channels = new ArrayList<>(channelCount);
|
for (int index = 1; index <= channelCount; index++)
|
{
|
channels.add(new CollectorChannelState(channelCode(index), List.of(
|
new CollectorMetricState("temperature", new BigDecimal("25.0")
|
.add(BigDecimal.valueOf(index, 1)), "℃"),
|
new CollectorMetricState("positive_potential", new BigDecimal("3.700"), "V"),
|
new CollectorMetricState("negative_potential", new BigDecimal("-0.100"), "V"))));
|
}
|
return List.copyOf(channels);
|
}
|
|
/** 调整通道数时保留已有通道配置,并为新增通道生成稳定默认配置。 */
|
public static CollectorState resize(CollectorState current, String ip, int channelCount, boolean online,
|
Instant changedAt)
|
{
|
List<CollectorChannelState> defaults = defaultChannels(channelCount);
|
List<CollectorChannelState> channels = new ArrayList<>(channelCount);
|
for (int index = 0; index < channelCount; index++)
|
channels.add(index < current.channels().size() ? current.channels().get(index) : defaults.get(index));
|
Instant lastSampledAt = online == current.online() ? current.lastSampledAt() : changedAt;
|
return copy(current, ip, channelCount, online, current.sampleIntervalMs(), current.nextSequence(),
|
lastSampledAt, channels, current.history(), current.historyFaults());
|
}
|
|
/** 更新采样频率和历史下载故障;测量原始历史保持只追加。 */
|
public static CollectorState configureSampling(CollectorState current, int sampleIntervalMs,
|
CollectorHistoryFaults historyFaults)
|
{
|
validateSampleInterval(sampleIntervalMs);
|
validateFaults(historyFaults);
|
return copy(current, current.ip(), current.channelCount(), current.online(), sampleIntervalMs,
|
current.nextSequence(), current.lastSampledAt(), current.channels(), current.history(), historyFaults);
|
}
|
|
/** 替换一个演示通道的指标配置;动态添加项与固定指标共用指标编码合同。 */
|
public static CollectorState configureChannel(CollectorState current, String channelCode,
|
List<CollectorMetricState> metrics)
|
{
|
validateMetrics(metrics);
|
int channelIndex = parseChannelIndex(channelCode, current.channelCount());
|
List<CollectorChannelState> channels = new ArrayList<>(current.channels());
|
channels.set(channelIndex, new CollectorChannelState(channelCode(channelIndex + 1), metrics));
|
return copy(current, current.ip(), current.channelCount(), current.online(), current.sampleIntervalMs(),
|
current.nextSequence(), current.lastSampledAt(), channels, current.history(), current.historyFaults());
|
}
|
|
/** 按采集器自身频率推进采样;离线期间不生成记录,恢复后从下一序号继续。 */
|
public static CollectorState advance(CollectorState current, Instant now)
|
{
|
if (!current.online()) return current;
|
Instant sampleAt = current.lastSampledAt() == null
|
? now
|
: current.lastSampledAt().plusMillis(current.sampleIntervalMs());
|
if (sampleAt.isAfter(now)) return current;
|
|
List<CollectorMeasurementRecord> history = new ArrayList<>(current.history());
|
long sequence = current.nextSequence();
|
int generated = 0;
|
Instant lastSampledAt = current.lastSampledAt();
|
while (!sampleAt.isAfter(now) && generated < MAX_SAMPLES_PER_ADVANCE)
|
{
|
for (CollectorChannelState channel : current.channels())
|
{
|
for (CollectorMetricState metric : channel.metrics())
|
{
|
history.add(new CollectorMeasurementRecord("dev-sim", current.deviceCode(),
|
channel.channelCode(), sequence, sampleAt,
|
DEVICE_TIME_FORMATTER.format(sampleAt.atZone(DEVICE_ZONE)), now,
|
metric.metricCode(), metric.value(), metric.unit()));
|
}
|
}
|
lastSampledAt = sampleAt;
|
sequence++;
|
generated++;
|
sampleAt = sampleAt.plusMillis(current.sampleIntervalMs());
|
}
|
if (history.size() > MAX_HISTORY_RECORDS)
|
history = new ArrayList<>(history.subList(history.size() - MAX_HISTORY_RECORDS, history.size()));
|
return copy(current, current.ip(), current.channelCount(), current.online(), current.sampleIntervalMs(),
|
sequence, lastSampledAt, current.channels(), history, current.historyFaults());
|
}
|
|
/** 返回每个通道和指标的最新实时快照,不将快照写入另一条历史路径。 */
|
public static CollectorRealtimeSnapshot realtime(CollectorState current)
|
{
|
Map<String, CollectorMeasurementRecord> latest = new LinkedHashMap<>();
|
for (CollectorMeasurementRecord record : current.history())
|
latest.put(record.channelCode() + "\u0000" + record.metricCode(), record);
|
return new CollectorRealtimeSnapshot(current.deviceCode(), current.online(), current.sampleIntervalMs(),
|
List.copyOf(latest.values()));
|
}
|
|
/** 对只追加原始模拟历史应用可重复的下载故障视图,再按偏移量分页。 */
|
public static CollectorHistoryPage history(CollectorState current, long offset, int limit)
|
{
|
if (offset < 0) throw new IllegalArgumentException("offset must not be negative");
|
if (limit < 1 || limit > MAX_HISTORY_PAGE_SIZE)
|
throw new IllegalArgumentException("limit must be between 1 and " + MAX_HISTORY_PAGE_SIZE);
|
|
List<CollectorMeasurementRecord> download = faultedHistory(current);
|
int from = (int) Math.min(offset, download.size());
|
int to = Math.min(from + limit, download.size());
|
return new CollectorHistoryPage(current.deviceCode(), offset, to, to < download.size(),
|
download.size(), download.subList(from, to));
|
}
|
|
/** 校验 Redis 恢复的采集器采样状态,拒绝损坏状态被静默替换。 */
|
public static void validate(CollectorState state)
|
{
|
validateSampleInterval(state.sampleIntervalMs());
|
if (state.nextSequence() < 1 || state.channels().size() != state.channelCount())
|
throw new IllegalStateException("Invalid collector sampling state in Redis");
|
for (int index = 0; index < state.channels().size(); index++)
|
{
|
CollectorChannelState channel = state.channels().get(index);
|
if (!channelCode(index + 1).equals(channel.channelCode()))
|
throw new IllegalStateException("Invalid collector channel identity in Redis");
|
validateMetrics(channel.metrics());
|
}
|
validateFaults(state.historyFaults());
|
}
|
|
private static List<CollectorMeasurementRecord> faultedHistory(CollectorState current)
|
{
|
CollectorHistoryFaults faults = current.historyFaults();
|
Set<Long> missing = Set.copyOf(faults.missingSequences());
|
List<CollectorMeasurementRecord> records = new ArrayList<>();
|
for (CollectorMeasurementRecord record : current.history())
|
{
|
if (missing.contains(record.sequenceId())) continue;
|
records.add(record);
|
if (Long.valueOf(record.sequenceId()).equals(faults.duplicateSequence())) records.add(record);
|
if (Long.valueOf(record.sequenceId()).equals(faults.conflictingSequence()))
|
records.add(new CollectorMeasurementRecord(record.adapterCode(), record.collectorCode(),
|
record.channelCode(), record.sequenceId(), record.deviceTime(), record.deviceTimeRaw(),
|
record.serverReceivedAt(), record.metricCode(),
|
record.value().add(new BigDecimal("0.001")), record.unit()));
|
}
|
if (faults.outOfOrder())
|
records.sort(Comparator.comparingLong(CollectorMeasurementRecord::sequenceId).reversed()
|
.thenComparing(CollectorMeasurementRecord::channelCode)
|
.thenComparing(CollectorMeasurementRecord::metricCode));
|
return records;
|
}
|
|
private static CollectorState copy(CollectorState current, String ip, int channelCount, boolean online,
|
int sampleIntervalMs, long nextSequence, Instant lastSampledAt,
|
List<CollectorChannelState> channels, List<CollectorMeasurementRecord> history,
|
CollectorHistoryFaults faults)
|
{
|
return new CollectorState(current.collectorId(), current.deviceCode(), ip.trim(), current.mac(),
|
current.name(), current.manufacturer(), current.model(), channelCount, online, sampleIntervalMs,
|
nextSequence, lastSampledAt, channels, history, faults);
|
}
|
|
private static void validateSampleInterval(int sampleIntervalMs)
|
{
|
if (sampleIntervalMs < MIN_SAMPLE_INTERVAL_MS || sampleIntervalMs > MAX_SAMPLE_INTERVAL_MS)
|
throw new IllegalArgumentException("sampleIntervalMs must be between " + MIN_SAMPLE_INTERVAL_MS
|
+ " and " + MAX_SAMPLE_INTERVAL_MS);
|
}
|
|
private static void validateMetrics(List<CollectorMetricState> metrics)
|
{
|
if (metrics == null || metrics.isEmpty())
|
throw new IllegalArgumentException("Collector channel must contain at least one metric");
|
java.util.HashSet<String> codes = new java.util.HashSet<>();
|
for (CollectorMetricState metric : metrics)
|
{
|
if (metric.metricCode() == null || metric.metricCode().isBlank() || metric.value() == null
|
|| metric.unit() == null || metric.unit().isBlank() || !codes.add(metric.metricCode().trim()))
|
throw new IllegalArgumentException("Collector metric code, value and unit must be valid and unique");
|
}
|
}
|
|
private static void validateFaults(CollectorHistoryFaults faults)
|
{
|
if (faults == null) throw new IllegalArgumentException("historyFaults must not be null");
|
if (faults.missingSequences().stream().anyMatch(sequence -> sequence == null || sequence < 1)
|
|| faults.duplicateSequence() != null && faults.duplicateSequence() < 1
|
|| faults.conflictingSequence() != null && faults.conflictingSequence() < 1)
|
throw new IllegalArgumentException("History fault sequences must be positive");
|
}
|
|
private static int parseChannelIndex(String value, int channelCount)
|
{
|
if (value == null || !value.matches("S-\\d{2}"))
|
throw new IllegalArgumentException("Collector channel must use S-01...S-N identity");
|
int index = Integer.parseInt(value.substring(2)) - 1;
|
if (index < 0 || index >= channelCount || !channelCode(index + 1).equals(value))
|
throw new IllegalArgumentException("Unknown collector channel: " + value);
|
return index;
|
}
|
|
private static String channelCode(int index)
|
{
|
return String.format("S-%02d", index);
|
}
|
|
public record CollectorRealtimeSnapshot(String collectorCode, boolean online, int sampleIntervalMs,
|
List<CollectorMeasurementRecord> measurements)
|
{
|
public CollectorRealtimeSnapshot { measurements = List.copyOf(measurements); }
|
}
|
|
public record CollectorHistoryPage(String collectorCode, long offset, long nextOffset, boolean hasMore,
|
long total, List<CollectorMeasurementRecord> records)
|
{
|
public CollectorHistoryPage { records = List.copyOf(records); }
|
}
|
}
|