潘志宝
2024-10-29 a2aa90efc5d75798b0b3dc3255c33c53983dce86
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
package com.iailab.module.data.influxdb.service.impl;
 
import com.iailab.module.data.api.dto.ApiPointValueQueryDTO;
import com.iailab.module.data.common.utils.ExcelUtil;
import com.iailab.framework.common.util.date.DateUtils;
import com.iailab.module.data.api.dto.ApiExportValueDTO;
import com.iailab.module.data.api.dto.ApiTagValueQueryDTO;
import com.iailab.module.data.influxdb.common.config.InfluxDBInstance;
import com.iailab.module.data.influxdb.common.enums.DataMeasurement;
import com.iailab.module.data.influxdb.common.utils.PointValueUtils;
import com.iailab.module.data.influxdb.common.utils.TagValueUtils;
import com.iailab.module.data.influxdb.pojo.InfluxPointValuePOJO;
import com.iailab.module.data.influxdb.pojo.InfluxTagValuePOJO;
import com.iailab.module.data.influxdb.service.InfluxDBService;
import com.iailab.module.data.point.dto.DaPointDTO;
import com.iailab.module.data.point.service.DaPointService;
import com.iailab.module.data.point.vo.PointValueExportVO;
import com.influxdb.client.InfluxQLQueryApi;
import com.influxdb.client.QueryApi;
import com.influxdb.client.WriteApi;
import com.influxdb.client.WriteApiBlocking;
import com.influxdb.client.domain.InfluxQLQuery;
import com.influxdb.client.domain.WritePrecision;
import com.influxdb.client.write.Point;
import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable;
import com.influxdb.query.InfluxQLQueryResult;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
 
import static com.iailab.framework.common.pojo.CommonResult.success;
 
/**
 * InfluxDB操作类
 */
@Slf4j
@Service
public class InfluxDBServiceImpl implements InfluxDBService {
 
    @Resource
    private InfluxDBInstance influxDBInstance;
 
    private WriteApi writeApi;
 
    @Autowired
    private DaPointService daPointService;
 
    private WriteApiBlocking writeApiBlocking;
 
    private QueryApi queryApi;
 
    private InfluxQLQueryApi influxQLQueryApi;
 
    public static final String VALUE = "value";
 
    public static final String TIME = "time";
 
    private int rawOffset = TimeZone.getDefault().getRawOffset();
 
    private int pas_ms = 1000;
 
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
    @Resource
    private InfluxDBService influxDBService;
 
    @Override
    public void syncWriteFloatValue(String pointNo, String dataValue, long time) {
        if (writeApiBlocking == null) {
            writeApiBlocking = influxDBInstance.getClient().getWriteApiBlocking();
        }
        Point point = Point.measurement(DataMeasurement.t_da_sim_value.name());
        point.addTag("point", pointNo);
        point.addField("value", Double.parseDouble(dataValue));
        point.time(time, WritePrecision.MS);
        writeApiBlocking.writePoint(influxDBInstance.getBucket(), influxDBInstance.org, point);
    }
 
    @Override
    public void syncWriteIntValue(String pointNo, String dataValue, long time) {
        if (writeApiBlocking == null) {
            writeApiBlocking = influxDBInstance.getClient().getWriteApiBlocking();
        }
        Point point = Point.measurement(DataMeasurement.t_da_dig_value.name());
        point.addTag("point", pointNo);
        point.addField("value", Integer.parseInt(dataValue));
        point.time(time, WritePrecision.MS);
        writeApiBlocking.writePoint(influxDBInstance.getBucket(), influxDBInstance.org, point);
    }
 
    @Override
    public void syncWriteBooleanValue(String pointNo, String dataValue, long time) {
        if (writeApiBlocking == null) {
            writeApiBlocking = influxDBInstance.getClient().getWriteApiBlocking();
        }
        Point point = Point.measurement(DataMeasurement.t_da_bool_value.name());
        point.addTag("point", pointNo);
        point.addField("value", Boolean.parseBoolean(dataValue));
        point.time(time, WritePrecision.MS);
        writeApiBlocking.writePoint(influxDBInstance.getBucket(), influxDBInstance.org, point);
    }
 
    @Override
    public void asyncWritePointValues(List<InfluxPointValuePOJO> pointValues) {
        if (writeApi == null) {
            writeApi = influxDBInstance.getClient().makeWriteApi();
        }
        if (!CollectionUtils.isEmpty(pointValues)) {
            pointValues.forEach(item -> {
                String bucket = influxDBInstance.getBucket();
                writeApi.writeMeasurement(bucket, influxDBInstance.org, WritePrecision.MS, item);
            });
        }
        writeApi.flush();
    }
 
    @Override
    public void asyncWriteTagValues(List<InfluxTagValuePOJO> tagValues) {
        if (writeApi == null) {
            writeApi = influxDBInstance.getClient().makeWriteApi();
        }
        if (!CollectionUtils.isEmpty(tagValues)) {
            tagValues.forEach(item -> {
                log.info("bucket==="+ influxDBInstance.getBucket() + ",org===" + influxDBInstance.org);
                writeApi.writeMeasurement(influxDBInstance.getBucket(), influxDBInstance.org, WritePrecision.MS, item);
            });
        }
        writeApi.flush();
    }
 
    @Override
    public Map<String, List<Object>> queryTagsValues(List<InfluxTagValuePOJO> influxParams, Date startTime, Date endTime) {
        if (queryApi == null) {
            queryApi = influxDBInstance.getClient().getQueryApi();
        }
        if (CollectionUtils.isEmpty(influxParams)) {
            return null;
        }
        Map<String, List<Object>> result = new HashMap<>();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MILLISECOND, 0);
        // String start = startTime.getTime() - calendar.getTime().getTime() + "ms";
        String start = startTime.getTime() - calendar.getTime().getTime() - pas_ms + "ms";
        if (endTime==null){
            endTime= new Date();
        }
        String stop = endTime.getTime() - calendar.getTime().getTime() + "ms";
 
        for (int i = 0; i < influxParams.size(); i++) {
            List<Object> dataList = new ArrayList<>();
            InfluxTagValuePOJO tag = influxParams.get(i);
            String measurement = TagValueUtils.getMeasurement(tag.getType());
            StringBuilder sb = new StringBuilder();
            sb.append("from(bucket:\"" + influxDBInstance.getBucket() + "\") ");
            sb.append("|> range(start: ").append(start).append(", stop: ").append(stop).append(") ");
            sb.append("|> filter(fn: (r) => r[\"_measurement\"] == \"" + measurement + "\")");
            sb.append("|> filter(fn: (r) => r[\"_field\"] == \"value\")");
            sb.append("|> filter(fn: (r) => r[\"id\"] == \"" + tag.getId() + "\")");
            sb.append("|> sort(columns: [\"_time\"]) ");
            sb.append("|> yield(name: \"mean\")");
            List<FluxTable> tables = queryApi.query(sb.toString(), influxDBInstance.org);
 
            for (FluxTable table : tables) {
                List<FluxRecord> records = table.getRecords();
                for (FluxRecord record : records) {
                    Map<String, Object> dataIem = new HashMap<>(2);
                    dataIem.put(VALUE, record.getValueByKey("_value"));
                    dataIem.put(TIME, Date.from(record.getTime()));
                    dataList.add(dataIem);
                }
            }
            result.put(tag.getId(), dataList);
        }
        return result;
    }
 
    private List<ApiExportValueDTO> getExportValue(InfluxTagValuePOJO tag, Date startTime, Date endTime) {
        List<ApiExportValueDTO> dataList = new ArrayList<>();
        if (queryApi == null) {
            queryApi = influxDBInstance.getClient().getQueryApi();
        }
        Map<String, List<Object>> result = new HashMap<>();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MILLISECOND, 0);
        String start = startTime.getTime() - calendar.getTime().getTime() + "ms";
        String stop = endTime.getTime() - calendar.getTime().getTime() + "ms";
 
 
        String measurement = TagValueUtils.getMeasurement(tag.getType());
        StringBuilder sb = new StringBuilder();
        sb.append("from(bucket:\"" + influxDBInstance.getBucket() + "\") ");
        sb.append("|> range(start: ").append(start).append(", stop: ").append(stop).append(") ");
        sb.append("|> filter(fn: (r) => r[\"_measurement\"] == \"" + measurement + "\")");
        sb.append("|> filter(fn: (r) => r[\"_field\"] == \"value\")");
        sb.append("|> filter(fn: (r) => r[\"id\"] == \"" + tag.getId() + "\")");
        sb.append("|> sort(columns: [\"_time\"]) ");
        sb.append("|> yield(name: \"mean\")");
        List<FluxTable> tables = queryApi.query(sb.toString(), influxDBInstance.org);
 
        for (FluxTable table : tables) {
            List<FluxRecord> records = table.getRecords();
            for (FluxRecord record : records) {
                ApiExportValueDTO dataIem = new ApiExportValueDTO();
                dataIem.setDataValue(record.getValueByKey("_value").toString());
                dataIem.setDataTime(DateUtils.format(Date.from(record.getTime()), DateUtils.FORMAT_YEAR_MONTH_DAY));
                dataList.add(dataIem);
            }
        }
        return dataList;
    }
 
    @Override
    public boolean exportTagValue(HttpServletResponse response, HttpServletRequest request, ApiTagValueQueryDTO queryDto) {
        //构建参数
        Map<String, Object> params = new HashMap<>(1);
        params.put("pointNos", queryDto.getTagIds());
 
        //查询point列表
        List<DaPointDTO> pointList = daPointService.list(params);
        if (CollectionUtils.isEmpty(pointList)) {
            return true;
        }
 
        //插入pointType
        List<InfluxPointValuePOJO> influxParams = pointList.stream().map(item -> {
            InfluxPointValuePOJO pojo = new InfluxPointValuePOJO();
            pojo.setPoint(item.getTagNo());
            pojo.setType(item.getDataType());
            return pojo;
        }).collect(Collectors.toList());
 
        //查询
        Map<String, List<Map<String, Object>>> data = queryPointsValues(influxParams, queryDto.getStart(), queryDto.getEnd());
 
        //提取list
        List<Map<String, Object>> list = data.get(queryDto.getTagIds().get(0));
 
        //导出
        try{
            String sheetTitle = "采集数据";
            String[] title = new String[]{"值", "时间"};
            ExcelUtil.exportPointValue(sheetTitle, title, new ArrayList<>(list), response);
        } catch (Exception ex) {
            return false;
        }
        return true;
    }
 
    @Override
    public List<PointValueExportVO> exportPointValue(ApiPointValueQueryDTO queryDto) {
 
        List<PointValueExportVO> pointValueExportList = new ArrayList<>();
 
        //构建参数
        Map<String, Object> params = new HashMap<>(1);
        params.put("pointNos", queryDto.getPointNos());
 
        //查询point列表
        List<DaPointDTO> pointList = daPointService.list(params);
        if (CollectionUtils.isEmpty(pointList)) {
            return pointValueExportList;
        }
 
        //插入pointType
        List<InfluxPointValuePOJO> influxParams = pointList.stream().map(item -> {
            InfluxPointValuePOJO pojo = new InfluxPointValuePOJO();
            pojo.setPoint(item.getPointNo());
            pojo.setType(item.getDataType());
            return pojo;
        }).collect(Collectors.toList());
 
        //查询
        Map<String, List<Map<String, Object>>> data = queryPointsValues(influxParams, queryDto.getStart(), queryDto.getEnd());
 
        //提取list
        List<Map<String, Object>> list = data.get(queryDto.getPointNos().get(0));
        for(Map<String, Object> map : list){
            PointValueExportVO dto = new PointValueExportVO();
            dto.setDatatime(map.get("time").toString());
            dto.setDatavalue(map.get("value").toString());
            pointValueExportList.add(dto);
        }
 
        return pointValueExportList;
    }
 
    @Override
    public Map<String, Object> queryPointsLastValue(List<InfluxPointValuePOJO> influxParams) {
        Map<String, Object> result = new HashMap<>(influxParams.size());
        if (influxQLQueryApi == null) {
            influxQLQueryApi = influxDBInstance.getClient().getInfluxQLQueryApi();
        }
        for (int i = 0; i < influxParams.size(); i++) {
            InfluxPointValuePOJO point = influxParams.get(i);
            String measurement = PointValueUtils.getMeasurement(point.getType());
            StringBuilder sql = new StringBuilder();
            sql.append("SELECT LAST(value) FROM ");
            sql.append(measurement);
            sql.append(" WHERE point = '");
            sql.append(point.getPoint());
            sql.append("'");
            InfluxQLQueryResult data = influxQLQueryApi.query(new InfluxQLQuery(sql.toString(), influxDBInstance.getBucket()));
            Object value = data.getResults().get(0).getSeries().get(0).getValues().get(0).getValueByKey("last");
            result.put(point.getPoint(), value);
        }
        return result;
    }
 
    @Override
    public Object queryPointMaxValue(InfluxPointValuePOJO point, Date startTime) {
        if (influxQLQueryApi == null) {
            influxQLQueryApi = influxDBInstance.getClient().getInfluxQLQueryApi();
        }
        long utcMillis = startTime.getTime() -rawOffset;
        String utsStart = DateUtils.format(new Date(utcMillis), DateUtils.FORMAT_YEAR_MONTH_DAY);
        log.info("utsStart=" + utsStart);
        String measurement = PointValueUtils.getMeasurement(point.getType());
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT MAX(value) FROM ");
        sql.append(measurement);
        sql.append(" WHERE point = '");
        sql.append(point.getPoint());
        sql.append("' AND time >= '" + utsStart +"'");
        InfluxQLQueryResult data = influxQLQueryApi.query(new InfluxQLQuery(sql.toString(), influxDBInstance.getBucket()));
        if (data == null) {
            return null;
        }
        return data.getResults().get(0).getSeries().get(0).getValues().get(0).getValues()[1];
    }
 
    @Override
    public List<Map<String, Object>> queryPointValues(InfluxPointValuePOJO pojo, Date startTime, Date endTime) {
        List<InfluxPointValuePOJO> influxParams = new ArrayList<>();
        influxParams.add(pojo);
        Map<String, List<Map<String, Object>>> data = this.queryPointsValues(influxParams, startTime, endTime);
        return data.get(pojo.getPoint());
    }
 
    @Override
    public Map<String, List<Map<String, Object>>> queryPointsValues(List<InfluxPointValuePOJO> influxParams, Date startTime, Date endTime) {
        if (queryApi == null) {
            queryApi = influxDBInstance.getClient().getQueryApi();
        }
        if (CollectionUtils.isEmpty(influxParams)) {
            return null;
        }
        Map<String, List<Map<String, Object>>> result = new HashMap<>();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MILLISECOND, 0);
        String start = startTime.getTime() - calendar.getTime().getTime() + "ms";
        if (endTime==null){
            endTime= new Date();
        }
        String stop = endTime.getTime() - calendar.getTime().getTime() + "ms";
 
        for (int i = 0; i < influxParams.size(); i++) {
            List<Map<String, Object>> dataList = new ArrayList<>();
            InfluxPointValuePOJO point = influxParams.get(i);
            String measurement = PointValueUtils.getMeasurement(point.getType());
            StringBuilder sb = new StringBuilder();
            sb.append("from(bucket:\"" + influxDBInstance.getBucket() + "\") ");
            sb.append("|> range(start: ").append(start).append(", stop: ").append(stop).append(") ");
            sb.append("|> filter(fn: (r) => r[\"_measurement\"] == \"" + measurement + "\")");
            sb.append("|> filter(fn: (r) => r[\"_field\"] == \"value\")");
            sb.append("|> filter(fn: (r) => r[\"point\"] == \"" + point.getPoint() + "\")");
            sb.append("|> sort(columns: [\"_time\"]) ");
            sb.append("|> yield(name: \"mean\")");
            System.out.println("influxdbSql===============" + sb.toString());
            List<FluxTable> tables = queryApi.query(sb.toString(), influxDBInstance.org);
 
            for (FluxTable table : tables) {
                List<FluxRecord> records = table.getRecords();
                for (FluxRecord record : records) {
                    Map<String, Object> dataIem = new HashMap<>(2);
                    dataIem.put(VALUE, record.getValueByKey("_value"));
                    dataIem.put(TIME, sdf.format(Date.from(record.getTime())));
                    dataList.add(dataIem);
                }
            }
            result.put(point.getPoint(), dataList);
        }
        return result;
    }
 
    @Override
    public Map<String, Object> queryPointsSpread(List<InfluxPointValuePOJO> influxParams, Date startTime, Date endTime) {
        Map<String, Object> result = new HashMap<>();
        Map<String, List<Map<String, Object>>> data = this.queryPointsValues(influxParams, startTime, endTime);
        if (CollectionUtils.isEmpty(data)) {
            return result;
        }
        data.forEach((k, v) -> {
            if (!CollectionUtils.isEmpty(v)) {
                BigDecimal lastValue = new BigDecimal(v.get(v.size() - 1).get(VALUE).toString());
                BigDecimal firstValue = new BigDecimal(v.get(0).get(VALUE).toString());
                BigDecimal spread = (lastValue.subtract(firstValue));
                result.put(k, spread.compareTo(BigDecimal.ZERO) < 0 ? lastValue : spread);
            }
            log.info(k + ",isEmpty");
        });
        return result;
    }
}