whycxzp
2021-06-03 59ec12fe73db1b68b8eddc9150778f276483a6a5
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
415
416
417
418
419
420
package com.whyc.service;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whyc.constant.ExperimentType;
import com.whyc.dto.ExperimentConditionDTO;
import com.whyc.dto.Response;
import com.whyc.mapper.*;
import com.whyc.pojo.Experiment;
import com.whyc.pojo.ExperimentBaseDataKZ;
import com.whyc.pojo.ExperimentPoint;
import com.whyc.pojo.ExperimentPrecondition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
 
import static java.lang.Thread.sleep;
 
@Service
@Slf4j
public class ExperimentService {
 
    @Resource
    private ExperimentMapper mapper;
    @Resource
    private ExperimentBaseDataKZMapper kzMapper;
    @Resource
    private ExperimentPointMapper pointMapper;
    @Resource
    private ExperimentPreconditionMapper preconditionMapper;
    @Resource
    private CommonMapper commonMapper;
 
    public Response exist() {
        ExperimentConditionDTO condition = new ExperimentConditionDTO();
        condition.setStatus(1);
        List<Experiment> experiments = mapper.getList(condition);
        //不存在试验
        if (experiments.isEmpty()){
            return new Response().setMsg(-1,"暂无试验");
        }
        Experiment experiment = experiments.get(0);
        String url = null;
        if (experiment.getId().toLowerCase().contains(ExperimentType.KZ.getValue())){
            url = "noLoadTest";
        }
        else if(experiment.getId().toLowerCase().contains(ExperimentType.FZ.getValue())){
            url = "loadTest";
        }
        else if(experiment.getId().toLowerCase().contains(ExperimentType.RZ.getValue())){
            url = "windingTest";
        }else{
            url ="不存在呀";
        }
        return new Response().set(1,experiments.get(0),url);
    }
 
    /**
     * 绕组:rz,
     * 空载:kz,
     * 负载:fz,
     * 升温:sw,
     * 超速:cs,
     * 空载反电动势:kzfdds,
     * 振动:zd,
     * 耐压:ny,
     * 转动惯量:zdgl
     * @param type
     * @return
     */
    public Response getExperimentId(String type) {
        String id = null;
        //查询当前试验类型的最大编号
        QueryWrapper<Experiment> wrapper = Wrappers.query();
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String nowFormat = dateFormat.format(now);
        String idLike = type.toUpperCase()+"_"+nowFormat;
        wrapper.select("id").likeRight("id",idLike).orderByDesc("id").last(" limit 1");
        Experiment experiment = mapper.selectOne(wrapper);
        if(experiment!=null) {
            int idPrefixLength = idLike.length();
            String idSuffixStr = experiment.getId().substring(idPrefixLength);
            Integer idSuffix = Integer.parseInt(idSuffixStr)+1;
            //前面填充0的位数
            int zeroCount = idSuffixStr.length()-idSuffix.toString().length();
            StringBuilder zeroStr = new StringBuilder();
            for (int i = 0; i < zeroCount; i++) {
                zeroStr.append("0");
            }
            id = idLike+zeroStr+idSuffix;
        }else{
            id = idLike+"001";
        }
        return new Response().set(1,id);
 
    }
 
    @Transactional
    public Response addKZFZ(Experiment experiment) {
        //插入experiment数据
        experiment.setCreateTime(new Date());
        //新增初始化状态为0未开始,正在进行
        experiment.setStatus(0);
        mapper.insert(experiment);
 
        //插入experiment_base_data数据
        kzMapper.insert((ExperimentBaseDataKZ) experiment.getBaseData());
 
        //插入experiment_point数据
        List<ExperimentPoint> points = (List<ExperimentPoint>) experiment.getPoint();
        points.stream().forEach(p->p.setStatus(0));
        pointMapper.insertBatchSomeColumn(points);
        //TODO 插入紧急停止数据
 
        return new Response().setMsg(1,"新增成功");
    }
 
    /**
     * 检查前置条件
     * @param type
     * @return
     */
    public Response checkPrecondition(String type) {
        AtomicReference<Integer> code = new AtomicReference<>(1);
        //2种方式
        //m1
        QueryWrapper<ExperimentPrecondition> wrapper = Wrappers.query();
        wrapper.eq("type",type).eq("flag",1);
        List<ExperimentPrecondition> preconditions = preconditionMapper.selectList(wrapper);
        preconditions.stream().forEach(precondition->{
            //获取对应的值
            /*ExperimentPrecondition preconditionStatus = commonMapper.getPreconditionStatus(precondition);
            precondition.setActualValue(preconditionStatus.getActualValue());
            precondition.setStatus(preconditionStatus.getStatus());*/
            Object preconditionActualValue = commonMapper.getPreconditionStatus(precondition);
            /*String preconditionActualValueStr = preconditionActualValue.toString();
            if(precondition.getValue().equals(preconditionActualValueStr)){*/
            //采用浮点/整型进行数值对比
            if(preconditionActualValue instanceof Integer) {
                Integer actualValue = (Integer) preconditionActualValue;
                Integer defaultValue = Integer.parseInt(precondition.getValue());
 
                if (defaultValue.equals(actualValue)) {
                    precondition.setStatus(1);
                } else {
                    precondition.setStatus(0);
                    code.set(-1);
                }
                precondition.setActualValue(actualValue.toString());
            }
            else if(preconditionActualValue instanceof Float) {
                Float actualValue = (Float) preconditionActualValue;
                Float defaultValue = Float.parseFloat(precondition.getValue());
 
                if (defaultValue.equals(actualValue)) {
                    precondition.setStatus(1);
                } else {
                    precondition.setStatus(0);
                    code.set(-1);
                }
                precondition.setActualValue(actualValue.toString());
            }
        });
        return new Response().set(code.get(),preconditions);
    }
 
    /**
     * 检查中置条件-当前功率和当前定子温度,如果符合标准,返回当前值
     */
    public Response checkPreconditionStep1(String experimentId){
        String type = experimentId.split("_")[0].toLowerCase();
        QueryWrapper<ExperimentPrecondition> wrapper = Wrappers.query();
        wrapper.eq("type",type+"_1");
        List<ExperimentPrecondition> preconditions = preconditionMapper.selectList(wrapper);
 
        //获取到条件数量
        int conditionNum = preconditions.size();
        AtomicReference<Integer> passNum = new AtomicReference(0);
        while (conditionNum!=passNum.get()) {
            //重置为0
            passNum.set(0);
            preconditions.stream().forEach(precondition -> {
                //获取对应的值
                Object preconditionActualValue = commonMapper.getPreconditionStatus(precondition);
                //采用浮点/整型进行数值对比
                if(preconditionActualValue instanceof Float) {
                    Float actualValue = (Float) preconditionActualValue;
                    Float defaultValue = Float.parseFloat(precondition.getValue());
 
                    if (defaultValue.equals(actualValue)) {
                        //条件达成,达成数上+1
                        passNum.set(passNum.get() + 1);
                        //记录当前值
                        precondition.setActualValue(actualValue.toString());
                    }
                }
                //采用浮点/整型进行数值对比
                if(preconditionActualValue instanceof Integer) {
                    Integer actualValue = (Integer) preconditionActualValue;
                    Integer defaultValue = Integer.parseInt(precondition.getValue());
 
                    if (defaultValue.equals(actualValue)) {
                        //条件达成,达成数上+1
                        passNum.set(passNum.get() + 1);
                        //记录当前值
                        precondition.setActualValue(actualValue.toString());
                    }
                }
            });
        }
        //演示需要
        try {
            sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //设置试验整体状态为1,启动时间更新
        mapper.updateStatusAndTime(experimentId,1,"start_time",new Date());
        return new Response().set(1,preconditions);
    }
 
    /**
     * 开始试验,更新 试验状态和启动试验时间
     */
    public Response updateStatus(String experimentId){
        Experiment<Object, Object> experiment = new Experiment<>();
        experiment.setId(experimentId);
        experiment.setStatus(1);
        experiment.setStartTime(new Date());
        mapper.updateById(experiment);
        return new Response().set(1,"状态更新成功");
    }
 
    /**
     * 获取测试点
     */
    public Response<List<ExperimentPoint>> getPoint(String experimentId){
        QueryWrapper<ExperimentPoint> wrapper = Wrappers.query();
        wrapper.eq("experiment_id",experimentId);
        List<ExperimentPoint> experimentPoints = pointMapper.selectList(wrapper);
        /*//TODO 针对已完成的测试点,计算出这段时间内的平均功率并返回,需要考虑是否将功率字段持久化到表中
        experimentPoints.stream().forEach(point -> {
            if(point.getStatus()==2){
                //计算出平均功率并赋值
                int power = (int) (100 + Math.random() * 10);
                point.setAveragePower(power);
            }
        });*/
        return new Response<List<ExperimentPoint>>().set(1,experimentPoints);
    }
 
    /**
     * 更新测试点的开始时间和状态
     */
    public Response updatePointStatus(ExperimentPoint experimentPoint){
        pointMapper.updateById(experimentPoint);
        return new Response().set(1,"状态更新成功");
    }
 
    /**
     * 启动测试点,并在测试时长过后,返回测试结果
     * 测试点的结束,结束分两种情况:
     *  情况一:经过预定的测试时长,停止
     *  情况二:更新了数据库的某个字段,代码循环判断这个字段,如果为2则停止实验并返回结果
     * @return
     */
    public Response startExperimentPoint(ExperimentPoint point){
        //更新测试时间和测试点状态
        point.setStartTime(new Date());
        point.setStatus(1);
        pointMapper.updateById(point);
        //等待duration时间
        Integer duration = point.getDuration();
        Integer durationSecond = duration*60;
        final boolean[] threadStatus = {true};
        //采用线程的原因是非线程sleep后无法执行手动结束条件判断代码
        Thread t = new Thread(){
            @Override
            public void run() {
                try {
                    sleep(durationSecond*1000);
                    threadStatus[0] = false;
                } catch (InterruptedException e) {
                    interrupt();
                    log.warn("t1线程被打断");
                    //e.printStackTrace();
                }
            };
        };
        t.start();
 
        boolean statusFlag =true;
        //手动停止和测试点预设时间,1个条件成立就终止测试
        while(statusFlag && threadStatus[0]){
            //查询测试点状态是否被打断
            QueryWrapper<ExperimentPoint> wrapper = Wrappers.query();
            wrapper.select("status").eq("id",point.getId());
            ExperimentPoint currentPoint = pointMapper.selectOne(wrapper);
            if(currentPoint.getStatus()==3){
                statusFlag = false;
            }
        }
        log.warn("测试点结束");
        if (t.isAlive()) {
            t.interrupt();
        }
 
        /*try {
            //sleep(durationSecond);
            //演示需要,使用5s
            sleep(5000);
 
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        pointMapper.updateEndTime(point.getId(),new Date());
        //返回这段时间的测试结果
        //TODO 这段时间内的数据,需要进行动态计算
        int value = (int) (100 + Math.random() * 10);
        ExperimentPoint pointTemp = new ExperimentPoint();
        pointTemp.setId(point.getId());
        pointTemp.setAveragePower(value);
        pointMapper.updateById(pointTemp);
        return new Response().setMsg(1,"测试点结束");
    }
 
 
    public Response finishExperiment(String experimentId) {
        mapper.updateStatusAndTime(experimentId,2,"end_time",new Date());
        return new Response().setMsg(1,"状态更新成功");
    }
 
    public Response finishExperimentPoint(Integer id) {
        ExperimentPoint point = new ExperimentPoint();
        point.setId(id);
        //中断信号
        point.setStatus(3);
        pointMapper.updateById(point);
        return new Response().setMsg(1,"测试点中断信号更新成功");
    }
 
    public Response restartExperimentPoint(Integer id) {
        ExperimentPoint point = new ExperimentPoint();
        point.setId(id);
        point.setStatus(0);
        point.setStartTime(null);
        point.setEndTime(null);
        point.setAveragePower(null);
        pointMapper.updateById(point);
        return new Response().setMsg(1,"重置测试点成功");
    }
 
    public Response setPrecondition(Integer id,Integer value) {
        switch (id){
            case 1:{
                commonMapper.setPrecondition("`db_3.5mw_motor`.tb_central_monitor_sys_rt","10001","switch_close",value.toString());
                break;
            }
            case 2:{
                commonMapper.setPrecondition("`db_3.5mw_motor`.tb_rectifier_power_rt","30001","rectifier_vol",value.toString());
                break;
            }
            case 3:{
                commonMapper.setPrecondition("`db_3.5mw_motor`.tb_central_monitor_sys_st","10005","vol_a",value.toString());
                break;
            }
            case 4:{
                commonMapper.setPrecondition("`db_3.5mw_motor`.tb_central_monitor_sys_st","10005","vol_b",value.toString());
                break;
            }
            case 5:{
                commonMapper.setPrecondition("`db_3.5mw_motor`.tb_device_state","40001","comm_status",value.toString());
                break;
            }
            case 6:{
                commonMapper.setPrecondition("`db_3.5mw_motor`.tb_device_state","40002","comm_status",value.toString());
                break;
            }
            case 7:{
                commonMapper.setPrecondition("`db_3.5mw_motor`.tb_device_state","50001","comm_status",value.toString());
                break;
            }
        }
        return new Response().setMsg(1,"设置完成");
    }
 
    /*======History======*/
 
    public Response<PageInfo<Experiment>> getPage(Integer pageNum, Integer pageSize, ExperimentConditionDTO condition) {
        condition.setStatus(2);
        PageHelper.startPage(pageNum,pageSize);
        List<Experiment> experimentList = mapper.getList(condition);
        //查询结果的duration是分钟,转换为 x时x分格式
        experimentList.stream().forEach(experiment -> {
            int duration = Integer.parseInt(experiment.getDuration());
            //获取时
            int hour = duration/60;
            //获取分
            int minute = duration%60;
            experiment.setDuration(hour+"小时"+minute+"分");
        });
 
        PageInfo<Experiment> pageInfo = new PageInfo<>(experimentList);
        return new Response<PageInfo<Experiment>>().set(1,pageInfo);
    }
 
}