baoshiwei
2025-06-26 55e0a19f3b1c113732f8ee56ac964e5208ec7afd
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
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.01;
        
        // 工作时间(8-20点)用水量增加
        if (hour >= 8 && hour < 20) {
            baseUsage += 0.19;
            
            // 工作日用水量更大
            if (!isWeekend) {
                baseUsage += 0.1;
            }
        }
        
        // 添加随机波动
        baseUsage += random.nextDouble() * 0.5;
        
        return baseUsage;
    }
}