| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970 |
- package com.ruoyi.sim.service.impl;
- import com.ruoyi.common.core.domain.AjaxResult;
- import com.ruoyi.common.utils.DateUtils;
- import com.ruoyi.sim.config.SimConfig;
- import com.ruoyi.sim.constant.CommConst;
- import com.ruoyi.sim.domain.*;
- import com.ruoyi.sim.domain.vo.SimSocketParamVo;
- import org.apache.commons.lang3.StringUtils;
- import org.slf4j.LoggerFactory;
- import org.slf4j.Logger;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.scheduling.annotation.Async;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.Socket;
- import java.util.*;
- import static com.ruoyi.sim.constant.CommConst.*;
- /**
- * 硬件通信
- * send service.
- * "commSendService"
- */
- @Service
- public class CommSendService {
- private static final Logger l = LoggerFactory.getLogger(CommSendService.class);
- @Autowired
- private CommReceiveService simReceiveService;
- @Autowired
- private SeatService seatService;
- @Autowired
- private SimService simService;
- @Autowired
- private FaultService faultService;
- @Autowired
- private RealExamService realExamService;
- @Autowired
- private RealExamFaultService realExamFaultService;
- @Autowired
- private RealExamCollectionService realExamCollectionService;
- @Autowired
- private CommBuildService commBuildService;
- @Autowired
- private DebugFaultService debugFaultService;
- // private SocketOldService socketOldService;
- @Autowired
- private SocketService socketService;
- @Autowired
- private CommCheckService commCheckService;
- @Autowired
- CommReceiveService commReceiveService;
- @Autowired
- private SimConfig config;
- @Autowired
- private CommStrategy commStrategy;
- /**
- * 定时任务。
- */
- public void scheduledLoopRead() {
- readAll();
- }
- public void readAll() {
- l.info("readAll");
- List<RealExam> listRe = realExamService.listAllByStatus(RealExam.State.ANSWERING);
- listRe.forEach(e -> {
- if (e == null) {
- return;
- }
- List<RealExamFault> listRef = realExamFaultService.listAllType2State2and3ByExamId(e.getExamId());
- listRef.forEach(ref -> {
- RealExam re = realExamService.selectRealExamByExamId(ref.getExamId());
- Seat seat = seatService.selectSeatBySeatId(re.getSeatId());
- Sim sim = simService.selectSimBySimId(e.getSimId());
- Fault f = faultService.selectFaultByFaultId(ref.getFaultId());
- if (f != null && Fault.Type.REAL_GZBW.equals(f.getFaultType()) && Fault.State.ENABLE.equals(f.getFaultState())) {
- readOneSimOneFaultResistance(seat, sim, ref, f, null);
- }
- });
- });
- }
- /**
- * Async version.
- */
- @Async("tp-comm")
- public void readAllAsync() {
- readAll();
- }
- public void readOneExamAtLast(RealExam re) {
- l.info("readOneExamAtLast");
- List<RealExamFault> list = realExamFaultService.listAllType2State2and3ByExamId(re.getExamId());
- for (RealExamFault ref : list) {
- Seat seat = seatService.selectSeatBySeatId(re.getSeatId());
- Sim sim = simService.selectSimBySimId(re.getSimId());
- Fault f = faultService.selectFaultByFaultId(ref.getFaultId());
- readOneSimOneFaultResistance(seat, sim, ref, f, RealExamFault.State.FINISH);
- }
- // 计算扣分。
- // 最后都读取到,才算扣分。
- {
- // todo:暂时不算。
- // calculateScore(re.getExamId());
- }
- }
- public void readOneSimAtLastByDebug(Seat seat, Sim sim) {
- l.info("readOneSimAtLastByDebug");
- List<Fault> list = faultService.listType3(sim.getSimType());
- for (Fault f : list) {
- readOneSimOneFaultResistance(seat, sim, null, f, null);
- }
- }
- public AjaxResult debugReadAllFaultResistanceBySimNum(final Long seatId) {
- // check
- //
- // 打开socket
- {
- socketService.tryOpenAll();
- }
- //
- Seat seat = seatService.selectSeatBySeatId(seatId);
- Sim sim = gggSimBySeatId(seatId);
- {
- AjaxResult arE3 = checkOneSimStateActive(seat);
- if (arE3.isError()) {
- return arE3;
- }
- }
- sim = simService.uniqueBySimNum(sim.getSimNum());
- // todo: aj改造
- readOneSimAtLastByDebug(seat, sim);
- return AjaxResult.success("成功读取!");
- }
- @Async("tp-comm")
- public void readOneExamAtLastAsync(RealExam re) {
- l.info("readOneExamAtLastAsync");
- readOneExamAtLast(re);
- }
- /**
- * 计算减分(不包括超时)。汇总到deduction_total_score字段。
- *
- * @param realExamId
- */
- public void calculateScore(Long realExamId) {
- realExamService.updateOneState(realExamId, RealExam.State.CALCULATING_SCORE);
- int minus = 0;
- // 排除故障部分 + 维修报告选择部分
- realExamFaultService.calculateMinusByRealExamId(realExamId);
- // 超时部分
- int timeoutMinute = 0;
- //
- realExamService.updateOneState(realExamId, RealExam.State.GOT_REPORT);
- }
- /**
- * todo:????
- * 定时任务。
- */
- public void scheduledReadSim() {
- l.info("scheduledReadSim");
- if (!realExamCollectionService.existAtLeastOneOpened()) {
- l.info("没有open的考试集合");
- return;
- }
- readAll();
- //
- // AA010102010000000055
- // AA010102010000000055
- String simNum = "01";
- String simType = "0002";
- // for (int i = 0; i < 3; i++) {
- // debugReadSimType(simNum);
- // }
- // debugClearAllFault(simNum, simType);
- // debugWriteAllFault(simNum, simType);
- // for (int i = 0; i < 3; i++) {
- // debugReadAllFaultResistance(simNum, simType);
- // }
- // debugClearOneFault(simNum, "02");
- // boolean bRea = isReachable("123.112.16.165");
- // debugReadSimType(simNum);
- // l.info("bRea:" + bRea);
- // debugReadAllFaultResistance(simNum, simType);
- // debugWriteAllFault(simNum, simType);
- // for (int i = 0; i < 5; i++) {
- // debugReadAllFaultResistance(simNum, simType);
- // }
- // if (isSocketOk()) {
- // readAllAsync();
- // } else {
- // scheduledConnect();
- // }
- }
- /**
- * 连接情况 的 定时任务。
- * 执行频率: 5min
- */
- public void scheduledConnect() {
- l.info("scheduled####Connect 连接情况 的 定时任务");
- // if (!SimDebugConfig.SCHEDULED_CONNECT) {
- if (true) {
- l.info("连接情况 的 定时任务被禁用!");
- return;
- }
- // 暂时注释
- // if (!realExamCollectionService.existAtLeastOneOpened()) {
- // l.info("没有open的任何集合");
- // return;
- // }
- //
- {
- AjaxResult ar = commCheckService.checkRouterState(config.getRouterIp());
- if (ar.isError()) {
- return;
- }
- }
- //
- {
- seatService.listAllRs485Ip().forEach(rs485Ip -> {
- commCheckService.checkPingRs485State(rs485Ip);
- });
- }
- // SocketOldService实现
- // if (socketOldService.isCachedSocketOk()) {
- // checkAllSeatAndSimState();
- // }
- socketService.tryOpenAll();
- commCheckService.checkAllSeatAndSimState();
- }
- /**
- * 主动更新模拟器状态。
- * <p>
- * <p>
- * 主动查询一次模拟器状态。更新模拟器在线/离线状态;否则返回对应错误。
- * todo:需要重新考虑,不再使用。
- *
- * @param seat
- * @return
- */
- @Deprecated
- public AjaxResult checkOneSimStateActive(Seat seat) {
- // 这句可能会调整模拟器状态,后面需要重新查询。
- commCheckService.checkOneSeatState(seat, true);
- AjaxResult ar1 = commCheckService.checkOneSimOnlineState(seat, true);
- if (ar1.isError()) {
- return ar1;
- }
- // 重新最新模拟器。
- Sim sim = gggSimBySeatId(seat.getSeatId());
- // 如果模拟器离线
- if (sim != null && Sim.State.ONLINE.equals(sim.getSimState())) {
- return AjaxResult.success();
- } else {
- return AjaxResult.error("未连接模拟器,请检查连接!");
- }
- }
- @Async("tp-comm")
- public void checkAllSimStateAsync() {
- commCheckService.checkAllSeatAndSimState();
- }
- /**
- * 清除一个考试的,对应的某型号一台模拟器的,所有故障部位。
- *
- * @param re
- */
- public void clearOneSimAllFaultByExam(RealExam re) {
- l.info("clearOneSimAllFaultByExam = {}", re);
- // check
- // 更新Exam状态。
- {
- realExamService.updateOneState(re.getExamId(), RealExam.State.SIM_WRITING);
- }
- //
- List<RealExamFault> list = realExamFaultService.listAllType2InitStateByExamId(re.getExamId());
- if (list != null) {
- l.info("清除exam list = {}", list.size());
- }
- assert list != null;
- Seat seat = seatService.selectSeatBySeatId(re.getSeatId());
- list.forEach(ref -> {
- Fault f = faultService.selectFaultByFaultId(ref.getFaultId());
- if (faultService.isDisable(f.getFaultId())) {
- l.warn("故障 {} -被禁用", f.getName());
- throw new IllegalArgumentException("故障被禁用");
- }
- Sim sim = simService.selectSimBySimId(re.getSimId());
- // check
- //
- clearOneSimOneFault(seat, sim, ref, f);
- });
- }
- public void clearOneSimAllFaultBySim(Seat seat, Sim sim) {
- l.info("clearOneSimAllFaultBySim = {}", sim);
- faultService.listType3EnableBySimType(sim.getSimType()).forEach(f -> {
- clearOneSimOneFault(seat, sim, null, f);
- });
- }
- /**
- * Async version.
- *
- * @param re
- */
- @Async("tp-comm")
- public void clearListFaultByRealExamAsync(RealExam re) {
- clearOneSimAllFaultByExam(re);
- }
- public void clearAll() {
- // todo:
- // 根据Seat数据遍历
- seatService.listAllEnable().forEach(seat -> {
- Sim sim = gggSimBySeatId(seat.getSeatId());
- String simType = sim.getSimType();
- List<Fault> listF = faultService.listType3EnableBySimType(simType);
- listF.forEach(f -> {
- clearOneSimOneFault(seat, sim, null, f);
- });
- });
- }
- /**
- * debug读取模拟器类型序列号
- *
- * @param seatId
- * @return
- */
- public SimMsg debugReadSimType(final Long seatId) {
- Seat seat = seatService.selectSeatBySeatId(seatId);
- Sim sim = gggSimBySeatId(seatId);
- SimMsg sm = commBuildService.buildSendMsgReadSimType(sim.getSimNum());
- return send(sm, seat, sim, CommConst.RETRY_COUNT_0, commStrategy.getSleepShort());
- }
- /**
- * debug清除一个故障
- *
- * @param seatId
- * @param bindHardwareMsg
- * @return
- */
- public SimMsg debugClearOneFault(final Long seatId, final String bindHardwareMsg) {
- Seat seat = seatService.selectSeatBySeatId(seatId);
- Sim sim = gggSimBySeatId(seatId);
- SimMsg sm = commBuildService.buildSendMsgClearFault(sim.getSimNum(), bindHardwareMsg);
- return send(sm, seat, sim, RETRY_COUNT_CLEAR_ONE_FAULT, commStrategy.getSleepLong());
- }
- public AjaxResult debugClearAllOnlineSimAllFault() {
- l.info("debugClearAllOnlineSimAllFault");
- simService.listAllOnline().forEach(s -> {
- // AjaxResult ar = debugClearAllFaultBySeatId(0);// todo:尚未实现
- });
- debugFaultService.deleteAll();
- return AjaxResult.success("清除成功,清除所有在线模拟器所有故障!");
- }
- /**
- * debug清除所有故障
- *
- * @param seatId
- * @return
- */
- @Transactional
- public AjaxResult debugClearAllFaultBySeatId(final Long seatId) {
- Seat seat = seatService.selectSeatBySeatId(seatId);
- Sim sim = gggSimBySeatId(seatId);
- // todo:
- {
- AjaxResult arE3 = checkOneSimStateActive(seat);
- if (arE3.isError()) {
- return arE3;
- }
- }
- sim = simService.uniqueBySimNum(sim.getSimNum());
- if (sim == null) {
- return AjaxResult.error("清除失败,对应simNum模拟器不存在!");
- }
- if (!Sim.State.ONLINE.equals(sim.getSimState())) {
- return AjaxResult.error("清除失败,模拟器尚未在线!");
- }
- List<SimMsg> list = new ArrayList<>();
- for (String b : getGZBWBySimType(sim.getSimType())) {
- SimMsg sm = debugClearOneFault(seatId, b);
- list.add(sm);
- // if (sm != null && !sm.isOk()) {
- //
- // }
- }
- debugFaultService.deleteAll();
- return AjaxResult.success("清除成功,清除当前模拟器所有故障!");
- }
- /**
- * @param sim
- * @param reF 可以为空,表示不关联考试的,单独执行的。调试模式下为空。
- * @param f
- */
- public void clearOneSimOneFault(Seat seat, Sim sim, RealExamFault reF, Fault f) {
- l.info("clearOneSimOneFault 清除One故障:getSimNum = {},getBindHardwareMsg = {},fault.getName = {}", sim.getSimNum(), f.getBindHardwareMsg(), f.getName());
- // check todo:
- // step1
- SimMsg smS = commBuildService.buildSendMsgClearFault(sim.getSimNum(), f.getBindHardwareMsg());
- SimMsg smR = send(smS, seat, sim, RETRY_COUNT_CLEAR_ONE_FAULT, commStrategy.getSleepLong());
- if (reF != null) {
- simReceiveService.clearOneFault(smR, sim, reF, f);
- } else {
- l.info("reF == null");
- }
- // step2
- // 下发故障独立运行。下面屏蔽。
- // if (reF != null &&
- // realExamFaultService.isState(reF.getRefId(), RealExamFault.State.CLEARED)) {
- // if (reF.getFlag().equals(RealExamFault.Flag.YES)) {
- // writeOneFault(s, reF, f);
- // } else if (reF.getFlag().equals(RealExamFault.Flag.NO)) {
- // RealExamFault f1 = realExamFaultService.selectRealExamFaultByRefId(reF.getRefId());
- // f1.setRefState(RealExamFault.State.LOOP_READ);
- // }
- // }
- }
- /**
- * debug下发一个故障
- *
- * @param seatId
- * @param bindHardwareMsg
- * @return
- * @throws IOException
- */
- public SimMsg debugWriteOneFault(final Long seatId, final String bindHardwareMsg) {
- Seat seat = seatService.selectSeatBySeatId(seatId);
- Sim sim = gggSimBySeatId(seatId);
- SimMsg sm = commBuildService.buildSendMsgWriteFault(sim.getSimNum(), bindHardwareMsg);
- return send(sm, seat, sim, RETRY_COUNT_WRITE_ONE_FAULT, commStrategy.getSleepLong());
- }
- /**
- * debug下发所有故障
- *
- * @param seatId
- * @return
- * @throws IOException
- */
- public List<SimMsg> debugWriteAllFault(final Long seatId) {
- List<SimMsg> list = new ArrayList<>();
- Sim sim = gggSimBySeatId(seatId);
- String simType = sim.getSimType();
- for (String bind : getGZBWBySimType(simType)) {
- list.add(debugWriteOneFault(seatId, bind));
- }
- return list;
- }
- /**
- * todo:尚未实现
- * 实现方式类似 studentStartRealExam方法。
- *
- * @param seatId
- * @param faultIds
- * @param checkReplace 是否进行可换件检查
- * @return
- */
- @Transactional
- public AjaxResult debugWriteSelectedFaultBySimNum(final Long seatId, final String[] faultIds, final Boolean checkReplace) {
- //
- l.info("faultIds.length = {}", faultIds.length);
- {
- int deleteCount = debugFaultService.deleteAll();
- l.info("deleteCount = {}", deleteCount);
- }
- // check faultIds 有效性
- //
- Seat seat = seatService.selectSeatBySeatId(seatId);
- Sim sim = gggSimBySeatId(seatId);
- // check sim
- // 打开socket
- {
- socketService.tryOpenAll();
- }
- // Step 1 主动查询一次模拟器状态。
- {
- AjaxResult arE3 = checkOneSimStateActive(seat);
- if (arE3.isError()) {
- return arE3;
- }
- }
- sim = simService.uniqueBySimNum(sim.getSimNum());
- // Step 2
- // msg判断,是否含有"故障部位"字符串
- {
- if (checkReplace) {
- AjaxResult arE2 = readOneSimAllFaultCheck(seat, sim);
- if (arE2.isError()) {
- return arE2;
- }
- }
- }
- // Step 3 清除对应一台模拟器 所有故障部位故障。
- {
- clearOneSimAllFaultBySim(seat, sim);
- }
- // Step 4 下发对应一台模拟器 出题选中的 故障位置故障。
- {
- Fault[] faults = new Fault[faultIds.length];
- for (int i = 0; i < faultIds.length; i++) {
- faults[i] = faultService.selectFaultByFaultId(faultIds[i]);
- }
- writeOneSimAllSelectFaultByDebug(seat, sim, faults);
- }
- // Step 5 读取
- {
- readOneSimAllFaultFirstTimeBySim(seat, sim, faultIds);
- }
- return AjaxResult.success("下发故障流程执行成功!");
- }
- public AjaxResult debugRefreshAllSeat() {
- return AjaxResult.success("执行成功!");
- }
- private String[] getGZBWBySimType(String simType) {
- if (StringUtils.isBlank(simType)) {
- return new String[0];
- }
- switch (simType) {
- case Sim.TYPE_0001 -> {
- return TYPE_1_BIND_MSG;
- }
- case Sim.TYPE_0002 -> {
- return TYPE_2_BIND_MSG;
- }
- case Sim.TYPE_0003 -> {
- return TYPE_3_BIND_MSG;
- }
- default -> {
- return new String[0];
- }
- }
- }
- /**
- * 下发所有选中的真实的故障部位。
- *
- * @param re
- */
- public void writeOneSimAllSelectFaultByExam(RealExam re) {
- // 更新Exam状态。
- realExamService.updateOneState(re.getExamId(), RealExam.State.SIM_WRITING);
- List<RealExamFault> list = realExamFaultService.listAllType2FlagYesClearedStateByExamId(re.getExamId());
- for (RealExamFault ref : list) {
- Seat seat = seatService.selectSeatBySeatId(re.getSeatId());
- Sim sim = simService.selectSimBySimId(re.getSimId());
- Fault f = faultService.selectFaultByFaultId(ref.getFaultId());
- // 选中的故障才下发。
- writeOneSimOneFault(seat, sim, ref, f);
- }
- }
- public void writeOneSimAllSelectFaultByDebug(Seat seat, Sim sim, Fault[] faults) {
- for (Fault f : faults) {
- writeOneSimOneFault(seat, sim, null, f);
- }
- }
- public void writeOneSimOneFault(Seat seat, Sim sim, RealExamFault ref, Fault f) {
- l.info("下发故障:getSimId = {},fault.getName = {}", sim.getSimId(), f.getName());
- // todo:ref is null.
- // 下发故障
- SimMsg smA1 = commBuildService.buildSendMsgWriteFault(sim.getSimNum(), f.getBindHardwareMsg());
- SimMsg smA2 = send(smA1, seat, sim, RETRY_COUNT_WRITE_ONE_FAULT, commStrategy.getSleepLong());
- }
- /**
- * 开始考试前检查读取。
- *
- * @param sim
- * @return
- */
- public AjaxResult readOneSimAllFaultCheck(Seat seat, Sim sim) {
- Fault q = new Fault();
- q.setFaultType(Fault.Type.REAL_GZBW);
- q.setSimType(sim.getSimType());
- List<Fault> list = faultService.selectFaultList(q);
- List<Fault> listNG = new ArrayList<>();
- for (Fault f : list) {
- AjaxResult ar = readOneSimOneFaultCheck(seat, sim, f);
- if (ar.isError()) {
- listNG.add(f);
- l.info("故障部位[" + f.getBindHardwareMsg() + "][" + f.getReplaceName() + "]未正确安装;");
- } else {
- l.info("故障部位[" + f.getBindHardwareMsg() + "][" + f.getReplaceName() + "]安装ok;");
- }
- }
- if (listNG.isEmpty()) {
- return AjaxResult.success("所有故障部位检查没有问题。");
- }
- StringBuilder sbNG = new StringBuilder();
- for (Fault f : listNG) {
- sbNG.append("[" + f.getReplaceName() + "]可换件异常;<br>");
- }
- sbNG.append("请正确安装可换件,检查后重新开始考试!");
- return AjaxResult.error(sbNG.toString());
- }
- /**
- * 检查读取。
- *
- * @param sim
- * @param f
- * @return
- */
- public AjaxResult readOneSimOneFaultCheck(Seat seat, Sim sim, Fault f) {
- l.info("readOneSimOneFaultCheck sim = {},f = {}", sim, f);
- SimMsg sm1 = commBuildService.buildSendMsgReadFaultResistance(sim.getSimNum(), f.getBindHardwareMsg());
- SimMsg sm2 = send(sm1, seat, sim, RETRY_COUNT_CHECK_ONE_FAULT, commStrategy.getSleepLong());
- return simReceiveService.getOneFaultCheck(sm2, sim, f);
- }
- /**
- * 第一次读取,作为出题值。
- *
- * @param re
- */
- public void readOneSimAllFaultFirstTimeByExam(RealExam re) {
- l.info("readOneSimAllFaultFirstTimeByExam re = {}", re);
- List<RealExamFault> list = realExamFaultService.listAllType2(re.getExamId());
- for (RealExamFault ref : list) {
- Seat seat = seatService.selectSeatBySeatId(re.getSeatId());
- Sim sim = simService.selectSimBySimId(re.getSimId());
- Fault f = faultService.selectFaultByFaultId(ref.getFaultId());
- readOneSimOneFaultFirstTime(seat, sim, ref, f, null);
- }
- }
- /**
- * 第一次读取,作为出题值。debug模式。
- *
- * @param sim
- * @param faultIds
- */
- public void readOneSimAllFaultFirstTimeBySim(Seat seat, Sim sim, final String[] faultIds) {
- l.info("readOneSimAllFaultFirstTimeBySim s = {}", sim);
- List<Fault> list = faultService.listType3(sim.getSimType());
- for (Fault f : list) {
- readOneSimOneFaultFirstTime(seat, sim, null, f, faultIds);
- }
- }
- /**
- * 第一次读取,作为出题值。
- *
- * @param sim
- * @param ref debug调试模式为空。可以为空。
- * @param f
- * @param faultIds debug调试模式为空。
- */
- public void readOneSimOneFaultFirstTime(Seat seat, Sim sim, RealExamFault ref, Fault f, String[] faultIds) {
- l.info("readOneSimOneFaultFirstTime");
- // 读取一次当前电阻代表值作为出题值。
- SimMsg sm1 = commBuildService.buildSendMsgReadFaultResistance(sim.getSimNum(), f.getBindHardwareMsg());
- SimMsg sm2 = send(sm1, seat, sim, RETRY_COUNT_WRITE_ONE_FAULT, commStrategy.getSleepLong());
- simReceiveService.setFaultQuestionValue(sm2, sim, ref, f, faultIds);
- }
- /**
- * debug读取一个故障位置数据
- *
- * @param seatId
- * @param bindHardwareMsg
- * @return
- */
- public SimMsg debugReadOneFaultResistance(final Long seatId, final String bindHardwareMsg) {
- Seat seat = seatService.selectSeatBySeatId(seatId);
- Sim sim = gggSimBySeatId(seatId);
- SimMsg sm = commBuildService.buildSendMsgReadFaultResistance(sim.getSimNum(), bindHardwareMsg);
- return send(sm, seat, null, RETRY_COUNT_0, commStrategy.getSleepShort());
- }
- /**
- * debug读取全部故障位置数据
- *
- * @param seatId
- * @return
- */
- public List<SimMsg> debugReadAllFaultResistance(final Long seatId) {
- Sim sim = gggSimBySeatId(seatId);
- List<SimMsg> list = new ArrayList<>();
- String simType = simService.uniqueBySimNum(sim.getSimNum()).getSimType();
- for (String b : getGZBWBySimType(simType)) {
- list.add(debugReadOneFaultResistance(seatId, b));
- }
- return list;
- }
- /**
- * @param sim
- * @param reF
- * @param f
- * @param refState 中间轮询是null,交卷最后一次读取为finish状态。用来修改状态的。debug模式下执行为null。
- */
- public void readOneSimOneFaultResistance(Seat seat, Sim sim, RealExamFault reF, Fault f, String refState) {
- l.info("readOneSimOneFaultResistance");
- SimMsg sm1 = commBuildService.buildSendMsgReadFaultResistance(sim.getSimNum(), f.getBindHardwareMsg());
- SimMsg sm2 = null;
- if (reF != null && refState != null) {
- if (RealExamFault.State.FINISH.equals(refState)) { // 是否最后一次读取。
- sm2 = send(sm1, seat, sim, RETRY_COUNT_READ_ONE_RESISTANCE, commStrategy.getSleepShort());
- } else {
- sm2 = send(sm1, seat, sim, RETRY_COUNT_0, commStrategy.getSleepShort());
- }
- } else {
- sm2 = send(sm1, seat, sim, RETRY_COUNT_READ_ONE_RESISTANCE, commStrategy.getSleepShort());
- }
- simReceiveService.setFaultAnswerValue(sm2, sim, reF, f, refState);
- }
- /**
- * 最基本的通信方法。
- * send hex message
- * <p>
- * 去掉synchronized
- *
- * @param sm 发送
- * @param seat 不能为空
- * @param sim 可以为空!更新最后发送/接收时间 用。
- * @param retryTotalCount 重试次数
- * @param sleep 不使用传入0,不进行挂起。
- * @return
- */
- public SimMsg send(final SimMsg sm, final Seat seat, final Sim sim, final int retryTotalCount, final long sleep) {
- try {
- if (!config.isCommGlobal()) {
- l.warn("isCommGlobal == false [模拟器通信被禁用!]");
- return sm;
- }
- if (sm == null || sm.getSendMsg() == null || StringUtils.isBlank(sm.getSendMsg())) {
- throw new IllegalArgumentException("SimMsg IllegalArgument");
- }
- // sim
- if (seat == null) {
- throw new IllegalArgumentException("seat is null");
- }
- if (sleep < 0) {
- throw new IllegalArgumentException("SimMsg sleep");
- }
- // log.
- {
- l.info("####发送#### == Seat[{}],SimMsg[{}]", seat, sm);
- }
- // 如果没有打开socket,顺道打开。正好后面要sleep。
- // 不强制重开Socket。
- // 先进行Socket相关处理。
- SimSocketParamVo sspv = seat.toSimSocketParamVo();
- socketService.openOne(sspv, socketService.isNotOk(sspv));
- // Socket情况不正确,直接返回。
- if (socketService.isNotOk(sspv)) {
- sm.setResult(SimMsg.Result.SOCKET_CONNECT_EXCEPTION);
- return sm;
- }
- {
- // sleep挂起线程,追求顺序请求。
- // 大于0才挂起。
- if (sleep > 0 && socketService.get(sspv).getPreviousSendSleep() > 0L) {
- // 时间间隔挂起。
- Thread.sleep(socketService.get(sspv).getPreviousSendSleep());
- }
- }
- socketService.get(sspv).setPreviousSendSleep(sleep);
- Socket socket = socketService.get(sspv).getSocket();
- InputStream is = socket.getInputStream();
- OutputStream os = socket.getOutputStream();
- os.write(hexStrToByteArrs(sm.getSendMsg()));
- sm.setSendTime(DateUtils.getNowDate());
- if (sim != null) {
- simService.updateLastSentTime(sim);
- }
- byte[] buffer = new byte[LENGTH_24];
- int length = is.read(buffer);
- StringBuilder sbHex = new StringBuilder();
- for (int i = 0; i < length; i++) {
- sbHex.append(String.format("%02X", buffer[i]));
- }
- String receiveWith0 = sbHex.toString();
- // 原始带0的收到报文。
- sm.setReceiveOriginalMsg(receiveWith0);
- sm.setReceiveMsg(commReceiveService.removeRrefix0(receiveWith0));
- sm.setReceiveTime(DateUtils.getNowDate());
- // log.
- {
- AjaxResult ar = commReceiveService.checkReceiveMsg(sm.getReceiveMsg());
- if (ar.isError()) {
- // todo:
- l.warn("####接收错误#### = {}", sm);
- sm.setResult(SimMsg.Result.RECEIVE_CHECK_FAIL);
- return sm;
- } else {
- l.info("####接收成功#### = {}", sm);
- }
- }
- if (sim != null) {
- simService.updateLastReceivedTime(sim);
- }
- sm.setResult(SimMsg.Result.SUCCESS);
- // 最后返回报文实体。
- return sm;
- } catch (InterruptedException | IOException e) {
- // SocketTimeoutException
- l.error("SocketTimeoutException");
- e.printStackTrace();
- sm.setResult(SimMsg.Result.SOCKET_READ_TIMEOUT_EXCEPTION);
- if (sim != null) {
- l.info("fail sim.getSimId() = {}", sim.getSimId());
- }
- SimSocketParamVo sspv = seat.toSimSocketParamVo();
- // Socket失败计数
- socketService.failedPlus1(sspv);
- if (socketService.failedIsReachedMax(sspv, SocketService.SOCKET_CONNECT_RETRY_COUNT_LIMIT)) {
- // 达到重试次数上限,认为模拟器离线
- if (sim != null) {
- simService.updateSimStateBySimId(sim.getSimId(), Sim.State.OFFLINE);
- }
- socketService.failedReset0(sspv);
- }
- // 先考虑一台模拟器演示。
- // 进行重试 start
- if (sm.getRetryCount() == RETRY_COUNT_0) {
- l.warn("####RetryTotalCount不重试RETRY_COUNT_0#### = getSimMsgId = {}", sm.getSimMsgId());
- return sm;
- }
- if (sm.getRetryCount() < retryTotalCount) {
- sm.retryCountPlus1();
- send(sm, seat, sim, retryTotalCount, sleep);
- l.warn("####RetryTotalCount重试#### = {}", sm);
- } else {
- l.warn("####RetryTotalCount达到重试上限#### = {}", sm);
- }
- // 进行重试 end
- // 最后返回报文实体。
- return sm;
- }
- }
- /**
- * todo:
- *
- * @param sm
- * @param s
- * @param retryTotalCount
- * @param sleep
- * @return
- */
- public SimMsg sendRetry(final SimMsg sm, final Sim s, final int retryTotalCount, final long sleep) {
- return null;
- }
- /**
- * https://mvnrepository.com/artifact/com.infiniteautomation/modbus4j/3.0.3
- */
- public void test02() {
- byte[] data = {0x01, 0x03, 0x00, 0x00, 0x00, 0x02}; // 示例数据
- // int crc = ModbusUtils.calculateCRC(data);
- // System.out.println("CRC-16/MODBUS 校验值: " + Integer.toHexString(crc));
- }
- public static byte[] hexStrToByteArrs(String hexString) {
- // if (StringUtils.isEmpty(hexString)) {
- // return null;
- // }
- hexString = hexString.replaceAll(" ", "");
- int len = hexString.length();
- int index = 0;
- byte[] bytes = new byte[len / 2];
- while (index < len) {
- String sub = hexString.substring(index, index + 2);
- bytes[index / 2] = (byte) Integer.parseInt(sub, 16);
- index += 2;
- }
- return bytes;
- }
- public String logBytesToString(byte[] bytes) {
- if (bytes == null || bytes.length == 0) {
- return "";
- }
- StringBuffer sbHex = new StringBuffer();
- byte[] buffer = new byte[bytes.length];
- for (int i = 0; i < bytes.length; i++) {
- sbHex.append(String.format("%02X", buffer[i]));
- }
- return sbHex.toString();
- }
- public static String bytesToHexV2(byte[] bytes) {
- StringBuilder hexString = new StringBuilder();
- for (byte b : bytes) {
- String hex = Integer.toHexString(0xFF & b); // 将字节转换为十六进制字符串
- if (hex.length() == 1) {
- hexString.append('0'); // 如果是单个字符,补零
- }
- hexString.append(hex);
- }
- return hexString.toString();
- }
- /**
- * todo:不存在部分数据
- *
- * @param seatId
- * @return
- */
- public Sim gggSimBySeatId(Long seatId) {
- Seat seat = seatService.selectSeatBySeatId(seatId);
- AjaxResult ar01 = commCheckService.checkOneSeatState(seat, true);
- if (ar01.isSuccess()) {
- Long simId = seatService.selectSeatBySeatId(seatId).getCurrentSimId();
- return simService.selectSimBySimId(simId);
- } else {
- throw new IllegalArgumentException("error gggSimBySeatId");
- }
- }
- }
|