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 WaterMeterSimulator {
|
private final String TAG = "tag";
|
private final String FIELD_VALUE = "value";
|
private final String TAGNAME = "shuibiao01_StTotal";
|
private final InfluxdbRepository repository;
|
private final InfluxdbConfig influxdbConfig;
|
private double lastWaterTotal = 0;
|
private final Random random = new Random();
|
|
@Autowired
|
public WaterMeterSimulator(InfluxdbRepository repository, InfluxdbConfig influxdbConfig) {
|
this.repository = repository;
|
this.influxdbConfig = influxdbConfig;
|
// 初始化时从时序数据库加载上次的数据
|
loadLastWaterData();
|
}
|
|
private void loadLastWaterData() {
|
// 这里应该实现从InfluxDB查询最后一次记录的逻辑
|
double lastValue = repository.getLastPoint(influxdbConfig.getMeasurement(),TAG, TAGNAME);
|
if (lastValue>0) {
|
log.info("查询出最后一次写入influxdb的数据:{}", lastValue);
|
lastWaterTotal = lastValue;
|
}
|
}
|
|
@Scheduled(fixedRate = 60000) // 每分钟执行一次
|
public void simulateWaterUsage() {
|
LocalDateTime now = LocalDateTime.now();
|
double waterUsage = calculateWaterUsage(now);
|
lastWaterTotal += waterUsage;
|
|
Point point = Point
|
.measurement(influxdbConfig.getMeasurement())
|
.addTag(TAG, TAGNAME)
|
.addField(FIELD_VALUE, lastWaterTotal)
|
.time(Instant.now(), WritePrecision.S);
|
|
repository.writePoint(point);
|
log.info("写入水表数据: {}", lastWaterTotal);
|
}
|
|
private double calculateWaterUsage(LocalDateTime time) {
|
int hour = time.getHour();
|
boolean isWeekend = time.getDayOfWeek().getValue() > 5;
|
|
// 基础用水量
|
double baseUsage = 0.05;
|
|
// 工作时间(8-20点)用水量增加
|
if (hour >= 8 && hour < 20) {
|
baseUsage += 0.15;
|
|
// 工作日用水量更大
|
if (!isWeekend) {
|
baseUsage += 0.1;
|
}
|
}
|
|
// 添加随机波动
|
baseUsage += random.nextDouble() * 0.5;
|
|
return baseUsage;
|
}
|
}
|