package com.zhitan.service.impl;
|
|
import com.influxdb.client.domain.WritePrecision;
|
import com.influxdb.client.write.Point;
|
import com.zhitan.config.influxdb.InfluxdbConfig;
|
import com.zhitan.influxdb.InfluxdbRepository;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.scheduling.annotation.Scheduled;
|
import org.springframework.stereotype.Service;
|
|
import java.time.Instant;
|
import java.time.LocalDateTime;
|
import java.time.ZoneId;
|
import java.util.Random;
|
|
@Slf4j
|
@Service
|
public class CompressedAirSimulator {
|
private final String TAG = "tag";
|
private final String FIELD_VALUE = "value";
|
private final String TAGNAME = "yasuokongqi01_StTotal";
|
private final InfluxdbRepository repository;
|
private final InfluxdbConfig influxdbConfig;
|
private double lastAirTotal = 0;
|
private final Random random = new Random();
|
|
@Autowired
|
public CompressedAirSimulator(InfluxdbRepository repository, InfluxdbConfig influxdbConfig) {
|
this.repository = repository;
|
this.influxdbConfig = influxdbConfig;
|
loadLastAirData();
|
}
|
|
private void loadLastAirData() {
|
double lastValue = repository.getLastPoint(influxdbConfig.getMeasurement(), TAG, TAGNAME);
|
if (lastValue > 0) {
|
log.info("查询出最后一次写入influxdb的压缩空气数据:{}", lastValue);
|
lastAirTotal = lastValue;
|
}
|
}
|
|
@Scheduled(fixedRate = 60000) // 每分钟执行一次
|
public void simulateAirUsage() {
|
LocalDateTime now = LocalDateTime.now();
|
double airUsage = calculateAirUsage(now);
|
lastAirTotal += airUsage;
|
|
Point point = Point
|
.measurement(influxdbConfig.getMeasurement())
|
.addTag(TAG, TAGNAME)
|
.addField(FIELD_VALUE, lastAirTotal)
|
.time(Instant.now(), WritePrecision.S);
|
|
repository.writePoint(point);
|
log.info("写入压缩空气表数据: {}", lastAirTotal);
|
}
|
|
private double calculateAirUsage(LocalDateTime time) {
|
int hour = time.getHour();
|
boolean isWeekend = time.getDayOfWeek().getValue() > 5;
|
|
// 基础用气量
|
double baseUsage = 0.01;
|
|
// 工作时间(8-20点)用气量增加
|
if (hour >= 8 && hour < 20) {
|
baseUsage += 0.4;
|
|
// 工作日用气量更大
|
if (!isWeekend) {
|
baseUsage += 0.2;
|
}
|
}
|
|
// 添加随机波动
|
baseUsage += random.nextDouble() * 0.8;
|
|
return baseUsage;
|
}
|
}
|