Compare commits

...

38 Commits

Author SHA1 Message Date
thesai 508b8fa086 [修改]人解进路功能增加关闭引导信号功能(成都三)
CI / Docker-Build (push) Successful in 2m14s Details
[新增]首区段占用时,办理引导进路延时15秒后关闭引导信号
2024-10-12 17:30:21 +08:00
tiger_zhou 3c9aeb82f6 列车运行图例,报错修复
CI / Docker-Build (push) Successful in 4m35s Details
2024-10-10 17:57:59 +08:00
thesai 81074bbb2a [修改]使车站折返策略生效;修改车次计划更新逻辑以消除折返策略导致的列车行驶到非计划折返轨的情况 2024-10-10 17:36:21 +08:00
thesai 82682452a1 [修改]列车在功能轨上时,会优先停在轨道的停车点上 2024-10-10 17:07:17 +08:00
thesai f14e377565 [新增]以终端反向信号机命名的信号机同样也用此信号机作为办理进路的按钮
CI / Docker-Build (push) Successful in 2m13s Details
2024-09-29 09:31:21 +08:00
thesai b302bb360b [新增]开启自动进路的信号机不能开放引导信号 2024-09-26 15:20:55 +08:00
thesai 1e2ed4d305 [新增]获取用户信息的接口中增加更新时间
CI / Docker-Build (push) Successful in 2m12s Details
2024-09-25 13:27:39 +08:00
thesai 436a07bcf4 [新增]获取所有用户信息的接口
CI / Docker-Build (push) Successful in 2m9s Details
2024-09-25 10:51:31 +08:00
thesai 235f4dce5b [新增]按id数组查询用户信息的接口
CI / Docker-Build (push) Successful in 2m14s Details
2024-09-24 16:43:07 +08:00
thesai ac87b0dbe9 [bug]实训中,有多个评分规则时,仅有一个评分规则被使用
CI / Docker-Build (push) Successful in 2m12s Details
2024-09-18 10:37:33 +08:00
thesai 3536ff75ad [修改]后备模式下,办理引导进路不再检查区段占用
CI / Docker-Build (push) Successful in 2m11s Details
2024-09-11 19:07:55 +08:00
thesai f57952b755 [修改]实训结束后的评分删除多余的memberId字段;查询实训按id逆序排列
CI / Docker-Build (push) Successful in 2m13s Details
2024-09-11 14:02:16 +08:00
thesai 9c9e7c60e3 [修改]场景实训结束后的评分展示中增加非用户角色的步骤(并增加每个步骤对应的角色id,非用户角色步骤没有分数)
CI / Docker-Build (push) Successful in 6m56s Details
2024-09-10 17:55:50 +08:00
thesai 98abf0691a Merge remote-tracking branch 'origin/develop' into develop 2024-09-10 17:01:45 +08:00
thesai 16e8dc191f [bug]对道岔区段的区故解仅解锁指定的区段,而非整个道岔计轴区段 2024-09-10 17:01:24 +08:00
tiger_zhou 4f151fae4a 修改 仿真销毁的时候发送cgy时间,有个可能是空的
CI / Docker-Build (push) Successful in 2m33s Details
2024-08-19 09:42:14 +08:00
tiger_zhou e93171e958 调整列车区段没有值得问题
CI / Docker-Build (push) Successful in 5m14s Details
2024-08-16 18:59:18 +08:00
thesai 4cd80bbec5 [bug]成都工业实体信号机黄灯、绿灯控制逻辑不对 2024-07-29 13:43:06 +08:00
thesai 8125e32d7e [bug]成都工业实体信号机黄灯、绿灯控制逻辑不对 2024-07-18 16:45:00 +08:00
thesai e23864fa72 [修改]探索如何设置maven镜像源
CI / Docker-Build (push) Successful in 5m3s Details
2024-06-11 20:40:34 +08:00
thesai 212773e679 [修改]gitea自动构建/发布脚本文件
CI / Docker-Build (push) Failing after 19m33s Details
2024-06-11 20:15:21 +08:00
thesai 495681db5d [修改]语音识别校验接口要求匹配率提高到70%
CI / Docker-Build (push) Failing after 1m49s Details
2024-06-07 18:10:20 +08:00
thesai dbe197eba6 [bug]成都工业区段联动服务没写 2024-05-24 11:40:13 +08:00
thesai cee9eda430 [修改]校验语音识别接口增加立体声转单声道逻辑
CI / Docker-Build (push) Successful in 2m36s Details
2024-05-17 17:38:22 +08:00
thesai 0d10203613 [修改]发布配置文件
CI / Docker-Build (push) Successful in 2m29s Details
公网服务发布 / Docker-Build-Push (push) Successful in 10s Details
2024-05-16 16:59:41 +08:00
thesai 99a772a050 [修改]语音识别并与正确文本进行校验接口的参数接收方式
CI / Docker-Build (push) Successful in 2m31s Details
2024-05-14 18:32:59 +08:00
thesai ba1e057bce [新增]语音识别并与正确文本进行校验接口
CI / Docker-Build (push) Successful in 8m28s Details
2024-05-14 15:14:16 +08:00
thesai 6187e6d667 [bug]成工院虚仿平台对接的统计数据同步服务bug 2024-05-11 09:09:33 +08:00
thesai bef6dda6b2 [新增]成工院虚仿平台对接的登录接口、统计数据并同步服务 2024-05-07 16:47:32 +08:00
thesai 5d15ba3240 [修改]成都工业职业技术学院项目设备联动逻辑 2024-04-17 10:42:05 +08:00
thesai aae729b637 【修改】试卷创建者信息查询接口GET请求参数绑定出错,改为POST 2024-04-11 13:18:17 +08:00
thesai 2416d21a4f 【新增】试卷创建者信息查询接口;查询试卷增加按创建人筛选 2024-04-10 14:53:34 +08:00
soul-walker 346a265164 添加readme文件说明分支及发布方式
CI / Docker-Build (push) Successful in 2m29s Details
公网服务发布 / Docker-Build-Push (push) Successful in 15s Details
2024-03-25 18:57:48 +08:00
soul-walker 9921aea15a 修改定时任务cron 2024-03-25 18:39:10 +08:00
soul-walker 3e19150a48 删除测试步骤
公网服务发布 / Docker-Build-Push (push) Successful in 28s Details
2024-03-25 18:28:52 +08:00
soul-walker 202037ec55 修改定时执行工作流
CI / Docker-Build (push) Successful in 2m30s Details
公网服务发布 / Docker-Build-Push (push) Failing after 14s Details
添加清理docker tag为none镜像步骤
2024-03-25 18:19:31 +08:00
soul-walker 5045f6152a 修改触发间隔
CI / Docker-Build (push) Successful in 2m28s Details
公网服务发布 / Docker-Build-Push (push) Successful in 3s Details
2024-03-25 17:14:43 +08:00
soul-walker 2a47dc5979 测试定时执行CI
修改工作流名称
2024-03-25 17:06:30 +08:00
88 changed files with 8498 additions and 10328 deletions

View File

@ -0,0 +1,32 @@
name: 公网服务发布
run-name: ${{ gitea.actor }} is testing out Gitea Actions
on:
schedule:
- cron: '30 3 * * 1' # 每周一的凌晨3:30
jobs:
Docker-Build-Push:
runs-on: joylink-local233
steps:
- name: 发布到正式环境1
uses: https://gitea.joylink.club/appleboy/ssh-action@v1.0.3
with:
host: ${{ secrets.PUB1_DOMAIN_SSH_HOST }}
port: ${{ secrets.PUB1_DOMAIN_SSH_PORT }}
username: ${{ secrets.PUB1_DOMAIN_SSH_USER }}
password: ${{ secrets.PUB1_DOMAIN_SSH_PASSWORD }}
script: |
docker rm -f rt-sim-training-service || echo "rt-sim-training-service not exist"
docker pull gitea.joylink.club/joylink/rt-sim-training-service:latest
docker run --name rt-sim-training-service -it -u root --restart=always -d -e APP_ENV=prd -p 9000:9000 -p 19000:19000 -v /usr/local/joylink/logs/rtss:/usr/local/joylink/logs/rtss gitea.joylink.club/joylink/rt-sim-training-service:latest
- name: 发布到正式环境2
uses: https://gitea.joylink.club/appleboy/ssh-action@v1.0.3
with:
host: ${{ secrets.PUB2_DOMAIN_SSH_HOST }}
port: ${{ secrets.PUB2_DOMAIN_SSH_PORT }}
username: ${{ secrets.PUB2_DOMAIN_SSH_USER }}
password: ${{ secrets.PUB2_DOMAIN_SSH_PASSWORD }}
script: |
docker rm -f rt-sim-training-service || echo "rt-sim-training-service not exist"
docker pull gitea.joylink.club/joylink/rt-sim-training-service:latest
docker run --name rt-sim-training-service -it -u root --restart=always -d -e APP_ENV=prd -p 9000:9000 -p 19000:19000 -v /usr/local/joylink/logs/rtss:/usr/local/joylink/logs/rtss gitea.joylink.club/joylink/rt-sim-training-service:latest

View File

@ -55,4 +55,7 @@ jobs:
script: | script: |
docker rm -f rt-sim-training-service || echo "rt-sim-training-service not exist" docker rm -f rt-sim-training-service || echo "rt-sim-training-service not exist"
docker pull gitea.joylink.club/joylink/rt-sim-training-service:local-test docker pull gitea.joylink.club/joylink/rt-sim-training-service:local-test
docker run --name rt-sim-training-service --restart=always --network net --ip 192.168.53.3 -d -e APP_ENV=local-test -p 9000:9000 -p 19000:19000 -v /usr/local/joylink/logs/rtss:/usr/local/joylink/logs/rtss gitea.joylink.club/joylink/rt-sim-training-service:local-test docker run --name rt-sim-training-service --restart=always --network net --ip 192.168.53.3 -d -e APP_ENV=local-test -p 9000:9000 -p 19000:19000 -v /usr/local/joylink/logs/rtss:/usr/local/joylink/logs/rtss gitea.joylink.club/joylink/rt-sim-training-service:local-test
# - name: 清理tag为none的镜像
# run: |
# docker rmi $(docker images --filter "dangling=true" -q --no-trunc) 2>/dev/null || echo "No dangling images to remove"

View File

@ -1,8 +1,8 @@
name: CI-master name: 版本发布docker构建并上传
run-name: ${{ gitea.actor }} is testing out Gitea Actions run-name: ${{ gitea.actor }} is testing out Gitea Actions
on: on:
release: release:
types: [published] types: [ published ]
jobs: jobs:
Docker-Build-Push: Docker-Build-Push:
@ -45,6 +45,9 @@ jobs:
tags: | tags: |
gitea.joylink.club/joylink/rt-sim-training-service:${{ github.event.release.tag_name }} gitea.joylink.club/joylink/rt-sim-training-service:${{ github.event.release.tag_name }}
gitea.joylink.club/joylink/rt-sim-training-service:latest gitea.joylink.club/joylink/rt-sim-training-service:latest
# - name: 清理tag为none的镜像
# run: |
# docker rmi $(docker images --filter "dangling=true" -q --no-trunc) 2>/dev/null || echo "No dangling images to remove"
# - name: 发布到本地测试环境 # - name: 发布到本地测试环境
# uses: https://gitea.joylink.club/appleboy/ssh-action@v1.0.3 # uses: https://gitea.joylink.club/appleboy/ssh-action@v1.0.3
# with: # with:

7
README.md Normal file
View File

@ -0,0 +1,7 @@
# CI、CD说明
- 分支主要为developlocal-testmaster
- 本地233服务器部署方式为push到local-test分支即可触发
- 公网服务器发布方式:
1. push到master虽然可以用别的分支但不建议
2. 在版本发布处发布新版本触发构建docker镜像
3. 待docker镜像构建完成后点击Actions中CD_pub_deploy.yaml进入第一个任务点击重新运行所有任务进行服务发布

471
pom.xml
View File

@ -1,231 +1,252 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>club.joylink</groupId>
<artifactId>rtss</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>rtss</name>
<description>Rail transit simulation system</description>
<properties>
<java.version>11</java.version>
<pagehelper.version>4.1.1</pagehelper.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- javax.validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<!--spring切面aop依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</dependency>
<dependency>
<groupId>com.digitalpetri.modbus</groupId>
<artifactId>modbus-codec</artifactId>
<version>1.1.1</version>
</dependency>
<!-- 硬件检测依赖 -->
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core-java11</artifactId>
<version>5.7.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.github.wechatpay-apiv3</groupId>
<artifactId>wechatpay-apache-httpclient</artifactId>
<version>0.2.1</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.huawei.sis</groupId>-->
<!-- <artifactId>huaweicloud-java-sdk-sis</artifactId>-->
<!-- <version>1.3.2</version>-->
<!-- <scope>system</scope>-->
<!-- <systemPath>${project.basedir}/libs/huaweicloud-java-sdk-sis-1.3.2.jar</systemPath>-->
<!-- </dependency>-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.4.4</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version>
</dependency>
<!-- <dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.3</version>
</dependency>
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
<!-- iscs -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.23.1</version>
</dependency>
<dependency>
<groupId>com.hubspot.jackson</groupId>
<artifactId>jackson-datatype-protobuf</artifactId>
<version>0.9.12</version>
</dependency>
<!-- <dependency>
<groupId>com.chenlb.mmseg4j</groupId>
<artifactId>mmseg4j-core</artifactId>
<version>1.10.0</version>
</dependency>-->
<!-- <dependency>
<groupId>org.ansj</groupId>
<artifactId>ansj_seg</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.11</version>
</dependency>-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<!-- <dependency>
<groupId>info.debatty</groupId>
<artifactId>java-string-similarity</artifactId>
<version>2.0.0</version>
</dependency>-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.10.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<configuration> <version>2.3.5.RELEASE</version>
<includeSystemScope>true</includeSystemScope> <relativePath/> <!-- lookup parent from repository -->
</configuration> </parent>
</plugin> <groupId>club.joylink</groupId>
<artifactId>rtss</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>rtss</name>
<description>Rail transit simulation system</description>
<plugin> <properties>
<groupId>com.github.shalousun</groupId> <java.version>11</java.version>
<artifactId>smart-doc-maven-plugin</artifactId> <pagehelper.version>4.1.1</pagehelper.version>
<version>2.1.9</version> </properties>
<configuration>
<!--指定生成文档的使用的配置文件,配置文件放在自己的项目中-->
<configFile>./src/main/resources/smart-doc.json</configFile>
<!--smart-doc实现自动分析依赖树加载第三方依赖的源码如果一些框架依赖库加载不到导致报错这时请使用excludes排除掉-->
<!-- <excludes>-->
<!-- &lt;!&ndash;格式为groupId:artifactId;参考如下&ndash;&gt;-->
<!-- <exclude>com.alibaba:fastjson</exclude>-->
<!-- </excludes>-->
<!-- &lt;!&ndash;自1.0.8版本开始插件提供includes支持,配置了includes后插件会按照用户配置加载而不是自动加载因此使用时需要注意&ndash;&gt;-->
<!-- &lt;!&ndash;smart-doc能自动分析依赖树加载所有依赖源码原则上会影响文档构建效率因此你可以使用includes来让插件加载你配置的组件&ndash;&gt;-->
<!-- <includes>-->
<!-- &lt;!&ndash;格式为groupId:artifactId;参考如下&ndash;&gt;-->
<!-- <include>com.alibaba:fastjson</include>-->
<!-- </includes>-->
</configuration>
<executions>
<execution>
<!--如果不需要在执行编译时启动smart-doc则将phase注释掉-->
<!-- <phase>compile</phase>-->
<goals>
<!--smart-doc提供了html、openapi、markdown等goal可按需配置-->
<goal>html</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- javax.validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<!--spring切面aop依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</dependency>
<dependency>
<groupId>com.digitalpetri.modbus</groupId>
<artifactId>modbus-codec</artifactId>
<version>1.1.1</version>
</dependency>
<!-- 硬件检测依赖 -->
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core-java11</artifactId>
<version>5.7.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.github.wechatpay-apiv3</groupId>
<artifactId>wechatpay-apache-httpclient</artifactId>
<version>0.2.1</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.huawei.sis</groupId>-->
<!-- <artifactId>huaweicloud-java-sdk-sis</artifactId>-->
<!-- <version>1.3.2</version>-->
<!-- <scope>system</scope>-->
<!-- <systemPath>${project.basedir}/libs/huaweicloud-java-sdk-sis-1.3.2.jar</systemPath>-->
<!-- </dependency>-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.4.4</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version>
</dependency>
<!-- <dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.3</version>
</dependency>
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
<!-- iscs -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.23.1</version>
</dependency>
<dependency>
<groupId>com.hubspot.jackson</groupId>
<artifactId>jackson-datatype-protobuf</artifactId>
<version>0.9.12</version>
</dependency>
<!-- <dependency>
<groupId>com.chenlb.mmseg4j</groupId>
<artifactId>mmseg4j-core</artifactId>
<version>1.10.0</version>
</dependency>-->
<!-- <dependency>
<groupId>org.ansj</groupId>
<artifactId>ansj_seg</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.11</version>
</dependency>-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<!-- <dependency>
<groupId>info.debatty</groupId>
<artifactId>java-string-similarity</artifactId>
<version>2.0.0</version>
</dependency>-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.10.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
<plugin>
<groupId>com.github.shalousun</groupId>
<artifactId>smart-doc-maven-plugin</artifactId>
<version>2.1.9</version>
<configuration>
<!--指定生成文档的使用的配置文件,配置文件放在自己的项目中-->
<configFile>./src/main/resources/smart-doc.json</configFile>
<!--smart-doc实现自动分析依赖树加载第三方依赖的源码如果一些框架依赖库加载不到导致报错这时请使用excludes排除掉-->
<!-- <excludes>-->
<!-- &lt;!&ndash;格式为groupId:artifactId;参考如下&ndash;&gt;-->
<!-- <exclude>com.alibaba:fastjson</exclude>-->
<!-- </excludes>-->
<!-- &lt;!&ndash;自1.0.8版本开始插件提供includes支持,配置了includes后插件会按照用户配置加载而不是自动加载因此使用时需要注意&ndash;&gt;-->
<!-- &lt;!&ndash;smart-doc能自动分析依赖树加载所有依赖源码原则上会影响文档构建效率因此你可以使用includes来让插件加载你配置的组件&ndash;&gt;-->
<!-- <includes>-->
<!-- &lt;!&ndash;格式为groupId:artifactId;参考如下&ndash;&gt;-->
<!-- <include>com.alibaba:fastjson</include>-->
<!-- </includes>-->
</configuration>
<executions>
<execution>
<!--如果不需要在执行编译时启动smart-doc则将phase注释掉-->
<!-- <phase>compile</phase>-->
<goals>
<!--smart-doc提供了html、openapi、markdown等goal可按需配置-->
<goal>html</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>aliyun-central</id>
<url>https://maven.aliyun.com/repository/central</url>
</repository>
<repository>
<id>aliyun-snapshots</id>
<url>https://maven.aliyun.com/repository/snapshots</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>aliyun-central</id>
<url>https://maven.aliyun.com/repository/central</url>
</pluginRepository>
</pluginRepositories>
</project> </project>

View File

@ -0,0 +1,41 @@
package club.joylink.rtss.aop;
import club.joylink.rtss.services.cgy.CgyStatsService;
import club.joylink.rtss.simulation.cbtc.SimulationService;
import club.joylink.rtss.vo.client.cgy.CgyThirdPartyLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Aspect
@Slf4j
@Component
public class CgyViewAspect {
private CgyStatsService cgyStatsService;
private RestTemplate restTemplate;
private SimulationService simulationService;
@Autowired
public CgyViewAspect(CgyStatsService cgyStatsService, RestTemplate restTemplate,
SimulationService simulationService) {
this.cgyStatsService = cgyStatsService;
this.restTemplate = restTemplate;
this.simulationService = simulationService;
}
/**
* 成工院第三方登录接口被调用后加一个浏览量并同步给虚仿平台
*/
@AfterReturning(value = "execution(public * club.joylink.rtss.controller.LoginController.cgyThirdPartyLogin(..))")
public void addViewCount(JoinPoint joinPoint) {
Object arg = joinPoint.getArgs()[0];
CgyThirdPartyLoginInfoVO loginInfoVO = (CgyThirdPartyLoginInfoVO) arg;
cgyStatsService.updateView(loginInfoVO.getAppId());
}
}

View File

@ -0,0 +1,32 @@
package club.joylink.rtss.bo.cgy;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
/**
* 成工院虚仿平台对接统计数据
*/
@Getter
@Setter
@RequiredArgsConstructor
public class CgyStatsBO {
private final String appId;
private final String appSecret;
private final Long FunctionId;
//统计数据是否发生变化
private AtomicBoolean change;
//浏览量
private AtomicLong view;
//实训人次
private AtomicLong visitor;
//实训人数
private final Set<Long> userSet = new HashSet<>();
//实训时长/s
private AtomicLong duration;
}

View File

@ -70,6 +70,8 @@ public class WebConfig implements WebMvcConfigurer {
whiteList.add("/api/v2/paper/composition/oldData/handle"); whiteList.add("/api/v2/paper/composition/oldData/handle");
whiteList.add("/api/user/sync"); whiteList.add("/api/user/sync");
whiteList.add("/dataHandle"); whiteList.add("/dataHandle");
//modbus测试
whiteList.add("/api/test/modbus/writeCoil");
registry.addInterceptor(authenticateInterceptor).excludePathPatterns(whiteList); registry.addInterceptor(authenticateInterceptor).excludePathPatterns(whiteList);
} }

View File

@ -6,5 +6,6 @@ public interface ProjectCode {
String SR_SANDBOX = "SR_SANDBOX"; String SR_SANDBOX = "SR_SANDBOX";
String NGY_SAND_TABLE = "NGY_SAND_TABLE"; String NGY_SAND_TABLE = "NGY_SAND_TABLE";
String CDGXY = "CDGXY"; String CDGXY = "CDGXY";
String CGY = "CGY";
} }

View File

@ -7,136 +7,148 @@ import club.joylink.rtss.vo.AccountVO;
import club.joylink.rtss.vo.LoginUserInfoVO; import club.joylink.rtss.vo.LoginUserInfoVO;
import club.joylink.rtss.vo.client.LoginStatusVO; import club.joylink.rtss.vo.client.LoginStatusVO;
import club.joylink.rtss.vo.client.LoginUserVO; import club.joylink.rtss.vo.client.LoginUserVO;
import club.joylink.rtss.vo.client.cgy.CgyThirdPartyLoginInfoVO;
import club.joylink.rtss.vo.client.validGroup.LoginInfoCheck; import club.joylink.rtss.vo.client.validGroup.LoginInfoCheck;
import club.joylink.rtss.vo.client.validGroup.ThirdLoginInfoCheck; import club.joylink.rtss.vo.client.validGroup.ThirdLoginInfoCheck;
import javax.validation.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import javax.validation.constraints.NotBlank; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@RequestMapping("/api/login") @RequestMapping("/api/login")
public class LoginController { public class LoginController {
@Autowired @Autowired
private IAuthenticateService iAuthenticateService; private IAuthenticateService iAuthenticateService;
@PostMapping(path = "/third") @PostMapping("/cgy/third")
public String thirdPartyLogin(@RequestBody @Validated(ThirdLoginInfoCheck.class) LoginUserVO loginInfo) { public String cgyThirdPartyLogin(@RequestBody @Validated CgyThirdPartyLoginInfoVO loginInfo) {
return this.iAuthenticateService.thirdPartyLogin(loginInfo); return this.iAuthenticateService.cgyThirdPartyLogin(loginInfo);
} }
/** @PostMapping(path = "/third")
* 获取微信小程序登陆二维码 public String thirdPartyLogin(
*/ @RequestBody @Validated(ThirdLoginInfoCheck.class) LoginUserVO loginInfo) {
@GetMapping(path = "/wmurl") return this.iAuthenticateService.thirdPartyLogin(loginInfo);
public LoginStatusVO getWmLoginUrl(@NotBlank String clientId, @NotBlank String secret, }
String project, @RequestParam(required = false) String deviceCode) {
try {
return this.iAuthenticateService.getWmLoginUrl(clientId, secret, project, deviceCode);
} catch (BaseException e) {
throw e;
} catch (Exception e) {
throw BusinessExceptionAssertEnum.SYSTEM_EXCEPTION.exception("获取登录二维码失败");
}
}
/** /**
* 用户微信小程序扫登陆二维码 * 获取微信小程序登陆二维码
*/ */
@GetMapping(path = "/scan/wmLoginUrl") @GetMapping(path = "/wmurl")
public AccountVO scanWmLoginQrCode(String code, String state) { public LoginStatusVO getWmLoginUrl(@NotBlank String clientId, @NotBlank String secret,
return this.iAuthenticateService.scanWmLoginQrCode(code, state); String project, @RequestParam(required = false) String deviceCode) {
try {
return this.iAuthenticateService.getWmLoginUrl(clientId, secret, project, deviceCode);
} catch (BaseException e) {
throw e;
} catch (Exception e) {
throw BusinessExceptionAssertEnum.SYSTEM_EXCEPTION.exception("获取登录二维码失败");
} }
}
/** /**
* 微信小程序确认登陆接口 * 用户微信小程序扫登陆二维码
*/ */
@PostMapping(path = "/wm") @GetMapping(path = "/scan/wmLoginUrl")
public void wmConfirmLogin(String code, String state) { public AccountVO scanWmLoginQrCode(String code, String state) {
this.iAuthenticateService.wmConfirmClientLogin(code, state); return this.iAuthenticateService.scanWmLoginQrCode(code, state);
} }
@PostMapping() /**
public String loginWithPwd(@RequestBody @Validated(LoginInfoCheck.class) LoginUserVO loginUser) { * 微信小程序确认登陆接口
return iAuthenticateService.loginWithPwd(loginUser); */
} @PostMapping(path = "/wm")
public void wmConfirmLogin(String code, String state) {
this.iAuthenticateService.wmConfirmClientLogin(code, state);
}
@GetMapping("/preLogout") @PostMapping()
public void preLogout(String token) { public String loginWithPwd(@RequestBody @Validated(LoginInfoCheck.class) LoginUserVO loginUser) {
this.iAuthenticateService.preLogout(token); return iAuthenticateService.loginWithPwd(loginUser);
} }
@GetMapping(path = "/logout") @GetMapping("/preLogout")
public void logout(String token) { public void preLogout(String token) {
this.iAuthenticateService.logout(token); this.iAuthenticateService.preLogout(token);
} }
@GetMapping(path = "/checkStatus") @GetMapping(path = "/logout")
public LoginStatusVO checkStatus(@NotBlank String sessionId) { public void logout(String token) {
return iAuthenticateService.checkStatus(sessionId); this.iAuthenticateService.logout(token);
} }
/** @GetMapping(path = "/checkStatus")
* 获取用户信息 - 通过token public LoginStatusVO checkStatus(@NotBlank String sessionId) {
* return iAuthenticateService.checkStatus(sessionId);
* @param token }
* @return
*/
@GetMapping(path = "/getUserInfo")
public AccountVO getUserInfo(String token) {
LoginUserInfoVO loginUserInfoVO = this.iAuthenticateService.getLoginUserInfoByToken(token);
return loginUserInfoVO.getAccountVO();
}
/** /**
* 获取用户登录信息包含登录的项目/客户端等 * 获取用户信息 - 通过token
* *
* @param token * @param token
* @return * @return
*/ */
@GetMapping("/loginUserInfo") @GetMapping(path = "/getUserInfo")
public LoginUserInfoVO getLoginUserInfo(String token) { public AccountVO getUserInfo(String token) {
return this.iAuthenticateService.getLoginUserInfoByToken(token); LoginUserInfoVO loginUserInfoVO = this.iAuthenticateService.getLoginUserInfoByToken(token);
} return loginUserInfoVO.getAccountVO();
}
/** /**
* <玖琏科技>微信小程序code换取token * 获取用户登录信息包含登录的项目/客户端等
*/ *
@GetMapping(path = "/wm/token") * @param token
public String getTokenByWmCode(String code) { * @return
return this.iAuthenticateService.getTokenByWmCode(code); */
} @GetMapping("/loginUserInfo")
public LoginUserInfoVO getLoginUserInfo(String token) {
return this.iAuthenticateService.getLoginUserInfoByToken(token);
}
/** /**
* 到那儿了小程序code换token * <玖琏科技>微信小程序code换取token
* */
* @param code @GetMapping(path = "/wm/token")
* @return public String getTokenByWmCode(String code) {
*/ return this.iAuthenticateService.getTokenByWmCode(code);
@GetMapping(path = "/wm2/token") }
public String getTokenByWmCode2(String code) {
return this.iAuthenticateService.getTokenByWmCode2(code);
}
/** /**
* 郑州共赢小程序code换token * 到那儿了小程序code换token
* *
* @param code * @param code
* @return * @return
*/ */
@GetMapping(path = "/wm/zzww/token") @GetMapping(path = "/wm2/token")
public String getTokenByWmCode3(String code) { public String getTokenByWmCode2(String code) {
return this.iAuthenticateService.getTokenByWmCode3(code); return this.iAuthenticateService.getTokenByWmCode2(code);
} }
/** /**
* token是否过期 * 郑州共赢小程序code换token
*/ *
@GetMapping(path = "/{token}/isExpired") * @param code
public boolean isTokenExpired(@PathVariable String token) { * @return
return this.iAuthenticateService.isTokenExpired(token); */
} @GetMapping(path = "/wm/zzww/token")
public String getTokenByWmCode3(String code) {
return this.iAuthenticateService.getTokenByWmCode3(code);
}
/**
* token是否过期
*/
@GetMapping(path = "/{token}/isExpired")
public boolean isTokenExpired(@PathVariable String token) {
return this.iAuthenticateService.isTokenExpired(token);
}
} }

View File

@ -9,6 +9,7 @@ import club.joylink.rtss.vo.paper.CreatePaperCompositionRspVo;
import club.joylink.rtss.vo.paper.FindPaperCompositionByAccountReqVo; import club.joylink.rtss.vo.paper.FindPaperCompositionByAccountReqVo;
import club.joylink.rtss.vo.paper.FindPaperCompositionPageReqVo; import club.joylink.rtss.vo.paper.FindPaperCompositionPageReqVo;
import club.joylink.rtss.vo.paper.PaperCompositionWithRuleVo; import club.joylink.rtss.vo.paper.PaperCompositionWithRuleVo;
import club.joylink.rtss.vo.paper.PaperCompositionWithRuleVo.CreatorBasic;
import java.util.List; import java.util.List;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -109,6 +110,14 @@ public class PaperCompositionController {
return this.compositionService.findPaperCompositionByPage(req); return this.compositionService.findPaperCompositionByPage(req);
} }
/**
* 查询试卷的创建者的信息
*/
@PostMapping("/list/creatorInfo")
public List<CreatorBasic> queryCreatorList(@RequestBody FindPaperCompositionPageReqVo req) {
return compositionService.queryCreatorList(req);
}
/** /**
* 根据mapId查询蓝图的基本信息 * 根据mapId查询蓝图的基本信息
* *

View File

@ -47,12 +47,10 @@ import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@ -591,16 +589,7 @@ public class SimulationV1Controller {
*/ */
@GetMapping("/list") @GetMapping("/list")
public List<SimulationInfoVO> queryInfo(SimulationInfoQueryVO queryVO) { public List<SimulationInfoVO> queryInfo(SimulationInfoQueryVO queryVO) {
List<Simulation> simulationList = this.simulationManager.getSimulationList(); return simulationService.listAllSimulation(queryVO);
Stream<Simulation> stream = simulationList.stream();
if (StringUtils.hasText(queryVO.getGroup())) {
stream = stream.filter(simulation -> simulation.getId().contains(queryVO.getGroup()));
}
if (StringUtils.hasText(queryVO.getUserName())) {
stream = stream.filter(simulation -> simulation.getSimulationUsers().stream()
.anyMatch(user -> user.getName().contains(queryVO.getUserName())));
}
return stream.map(Simulation::convertToVO).collect(Collectors.toList());
} }
/** /**

View File

@ -124,8 +124,7 @@ public class TrainingV2PublishController {
*/ */
@PostMapping("/infos") @PostMapping("/infos")
public List<PublishedTraining2InfoRspVo> findTrainingListInfos( public List<PublishedTraining2InfoRspVo> findTrainingListInfos(
@RequestBody PublishedTrainingListRspVo vo @RequestBody PublishedTrainingListRspVo vo,
,
@RequestAttribute(name = AuthenticateInterceptor.LOGIN_INFO_KEY) LoginUserInfoVO loginUserInfoVO) { @RequestAttribute(name = AuthenticateInterceptor.LOGIN_INFO_KEY) LoginUserInfoVO loginUserInfoVO) {
//只查询以上架 //只查询以上架
vo.setState(BusinessConsts.STATUS_USE_INT); vo.setState(BusinessConsts.STATUS_USE_INT);

View File

@ -4,15 +4,25 @@ import club.joylink.rtss.services.ISysUserService;
import club.joylink.rtss.vo.AccountVO; import club.joylink.rtss.vo.AccountVO;
import club.joylink.rtss.vo.UserQueryVO; import club.joylink.rtss.vo.UserQueryVO;
import club.joylink.rtss.vo.client.PageVO; import club.joylink.rtss.vo.client.PageVO;
import club.joylink.rtss.vo.client.user.*; import club.joylink.rtss.vo.client.user.MobileInfoVO;
import club.joylink.rtss.vo.client.user.RetrievePwdVO;
import club.joylink.rtss.vo.client.user.UpdateEmailVO;
import club.joylink.rtss.vo.client.user.UpdateMobileVO;
import club.joylink.rtss.vo.client.user.UpdatePasswordVO;
import club.joylink.rtss.vo.user.AccountCreateVO; import club.joylink.rtss.vo.user.AccountCreateVO;
import club.joylink.rtss.vo.user.AccountRegisterVO; import club.joylink.rtss.vo.user.AccountRegisterVO;
import club.joylink.rtss.vo.user.UserRegisterCheck; import club.joylink.rtss.vo.user.UserRegisterCheck;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/** /**
* 系统账户接口 * 系统账户接口
@ -21,165 +31,186 @@ import java.util.List;
@RequestMapping("/api/userinfo") @RequestMapping("/api/userinfo")
public class SysAccountController { public class SysAccountController {
@Autowired @Autowired
private ISysUserService iSysUserService; private ISysUserService iSysUserService;
@PostMapping("/register") @PostMapping("/register")
public void register(@RequestBody @Validated(value = UserRegisterCheck.class) AccountCreateVO accountCreateVO) { public void register(
this.iSysUserService.register(accountCreateVO); @RequestBody @Validated(value = UserRegisterCheck.class) AccountCreateVO accountCreateVO) {
} this.iSysUserService.register(accountCreateVO);
}
/** /**
* 新注册接口 * 新注册接口
*/ */
@PostMapping("/register2") @PostMapping("/register2")
public void register2(@RequestBody @Validated AccountRegisterVO registerVO) { public void register2(@RequestBody @Validated AccountRegisterVO registerVO) {
this.iSysUserService.register2(registerVO); this.iSysUserService.register2(registerVO);
} }
/** /**
*根据姓名或电话号查询用户 * 根据姓名或电话号查询用户
*/ */
@GetMapping(path="/nameOrMobile") @GetMapping(path = "/nameOrMobile")
public List<AccountVO> queryUserByNameOrMobile(String query) { public List<AccountVO> queryUserByNameOrMobile(String query) {
List<AccountVO> list = this.iSysUserService.queryUserByNameOrMobile(query); List<AccountVO> list = this.iSysUserService.queryUserByNameOrMobile(query);
return list; return list;
} }
/** /**
* 手机号是否已经注册 * 手机号是否已经注册
*/ */
@GetMapping("/isExist/mobile") @GetMapping("/isExist/mobile")
public boolean isMobileExist(String mobile) { public boolean isMobileExist(String mobile) {
return iSysUserService.isSameMobileExist(mobile); return iSysUserService.isSameMobileExist(mobile);
} }
/** /**
* 邮箱是否已经注册 * 邮箱是否已经注册
*/ */
@GetMapping("/isExist/email") @GetMapping("/isExist/email")
public boolean isEmailExist(String email) { public boolean isEmailExist(String email) {
return iSysUserService.isSameEmailExist(email); return iSysUserService.isSameEmailExist(email);
} }
/** /**
*根据用户id获取用户信息 * 根据用户id获取用户信息
*/ */
@GetMapping(path = "/{id}") @GetMapping(path = "/{id}")
public AccountVO getUserBaseInfoById(@PathVariable Long id) { public AccountVO getUserBaseInfoById(@PathVariable Long id) {
return this.iSysUserService.getUserBaseInfoById(id); return this.iSysUserService.getUserBaseInfoById(id);
} }
/** /**
*修改用户信息 * 修改用户信息
*/ */
@PutMapping(path = "/{id}") @PutMapping(path = "/{id}")
public void modify(@PathVariable Long id, @RequestBody AccountVO userInfo, String vdcode) { public void modify(@PathVariable Long id, @RequestBody AccountVO userInfo, String vdcode) {
this.iSysUserService.modify(id, userInfo, vdcode); this.iSysUserService.modify(id, userInfo, vdcode);
} }
/** /**
*微信关注事件 * 微信关注事件
*/ */
@GetMapping(path = "/wxsubscribe") @GetMapping(path = "/wxsubscribe")
public void wxSubscribe(@RequestParam String wxId) { public void wxSubscribe(@RequestParam String wxId) {
iSysUserService.wxSubscribeEventHandle(wxId); iSysUserService.wxSubscribeEventHandle(wxId);
} }
/** /**
*批量修改用户的openId为unionId * 批量修改用户的openId为unionId
*/ */
@PutMapping(path = "/batchchange/unionid") @PutMapping(path = "/batchchange/unionid")
public void batchChangeOpenId2UnionId() { public void batchChangeOpenId2UnionId() {
this.iSysUserService.batchChangeOpenId2UnionId(); this.iSysUserService.batchChangeOpenId2UnionId();
} }
/** /**
*更新用户真实姓名 * 更新用户真实姓名
*/ */
@PutMapping(path = "/{id}/name") @PutMapping(path = "/{id}/name")
public void updateName(@PathVariable Long id, String name) { public void updateName(@PathVariable Long id, String name) {
this.iSysUserService.updateUserName(id, name); this.iSysUserService.updateUserName(id, name);
} }
/** /**
*更新用户昵称 * 更新用户昵称
*/ */
@PutMapping(path = "/{id}/nickname") @PutMapping(path = "/{id}/nickname")
public void updateNickname(@PathVariable Long id, String nickname) { public void updateNickname(@PathVariable Long id, String nickname) {
this.iSysUserService.updateNickname(id, nickname); this.iSysUserService.updateNickname(id, nickname);
} }
/** /**
*用户上传头像 * 用户上传头像
*/ */
@PostMapping(path = "/{id}/avatar") @PostMapping(path = "/{id}/avatar")
public void uploadAvatar(@PathVariable Long id, @RequestBody AccountVO accountVO) { public void uploadAvatar(@PathVariable Long id, @RequestBody AccountVO accountVO) {
this.iSysUserService.updateAvatar(id, accountVO.getAvatarPath()); this.iSysUserService.updateAvatar(id, accountVO.getAvatarPath());
} }
/** /**
*发送手机验证码 * 发送手机验证码
*/ */
@PostMapping(path = "/mobile/code") @PostMapping(path = "/mobile/code")
public String sendMobileValidCode(@RequestBody MobileInfoVO mobileInfoVO) { public String sendMobileValidCode(@RequestBody MobileInfoVO mobileInfoVO) {
return this.iSysUserService.sendMobileValidCode(mobileInfoVO); return this.iSysUserService.sendMobileValidCode(mobileInfoVO);
} }
/** /**
*发送邮箱验证码 * 发送邮箱验证码
*/ */
@PostMapping(path = "/email/code") @PostMapping(path = "/email/code")
public String sendEmailValidCode(String email) { public String sendEmailValidCode(String email) {
return this.iSysUserService.sendEmailValidCode(email); return this.iSysUserService.sendEmailValidCode(email);
} }
/** /**
*更新用户手机号 * 更新用户手机号
*/ */
@PutMapping(path = "/{id}/mobile") @PutMapping(path = "/{id}/mobile")
public void updateMobile(@PathVariable Long id, @RequestBody @Validated UpdateMobileVO updateMobileVO) { public void updateMobile(@PathVariable Long id,
this.iSysUserService.updateMobile(id, updateMobileVO); @RequestBody @Validated UpdateMobileVO updateMobileVO) {
} this.iSysUserService.updateMobile(id, updateMobileVO);
}
/** /**
*更新用户邮箱 * 更新用户邮箱
*/ */
@PutMapping(path = "/{id}/email") @PutMapping(path = "/{id}/email")
public void updateEmail(@PathVariable Long id, @RequestBody @Validated UpdateEmailVO updateEmailVO) { public void updateEmail(@PathVariable Long id,
this.iSysUserService.updateEmail(id, updateEmailVO); @RequestBody @Validated UpdateEmailVO updateEmailVO) {
} this.iSysUserService.updateEmail(id, updateEmailVO);
}
/** /**
*更新用户登陆密码 * 更新用户登陆密码
*/ */
@PutMapping(path = "/{id}/password") @PutMapping(path = "/{id}/password")
public void updatePassword(@PathVariable Long id, @RequestBody @Validated UpdatePasswordVO updatePasswordVO) { public void updatePassword(@PathVariable Long id,
this.iSysUserService.updatePassword(id, updatePasswordVO); @RequestBody @Validated UpdatePasswordVO updatePasswordVO) {
} this.iSysUserService.updatePassword(id, updatePasswordVO);
}
/** /**
* 按条件分页查询指定来源的账号 * 按条件分页查询指定来源的账号
*/ */
@GetMapping("/page/criteria/{source}") @GetMapping("/page/criteria/{source}")
public PageVO<AccountVO> queryPagedAccountOfTheSource(UserQueryVO queryVO, @PathVariable String source) { public PageVO<AccountVO> queryPagedAccountOfTheSource(UserQueryVO queryVO,
queryVO.setSource(source); @PathVariable String source) {
return this.iSysUserService.queryPagedUser(queryVO); queryVO.setSource(source);
} return this.iSysUserService.queryPagedUser(queryVO);
}
/** /**
* 超管重置用户密码 * 超管重置用户密码
*/ */
@PutMapping("/{id}/reset/pwd") @PutMapping("/{id}/reset/pwd")
public void resetPwd(@PathVariable long id) { public void resetPwd(@PathVariable long id) {
iSysUserService.resetPwd(id); iSysUserService.resetPwd(id);
} }
/** /**
* 找回密码 * 找回密码
*/ */
@PutMapping("/retrieve/pwd") @PutMapping("/retrieve/pwd")
public void retrievePwd(@RequestBody @Validated RetrievePwdVO vo) { public void retrievePwd(@RequestBody @Validated RetrievePwdVO vo) {
iSysUserService.retrievePwd(vo); iSysUserService.retrievePwd(vo);
} }
/**
* 根据用户id列表获取用户信息
*/
@PostMapping("/list/ids")
public List<AccountVO> listByIds(@RequestBody List<Long> ids) {
return iSysUserService.listByIds(ids);
}
/**
* 查询所有用户
*/
@GetMapping("/list/all")
public List<AccountVO> listAll() {
return iSysUserService.listAll();
}
} }

View File

@ -4,11 +4,14 @@ import club.joylink.rtss.services.voice.IVoiceTrainingService;
import club.joylink.rtss.services.voice.baidu.TokenHolder; import club.joylink.rtss.services.voice.baidu.TokenHolder;
import club.joylink.rtss.vo.client.PageQueryVO; import club.joylink.rtss.vo.client.PageQueryVO;
import club.joylink.rtss.vo.client.PageVO; import club.joylink.rtss.vo.client.PageVO;
import club.joylink.rtss.vo.client.voice.VoiceRecognitionResult;
import club.joylink.rtss.vo.client.competition.VoiceErrorVO; import club.joylink.rtss.vo.client.competition.VoiceErrorVO;
import club.joylink.rtss.vo.client.voice.VoiceRecognitionResult;
import club.joylink.rtss.vo.voice.VoiceVerifyResultVO;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
@ -20,34 +23,46 @@ import org.springframework.web.multipart.MultipartFile;
@RequestMapping("/api/voice") @RequestMapping("/api/voice")
public class VoiceController { public class VoiceController {
@Autowired @Autowired
private IVoiceTrainingService iVoiceTrainingService; private IVoiceTrainingService iVoiceTrainingService;
/** /**
* 语音识别 * 语音识别
* @param file *
* @return * @param file
*/ * @return
@PostMapping("recognition") */
public VoiceRecognitionResult voiceRecognition(MultipartFile file) { @PostMapping("recognition")
return iVoiceTrainingService.voiceRecognition(file); public VoiceRecognitionResult voiceRecognition(MultipartFile file) {
} return iVoiceTrainingService.voiceRecognition(file);
}
/** /**
* 查询语音识别错误集 * 查询语音识别错误集
* @param queryVO *
* @return * @param queryVO
*/ * @return
@GetMapping("/errorSet/paged") */
public PageVO<VoiceErrorVO> pagedQueryErrorSet(PageQueryVO queryVO) { @GetMapping("/errorSet/paged")
return iVoiceTrainingService.pagedQueryErrorSet(queryVO); public PageVO<VoiceErrorVO> pagedQueryErrorSet(PageQueryVO queryVO) {
} return iVoiceTrainingService.pagedQueryErrorSet(queryVO);
}
/** /**
* 获取百度语音识别token * 获取百度语音识别token
*/ */
@GetMapping("/token/baidu") @GetMapping("/token/baidu")
public String getBaiduToken() { public String getBaiduToken() {
return TokenHolder.getInstance().getToken(); return TokenHolder.getInstance().getToken();
} }
/**
* 校验语音识别结果
*/
@PostMapping("/verify")
public VoiceVerifyResultVO verifyVoice(HttpServletRequest request, @RequestBody byte[] fileData,
String text) {
String contentType = request.getHeader("Content-Type");
return iVoiceTrainingService.verifyVoice(contentType, fileData, text);
}
} }

View File

@ -2,51 +2,55 @@ package club.joylink.rtss.controller.voice;
import club.joylink.rtss.controller.advice.AuthenticateInterceptor; import club.joylink.rtss.controller.advice.AuthenticateInterceptor;
import club.joylink.rtss.services.voice.IVoiceDataConfigService; import club.joylink.rtss.services.voice.IVoiceDataConfigService;
import club.joylink.rtss.services.voice.IVoiceTrainingService;
import club.joylink.rtss.services.voice.baidu.TokenHolder;
import club.joylink.rtss.vo.LoginUserInfoVO; import club.joylink.rtss.vo.LoginUserInfoVO;
import club.joylink.rtss.vo.client.PageQueryVO;
import club.joylink.rtss.vo.client.PageVO; import club.joylink.rtss.vo.client.PageVO;
import club.joylink.rtss.vo.client.competition.VoiceErrorVO;
import club.joylink.rtss.vo.client.voice.VoiceRecognitionResult;
import club.joylink.rtss.vo.voice.VoiceDiscriminateConfigVO; import club.joylink.rtss.vo.voice.VoiceDiscriminateConfigVO;
import club.joylink.rtss.vo.voice.VoiceQueryVO; import club.joylink.rtss.vo.voice.VoiceQueryVO;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/** /**
* 语音AI接口 * 语音管理接口
*/ */
@RestController @RestController
@RequestMapping("/api/voice/manage") @RequestMapping("/api/voice/manage")
public class VoiceManageController { public class VoiceManageController {
@Autowired @Autowired
private IVoiceDataConfigService configService; private IVoiceDataConfigService configService;
@PostMapping("saveOrUpdate") @PostMapping("saveOrUpdate")
public void saveOrUpdate(@RequestBody VoiceDiscriminateConfigVO configVO, @RequestAttribute(name= AuthenticateInterceptor.LOGIN_INFO_KEY) LoginUserInfoVO userInfoVO) { public void saveOrUpdate(@RequestBody VoiceDiscriminateConfigVO configVO,
this.configService.saveOrUpdate(configVO,userInfoVO); @RequestAttribute(name = AuthenticateInterceptor.LOGIN_INFO_KEY) LoginUserInfoVO userInfoVO) {
} this.configService.saveOrUpdate(configVO, userInfoVO);
}
@GetMapping("find/{id}") @GetMapping("find/{id}")
public VoiceDiscriminateConfigVO find(@PathVariable(value = "id") Long id) { public VoiceDiscriminateConfigVO find(@PathVariable(value = "id") Long id) {
return this.configService.byId(id); return this.configService.byId(id);
} }
@GetMapping("query") @GetMapping("query")
public PageVO<VoiceDiscriminateConfigVO> query(@ModelAttribute VoiceQueryVO queryVO){ public PageVO<VoiceDiscriminateConfigVO> query(@ModelAttribute VoiceQueryVO queryVO) {
return this.configService.query(queryVO); return this.configService.query(queryVO);
} }
/** /**
* 获取百度语音识别token * 获取百度语音识别token
*/ */
@GetMapping("{id}/{status}") @GetMapping("{id}/{status}")
public void changeStatus(@PathVariable(value = "id") Long id,@PathVariable(value = "status")Integer status,@RequestAttribute(name= AuthenticateInterceptor.LOGIN_INFO_KEY) LoginUserInfoVO userInfoVO) { public void changeStatus(@PathVariable(value = "id") Long id,
this.configService.changeStatus(id,status,userInfoVO); @PathVariable(value = "status") Integer status,
} @RequestAttribute(name = AuthenticateInterceptor.LOGIN_INFO_KEY) LoginUserInfoVO userInfoVO) {
this.configService.changeStatus(id, status, userInfoVO);
}
} }

View File

@ -0,0 +1,12 @@
package club.joylink.rtss.dao;
import club.joylink.rtss.entity.CgyView;
import club.joylink.rtss.entity.CgyViewExample;
import org.springframework.stereotype.Repository;
/**
* CgyViewDAO继承基类
*/
@Repository
public interface CgyViewDAO extends MyBatisBaseDao<CgyView, String, CgyViewExample> {
}

View File

@ -1,12 +0,0 @@
//package club.joylink.rtss.dao;
//
//import club.joylink.rtss.entity.Company;
//import club.joylink.rtss.entity.CompanyExample;
//import org.springframework.stereotype.Repository;
//
///**
// * CompanyDAO继承基类
// */
////@Repository
////public interface CompanyDAO extends MyBatisBaseDao<Company, Integer, CompanyExample> {
////}

View File

@ -0,0 +1,107 @@
package club.joylink.rtss.entity;
import java.io.Serializable;
/**
* cgy_view
* @author
*/
public class CgyView implements Serializable {
/**
* 接入虚仿平台后获取
*/
private String appId;
/**
* 接入虚仿平台后获取
*/
private String appSecret;
/**
* 地图功能id
*/
private Long functionId;
/**
* 浏览量
*/
private Long viewCount;
private static final long serialVersionUID = 1L;
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getAppSecret() {
return appSecret;
}
public void setAppSecret(String appSecret) {
this.appSecret = appSecret;
}
public Long getFunctionId() {
return functionId;
}
public void setFunctionId(Long functionId) {
this.functionId = functionId;
}
public Long getViewCount() {
return viewCount;
}
public void setViewCount(Long viewCount) {
this.viewCount = viewCount;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
CgyView other = (CgyView) that;
return (this.getAppId() == null ? other.getAppId() == null : this.getAppId().equals(other.getAppId()))
&& (this.getAppSecret() == null ? other.getAppSecret() == null : this.getAppSecret().equals(other.getAppSecret()))
&& (this.getFunctionId() == null ? other.getFunctionId() == null : this.getFunctionId().equals(other.getFunctionId()))
&& (this.getViewCount() == null ? other.getViewCount() == null : this.getViewCount().equals(other.getViewCount()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getAppId() == null) ? 0 : getAppId().hashCode());
result = prime * result + ((getAppSecret() == null) ? 0 : getAppSecret().hashCode());
result = prime * result + ((getFunctionId() == null) ? 0 : getFunctionId().hashCode());
result = prime * result + ((getViewCount() == null) ? 0 : getViewCount().hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", appId=").append(appId);
sb.append(", appSecret=").append(appSecret);
sb.append(", functionId=").append(functionId);
sb.append(", viewCount=").append(viewCount);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}

View File

@ -0,0 +1,482 @@
package club.joylink.rtss.entity;
import java.util.ArrayList;
import java.util.List;
public class CgyViewExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
private Integer limit;
private Long offset;
public CgyViewExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
public Integer getLimit() {
return limit;
}
public void setOffset(Long offset) {
this.offset = offset;
}
public Long getOffset() {
return offset;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andAppIdIsNull() {
addCriterion("app_id is null");
return (Criteria) this;
}
public Criteria andAppIdIsNotNull() {
addCriterion("app_id is not null");
return (Criteria) this;
}
public Criteria andAppIdEqualTo(String value) {
addCriterion("app_id =", value, "appId");
return (Criteria) this;
}
public Criteria andAppIdNotEqualTo(String value) {
addCriterion("app_id <>", value, "appId");
return (Criteria) this;
}
public Criteria andAppIdGreaterThan(String value) {
addCriterion("app_id >", value, "appId");
return (Criteria) this;
}
public Criteria andAppIdGreaterThanOrEqualTo(String value) {
addCriterion("app_id >=", value, "appId");
return (Criteria) this;
}
public Criteria andAppIdLessThan(String value) {
addCriterion("app_id <", value, "appId");
return (Criteria) this;
}
public Criteria andAppIdLessThanOrEqualTo(String value) {
addCriterion("app_id <=", value, "appId");
return (Criteria) this;
}
public Criteria andAppIdLike(String value) {
addCriterion("app_id like", value, "appId");
return (Criteria) this;
}
public Criteria andAppIdNotLike(String value) {
addCriterion("app_id not like", value, "appId");
return (Criteria) this;
}
public Criteria andAppIdIn(List<String> values) {
addCriterion("app_id in", values, "appId");
return (Criteria) this;
}
public Criteria andAppIdNotIn(List<String> values) {
addCriterion("app_id not in", values, "appId");
return (Criteria) this;
}
public Criteria andAppIdBetween(String value1, String value2) {
addCriterion("app_id between", value1, value2, "appId");
return (Criteria) this;
}
public Criteria andAppIdNotBetween(String value1, String value2) {
addCriterion("app_id not between", value1, value2, "appId");
return (Criteria) this;
}
public Criteria andAppSecretIsNull() {
addCriterion("app_secret is null");
return (Criteria) this;
}
public Criteria andAppSecretIsNotNull() {
addCriterion("app_secret is not null");
return (Criteria) this;
}
public Criteria andAppSecretEqualTo(String value) {
addCriterion("app_secret =", value, "appSecret");
return (Criteria) this;
}
public Criteria andAppSecretNotEqualTo(String value) {
addCriterion("app_secret <>", value, "appSecret");
return (Criteria) this;
}
public Criteria andAppSecretGreaterThan(String value) {
addCriterion("app_secret >", value, "appSecret");
return (Criteria) this;
}
public Criteria andAppSecretGreaterThanOrEqualTo(String value) {
addCriterion("app_secret >=", value, "appSecret");
return (Criteria) this;
}
public Criteria andAppSecretLessThan(String value) {
addCriterion("app_secret <", value, "appSecret");
return (Criteria) this;
}
public Criteria andAppSecretLessThanOrEqualTo(String value) {
addCriterion("app_secret <=", value, "appSecret");
return (Criteria) this;
}
public Criteria andAppSecretLike(String value) {
addCriterion("app_secret like", value, "appSecret");
return (Criteria) this;
}
public Criteria andAppSecretNotLike(String value) {
addCriterion("app_secret not like", value, "appSecret");
return (Criteria) this;
}
public Criteria andAppSecretIn(List<String> values) {
addCriterion("app_secret in", values, "appSecret");
return (Criteria) this;
}
public Criteria andAppSecretNotIn(List<String> values) {
addCriterion("app_secret not in", values, "appSecret");
return (Criteria) this;
}
public Criteria andAppSecretBetween(String value1, String value2) {
addCriterion("app_secret between", value1, value2, "appSecret");
return (Criteria) this;
}
public Criteria andAppSecretNotBetween(String value1, String value2) {
addCriterion("app_secret not between", value1, value2, "appSecret");
return (Criteria) this;
}
public Criteria andFunctionIdIsNull() {
addCriterion("function_id is null");
return (Criteria) this;
}
public Criteria andFunctionIdIsNotNull() {
addCriterion("function_id is not null");
return (Criteria) this;
}
public Criteria andFunctionIdEqualTo(Long value) {
addCriterion("function_id =", value, "functionId");
return (Criteria) this;
}
public Criteria andFunctionIdNotEqualTo(Long value) {
addCriterion("function_id <>", value, "functionId");
return (Criteria) this;
}
public Criteria andFunctionIdGreaterThan(Long value) {
addCriterion("function_id >", value, "functionId");
return (Criteria) this;
}
public Criteria andFunctionIdGreaterThanOrEqualTo(Long value) {
addCriterion("function_id >=", value, "functionId");
return (Criteria) this;
}
public Criteria andFunctionIdLessThan(Long value) {
addCriterion("function_id <", value, "functionId");
return (Criteria) this;
}
public Criteria andFunctionIdLessThanOrEqualTo(Long value) {
addCriterion("function_id <=", value, "functionId");
return (Criteria) this;
}
public Criteria andFunctionIdIn(List<Long> values) {
addCriterion("function_id in", values, "functionId");
return (Criteria) this;
}
public Criteria andFunctionIdNotIn(List<Long> values) {
addCriterion("function_id not in", values, "functionId");
return (Criteria) this;
}
public Criteria andFunctionIdBetween(Long value1, Long value2) {
addCriterion("function_id between", value1, value2, "functionId");
return (Criteria) this;
}
public Criteria andFunctionIdNotBetween(Long value1, Long value2) {
addCriterion("function_id not between", value1, value2, "functionId");
return (Criteria) this;
}
public Criteria andViewCountIsNull() {
addCriterion("view_count is null");
return (Criteria) this;
}
public Criteria andViewCountIsNotNull() {
addCriterion("view_count is not null");
return (Criteria) this;
}
public Criteria andViewCountEqualTo(Long value) {
addCriterion("view_count =", value, "viewCount");
return (Criteria) this;
}
public Criteria andViewCountNotEqualTo(Long value) {
addCriterion("view_count <>", value, "viewCount");
return (Criteria) this;
}
public Criteria andViewCountGreaterThan(Long value) {
addCriterion("view_count >", value, "viewCount");
return (Criteria) this;
}
public Criteria andViewCountGreaterThanOrEqualTo(Long value) {
addCriterion("view_count >=", value, "viewCount");
return (Criteria) this;
}
public Criteria andViewCountLessThan(Long value) {
addCriterion("view_count <", value, "viewCount");
return (Criteria) this;
}
public Criteria andViewCountLessThanOrEqualTo(Long value) {
addCriterion("view_count <=", value, "viewCount");
return (Criteria) this;
}
public Criteria andViewCountIn(List<Long> values) {
addCriterion("view_count in", values, "viewCount");
return (Criteria) this;
}
public Criteria andViewCountNotIn(List<Long> values) {
addCriterion("view_count not in", values, "viewCount");
return (Criteria) this;
}
public Criteria andViewCountBetween(Long value1, Long value2) {
addCriterion("view_count between", value1, value2, "viewCount");
return (Criteria) this;
}
public Criteria andViewCountNotBetween(Long value1, Long value2) {
addCriterion("view_count not between", value1, value2, "viewCount");
return (Criteria) this;
}
}
/**
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}

View File

@ -6,14 +6,19 @@ import club.joylink.rtss.vo.LoginUserInfoVO;
import club.joylink.rtss.vo.UserQueryVO; import club.joylink.rtss.vo.UserQueryVO;
import club.joylink.rtss.vo.client.PageVO; import club.joylink.rtss.vo.client.PageVO;
import club.joylink.rtss.vo.client.org.OrgVO; import club.joylink.rtss.vo.client.org.OrgVO;
import club.joylink.rtss.vo.client.user.*; import club.joylink.rtss.vo.client.user.MobileInfoVO;
import club.joylink.rtss.vo.client.user.RetrievePwdVO;
import club.joylink.rtss.vo.client.user.UpdateEmailVO;
import club.joylink.rtss.vo.client.user.UpdateMobileVO;
import club.joylink.rtss.vo.client.user.UpdatePasswordVO;
import club.joylink.rtss.vo.client.user.WeChatBindStatusVO;
import club.joylink.rtss.vo.user.AccountCreateVO; import club.joylink.rtss.vo.user.AccountCreateVO;
import club.joylink.rtss.vo.user.AccountRegisterVO; import club.joylink.rtss.vo.user.AccountRegisterVO;
import club.joylink.rtss.vo.wx.WmUserSession; import club.joylink.rtss.vo.wx.WmUserSession;
import java.util.Map;
import lombok.NonNull;
import java.util.List; import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotEmpty;
import lombok.NonNull;
public interface ISysUserService { public interface ISysUserService {
@ -337,7 +342,7 @@ public interface ISysUserService {
*/ */
List<AccountVO> queryAdminsAndSuperAdmins(); List<AccountVO> queryAdminsAndSuperAdmins();
AccountVO queryOrCreateThirdAccount(String parentAccount, String account); AccountVO queryOrCreateThirdAccount(String parentAccount, String account, @NotEmpty String name);
AccountVO getThirdAccount(String account); AccountVO getThirdAccount(String account);
@ -358,4 +363,8 @@ public interface ISysUserService {
boolean isSameMobileExist(String mobile); boolean isSameMobileExist(String mobile);
boolean isSameEmailExist(String email); boolean isSameEmailExist(String email);
List<AccountVO> listByIds(List<Long> ids);
List<AccountVO> listAll();
} }

View File

@ -6,14 +6,25 @@ import club.joylink.rtss.constants.SystemEnv;
import club.joylink.rtss.dao.LearnCommentDAO; import club.joylink.rtss.dao.LearnCommentDAO;
import club.joylink.rtss.dao.LearnMessageDAO; import club.joylink.rtss.dao.LearnMessageDAO;
import club.joylink.rtss.dao.LearnPostDAO; import club.joylink.rtss.dao.LearnPostDAO;
import club.joylink.rtss.entity.*; import club.joylink.rtss.entity.LearnComment;
import club.joylink.rtss.entity.LearnCommentExample;
import club.joylink.rtss.entity.LearnMessage;
import club.joylink.rtss.entity.LearnMessageExample;
import club.joylink.rtss.entity.LearnPost;
import club.joylink.rtss.entity.LearnPostExample;
import club.joylink.rtss.exception.BusinessExceptionAssertEnum; import club.joylink.rtss.exception.BusinessExceptionAssertEnum;
import club.joylink.rtss.simulation.cbtc.exception.SimulationException; import club.joylink.rtss.simulation.cbtc.exception.SimulationException;
import club.joylink.rtss.simulation.cbtc.exception.SimulationExceptionType; import club.joylink.rtss.simulation.cbtc.exception.SimulationExceptionType;
import club.joylink.rtss.vo.AccountVO; import club.joylink.rtss.vo.AccountVO;
import club.joylink.rtss.vo.client.PageQueryVO; import club.joylink.rtss.vo.client.PageQueryVO;
import club.joylink.rtss.vo.client.PageVO; import club.joylink.rtss.vo.client.PageVO;
import club.joylink.rtss.vo.client.learn.*; import club.joylink.rtss.vo.client.learn.LearnCommentUpdateVO;
import club.joylink.rtss.vo.client.learn.LearnCommentVO;
import club.joylink.rtss.vo.client.learn.LearnCreateVO;
import club.joylink.rtss.vo.client.learn.LearnMessageUpdateVO;
import club.joylink.rtss.vo.client.learn.LearnPostCreateVO;
import club.joylink.rtss.vo.client.learn.LearnPostUpdateVO;
import club.joylink.rtss.vo.client.learn.LearnPostVO;
import club.joylink.rtss.vo.client.post.LearnMessageCreateVO; import club.joylink.rtss.vo.client.post.LearnMessageCreateVO;
import club.joylink.rtss.vo.client.post.LearnMessagePagedQueryVO; import club.joylink.rtss.vo.client.post.LearnMessagePagedQueryVO;
import club.joylink.rtss.vo.client.post.LearnMessageVO; import club.joylink.rtss.vo.client.post.LearnMessageVO;
@ -22,362 +33,374 @@ import club.joylink.rtss.wechat.MiniProgramService;
import club.joylink.rtss.wechat.vo.WxError; import club.joylink.rtss.wechat.vo.WxError;
import com.github.pagehelper.Page; import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
@Slf4j @Slf4j
@Service @Service
public class LearnService implements ILearnService { public class LearnService implements ILearnService {
@Autowired @Autowired
private LearnPostDAO learnPostDAO; private LearnPostDAO learnPostDAO;
@Autowired @Autowired
private LearnCommentDAO learnCommentDAO; private LearnCommentDAO learnCommentDAO;
@Autowired @Autowired
private ISysUserService iSysUserService; private ISysUserService iSysUserService;
@Autowired @Autowired
private RestTemplate restTemplate; private WeChatConfig weChatConfig;
@Autowired @Autowired
private WeChatConfig weChatConfig; private MiniProgramService miniProgramService;
@Autowired @Autowired
private MiniProgramService miniProgramService; private LearnMessageDAO learnMessageDAO;
@Autowired @Autowired
private LearnMessageDAO learnMessageDAO; private OtherConfig otherConfig;
@Autowired @Override
private OtherConfig otherConfig; public PageVO<LearnPostVO> queryPagedPost(LearnPostPagedQueryVO queryVO) {
PageHelper.startPage(queryVO.getPageNum(), queryVO.getPageSize());
@Override LearnPostExample example = new LearnPostExample();
public PageVO<LearnPostVO> queryPagedPost(LearnPostPagedQueryVO queryVO) { if (queryVO.getProject() != null) {
PageHelper.startPage(queryVO.getPageNum(), queryVO.getPageSize()); example.createCriteria().andProjectEqualTo(queryVO.getProject());
LearnPostExample example = new LearnPostExample();
if (queryVO.getProject() != null) {
example.createCriteria().andProjectEqualTo(queryVO.getProject());
}
Page<LearnPost> page = (Page<LearnPost>) learnPostDAO.selectByExample(example);
List<LearnPostVO> vos = page.getResult().stream().map(LearnPostVO::new).collect(Collectors.toList());
return PageVO.convert(page, vos);
} }
Page<LearnPost> page = (Page<LearnPost>) learnPostDAO.selectByExample(example);
List<LearnPostVO> vos = page.getResult().stream().map(LearnPostVO::new)
.collect(Collectors.toList());
return PageVO.convert(page, vos);
}
@Override @Override
public Long createPost(LearnPostCreateVO createVO, AccountVO user) { public Long createPost(LearnPostCreateVO createVO, AccountVO user) {
//校验 //校验
String title = createVO.getTitle(); String title = createVO.getTitle();
String project = createVO.getProject(); String project = createVO.getProject();
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertHasText(title, "名称不能为空"); BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertHasText(title, "名称不能为空");
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotNull(project, "所属项目不能为空"); BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotNull(project, "所属项目不能为空");
confirmPostIsNotExist(project); confirmPostIsNotExist(project);
//添加 //添加
LearnPost post = new LearnPost(); LearnPost post = new LearnPost();
post.setProject(project); post.setProject(project);
post.setTitle(title); post.setTitle(title);
post.setCreatorId(user.getId()); post.setCreatorId(user.getId());
post.setCreateTime(LocalDateTime.now()); post.setCreateTime(LocalDateTime.now());
post.setTopping(false); post.setTopping(false);
post.setLike(0); post.setLike(0);
post.setUnlike(0); post.setUnlike(0);
learnPostDAO.insert(post); learnPostDAO.insert(post);
return post.getId(); return post.getId();
} }
@Override @Override
@Transactional @Transactional
public void likePost(Long postId, AccountVO accountVO) { public void likePost(Long postId, AccountVO accountVO) {
LearnPost post = getPostEntity(postId); LearnPost post = getPostEntity(postId);
post.setLike(post.getLike() + 1); post.setLike(post.getLike() + 1);
learnPostDAO.updateByPrimaryKey(post); learnPostDAO.updateByPrimaryKey(post);
} }
@Override @Override
@Transactional @Transactional
public void unlikePost(Long postId, AccountVO accountVO) { public void unlikePost(Long postId, AccountVO accountVO) {
LearnPost post = getPostEntity(postId); LearnPost post = getPostEntity(postId);
post.setUnlike(post.getUnlike() + 1); post.setUnlike(post.getUnlike() + 1);
learnPostDAO.updateByPrimaryKey(post); learnPostDAO.updateByPrimaryKey(post);
} }
@Override @Override
public LearnPostVO getPostInfo(Long postId) { public LearnPostVO getPostInfo(Long postId) {
LearnPost post = getPostEntity(postId); LearnPost post = getPostEntity(postId);
LearnPostVO postVO = new LearnPostVO(post); LearnPostVO postVO = new LearnPostVO(post);
// 用户昵称 // 用户昵称
AccountVO user = iSysUserService.findUserById(post.getCreatorId()); AccountVO user = iSysUserService.findUserById(post.getCreatorId());
postVO.setUserNickname(user.getNickname()); postVO.setUserNickname(user.getNickname());
postVO.setAvatarPath(user.getAvatarPath()); postVO.setAvatarPath(user.getAvatarPath());
return postVO; return postVO;
} }
@Override @Override
public PageVO<LearnCommentVO> pagedQueryComment(Long messageId, PageQueryVO queryVO) { public PageVO<LearnCommentVO> pagedQueryComment(Long messageId, PageQueryVO queryVO) {
checkMessageExist(messageId); checkMessageExist(messageId);
List<LearnCommentVO> commentVOList = new ArrayList<>(); List<LearnCommentVO> commentVOList = new ArrayList<>();
PageHelper.startPage(queryVO.getPageNum(), queryVO.getPageSize()); PageHelper.startPage(queryVO.getPageNum(), queryVO.getPageSize());
LearnCommentExample commentExample = new LearnCommentExample(); LearnCommentExample commentExample = new LearnCommentExample();
commentExample.setOrderByClause("id"); commentExample.setOrderByClause("id");
commentExample.createCriteria().andMessageIdEqualTo(messageId); commentExample.createCriteria().andMessageIdEqualTo(messageId);
Page<LearnComment> page = (Page<LearnComment>) learnCommentDAO.selectByExample(commentExample); Page<LearnComment> page = (Page<LearnComment>) learnCommentDAO.selectByExample(commentExample);
page.getResult().forEach(comment -> commentVOList.add(convertComment(comment))); page.getResult().forEach(comment -> commentVOList.add(convertComment(comment)));
return PageVO.convert(page, commentVOList); return PageVO.convert(page, commentVOList);
} }
@Override @Override
public List<LearnCommentVO> queryCommentList(Long messageId) { public List<LearnCommentVO> queryCommentList(Long messageId) {
LearnCommentExample commentExample = new LearnCommentExample(); LearnCommentExample commentExample = new LearnCommentExample();
commentExample.createCriteria().andMessageIdEqualTo(messageId); commentExample.createCriteria().andMessageIdEqualTo(messageId);
List<LearnComment> comments = learnCommentDAO.selectByExample(commentExample); List<LearnComment> comments = learnCommentDAO.selectByExample(commentExample);
List<LearnCommentVO> commentVOList = new ArrayList<>(); List<LearnCommentVO> commentVOList = new ArrayList<>();
comments.forEach(comment -> commentVOList.add(convertComment(comment))); comments.forEach(comment -> commentVOList.add(convertComment(comment)));
return commentVOList; return commentVOList;
} }
/** /**
* 回复数据完善 * 回复数据完善
* *
* @param comment * @param comment
* @return * @return
*/ */
private LearnCommentVO convertComment(LearnComment comment) { private LearnCommentVO convertComment(LearnComment comment) {
LearnCommentVO commentVO = new LearnCommentVO(comment); LearnCommentVO commentVO = new LearnCommentVO(comment);
// 用户昵称 // 用户昵称
if (comment.getCreatorId() != null) { if (comment.getCreatorId() != null) {
String nickname = iSysUserService.findUserById(comment.getCreatorId()).getNickname(); String nickname = iSysUserService.findUserById(comment.getCreatorId()).getNickname();
commentVO.setUserNickname(nickname); commentVO.setUserNickname(nickname);
}
// 回复的用户的昵称
if (comment.getParentId() != null) {
commentVO.setReplyUserNickName(iSysUserService.findUserById(comment.getParentId()).getNickname());
}
// 回复数
LearnCommentExample learnCommentExample = new LearnCommentExample();
learnCommentExample.createCriteria().andMessageIdEqualTo(comment.getMessageId()).andRootIdEqualTo(comment.getId());
commentVO.setCommentCount(learnCommentDAO.countByExample(learnCommentExample));
return commentVO;
} }
// 回复的用户的昵称
if (comment.getParentId() != null) {
commentVO.setReplyUserNickName(
iSysUserService.findUserById(comment.getParentId()).getNickname());
}
// 回复数
LearnCommentExample learnCommentExample = new LearnCommentExample();
learnCommentExample.createCriteria().andMessageIdEqualTo(comment.getMessageId())
.andRootIdEqualTo(comment.getId());
commentVO.setCommentCount(learnCommentDAO.countByExample(learnCommentExample));
return commentVO;
}
@Override @Override
public void addComment(Long messageId, LearnCreateVO commentCreateVO, AccountVO accountVO) { public void addComment(Long messageId, LearnCreateVO commentCreateVO, AccountVO accountVO) {
checkMessageExist(messageId); checkMessageExist(messageId);
if (SystemEnv.isPrdEnv(otherConfig.getEnv())) { if (SystemEnv.isPrdEnv(otherConfig.getEnv())) {
this.checkContent(commentCreateVO.getContent()); this.checkContent(commentCreateVO.getContent());
}
LearnComment comment = new LearnComment();
comment.setContent(commentCreateVO.getContent());
comment.setMessageId(messageId);
comment.setCreatorId(accountVO.getId());
comment.setCreateTime(LocalDateTime.now());
learnCommentDAO.insertSelective(comment);
} }
LearnComment comment = new LearnComment();
comment.setContent(commentCreateVO.getContent());
comment.setMessageId(messageId);
comment.setCreatorId(accountVO.getId());
comment.setCreateTime(LocalDateTime.now());
learnCommentDAO.insertSelective(comment);
}
@Override @Override
public void addComment(Long messageId, Long commentId, LearnCreateVO postCreateVO, AccountVO accountVO) { public void addComment(Long messageId, Long commentId, LearnCreateVO postCreateVO,
checkMessageExist(messageId); AccountVO accountVO) {
if (SystemEnv.isPrdEnv(otherConfig.getEnv())) { checkMessageExist(messageId);
this.checkContent(postCreateVO.getContent()); if (SystemEnv.isPrdEnv(otherConfig.getEnv())) {
} this.checkContent(postCreateVO.getContent());
LearnComment comment = new LearnComment();
comment.setContent(postCreateVO.getContent());
comment.setMessageId(messageId);
LearnComment parentComment = learnCommentDAO.selectByPrimaryKey(commentId);
if (Objects.isNull(parentComment.getRootId())) { // 对评论的回复
comment.setRootId(commentId);
} else { // 对回复的回复
comment.setRootId(parentComment.getRootId());
}
comment.setParentId(parentComment.getCreatorId());
comment.setCreatorId(accountVO.getId());
comment.setCreateTime(LocalDateTime.now());
learnCommentDAO.insertSelective(comment);
} }
LearnComment comment = new LearnComment();
comment.setContent(postCreateVO.getContent());
comment.setMessageId(messageId);
LearnComment parentComment = learnCommentDAO.selectByPrimaryKey(commentId);
if (Objects.isNull(parentComment.getRootId())) { // 对评论的回复
comment.setRootId(commentId);
} else { // 对回复的回复
comment.setRootId(parentComment.getRootId());
}
comment.setParentId(parentComment.getCreatorId());
comment.setCreatorId(accountVO.getId());
comment.setCreateTime(LocalDateTime.now());
learnCommentDAO.insertSelective(comment);
}
@Override @Override
@Transactional @Transactional
public void likeComment(Long commentId, AccountVO accountVO) { public void likeComment(Long commentId, AccountVO accountVO) {
LearnComment comment = getCommentEntity(commentId); LearnComment comment = getCommentEntity(commentId);
comment.setLike(comment.getLike() + 1); comment.setLike(comment.getLike() + 1);
learnCommentDAO.updateByPrimaryKey(comment); learnCommentDAO.updateByPrimaryKey(comment);
} }
@Override @Override
@Transactional @Transactional
public void unlikeComment(Long commentId, AccountVO accountVO) { public void unlikeComment(Long commentId, AccountVO accountVO) {
LearnComment comment = getCommentEntity(commentId); LearnComment comment = getCommentEntity(commentId);
comment.setUnlike(comment.getUnlike() + 1); comment.setUnlike(comment.getUnlike() + 1);
learnCommentDAO.updateByPrimaryKey(comment); learnCommentDAO.updateByPrimaryKey(comment);
} }
@Override @Override
public void top(Long postId, AccountVO accountVO) { public void top(Long postId, AccountVO accountVO) {
LearnPost post = topCheck(postId, accountVO); LearnPost post = topCheck(postId, accountVO);
post.setTopping(true); post.setTopping(true);
learnPostDAO.updateByPrimaryKey(post); learnPostDAO.updateByPrimaryKey(post);
} }
@Override @Override
public void unTop(Long postId, AccountVO accountVO) { public void unTop(Long postId, AccountVO accountVO) {
LearnPost post = topCheck(postId, accountVO); LearnPost post = topCheck(postId, accountVO);
post.setTopping(false); post.setTopping(false);
learnPostDAO.updateByPrimaryKey(post); learnPostDAO.updateByPrimaryKey(post);
} }
@Override @Override
public void deletePost(Long postId, AccountVO accountVO) { public void deletePost(Long postId, AccountVO accountVO) {
topCheck(postId, accountVO); topCheck(postId, accountVO);
//删除留言 //删除留言
LearnMessageExample messageExample = new LearnMessageExample(); LearnMessageExample messageExample = new LearnMessageExample();
messageExample.createCriteria().andPostIdEqualTo(postId); messageExample.createCriteria().andPostIdEqualTo(postId);
List<Long> messageIds = learnMessageDAO.selectByExample(messageExample).stream().map(LearnMessage::getId).collect(Collectors.toList()); List<Long> messageIds = learnMessageDAO.selectByExample(messageExample).stream()
learnMessageDAO.deleteByExample(messageExample); .map(LearnMessage::getId).collect(Collectors.toList());
//删除评论 learnMessageDAO.deleteByExample(messageExample);
LearnCommentExample commentExample = new LearnCommentExample(); //删除评论
commentExample.createCriteria().andMessageIdIn(messageIds); LearnCommentExample commentExample = new LearnCommentExample();
learnCommentDAO.deleteByExample(commentExample); commentExample.createCriteria().andMessageIdIn(messageIds);
learnPostDAO.deleteByPrimaryKey(postId); learnCommentDAO.deleteByExample(commentExample);
} learnPostDAO.deleteByPrimaryKey(postId);
}
@Override @Override
public void adminDeleteComment(Long commentId, AccountVO user) { public void adminDeleteComment(Long commentId, AccountVO user) {
iSysUserService.confirmAdmin(user); iSysUserService.confirmAdmin(user);
learnCommentDAO.deleteByPrimaryKey(commentId); learnCommentDAO.deleteByPrimaryKey(commentId);
} }
@Override @Override
public void userDeleteComment(Long commentId, AccountVO user) { public void userDeleteComment(Long commentId, AccountVO user) {
LearnComment comment = getCommentEntity(commentId); LearnComment comment = getCommentEntity(commentId);
if (!comment.getCreatorId().equals(user.getId())) { if (!comment.getCreatorId().equals(user.getId())) {
log.error(String.format("用户[%s]意外尝试删除别人的评论[%s]", user.getId(), commentId)); log.error(String.format("用户[%s]意外尝试删除别人的评论[%s]", user.getId(), commentId));
throw BusinessExceptionAssertEnum.INVALID_OPERATION.exception("无法删除非本人的评论"); throw BusinessExceptionAssertEnum.INVALID_OPERATION.exception("无法删除非本人的评论");
}
learnCommentDAO.deleteByPrimaryKey(commentId);
} }
learnCommentDAO.deleteByPrimaryKey(commentId);
}
@Override @Override
public long createMessage(LearnMessageCreateVO messageCreateVO, AccountVO user) { public long createMessage(LearnMessageCreateVO messageCreateVO, AccountVO user) {
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue(StringUtils.hasText(messageCreateVO.getContent()), BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue(
"内容不能空白"); StringUtils.hasText(messageCreateVO.getContent()),
if (SystemEnv.isPrdEnv(otherConfig.getEnv())) { "内容不能空白");
this.checkContent(messageCreateVO.getContent()); if (SystemEnv.isPrdEnv(otherConfig.getEnv())) {
} this.checkContent(messageCreateVO.getContent());
LearnMessage message = messageCreateVO.convert2DB(user.getId());
learnMessageDAO.insert(message);
LearnMessageExample example = new LearnMessageExample();
example.createCriteria().andPostIdEqualTo(messageCreateVO.getPostId());
return learnMessageDAO.countByExample(example);
} }
LearnMessage message = messageCreateVO.convert2DB(user.getId());
learnMessageDAO.insert(message);
LearnMessageExample example = new LearnMessageExample();
example.createCriteria().andPostIdEqualTo(messageCreateVO.getPostId());
return learnMessageDAO.countByExample(example);
}
@Override @Override
public PageVO<LearnMessageVO> pagedQueryMessageByPostId(Long postId, LearnMessagePagedQueryVO queryVO) { public PageVO<LearnMessageVO> pagedQueryMessageByPostId(Long postId,
PageHelper.startPage(queryVO.getPageNum(), queryVO.getPageSize()); LearnMessagePagedQueryVO queryVO) {
Page<LearnMessageVO> page = (Page<LearnMessageVO>) learnMessageDAO.select(postId, queryVO); PageHelper.startPage(queryVO.getPageNum(), queryVO.getPageSize());
for (LearnMessageVO vo : page.getResult()) { Page<LearnMessageVO> page = (Page<LearnMessageVO>) learnMessageDAO.select(postId, queryVO);
vo.setComments(pagedQueryComment(vo.getId(), new PageQueryVO(1, 3))); for (LearnMessageVO vo : page.getResult()) {
} vo.setComments(pagedQueryComment(vo.getId(), new PageQueryVO(1, 3)));
return PageVO.convert(page);
} }
return PageVO.convert(page);
}
@Override @Override
public void adminDeleteMessage(Long messageId, AccountVO user) { public void adminDeleteMessage(Long messageId, AccountVO user) {
iSysUserService.confirmAdmin(user); iSysUserService.confirmAdmin(user);
deleteMessage(messageId); deleteMessage(messageId);
} }
@Override @Override
public void userDeleteMessage(Long messageId, AccountVO user) { public void userDeleteMessage(Long messageId, AccountVO user) {
LearnMessage message = getMessageEntity(messageId); LearnMessage message = getMessageEntity(messageId);
if (!message.getCreatorId().equals(user.getId())) { if (!message.getCreatorId().equals(user.getId())) {
log.error(String.format("用户[%s]意外尝试删除别人的留言[%s]", user.getId(), messageId)); log.error(String.format("用户[%s]意外尝试删除别人的留言[%s]", user.getId(), messageId));
throw BusinessExceptionAssertEnum.INVALID_OPERATION.exception("无法删除非本人的留言"); throw BusinessExceptionAssertEnum.INVALID_OPERATION.exception("无法删除非本人的留言");
}
deleteMessage(messageId);
} }
deleteMessage(messageId);
}
@Override @Override
public LearnPostVO queryPost(String project) { public LearnPostVO queryPost(String project) {
LearnPostExample example = new LearnPostExample(); LearnPostExample example = new LearnPostExample();
example.createCriteria().andProjectEqualTo(project); example.createCriteria().andProjectEqualTo(project);
List<LearnPost> learnPosts = learnPostDAO.selectByExample(example); List<LearnPost> learnPosts = learnPostDAO.selectByExample(example);
if (CollectionUtils.isEmpty(learnPosts)) { if (CollectionUtils.isEmpty(learnPosts)) {
return null; return null;
}
return new LearnPostVO(learnPosts.get(0));
} }
return new LearnPostVO(learnPosts.get(0));
}
@Override @Override
public PageVO<LearnMessageVO> pagedQueryMessageByProject(String project, LearnMessagePagedQueryVO queryVO) { public PageVO<LearnMessageVO> pagedQueryMessageByProject(String project,
LearnPostVO post = queryPost(project); LearnMessagePagedQueryVO queryVO) {
if (post == null) { LearnPostVO post = queryPost(project);
log.error(String.format("项目[%s]的留言板不存在", project)); if (post == null) {
throw new SimulationException(SimulationExceptionType.System_Fault, "该项目的留言板不存在"); log.error(String.format("项目[%s]的留言板不存在", project));
} throw new SimulationException(SimulationExceptionType.System_Fault, "该项目的留言板不存在");
return pagedQueryMessageByPostId(post.getId(), queryVO);
} }
return pagedQueryMessageByPostId(post.getId(), queryVO);
}
@Override @Override
public void updatePost(Long postId, LearnPostUpdateVO updateVO, AccountVO user) { public void updatePost(Long postId, LearnPostUpdateVO updateVO, AccountVO user) {
iSysUserService.confirmAdmin(user); iSysUserService.confirmAdmin(user);
LearnPost entity = getPostEntity(postId); LearnPost entity = getPostEntity(postId);
if (Objects.equals(updateVO.getTitle(), entity.getTitle())) if (Objects.equals(updateVO.getTitle(), entity.getTitle())) {
return; return;
entity.setTitle(updateVO.getTitle());
learnPostDAO.updateByPrimaryKey(entity);
} }
entity.setTitle(updateVO.getTitle());
learnPostDAO.updateByPrimaryKey(entity);
}
@Override @Override
public long cgyCreateMessage(LearnMessageCreateVO messageCreateVO) { public long cgyCreateMessage(LearnMessageCreateVO messageCreateVO) {
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue(StringUtils.hasText(messageCreateVO.getContent()), BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue(
"内容不能空白"); StringUtils.hasText(messageCreateVO.getContent()),
LearnMessage message = messageCreateVO.convert2DB(1L); "内容不能空白");
message.setCreatorId(null); LearnMessage message = messageCreateVO.convert2DB(1L);
message.setUserName(messageCreateVO.getUserName()); message.setCreatorId(null);
learnMessageDAO.insert(message); message.setUserName(messageCreateVO.getUserName());
LearnMessageExample example = new LearnMessageExample(); learnMessageDAO.insert(message);
example.createCriteria().andPostIdEqualTo(messageCreateVO.getPostId()); LearnMessageExample example = new LearnMessageExample();
return learnMessageDAO.countByExample(example); example.createCriteria().andPostIdEqualTo(messageCreateVO.getPostId());
} return learnMessageDAO.countByExample(example);
}
@Override @Override
public void cgyAddComment(Long messageId, LearnCreateVO commentCreateVO) { public void cgyAddComment(Long messageId, LearnCreateVO commentCreateVO) {
checkMessageExist(messageId); checkMessageExist(messageId);
LearnComment comment = new LearnComment(); LearnComment comment = new LearnComment();
comment.setContent(commentCreateVO.getContent()); comment.setContent(commentCreateVO.getContent());
comment.setMessageId(messageId); comment.setMessageId(messageId);
comment.setCreateTime(LocalDateTime.now()); comment.setCreateTime(LocalDateTime.now());
comment.setUserName(commentCreateVO.getUserName()); comment.setUserName(commentCreateVO.getUserName());
learnCommentDAO.insertSelective(comment); learnCommentDAO.insertSelective(comment);
} }
@Override @Override
public void adminUpdateMessage(LearnMessageUpdateVO messageUpdateVO) { public void adminUpdateMessage(LearnMessageUpdateVO messageUpdateVO) {
LearnMessage messageEntity = getMessageEntity(messageUpdateVO.getId()); LearnMessage messageEntity = getMessageEntity(messageUpdateVO.getId());
messageEntity.setContent(messageUpdateVO.getContent()); messageEntity.setContent(messageUpdateVO.getContent());
messageEntity.setCreateTime(messageUpdateVO.getCreateTime()); messageEntity.setCreateTime(messageUpdateVO.getCreateTime());
learnMessageDAO.updateByPrimaryKey(messageEntity); learnMessageDAO.updateByPrimaryKey(messageEntity);
} }
@Override @Override
public void adminUpdateComment(LearnCommentUpdateVO commentUpdateVO) { public void adminUpdateComment(LearnCommentUpdateVO commentUpdateVO) {
LearnComment commentEntity = getCommentEntity(commentUpdateVO.getId()); LearnComment commentEntity = getCommentEntity(commentUpdateVO.getId());
commentEntity.setMessageId(commentUpdateVO.getMessageId()); commentEntity.setMessageId(commentUpdateVO.getMessageId());
commentEntity.setContent(commentUpdateVO.getContent()); commentEntity.setContent(commentUpdateVO.getContent());
commentEntity.setCreatorId(commentUpdateVO.getCreatorId()); commentEntity.setCreatorId(commentUpdateVO.getCreatorId());
commentEntity.setCreateTime(commentUpdateVO.getCreateTime()); commentEntity.setCreateTime(commentUpdateVO.getCreateTime());
learnCommentDAO.updateByPrimaryKey(commentEntity); learnCommentDAO.updateByPrimaryKey(commentEntity);
} }
// @Transactional // @Transactional
// @Override // @Override
@ -400,50 +423,55 @@ public class LearnService implements ILearnService {
// } // }
// } // }
@Transactional @Transactional
@Override @Override
public void cgyUpdateMessageTime() { public void cgyUpdateMessageTime() {
LearnMessageExample example = new LearnMessageExample(); LearnMessageExample example = new LearnMessageExample();
example.createCriteria().andPostIdEqualTo(27L); example.createCriteria().andPostIdEqualTo(27L);
List<LearnMessage> allMessage = learnMessageDAO.selectByExample(example); List<LearnMessage> allMessage = learnMessageDAO.selectByExample(example);
//删重复数据 //删重复数据
List<LearnMessage> list = allMessage.stream().collect(Collectors.toMap(LearnMessage::getContent, Function.identity(), (old, newValue) -> old)) List<LearnMessage> list = allMessage.stream().collect(
.values().stream().sorted(Comparator.comparingLong(LearnMessage::getId)).collect(Collectors.toList()); Collectors.toMap(LearnMessage::getContent, Function.identity(), (old, newValue) -> old))
HashSet<LearnMessage> distinctSet = new HashSet<>(list); .values().stream().sorted(Comparator.comparingLong(LearnMessage::getId))
List<Long> deleteIds = allMessage.stream().filter(message -> !distinctSet.contains(message)).map(LearnMessage::getId).collect(Collectors.toList()); .collect(Collectors.toList());
if (!CollectionUtils.isEmpty(deleteIds)) { HashSet<LearnMessage> distinctSet = new HashSet<>(list);
example.clear(); List<Long> deleteIds = allMessage.stream().filter(message -> !distinctSet.contains(message))
example.createCriteria().andIdIn(deleteIds); .map(LearnMessage::getId).collect(Collectors.toList());
learnMessageDAO.deleteByExample(example); if (!CollectionUtils.isEmpty(deleteIds)) {
} example.clear();
//修改时间 example.createCriteria().andIdIn(deleteIds);
int day = 365 * 4; learnMessageDAO.deleteByExample(example);
Random random = new Random();
List<Integer> dayOffsetList = new ArrayList<>();
for (LearnMessage ignored : list) {
dayOffsetList.add(random.nextInt(day));
}
dayOffsetList.sort((i1, i2) -> i2 - i1);
Map<Integer, Long> dayCountMap = dayOffsetList.stream().collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
int startIndex = 0;
LocalDateTime now = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
for (Integer dayOffset : dayCountMap.keySet()) {
List<Integer> secondsOffsetList = new ArrayList<>();
Long dayCount = dayCountMap.get(dayOffset);
for (int i = 0; i < dayCount; i++) {
secondsOffsetList.add(random.nextInt(24 * 3600 - 8 * 3600) + 8 * 3600);
secondsOffsetList.sort(Integer::compareTo);
}
for (int i = startIndex; i < startIndex + dayCount; i++) {
LearnMessage message = list.get(i);
message.setCreateTime(now.minusDays(dayOffset).plusSeconds(secondsOffsetList.get(i - startIndex)));
learnMessageDAO.updateByPrimaryKey(message);
}
startIndex += dayCount;
}
} }
//修改时间
int day = 365 * 4;
Random random = new Random();
List<Integer> dayOffsetList = new ArrayList<>();
for (LearnMessage ignored : list) {
dayOffsetList.add(random.nextInt(day));
}
dayOffsetList.sort((i1, i2) -> i2 - i1);
Map<Integer, Long> dayCountMap = dayOffsetList.stream().collect(
Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
int startIndex = 0;
LocalDateTime now = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
for (Integer dayOffset : dayCountMap.keySet()) {
List<Integer> secondsOffsetList = new ArrayList<>();
Long dayCount = dayCountMap.get(dayOffset);
for (int i = 0; i < dayCount; i++) {
secondsOffsetList.add(random.nextInt(24 * 3600 - 8 * 3600) + 8 * 3600);
secondsOffsetList.sort(Integer::compareTo);
}
for (int i = startIndex; i < startIndex + dayCount; i++) {
LearnMessage message = list.get(i);
message.setCreateTime(
now.minusDays(dayOffset).plusSeconds(secondsOffsetList.get(i - startIndex)));
learnMessageDAO.updateByPrimaryKey(message);
}
startIndex += dayCount;
}
}
// @Override // @Override
// public Integer likeMessage(Long messageId) { // public Integer likeMessage(Long messageId) {
// LearnMessageWithBLOBs message = getMessage(messageId); // LearnMessageWithBLOBs message = getMessage(messageId);
// message.setLike(message.getLike() == null ? 0 : message.getLike() + 1); // message.setLike(message.getLike() == null ? 0 : message.getLike() + 1);
@ -459,38 +487,38 @@ public class LearnService implements ILearnService {
// return message.getUnlike(); // return message.getUnlike();
// } // }
private LearnComment findCommentEntity(Long commentId) { private LearnComment findCommentEntity(Long commentId) {
return learnCommentDAO.selectByPrimaryKey(commentId); return learnCommentDAO.selectByPrimaryKey(commentId);
} }
private LearnComment getCommentEntity(Long commentId) { private LearnComment getCommentEntity(Long commentId) {
LearnComment comment = findCommentEntity(commentId); LearnComment comment = findCommentEntity(commentId);
BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertNotNull(comment, BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertNotNull(comment,
"该评论不存在或已被删除"); "该评论不存在或已被删除");
return comment; return comment;
} }
private void deleteMessage(Long messageId) { private void deleteMessage(Long messageId) {
learnMessageDAO.deleteByPrimaryKey(messageId); learnMessageDAO.deleteByPrimaryKey(messageId);
deleteCommentByMessageId(messageId); deleteCommentByMessageId(messageId);
} }
private void deleteCommentByMessageId(Long messageId) { private void deleteCommentByMessageId(Long messageId) {
LearnCommentExample example = new LearnCommentExample(); LearnCommentExample example = new LearnCommentExample();
example.createCriteria().andMessageIdEqualTo(messageId); example.createCriteria().andMessageIdEqualTo(messageId);
learnCommentDAO.deleteByExample(example); learnCommentDAO.deleteByExample(example);
} }
private LearnPost topCheck(Long postId, AccountVO accountVO) { private LearnPost topCheck(Long postId, AccountVO accountVO) {
iSysUserService.confirmAdmin(accountVO); iSysUserService.confirmAdmin(accountVO);
LearnPost post = getPostEntity(postId); LearnPost post = getPostEntity(postId);
return post; return post;
} }
private void checkContent(String content) { private void checkContent(String content) {
WxError wxError = this.miniProgramService.msgSecCheck(content); WxError wxError = this.miniProgramService.msgSecCheck(content);
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotTrue(wxError.isError(), BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotTrue(wxError.isError(),
String.format("内容校验不通过: [%s]", wxError.toString())); String.format("内容校验不通过: [%s]", wxError.toString()));
// Map<String, String> param = new HashMap<>(); // Map<String, String> param = new HashMap<>();
// param.put("content", content); // param.put("content", content);
// WxBaseResp resp = restTemplate.postForObject(weChatConfig.getMsgSecCheckUrl(), param, WxBaseResp.class); // WxBaseResp resp = restTemplate.postForObject(weChatConfig.getMsgSecCheckUrl(), param, WxBaseResp.class);
@ -502,44 +530,46 @@ public class LearnService implements ILearnService {
// } else { // } else {
// throw new BusinessException(ExceptionMapping.SERVER_CALL_EXCEPTION); // throw new BusinessException(ExceptionMapping.SERVER_CALL_EXCEPTION);
// } // }
} }
/** /**
* 留言检查 * 留言检查
*/ */
private void checkMessageExist(Long messageId) { private void checkMessageExist(Long messageId) {
BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertNotNull(findMessageEntity(messageId), BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertNotNull(findMessageEntity(messageId),
String.format("id为[%s]的留言不存在", messageId)); String.format("id为[%s]的留言不存在", messageId));
} }
private LearnMessage findMessageEntity(Long messageId) { private LearnMessage findMessageEntity(Long messageId) {
return learnMessageDAO.selectByPrimaryKey(messageId); return learnMessageDAO.selectByPrimaryKey(messageId);
} }
private LearnMessage getMessageEntity(Long messageId) { private LearnMessage getMessageEntity(Long messageId) {
LearnMessage message = findMessageEntity(messageId); LearnMessage message = findMessageEntity(messageId);
BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertNotNull(message, String.format("id为[%s]的留言不存在", messageId)); BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertNotNull(message,
return message; String.format("id为[%s]的留言不存在", messageId));
} return message;
}
private LearnPost findPostEntity(Long postId) { private LearnPost findPostEntity(Long postId) {
return learnPostDAO.selectByPrimaryKey(postId); return learnPostDAO.selectByPrimaryKey(postId);
} }
private LearnPost getPostEntity(Long postId) { private LearnPost getPostEntity(Long postId) {
LearnPost post = findPostEntity(postId); LearnPost post = findPostEntity(postId);
BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertNotNull(post); BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertNotNull(post);
return post; return post;
} }
/** /**
* 确认该项目的留言板不存在 * 确认该项目的留言板不存在
*/ */
private void confirmPostIsNotExist(String project) { private void confirmPostIsNotExist(String project) {
LearnPostExample example = new LearnPostExample(); LearnPostExample example = new LearnPostExample();
example.createCriteria().andProjectEqualTo(project); example.createCriteria().andProjectEqualTo(project);
BusinessExceptionAssertEnum.DATA_ALREADY_EXIST.assertTrue(learnPostDAO.countByExample(example) == 0, BusinessExceptionAssertEnum.DATA_ALREADY_EXIST.assertTrue(
String.format("项目[%s]下留言板已存在", project)); learnPostDAO.countByExample(example) == 0,
} String.format("项目[%s]下留言板已存在", project));
}
} }

View File

@ -6,7 +6,12 @@ import club.joylink.rtss.constants.StatusEnum;
import club.joylink.rtss.dao.OrgDAO; import club.joylink.rtss.dao.OrgDAO;
import club.joylink.rtss.dao.SysAccountDAO; import club.joylink.rtss.dao.SysAccountDAO;
import club.joylink.rtss.dao.UserSubscribeMapper; import club.joylink.rtss.dao.UserSubscribeMapper;
import club.joylink.rtss.entity.*; import club.joylink.rtss.entity.Org;
import club.joylink.rtss.entity.OrgUser;
import club.joylink.rtss.entity.SysAccount;
import club.joylink.rtss.entity.SysAccountExample;
import club.joylink.rtss.entity.UserSubscribe;
import club.joylink.rtss.entity.UserSubscribeExample;
import club.joylink.rtss.exception.BusinessExceptionAssertEnum; import club.joylink.rtss.exception.BusinessExceptionAssertEnum;
import club.joylink.rtss.services.cache.ICacheService; import club.joylink.rtss.services.cache.ICacheService;
import club.joylink.rtss.services.org.IOrgProjectService; import club.joylink.rtss.services.org.IOrgProjectService;
@ -14,10 +19,19 @@ import club.joylink.rtss.services.org.IOrgService;
import club.joylink.rtss.services.org.IOrgUserService; import club.joylink.rtss.services.org.IOrgUserService;
import club.joylink.rtss.util.EncryptUtil; import club.joylink.rtss.util.EncryptUtil;
import club.joylink.rtss.util.RandomGenerator; import club.joylink.rtss.util.RandomGenerator;
import club.joylink.rtss.vo.*; import club.joylink.rtss.vo.AccountVO;
import club.joylink.rtss.vo.LoginUserInfoVO;
import club.joylink.rtss.vo.SmsResponse;
import club.joylink.rtss.vo.UserQueryVO;
import club.joylink.rtss.vo.VdCode;
import club.joylink.rtss.vo.client.PageVO; import club.joylink.rtss.vo.client.PageVO;
import club.joylink.rtss.vo.client.org.OrgVO; import club.joylink.rtss.vo.client.org.OrgVO;
import club.joylink.rtss.vo.client.user.*; import club.joylink.rtss.vo.client.user.MobileInfoVO;
import club.joylink.rtss.vo.client.user.RetrievePwdVO;
import club.joylink.rtss.vo.client.user.UpdateEmailVO;
import club.joylink.rtss.vo.client.user.UpdateMobileVO;
import club.joylink.rtss.vo.client.user.UpdatePasswordVO;
import club.joylink.rtss.vo.client.user.WeChatBindStatusVO;
import club.joylink.rtss.vo.map.MapVO; import club.joylink.rtss.vo.map.MapVO;
import club.joylink.rtss.vo.user.AccountCreateVO; import club.joylink.rtss.vo.user.AccountCreateVO;
import club.joylink.rtss.vo.user.AccountRegisterVO; import club.joylink.rtss.vo.user.AccountRegisterVO;
@ -25,6 +39,18 @@ import club.joylink.rtss.vo.wx.WmUserSession;
import club.joylink.rtss.vo.wx.WxUserGet; import club.joylink.rtss.vo.wx.WxUserGet;
import com.github.pagehelper.Page; import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.NonNull; import lombok.NonNull;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -34,13 +60,6 @@ import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service @Service
@Slf4j @Slf4j
public class SysUserService implements ISysUserService { public class SysUserService implements ISysUserService {
@ -360,7 +379,8 @@ public class SysUserService implements ISysUserService {
BusinessExceptionAssertEnum.INVALID_OPERATION.assertNotHasText(account.getWmOpenId(), BusinessExceptionAssertEnum.INVALID_OPERATION.assertNotHasText(account.getWmOpenId(),
String.format("用户[%s]已经绑定微信小程序", account.getNickname())); String.format("用户[%s]已经绑定微信小程序", account.getNickname()));
// 如果之前已经存在绑定解除之前的绑定 // 如果之前已经存在绑定解除之前的绑定
WmUserSession userSession = this.iWxApiService.getWmUserSession(WxApiService.MiniApp.JoyLink, code); WmUserSession userSession = this.iWxApiService.getWmUserSession(WxApiService.MiniApp.JoyLink,
code);
String openid = userSession.getOpenid(); String openid = userSession.getOpenid();
SysAccountExample example = new SysAccountExample(); SysAccountExample example = new SysAccountExample();
example.createCriteria() example.createCriteria()
@ -392,7 +412,8 @@ public class SysUserService implements ISysUserService {
@Transactional @Transactional
public OrgVO userScanCodeBindCompanyManager(Long userId, Long companyId) { public OrgVO userScanCodeBindCompanyManager(Long userId, Long companyId) {
SysAccount sysAccount = sysAccountDAO.selectByPrimaryKey(userId); SysAccount sysAccount = sysAccountDAO.selectByPrimaryKey(userId);
BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertNotNull(sysAccount, String.format("id为[%s]的用户不存在", userId)); BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertNotNull(sysAccount,
String.format("id为[%s]的用户不存在", userId));
AccountVO accountVO = new AccountVO(sysAccount); AccountVO accountVO = new AccountVO(sysAccount);
OrgVO orgVO = iOrgUserService.userBindCompanyManager(accountVO, companyId); OrgVO orgVO = iOrgUserService.userBindCompanyManager(accountVO, companyId);
this.loginSessionManager.updateLoginUser(accountVO); this.loginSessionManager.updateLoginUser(accountVO);
@ -655,7 +676,8 @@ public class SysUserService implements ISysUserService {
@Override @Override
public void updateMobile(Long id, UpdateMobileVO updateMobileVO) { public void updateMobile(Long id, UpdateMobileVO updateMobileVO) {
Objects.requireNonNull(id, "用户id不能为空"); Objects.requireNonNull(id, "用户id不能为空");
validateMobileVerificationCode(updateMobileVO.getNationCode(), updateMobileVO.getMobile(), updateMobileVO.getValidCode()); validateMobileVerificationCode(updateMobileVO.getNationCode(), updateMobileVO.getMobile(),
updateMobileVO.getValidCode());
SysAccount account = this.sysAccountDAO.selectByPrimaryKey(id); SysAccount account = this.sysAccountDAO.selectByPrimaryKey(id);
if (Objects.nonNull(account)) { if (Objects.nonNull(account)) {
account.setNationcode(updateMobileVO.getNationCode()); account.setNationcode(updateMobileVO.getNationCode());
@ -666,7 +688,8 @@ public class SysUserService implements ISysUserService {
} }
} }
private void validateMobileVerificationCode(String nationCode, String mobile, String verificationCode) { private void validateMobileVerificationCode(String nationCode, String mobile,
String verificationCode) {
VdCode vdCode = (VdCode) this.iCacheService.get(nationCode + mobile); VdCode vdCode = (VdCode) this.iCacheService.get(nationCode + mobile);
// 验证验证码 // 验证验证码
BusinessExceptionAssertEnum.INCORRECT_VERIFICATION_CODE.assertNotNull(vdCode); BusinessExceptionAssertEnum.INCORRECT_VERIFICATION_CODE.assertNotNull(vdCode);
@ -705,16 +728,20 @@ public class SysUserService implements ISysUserService {
@Override @Override
public String sendMobileValidCode(MobileInfoVO mobileInfoVO) { public String sendMobileValidCode(MobileInfoVO mobileInfoVO) {
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue(mobileInfoVO.validate(), "发送验证码请求未通过"); BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue(mobileInfoVO.validate(),
"发送验证码请求未通过");
String code = RandomGenerator.getByLen(4); String code = RandomGenerator.getByLen(4);
long ts = System.currentTimeMillis(); long ts = System.currentTimeMillis();
List<String> params = new ArrayList<>(); List<String> params = new ArrayList<>();
params.add(code); params.add(code);
params.add(VdCode.CODE_TIMEOUT + ""); params.add(VdCode.CODE_TIMEOUT + "");
SmsResponse resp = this.iSmsService.sendValidateCode(mobileInfoVO.getMobile(), mobileInfoVO.getNationCode(), params, ts); SmsResponse resp = this.iSmsService.sendValidateCode(mobileInfoVO.getMobile(),
mobileInfoVO.getNationCode(), params, ts);
BusinessExceptionAssertEnum.THIRD_SERVICE_CALL_EXCEPTION.assertTrue(resp.getResult() == 0, BusinessExceptionAssertEnum.THIRD_SERVICE_CALL_EXCEPTION.assertTrue(resp.getResult() == 0,
String.format("短信发送服务调用异常:[result: %s, errmsg: %s]", resp.getResult(), resp.getErrmsg())); String.format("短信发送服务调用异常:[result: %s, errmsg: %s]", resp.getResult(),
iCacheService.putExpired(mobileInfoVO.buildUp(), new VdCode(code, ts), VdCode.CODE_TIMEOUT, TimeUnit.MINUTES); resp.getErrmsg()));
iCacheService.putExpired(mobileInfoVO.buildUp(), new VdCode(code, ts), VdCode.CODE_TIMEOUT,
TimeUnit.MINUTES);
log.debug(String.format("短息发送手机%s验证码[%s]", mobileInfoVO.buildUp(), code)); log.debug(String.format("短息发送手机%s验证码[%s]", mobileInfoVO.buildUp(), code));
return EncryptUtil.md5(code); return EncryptUtil.md5(code);
} }
@ -729,7 +756,8 @@ public class SysUserService implements ISysUserService {
private void updatePwdByMobileVdCode(UpdatePasswordVO updatePasswordVO, SysAccount account) { private void updatePwdByMobileVdCode(UpdatePasswordVO updatePasswordVO, SysAccount account) {
if (Objects.nonNull(account)) { if (Objects.nonNull(account)) {
VdCode vdCode = (VdCode) this.iCacheService.get(account.getNationcode() + account.getMobile()); VdCode vdCode = (VdCode) this.iCacheService.get(
account.getNationcode() + account.getMobile());
BusinessExceptionAssertEnum.INCORRECT_VERIFICATION_CODE.assertNotNull(vdCode); BusinessExceptionAssertEnum.INCORRECT_VERIFICATION_CODE.assertNotNull(vdCode);
// 验证验证码 // 验证验证码
vdCode.isValidCode(updatePasswordVO.getVfCode()); vdCode.isValidCode(updatePasswordVO.getVfCode());
@ -787,7 +815,8 @@ public class SysUserService implements ISysUserService {
SysAccountExample example = new SysAccountExample(); SysAccountExample example = new SysAccountExample();
example.createCriteria().andNameLike(String.format("%%%s%%", name)); example.createCriteria().andNameLike(String.format("%%%s%%", name));
List<SysAccount> users = sysAccountDAO.selectByExample(example); List<SysAccount> users = sysAccountDAO.selectByExample(example);
List<AccountVO> voList = users.stream().map(account -> new AccountVO(account)).collect(Collectors.toList()); List<AccountVO> voList = users.stream().map(account -> new AccountVO(account))
.collect(Collectors.toList());
return voList; return voList;
} }
@ -800,7 +829,8 @@ public class SysUserService implements ISysUserService {
@Override @Override
public List<AccountVO> getUsersWithEmail() { public List<AccountVO> getUsersWithEmail() {
SysAccountExample example = new SysAccountExample(); SysAccountExample example = new SysAccountExample();
example.createCriteria().andMobileIsNotNull().andNationcodeIsNotNull().andStatusEqualTo(BusinessConsts.STATUS_USE); example.createCriteria().andMobileIsNotNull().andNationcodeIsNotNull()
.andStatusEqualTo(BusinessConsts.STATUS_USE);
List<SysAccount> sysUsers = sysAccountDAO.selectByExample(example); List<SysAccount> sysUsers = sysAccountDAO.selectByExample(example);
List<AccountVO> users = sysUsers.stream().map(AccountVO::new).collect(Collectors.toList()); List<AccountVO> users = sysUsers.stream().map(AccountVO::new).collect(Collectors.toList());
return users; return users;
@ -882,7 +912,8 @@ public class SysUserService implements ISysUserService {
private SysAccount getEntity(Long id) { private SysAccount getEntity(Long id) {
SysAccount account = sysAccountDAO.selectByPrimaryKey(id); SysAccount account = sysAccountDAO.selectByPrimaryKey(id);
BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertNotNull(account, String.format("id为[%s]的用户不存在", id)); BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertNotNull(account,
String.format("id为[%s]的用户不存在", id));
return account; return account;
} }
@ -893,7 +924,8 @@ public class SysUserService implements ISysUserService {
@Override @Override
public void register(AccountCreateVO accountCreateVO) { public void register(AccountCreateVO accountCreateVO) {
BusinessExceptionAssertEnum.DATA_ALREADY_EXIST.assertNotTrue(this.isSameEmailExist(accountCreateVO.getEmail())); BusinessExceptionAssertEnum.DATA_ALREADY_EXIST.assertNotTrue(
this.isSameEmailExist(accountCreateVO.getEmail()));
SysAccount account = accountCreateVO.toDB(); SysAccount account = accountCreateVO.toDB();
account.setRoles(BusinessConsts.ROLE_01); account.setRoles(BusinessConsts.ROLE_01);
account.setCreateTime(LocalDateTime.now()); account.setCreateTime(LocalDateTime.now());
@ -918,7 +950,7 @@ public class SysUserService implements ISysUserService {
} }
@Override @Override
public AccountVO queryOrCreateThirdAccount(String parentAccount, String account) { public AccountVO queryOrCreateThirdAccount(String parentAccount, String account, String name) {
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertHasText(parentAccount); BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertHasText(parentAccount);
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertHasText(account); BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertHasText(account);
String key = parentAccount + account; String key = parentAccount + account;
@ -939,9 +971,14 @@ public class SysUserService implements ISysUserService {
SysAccount sysAccount = new SysAccount(); SysAccount sysAccount = new SysAccount();
sysAccount.setAccount(account); sysAccount.setAccount(account);
sysAccount.setParentAccount(parentAccount); sysAccount.setParentAccount(parentAccount);
sysAccount.setNickname(String.format("第三方账户%s", account)); if (StringUtils.hasText(name)) {
sysAccount.setName(name);
sysAccount.setNickname(name);
} else {
sysAccount.setNickname(String.format("第三方账户%s", account));
}
sysAccount.setType(AccountVO.Type_3); sysAccount.setType(AccountVO.Type_3);
String initPassword = EncryptUtil.md5("123456"); String initPassword = EncryptUtil.md5(BusinessConsts.DEFAULT_PASSWORD);
sysAccount.setPassword(initPassword); sysAccount.setPassword(initPassword);
sysAccount.setStatus(BusinessConsts.STATUS_USE); sysAccount.setStatus(BusinessConsts.STATUS_USE);
sysAccount.setRoles(BusinessConsts.ROLE_01); sysAccount.setRoles(BusinessConsts.ROLE_01);
@ -1017,10 +1054,13 @@ public class SysUserService implements ISysUserService {
@Override @Override
public void register2(AccountRegisterVO registerVO) { public void register2(AccountRegisterVO registerVO) {
if (StringUtils.hasText(registerVO.getMobile())) { if (StringUtils.hasText(registerVO.getMobile())) {
BusinessExceptionAssertEnum.DATA_ALREADY_EXIST.assertNotTrue(isSameMobileExist(registerVO.getMobile())); BusinessExceptionAssertEnum.DATA_ALREADY_EXIST.assertNotTrue(
validateMobileVerificationCode(registerVO.getNationCode(), registerVO.getMobile(), registerVO.getVerificationCode()); isSameMobileExist(registerVO.getMobile()));
validateMobileVerificationCode(registerVO.getNationCode(), registerVO.getMobile(),
registerVO.getVerificationCode());
} else if (StringUtils.hasText(registerVO.getEmail())) { } else if (StringUtils.hasText(registerVO.getEmail())) {
BusinessExceptionAssertEnum.DATA_ALREADY_EXIST.assertNotTrue(isSameEmailExist(registerVO.getEmail())); BusinessExceptionAssertEnum.DATA_ALREADY_EXIST.assertNotTrue(
isSameEmailExist(registerVO.getEmail()));
validateEmailVerificationCode(registerVO.getEmail(), registerVO.getVerificationCode()); validateEmailVerificationCode(registerVO.getEmail(), registerVO.getVerificationCode());
} }
SysAccount sysAccount = registerVO.toDB(); SysAccount sysAccount = registerVO.toDB();
@ -1072,6 +1112,20 @@ public class SysUserService implements ISysUserService {
return sysAccountDAO.countByExample(example) > 0; return sysAccountDAO.countByExample(example) > 0;
} }
@Override
public List<AccountVO> listByIds(List<Long> ids) {
SysAccountExample example = new SysAccountExample();
example.createCriteria().andIdIn(ids);
List<SysAccount> sysAccounts = sysAccountDAO.selectByExample(example);
return AccountVO.convertFromDB(sysAccounts);
}
@Override
public List<AccountVO> listAll() {
List<SysAccount> sysAccounts = sysAccountDAO.selectByExample(null);
return AccountVO.convertFromDB(sysAccounts);
}
/** /**
* 查询包含组织信息的用户信息 * 查询包含组织信息的用户信息
*/ */
@ -1097,7 +1151,8 @@ public class SysUserService implements ISysUserService {
* @param account * @param account
*/ */
private void updateLoginUserInfoWithOrgInfo(SysAccount account) { private void updateLoginUserInfoWithOrgInfo(SysAccount account) {
List<LoginUserInfoVO> loginUserInfoVOS = loginSessionManager.queryLoginInfoByUserId(account.getId()); List<LoginUserInfoVO> loginUserInfoVOS = loginSessionManager.queryLoginInfoByUserId(
account.getId());
if (!CollectionUtils.isEmpty(loginUserInfoVOS)) { if (!CollectionUtils.isEmpty(loginUserInfoVOS)) {
for (LoginUserInfoVO loginInfo : loginUserInfoVOS) { for (LoginUserInfoVO loginInfo : loginUserInfoVOS) {
AccountVO oldAccountVO = loginInfo.getAccountVO(); AccountVO oldAccountVO = loginInfo.getAccountVO();

View File

@ -3,6 +3,7 @@ package club.joylink.rtss.services.auth;
import club.joylink.rtss.configuration.configProp.OtherConfig; import club.joylink.rtss.configuration.configProp.OtherConfig;
import club.joylink.rtss.configuration.configProp.WeChatConfig; import club.joylink.rtss.configuration.configProp.WeChatConfig;
import club.joylink.rtss.constants.Client; import club.joylink.rtss.constants.Client;
import club.joylink.rtss.constants.ProjectCode;
import club.joylink.rtss.dao.SysAccountLoginDAO; import club.joylink.rtss.dao.SysAccountLoginDAO;
import club.joylink.rtss.entity.SysAccountLogin; import club.joylink.rtss.entity.SysAccountLogin;
import club.joylink.rtss.entity.project.Project; import club.joylink.rtss.entity.project.Project;
@ -22,6 +23,7 @@ import club.joylink.rtss.vo.LoginUserInfoVO;
import club.joylink.rtss.vo.client.LoginStatusVO; import club.joylink.rtss.vo.client.LoginStatusVO;
import club.joylink.rtss.vo.client.LoginUserVO; import club.joylink.rtss.vo.client.LoginUserVO;
import club.joylink.rtss.vo.client.SocketMessageVO; import club.joylink.rtss.vo.client.SocketMessageVO;
import club.joylink.rtss.vo.client.cgy.CgyThirdPartyLoginInfoVO;
import club.joylink.rtss.vo.client.factory.SocketMessageFactory; import club.joylink.rtss.vo.client.factory.SocketMessageFactory;
import club.joylink.rtss.vo.client.project.ProjectDeviceVO; import club.joylink.rtss.vo.client.project.ProjectDeviceVO;
import club.joylink.rtss.vo.client.project.RelationLoginConfigVO; import club.joylink.rtss.vo.client.project.RelationLoginConfigVO;
@ -239,6 +241,24 @@ public class AuthenticateService implements IAuthenticateService {
} }
} }
@Override
public String cgyThirdPartyLogin(CgyThirdPartyLoginInfoVO loginInfo) {
BusinessExceptionAssertEnum.INVALID_OPERATION
.assertTrue(this.iSysUserService.isThirdParentAccountExist(loginInfo.getParentAccount()),
String.format("成工院父账号不存在: %s", loginInfo.getParentAccount()));
AccountVO accountVO = this.iSysUserService.queryOrCreateThirdAccount(
loginInfo.getParentAccount(),
loginInfo.getAccount(),
loginInfo.getName());
ProjectVO projectVO = projectService.queryLoginProjectByCode(ProjectCode.CGY);
// 构造登陆用户信息
LoginUserInfoVO loginUserInfo = new LoginUserInfoVO(accountVO, Client.Joylink, projectVO, null);
loginUserInfo.setThirdLogin(true);
// 执行登录
login(loginUserInfo, true);
return loginUserInfo.getToken();
}
/** /**
* @update 20221019 去除设置组织信息 * @update 20221019 去除设置组织信息
*/ */
@ -384,8 +404,7 @@ public class AuthenticateService implements IAuthenticateService {
.assertTrue(this.iSysUserService.isThirdParentAccountExist(loginInfo.getParentAccount()), .assertTrue(this.iSysUserService.isThirdParentAccountExist(loginInfo.getParentAccount()),
String.format("第三方企业账号不存在: %s", loginInfo.getParentAccount())); String.format("第三方企业账号不存在: %s", loginInfo.getParentAccount()));
AccountVO accountVO = this.iSysUserService.queryOrCreateThirdAccount( AccountVO accountVO = this.iSysUserService.queryOrCreateThirdAccount(
loginInfo.getParentAccount(), loginInfo.getParentAccount(), loginInfo.getAccount(), null);
loginInfo.getAccount());
Client client = Client.getByIdAndSecret(loginInfo.getClientId(), loginInfo.getSecret()); Client client = Client.getByIdAndSecret(loginInfo.getClientId(), loginInfo.getSecret());
ProjectVO projectVO = projectService.queryLoginProjectByCode(loginInfo.getProject()); ProjectVO projectVO = projectService.queryLoginProjectByCode(loginInfo.getProject());
// 构造登陆用户信息 // 构造登陆用户信息

View File

@ -5,120 +5,127 @@ import club.joylink.rtss.vo.AccountVO;
import club.joylink.rtss.vo.LoginUserInfoVO; import club.joylink.rtss.vo.LoginUserInfoVO;
import club.joylink.rtss.vo.client.LoginStatusVO; import club.joylink.rtss.vo.client.LoginStatusVO;
import club.joylink.rtss.vo.client.LoginUserVO; import club.joylink.rtss.vo.client.LoginUserVO;
import club.joylink.rtss.vo.client.cgy.CgyThirdPartyLoginInfoVO;
public interface IAuthenticateService { public interface IAuthenticateService {
/** /**
* 获取登陆状态/token * 获取登陆状态/token
* *
* @param sessionId * @param sessionId
* @return * @return
*/ */
LoginStatusVO checkStatus(String sessionId); LoginStatusVO checkStatus(String sessionId);
/** /**
* 通过密码登陆 * 通过密码登陆
* *
* @param loginUser * @param loginUser
*/ */
String loginWithPwd(LoginUserVO loginUser); String loginWithPwd(LoginUserVO loginUser);
/** /**
* 第三方登录 * 第三方登录
* *
* @param loginInfo * @param loginInfo
* @return * @return
*/ */
String thirdPartyLogin(LoginUserVO loginInfo); String thirdPartyLogin(LoginUserVO loginInfo);
/** /**
* 登出 * 登出
* *
* @param token * @param token
*/ */
void logout(String token); void logout(String token);
/** /**
* 微信小程序扫登陆二维码 * 微信小程序扫登陆二维码
* *
* @param code * @param code
* @param state * @param state
* @return * @return
*/ */
AccountVO scanWmLoginQrCode(String code, String state); AccountVO scanWmLoginQrCode(String code, String state);
/** /**
* 获取微信小程序登陆url * 获取微信小程序登陆url
* *
* @param clientId * @param clientId
* @param secret * @param secret
* @param project * @param project
* @param deviceCode * @param deviceCode
* @return * @return
*/ */
// LoginStatusVO getWmLoginUrl(String clientId, String secret, Project project, String deviceCode); // LoginStatusVO getWmLoginUrl(String clientId, String secret, Project project, String deviceCode);
/** /**
* TODO 20220922 用于替换上方方法 占位 * TODO 20220922 用于替换上方方法 占位
* <p> * <p>
* 测试文档后删除相关注释 * 测试文档后删除相关注释
*/ */
LoginStatusVO getWmLoginUrl(String clientId, String secret, String projectCode, String deviceCode); LoginStatusVO getWmLoginUrl(String clientId, String secret, String projectCode,
String deviceCode);
/** /**
* 微信小程序确认登陆 * 微信小程序确认登陆
* *
* @param code * @param code
* @param state * @param state
*/ */
void wmConfirmClientLogin(String code, String state); void wmConfirmClientLogin(String code, String state);
/** /**
* 通过token获取登陆用户信息 * 通过token获取登陆用户信息
* *
* @param token * @param token
*/ */
LoginUserInfoVO getLoginUserInfoByToken(String token); LoginUserInfoVO getLoginUserInfoByToken(String token);
/** /**
* 根据微信小程序code获取用户若不存在创建用户若已登录则绑定微信 * 根据微信小程序code获取用户若不存在创建用户若已登录则绑定微信
* *
* @param code * @param code
* @return * @return
*/ */
AccountVO getOrCreateUserByWmcode(WxApiService.MiniApp miniApp, String code); AccountVO getOrCreateUserByWmcode(WxApiService.MiniApp miniApp, String code);
/** /**
* 玖琏科技小程序code换token * 玖琏科技小程序code换token
* *
* @param code * @param code
* @return * @return
*/ */
String getTokenByWmCode(String code); String getTokenByWmCode(String code);
/** /**
* 到那儿了小程序code换token * 到那儿了小程序code换token
* *
* @param code * @param code
* @return * @return
*/ */
String getTokenByWmCode2(String code); String getTokenByWmCode2(String code);
/** /**
* 郑州共赢小程序code换token * 郑州共赢小程序code换token
* *
* @param code * @param code
* @return * @return
*/ */
String getTokenByWmCode3(String code); String getTokenByWmCode3(String code);
boolean isTokenExpired(String token); boolean isTokenExpired(String token);
/** /**
* 预登出前端在刷新/关闭标签页的时候调用 * 预登出前端在刷新/关闭标签页的时候调用
* *
* @param token * @param token
*/ */
void preLogout(String token); void preLogout(String token);
/**
* 成工业虚仿平台跳转登录接口
*/
String cgyThirdPartyLogin(CgyThirdPartyLoginInfoVO loginInfo);
} }

View File

@ -0,0 +1,171 @@
package club.joylink.rtss.services.cgy;
import club.joylink.rtss.bo.cgy.CgyStatsBO;
import club.joylink.rtss.dao.CgyViewDAO;
import club.joylink.rtss.entity.CgyView;
import club.joylink.rtss.entity.CgyViewExample;
import club.joylink.rtss.entity.UserSimulationRecord;
import club.joylink.rtss.event.UserSimulationRecordEvent;
import club.joylink.rtss.services.user.UserSimulationRecordService;
import club.joylink.rtss.simulation.cbtc.SimulationService;
import club.joylink.rtss.simulation.vo.SimulationInfoVO;
import club.joylink.rtss.util.EncryptUtil;
import club.joylink.rtss.vo.client.simulationUsage.SimulationUsageRecordQueryVO;
import club.joylink.rtss.vo.client.simulationv1.SimulationInfoQueryVO;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
/**
* 成工院虚仿平台对接统计服务
*/
@Slf4j
@Service
public class CgyStatsService {
private CgyViewDAO cgyViewDAO;
private UserSimulationRecordService userSimulationRecordService;
private SimulationService simulationService;
private RestTemplate restTemplate;
@Autowired
public CgyStatsService(CgyViewDAO cgyViewDAO,
UserSimulationRecordService userSimulationRecordService,
SimulationService simulationService, RestTemplate restTemplate) {
this.cgyViewDAO = cgyViewDAO;
this.userSimulationRecordService = userSimulationRecordService;
this.simulationService = simulationService;
this.restTemplate = restTemplate;
}
private final ConcurrentHashMap<String, CgyStatsBO> appStatsMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Long, CgyStatsBO> functionStatsMap = new ConcurrentHashMap<>();
@PostConstruct
public void makeCache() {
List<CgyView> cgyViews = cgyViewDAO.selectByExample(new CgyViewExample());
if (CollectionUtils.isEmpty(cgyViews)) {
return;
}
cgyViews.forEach(cgyView -> {
CgyStatsBO bo = new CgyStatsBO(cgyView.getAppId(), cgyView.getAppSecret(),
cgyView.getFunctionId());
bo.setChange(new AtomicBoolean(true));
bo.setView(new AtomicLong(cgyView.getViewCount()));
makeCache(bo);
appStatsMap.put(cgyView.getAppId(), bo);
functionStatsMap.put(cgyView.getFunctionId(), bo);
});
}
/**
* 向虚仿平台同步数据
*/
@Scheduled(fixedRate = 2000)
public void syncData() {
appStatsMap.forEach((appId, statsBO) -> {
if (!statsBO.getChange().getAndSet(false)) {
return;
}
//同步汇总数据
Map<String, Object> body = new HashMap<>();
body.put("app_id", appId);
body.put("timestamp", System.currentTimeMillis());
body.put("view", statsBO.getView().get());
body.put("visitor", statsBO.getVisitor().get());
body.put("user", statsBO.getUserSet().size());
String sb = "app_id=" + body.get("app_id") + "&"
+ "timestamp=" + body.get("timestamp") + "&"
+ "user=" + body.get("user") + "&"
+ "view=" + body.get("view") + "&"
+ "visitor=" + body.get("visitor") + "&"
+ "app_secret=" + statsBO.getAppSecret();
body.put("sign", EncryptUtil.md5(sb).toLowerCase());
//扩展字段
body.put("duration", statsBO.getDuration().get() / 60); //分钟
SimulationInfoQueryVO queryVO = new SimulationInfoQueryVO();
queryVO.setFunctionId(statsBO.getFunctionId());
List<SimulationInfoVO> sims = simulationService.listAllSimulation(queryVO);
body.put("onlineUser", sims.size());
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(body, httpHeaders);
Map<String, String> resBody = restTemplate.postForObject(
"http://gdjtapp.cdivtc.edu.cn/api/applicationCenter/openapi/summary", httpEntity,
Map.class);
if (resBody != null && Objects.equals(resBody.get("code"), "100001")) {
log.error(String.format("成工院虚仿平台同步数据失败:[%s][%s]", resBody.get("msg"),
resBody.get("data")));
}
});
}
@Async("thirdAccountDataSyncExecutor")
@EventListener
public void syncUserSimulationUsing(UserSimulationRecordEvent event) {
UserSimulationRecord record = event.getRecord();
CgyStatsBO cgyStatsBO = functionStatsMap.get(record.getFunctionId());
if (Objects.nonNull(cgyStatsBO)) {
cgyStatsBO.getVisitor().incrementAndGet();
cgyStatsBO.getUserSet().add(record.getUserId());
cgyStatsBO.getDuration().addAndGet(record.getDuration());
cgyStatsBO.getChange().set(true);
}
}
/**
* 更新此App的浏览量数据
*/
public void updateView(String appId) {
CgyStatsBO cgyStatsBO = appStatsMap.get(appId);
if (cgyStatsBO == null) {
log.warn(String.format("成工院虚仿平台未知的appId%s", appId));
return;
}
long count = cgyStatsBO.getView().incrementAndGet();
CgyView record = new CgyView();
record.setAppId(appId);
record.setViewCount(count);
CgyViewExample example = new CgyViewExample();
example.createCriteria().andAppIdEqualTo(appId).andViewCountLessThan(count);
cgyViewDAO.updateByExampleSelective(record, example);
cgyStatsBO.getChange().set(true);
}
/**
* 实训人数实训人次实训时长缓存
*/
private void makeCache(CgyStatsBO bo) {
long visitor = 0;
long duration = 0;
//实训人数人次时长
List<UserSimulationRecord> records = userSimulationRecordService.listSimulationUsageRecords(
new SimulationUsageRecordQueryVO(null, bo.getFunctionId()));
if (!CollectionUtils.isEmpty(records)) {
visitor = records.size();
for (UserSimulationRecord record : records) {
bo.getUserSet().add(record.getUserId()); //实训人数
duration += record.getDuration();
}
}
bo.setVisitor(new AtomicLong(visitor)); //实训人次
bo.setDuration(new AtomicLong(duration)); //实训时长
}
}

View File

@ -15,6 +15,7 @@ import club.joylink.rtss.exception.PaperExceptionAssert;
import club.joylink.rtss.vo.AccountVO; import club.joylink.rtss.vo.AccountVO;
import club.joylink.rtss.vo.client.PageVO; import club.joylink.rtss.vo.client.PageVO;
import club.joylink.rtss.vo.paper.*; import club.joylink.rtss.vo.paper.*;
import club.joylink.rtss.vo.paper.PaperCompositionWithRuleVo.CreatorBasic;
import club.joylink.rtss.vo.paper.convertor.PaperCompositionConvertor; import club.joylink.rtss.vo.paper.convertor.PaperCompositionConvertor;
import club.joylink.rtss.vo.paper.convertor.PaperRuleConvertor; import club.joylink.rtss.vo.paper.convertor.PaperRuleConvertor;
import com.github.pagehelper.Page; import com.github.pagehelper.Page;
@ -37,139 +38,170 @@ import java.util.stream.Collectors;
@Slf4j @Slf4j
@Service @Service
public class PaperCompositionService { public class PaperCompositionService {
@Autowired
private PaperCompositionDAO compositionDAO;
@Autowired
private PaperRuleDAO ruleDAO;
@Autowired
private SysAccountDAO sysAccountDAO;
/** @Autowired
* 创建试卷蓝图包括规则定义 private PaperCompositionDAO compositionDAO;
*/ @Autowired
@Transactional(rollbackFor = Exception.class) private PaperRuleDAO ruleDAO;
public CreatePaperCompositionRspVo createPaperCompositionWithRule(PaperCompositionWithRuleVo req, AccountVO user) { @Autowired
//根据项目和名称来查如果存在则结束 private SysAccountDAO sysAccountDAO;
PaperExceptionAssert.PcNotExisted.assertTrue(Objects.nonNull(req.getMapId()), "请选择对应的线路");
List<PaperComposition> pcList = this.findCompositionByCompanyIdAndName(req.getOrgId(), req.getName());
PaperExceptionAssert.PcNotExisted.assertTrue(CollectionUtils.isEmpty(pcList), "试卷定义已经存在orgId=" + req.getOrgId() + " name=" + req.getName());
Optional<PaperCompositionWithRuleVo.PaperRuleVo> optionalRule = req.getRuleList().stream().filter(d->d.getSubtype() == PaperQType.SubType.Single
&& (Objects.isNull(d.getSubTypeParam()) || Objects.isNull(d.getSubTypeParam().getClient()))).findAny();
PaperExceptionAssert.PcNotHavePr.assertTrue(optionalRule.isEmpty(), "试卷规则-单操缺少客户端的定义"); /**
PaperComposition newPc = PaperCompositionConvertor.convertToBean(req); * 创建试卷蓝图包括规则定义
*/
@Transactional(rollbackFor = Exception.class)
public CreatePaperCompositionRspVo createPaperCompositionWithRule(PaperCompositionWithRuleVo req,
AccountVO user) {
//根据项目和名称来查如果存在则结束
PaperExceptionAssert.PcNotExisted.assertTrue(Objects.nonNull(req.getMapId()),
"请选择对应的线路");
List<PaperComposition> pcList = this.findCompositionByCompanyIdAndName(req.getOrgId(),
req.getName());
PaperExceptionAssert.PcNotExisted.assertTrue(CollectionUtils.isEmpty(pcList),
"试卷定义已经存在orgId=" + req.getOrgId() + " name=" + req.getName());
Optional<PaperCompositionWithRuleVo.PaperRuleVo> optionalRule = req.getRuleList().stream()
.filter(d -> d.getSubtype() == PaperQType.SubType.Single
&& (Objects.isNull(d.getSubTypeParam()) || Objects.isNull(
d.getSubTypeParam().getClient()))).findAny();
newPc.setCreateTime(LocalDateTime.now()); PaperExceptionAssert.PcNotHavePr.assertTrue(optionalRule.isEmpty(),
newPc.setUpdateTime(LocalDateTime.now()); "试卷规则-单操缺少客户端的定义");
newPc.setCreatorId(user.getId()); PaperComposition newPc = PaperCompositionConvertor.convertToBean(req);
newPc.setUpdateId(user.getId());
newPc.setState(PaperCompositionState.Editing.getValue());
compositionDAO.insertSelective(newPc);
if (!CollectionUtils.isEmpty(req.getRuleList())) { newPc.setCreateTime(LocalDateTime.now());
final Long pcId = newPc.getId(); newPc.setUpdateTime(LocalDateTime.now());
this.createPaperCompositionRule(pcId, req.getRuleList()); newPc.setCreatorId(user.getId());
} newPc.setUpdateId(user.getId());
// newPc.setState(PaperCompositionState.Editing.getValue());
CreatePaperCompositionRspVo rsp = new CreatePaperCompositionRspVo(); compositionDAO.insertSelective(newPc);
rsp.setId(newPc.getId());
rsp.setName(newPc.getName()); if (!CollectionUtils.isEmpty(req.getRuleList())) {
rsp.setProfile(newPc.getProfile()); final Long pcId = newPc.getId();
rsp.setOrgId(newPc.getOrgId()); this.createPaperCompositionRule(pcId, req.getRuleList());
return rsp;
} }
//
CreatePaperCompositionRspVo rsp = new CreatePaperCompositionRspVo();
rsp.setId(newPc.getId());
rsp.setName(newPc.getName());
rsp.setProfile(newPc.getProfile());
rsp.setOrgId(newPc.getOrgId());
return rsp;
}
private String ruleMapKey(PaperCompositionWithRuleVo.PaperRuleVo vo){ private String ruleMapKey(PaperCompositionWithRuleVo.PaperRuleVo vo) {
String key = String.format("%s-%s-%s",vo.getType(),vo.getSubtype(), CollectionUtils.isEmpty(vo.getTags())? "" : Joiner.on(",").join(vo.getTags())); String key = String.format("%s-%s-%s", vo.getType(), vo.getSubtype(),
return key; CollectionUtils.isEmpty(vo.getTags()) ? "" : Joiner.on(",").join(vo.getTags()));
return key;
}
/**
* 试卷蓝图添加规则
*/
private void createPaperCompositionRule(Long pcId,
List<PaperCompositionWithRuleVo.PaperRuleVo> reqList) {
Map<String, List<PaperCompositionWithRuleVo.PaperRuleVo>> tmpList = reqList.stream()
.collect(Collectors.groupingBy(this::ruleMapKey));
for (PaperCompositionWithRuleVo.PaperRuleVo req : reqList) {
req.setPcId(pcId);
PaperQType.assertPaperSubTypeMatchGroupType(req.getSubtype(), req.getType());
String key = this.ruleMapKey(req);
List<PaperCompositionWithRuleVo.PaperRuleVo> voList = tmpList.get(key);
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue(
!CollectionUtils.isEmpty(voList) && voList.size() <= 1,
String.format("试题规则类型[%s],规则类型[%s] 规则只能有一个",
PaperQType.GroupType.getTypeName(req.getType()),
PaperQType.SubType.getItemName(req.getSubtype())));
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue(
!CollectionUtils.isEmpty(req.getTags()) && req.getTags().size() <= 1,
String.format("试题规则类型[%s],规则类型[%s],分类%s最多只能有一个",
PaperQType.GroupType.getTypeName(req.getType()),
PaperQType.SubType.getItemName(req.getSubtype()), req.getTags()));
PaperRule rule = PaperRuleConvertor.convert(req);
ruleDAO.insertSelective(rule);
} }
}
/** /**
* 试卷蓝图添加规则 * 更新试卷蓝图包括规则定义
*/ */
private void createPaperCompositionRule(Long pcId, List<PaperCompositionWithRuleVo.PaperRuleVo> reqList) { @Transactional(rollbackFor = Exception.class)
Map<String,List<PaperCompositionWithRuleVo.PaperRuleVo>> tmpList = reqList.stream().collect(Collectors.groupingBy(this::ruleMapKey)); public void updatePaperCompositionWithRule(PaperCompositionWithRuleVo req, AccountVO user) {
PaperExceptionAssert.PcNotExisted.assertTrue(Objects.nonNull(req.getMapId()),
"请选择对应的线路");
Optional<PaperCompositionWithRuleVo.PaperRuleVo> optionalRule = req.getRuleList().stream()
.filter(d -> d.getSubtype() == PaperQType.SubType.Single
&& (Objects.isNull(d.getSubTypeParam()) || Objects.isNull(
d.getSubTypeParam().getClient()))).findAny();
PaperExceptionAssert.PcNotHavePr.assertTrue(optionalRule.isEmpty(),
"试卷规则-单操缺少客户端的定义");
for (PaperCompositionWithRuleVo.PaperRuleVo req : reqList) { PaperComposition curPc = compositionDAO.selectByPrimaryKey(req.getId());
req.setPcId(pcId); assertPaperCompositionCanModify(curPc);
PaperQType.assertPaperSubTypeMatchGroupType(req.getSubtype(), req.getType()); //
String key = this.ruleMapKey(req); List<PaperComposition> pcList = this.findCompositionByCompanyIdAndName(req.getOrgId(),
List<PaperCompositionWithRuleVo.PaperRuleVo> voList = tmpList.get(key); req.getName());
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue(!CollectionUtils.isEmpty(voList) && voList.size() <= 1 ,String.format("试题规则类型[%s],规则类型[%s] 规则只能有一个", PaperQType.GroupType.getTypeName(req.getType()), PaperQType.SubType.getItemName(req.getSubtype()))); if (!CollectionUtils.isEmpty(pcList)) {
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue(!CollectionUtils.isEmpty(req.getTags()) && req.getTags().size() <= 1 ,String.format("试题规则类型[%s],规则类型[%s],分类%s最多只能有一个", PaperQType.GroupType.getTypeName(req.getType()), PaperQType.SubType.getItemName(req.getSubtype()),req.getTags())); boolean exist = pcList.stream().anyMatch(c -> c.getId().compareTo(curPc.getId()) != 0);
PaperRule rule = PaperRuleConvertor.convert(req); PaperExceptionAssert.PcExisted.assertNotTrue(exist,
ruleDAO.insertSelective(rule); "试卷定义已经存在orgId=" + req.getOrgId() + " name=" + req.getName());
}
} }
PaperComposition newPc = PaperCompositionConvertor.convertToBean(req);
newPc.setId(curPc.getId());
newPc.setUpdateTime(LocalDateTime.now());
curPc.setUpdateId(user.getId());
compositionDAO.updateByPrimaryKeySelective(newPc);
// 更新规则
this.updateCompositionRule(req.getRuleList(), req.getId());
}
/** private void updateCompositionRule(List<PaperCompositionWithRuleVo.PaperRuleVo> updateRuleList,
* 更新试卷蓝图包括规则定义 Long pcId) {
*/ PaperRuleExample ruleExample = new PaperRuleExample();
@Transactional(rollbackFor = Exception.class) ruleExample.createCriteria().andPcIdEqualTo(pcId);
public void updatePaperCompositionWithRule(PaperCompositionWithRuleVo req, AccountVO user) { this.ruleDAO.deleteByExample(ruleExample);
PaperExceptionAssert.PcNotExisted.assertTrue(Objects.nonNull(req.getMapId()), "请选择对应的线路"); this.createPaperCompositionRule(pcId, updateRuleList);
Optional<PaperCompositionWithRuleVo.PaperRuleVo> optionalRule = req.getRuleList().stream().filter(d->d.getSubtype() == PaperQType.SubType.Single }
&& (Objects.isNull(d.getSubTypeParam()) || Objects.isNull(d.getSubTypeParam().getClient()))).findAny();
PaperExceptionAssert.PcNotHavePr.assertTrue(optionalRule.isEmpty(), "试卷规则-单操缺少客户端的定义");
PaperComposition curPc = compositionDAO.selectByPrimaryKey(req.getId()); /**
assertPaperCompositionCanModify(curPc); * 将编辑好的试卷蓝图封存
// */
List<PaperComposition> pcList = this.findCompositionByCompanyIdAndName(req.getOrgId(), req.getName()); @Transactional(rollbackFor = Exception.class)
if (!CollectionUtils.isEmpty(pcList)) { public void lockPaperComposition(Long pcId, AccountVO user) {
boolean exist = pcList.stream().anyMatch(c ->c.getId().compareTo(curPc.getId()) != 0); PaperComposition curPc = compositionDAO.selectByPrimaryKey(pcId);
PaperExceptionAssert.PcExisted.assertNotTrue(exist, "试卷定义已经存在orgId=" + req.getOrgId() + " name=" + req.getName()); PaperExceptionAssert.PcCanModify.assertTrue(
} null != curPc && PaperCompositionState.Editing.equals(
PaperComposition newPc = PaperCompositionConvertor.convertToBean(req); PaperCompositionState.getItem(curPc.getState())), "试卷定义不存在或非编辑中");
newPc.setId(curPc.getId()); PaperExceptionAssert.PcScore.assertTrue(this.checkRulesScoreEqualFull(curPc.getId()),
newPc.setUpdateTime(LocalDateTime.now()); "规则总分值不等于试卷总分值");
curPc.setUpdateId(user.getId()); //
compositionDAO.updateByPrimaryKeySelective(newPc); PaperComposition nPc = new PaperComposition();
// 更新规则 nPc.setId(curPc.getId());
this.updateCompositionRule(req.getRuleList(), req.getId()); nPc.setState(PaperCompositionState.Locked.getValue());
} compositionDAO.updateByPrimaryKeySelective(nPc);
// 封存试卷时校验总分值与规则总分值是否相等
}
private void updateCompositionRule(List<PaperCompositionWithRuleVo.PaperRuleVo> updateRuleList, Long pcId) { /**
PaperRuleExample ruleExample = new PaperRuleExample(); * 将封存的试卷蓝图设置失效
ruleExample.createCriteria().andPcIdEqualTo(pcId); */
this.ruleDAO.deleteByExample(ruleExample); @Transactional(rollbackFor = Exception.class)
this.createPaperCompositionRule(pcId,updateRuleList); public void unlockPaperComposition(Long pcId, AccountVO user) {
} PaperComposition curPc = compositionDAO.selectByPrimaryKey(pcId);
PaperExceptionAssert.PcCanModify.assertTrue(
null != curPc && PaperCompositionState.Locked.equals(
PaperCompositionState.getItem(curPc.getState())), "试卷定义不存在或非封存中");
//
PaperComposition nPc = new PaperComposition();
nPc.setId(curPc.getId());
nPc.setState(PaperCompositionState.Invalid.getValue());
nPc.setUpdateId(user.getId());
compositionDAO.updateByPrimaryKeySelective(nPc);
}
/** /**
* 将编辑好的试卷蓝图封存 * 标记已封存的试卷已使用
*/ */
@Transactional(rollbackFor = Exception.class)
public void lockPaperComposition(Long pcId, AccountVO user) {
PaperComposition curPc = compositionDAO.selectByPrimaryKey(pcId);
PaperExceptionAssert.PcCanModify.assertTrue(null != curPc && PaperCompositionState.Editing.equals(PaperCompositionState.getItem(curPc.getState())), "试卷定义不存在或非编辑中");
PaperExceptionAssert.PcScore.assertTrue(this.checkRulesScoreEqualFull(curPc.getId()), "规则总分值不等于试卷总分值");
//
PaperComposition nPc = new PaperComposition();
nPc.setId(curPc.getId());
nPc.setState(PaperCompositionState.Locked.getValue());
compositionDAO.updateByPrimaryKeySelective(nPc);
// 封存试卷时校验总分值与规则总分值是否相等
}
/**
* 将封存的试卷蓝图设置失效
*/
@Transactional(rollbackFor = Exception.class)
public void unlockPaperComposition(Long pcId, AccountVO user) {
PaperComposition curPc = compositionDAO.selectByPrimaryKey(pcId);
PaperExceptionAssert.PcCanModify.assertTrue(null != curPc && PaperCompositionState.Locked.equals(PaperCompositionState.getItem(curPc.getState())), "试卷定义不存在或非封存中");
//
PaperComposition nPc = new PaperComposition();
nPc.setId(curPc.getId());
nPc.setState(PaperCompositionState.Invalid.getValue());
nPc.setUpdateId(user.getId());
compositionDAO.updateByPrimaryKeySelective(nPc);
}
/**
* 标记已封存的试卷已使用
*/
/* @Transactional(rollbackFor = Exception.class) /* @Transactional(rollbackFor = Exception.class)
public void usePaperComposition(Long pcId) { public void usePaperComposition(Long pcId) {
PaperComposition curPc = compositionDAO.selectByPrimaryKey(pcId); PaperComposition curPc = compositionDAO.selectByPrimaryKey(pcId);
@ -181,289 +213,299 @@ public class PaperCompositionService {
} }
}*/ }*/
/** /**
* 删除试卷蓝图(只能删除处于编辑状态的) * 删除试卷蓝图(只能删除处于编辑状态的)
* *
* @param pcId 试卷蓝图id * @param pcId 试卷蓝图id
*/ */
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void deletePaperComposition(Long pcId, AccountVO user) { public void deletePaperComposition(Long pcId, AccountVO user) {
PaperComposition curPc = compositionDAO.selectByPrimaryKey(pcId); PaperComposition curPc = compositionDAO.selectByPrimaryKey(pcId);
if (null != curPc) { if (null != curPc) {
assertPaperCompositionCanModify(curPc); assertPaperCompositionCanModify(curPc);
//先删除试卷定义中的规则 //先删除试卷定义中的规则
PaperRuleExample ruleExample = new PaperRuleExample(); PaperRuleExample ruleExample = new PaperRuleExample();
ruleExample.createCriteria().andPcIdEqualTo(pcId); ruleExample.createCriteria().andPcIdEqualTo(pcId);
ruleDAO.deleteByExample(ruleExample); ruleDAO.deleteByExample(ruleExample);
//删除试卷定义 //删除试卷定义
compositionDAO.deleteByPrimaryKey(pcId); compositionDAO.deleteByPrimaryKey(pcId);
}
} }
}
/** /**
* 断言试卷蓝图可以修改 * 断言试卷蓝图可以修改
*/ */
@Transactional(readOnly = true) @Transactional(readOnly = true)
public void assertPaperCompositionCanModify(Long pcId) { public void assertPaperCompositionCanModify(Long pcId) {
PaperComposition curPc = compositionDAO.selectByPrimaryKey(pcId); PaperComposition curPc = compositionDAO.selectByPrimaryKey(pcId);
this.assertPaperCompositionCanModify(curPc); this.assertPaperCompositionCanModify(curPc);
} }
/** /**
* 断言试卷蓝图可以修改 * 断言试卷蓝图可以修改
*/ */
public void assertPaperCompositionCanModify(PaperComposition curPc) { public void assertPaperCompositionCanModify(PaperComposition curPc) {
PaperExceptionAssert.PcCanModify.assertTrue(null != curPc && PaperCompositionState.Editing.equals(PaperCompositionState.getItem(curPc.getState())), "试卷定义不存在或状态非编辑中不能修改pcId = " + curPc.getId()); PaperExceptionAssert.PcCanModify.assertTrue(
} null != curPc && PaperCompositionState.Editing.equals(
PaperCompositionState.getItem(curPc.getState())),
"试卷定义不存在或状态非编辑中不能修改pcId = " + curPc.getId());
}
@Transactional(readOnly = true) @Transactional(readOnly = true)
public PageVO<PaperCompositionWithRuleVo> findPaperCompositionByPageForAccount(FindPaperCompositionByAccountReqVo req) { public PageVO<PaperCompositionWithRuleVo> findPaperCompositionByPageForAccount(
PaperExceptionAssert.PpValid.assertTrue(null != req.getAccount() || null != req.getUserId(), "账号和用户id不能同时为空"); FindPaperCompositionByAccountReqVo req) {
Long userId = req.getUserId(); PaperExceptionAssert.PpValid.assertTrue(null != req.getAccount() || null != req.getUserId(),
if (null == userId) { "账号和用户id不能同时为空");
SysAccountExample accountExample = new SysAccountExample(); Long userId = req.getUserId();
// if (null == userId) {
SysAccountExample.Criteria mobileC = accountExample.or(); SysAccountExample accountExample = new SysAccountExample();
mobileC.andMobileEqualTo(req.getAccount()); //
if (null != req.getPwd()) { SysAccountExample.Criteria mobileC = accountExample.or();
mobileC.andPasswordEqualTo(req.getPwd()); mobileC.andMobileEqualTo(req.getAccount());
} if (null != req.getPwd()) {
// mobileC.andPasswordEqualTo(req.getPwd());
SysAccountExample.Criteria emailC = accountExample.or(); }
emailC.andEmailEqualTo(req.getAccount()); //
if (null != req.getPwd()) { SysAccountExample.Criteria emailC = accountExample.or();
emailC.andPasswordEqualTo(req.getPwd()); emailC.andEmailEqualTo(req.getAccount());
} if (null != req.getPwd()) {
// emailC.andPasswordEqualTo(req.getPwd());
SysAccountExample.Criteria accountC = accountExample.or(); }
accountC.andAccountEqualTo(req.getAccount()); //
if (null != req.getPwd()) { SysAccountExample.Criteria accountC = accountExample.or();
accountC.andPasswordEqualTo(req.getPwd()); accountC.andAccountEqualTo(req.getAccount());
} if (null != req.getPwd()) {
// accountC.andPasswordEqualTo(req.getPwd());
List<SysAccount> users = this.sysAccountDAO.selectByExample(accountExample); }
PaperExceptionAssert.PdValid.assertTrue(null != users && users.size() == 1, "用户不存在或根据账户信息匹配了多个"); //
userId = users.get(0).getId(); List<SysAccount> users = this.sysAccountDAO.selectByExample(accountExample);
} PaperExceptionAssert.PdValid.assertTrue(null != users && users.size() == 1,
// "用户不存在或根据账户信息匹配了多个");
PaperCompositionExample pcEx = new PaperCompositionExample(); userId = users.get(0).getId();
PaperCompositionExample.Criteria pcExCriteria = pcEx.createCriteria();
pcExCriteria.andCreatorIdEqualTo(userId);
List<PaperCompositionState> findStates = req.stateList();
pcExCriteria.andStateIn(findStates.stream().map(pcState -> {
return pcState.getValue();
}).collect(Collectors.toList()));
//
//1--创建时间 2--更新时间 3--名称默认值为1
String orderBy = "create_time";
switch (req.getOrderBy()) {
case 1:
orderBy = "create_time";
break;
case 2:
orderBy = "update_time";
break;
case 3:
orderBy = "name";
break;
}
orderBy+=(req.getDesc()?" desc":"");
//
PageHelper.clearPage();
PageHelper.startPage(req.getPageNum(),req.getPageSize(),orderBy);
Page<PaperComposition> sqlPage = (Page<PaperComposition>) compositionDAO.selectByExample(pcEx);
//
final List<PaperCompositionWithRuleVo> rtList = new ArrayList<>();
if(!CollectionUtils.isEmpty(sqlPage.getResult())){
sqlPage.getResult().forEach(pc->{
List<PaperRule> prList = this.findRuleByPcId(pc.getId());
rtList.add(PaperCompositionConvertor.convert(pc, prList));
});
}
//
PageVO<PaperCompositionWithRuleVo> page = PageVO.convert(sqlPage,rtList);
//
if (!CollectionUtils.isEmpty(page.getList())) {
page.getList().forEach(pc -> {
pc.setCreatorInfo(this.findCreatorInfo(pc.getCreatorId()));
});
}
//
return page;
} }
//
PaperCompositionExample pcEx = new PaperCompositionExample();
PaperCompositionExample.Criteria pcExCriteria = pcEx.createCriteria();
pcExCriteria.andCreatorIdEqualTo(userId);
List<PaperCompositionState> findStates = req.stateList();
pcExCriteria.andStateIn(findStates.stream().map(pcState -> {
return pcState.getValue();
}).collect(Collectors.toList()));
//
//1--创建时间 2--更新时间 3--名称默认值为1
String orderBy = "create_time";
switch (req.getOrderBy()) {
case 1:
orderBy = "create_time";
break;
case 2:
orderBy = "update_time";
break;
case 3:
orderBy = "name";
break;
}
orderBy += (req.getDesc() ? " desc" : "");
//
PageHelper.clearPage();
PageHelper.startPage(req.getPageNum(), req.getPageSize(), orderBy);
Page<PaperComposition> sqlPage = (Page<PaperComposition>) compositionDAO.selectByExample(pcEx);
//
final List<PaperCompositionWithRuleVo> rtList = new ArrayList<>();
if (!CollectionUtils.isEmpty(sqlPage.getResult())) {
sqlPage.getResult().forEach(pc -> {
List<PaperRule> prList = this.findRuleByPcId(pc.getId());
rtList.add(PaperCompositionConvertor.convert(pc, prList));
});
}
//
PageVO<PaperCompositionWithRuleVo> page = PageVO.convert(sqlPage, rtList);
//
if (!CollectionUtils.isEmpty(page.getList())) {
page.getList().forEach(pc -> {
pc.setCreatorInfo(this.findCreatorInfo(pc.getCreatorId()));
});
}
//
return page;
}
/** /**
* 返回蓝图的列表基本信息 * 返回蓝图的列表基本信息
*/ */
public List<PaperCompositionWithRuleVo> findPaperCompositionList(FindPaperCompositionPageReqVo req){ public List<PaperCompositionWithRuleVo> findPaperCompositionList(
PaperCompositionExample pcEx = this.queryExample(req); FindPaperCompositionPageReqVo req) {
pcEx.setOrderByClause(" create_time desc "); PaperCompositionExample pcEx = this.queryExample(req);
List<PaperComposition> sqlPage = compositionDAO.selectByExample(pcEx); pcEx.setOrderByClause(" create_time desc ");
// List<PaperComposition> sqlPage = compositionDAO.selectByExample(pcEx);
final List<PaperCompositionWithRuleVo> rtList = new ArrayList<>(); //
for (PaperComposition pc : sqlPage) { final List<PaperCompositionWithRuleVo> rtList = new ArrayList<>();
rtList.add(PaperCompositionConvertor.convert(pc,null)); for (PaperComposition pc : sqlPage) {
} rtList.add(PaperCompositionConvertor.convert(pc, null));
return rtList;
} }
return rtList;
}
private PaperCompositionExample queryExample(FindPaperCompositionPageReqVo req){ private PaperCompositionExample queryExample(FindPaperCompositionPageReqVo req) {
PaperCompositionExample pcEx = new PaperCompositionExample(); PaperCompositionExample pcEx = new PaperCompositionExample();
PaperCompositionExample.Criteria pcExCriteria = pcEx.createCriteria(); PaperCompositionExample.Criteria pcExCriteria = pcEx.createCriteria();
if (Objects.nonNull(req.getOrgId())) { if (Objects.nonNull(req.getOrgId())) {
pcExCriteria.andOrgIdEqualTo(req.getOrgId()); pcExCriteria.andOrgIdEqualTo(req.getOrgId());
}
if(Objects.nonNull(req.getMapId())){
pcExCriteria.andMapIdEqualTo(req.getMapId());
}
if (StringUtils.hasText(req.getName())) {
if (req.getNameLike()) {
pcExCriteria.andNameLike(String.format("%%%s%%", req.getName()));
} else {
pcExCriteria.andNameEqualTo(req.getName());
}
}
if (StringUtils.hasText(req.getProfile())) {
if (req.getProfileLike()) {
pcExCriteria.andProfileLike(String.format("%%%s%%", req.getProfile()));
} else {
pcExCriteria.andProfileEqualTo(req.getProfile());
}
}
List<PaperCompositionState> findStates = req.stateList();
pcExCriteria.andStateIn(findStates.stream().map(pcState -> {
return pcState.getValue();
}).collect(Collectors.toList()));
return pcEx;
} }
/** if (Objects.nonNull(req.getMapId())) {
* 分页查找试卷蓝图 pcExCriteria.andMapIdEqualTo(req.getMapId());
*/
@Transactional(readOnly = true)
public PageVO<PaperCompositionWithRuleVo> findPaperCompositionByPage(FindPaperCompositionPageReqVo req) {
PaperCompositionExample pcEx = this.queryExample(req);
//
//1--创建时间 2--更新时间 3--名称默认值为1
String orderBy = "create_time";
switch (req.getOrderBy()) {
case 1:
orderBy = "create_time";
break;
case 2:
orderBy = "update_time";
break;
case 3:
orderBy = "name";
break;
}
orderBy+=(req.getDesc()?" desc":"");
//
PageHelper.clearPage();
PageHelper.startPage(req.getPageNum(),req.getPageSize(),orderBy);
Page<PaperComposition> sqlPage = (Page<PaperComposition>) compositionDAO.selectByExample(pcEx);
//
final List<PaperCompositionWithRuleVo> rtList = new ArrayList<>();
if(!CollectionUtils.isEmpty(sqlPage.getResult())){
for (PaperComposition pc : sqlPage.getResult()) {
List<PaperRule> prList = this.findRuleByPcId(pc.getId());
rtList.add(PaperCompositionConvertor.convert(pc, prList));
}
}
//
PageVO<PaperCompositionWithRuleVo> page = PageVO.convert(sqlPage,rtList);
//
if (!CollectionUtils.isEmpty(page.getList())) {
page.getList().forEach(pc -> {
pc.setCreatorInfo(this.findCreatorInfo(pc.getCreatorId()));
});
}
//
return page;
} }
if (StringUtils.hasText(req.getName())) {
if (req.getNameLike()) {
pcExCriteria.andNameLike(String.format("%%%s%%", req.getName()));
} else {
pcExCriteria.andNameEqualTo(req.getName());
}
}
if (StringUtils.hasText(req.getProfile())) {
if (req.getProfileLike()) {
pcExCriteria.andProfileLike(String.format("%%%s%%", req.getProfile()));
} else {
pcExCriteria.andProfileEqualTo(req.getProfile());
}
}
if (req.getCreatorId() != null) {
pcExCriteria.andCreatorIdEqualTo(req.getCreatorId());
}
List<PaperCompositionState> findStates = req.stateList();
pcExCriteria.andStateIn(findStates.stream().map(pcState -> {
return pcState.getValue();
}).collect(Collectors.toList()));
return pcEx;
}
private PaperCompositionWithRuleVo.CreatorBasic findCreatorInfo(Long creatorId) { /**
SysAccount sa = this.sysAccountDAO.selectByPrimaryKey(creatorId); * 分页查找试卷蓝图
if (null != sa) { */
PaperCompositionWithRuleVo.CreatorBasic rt = new PaperCompositionWithRuleVo.CreatorBasic(); @Transactional(readOnly = true)
rt.setId(sa.getId()); public PageVO<PaperCompositionWithRuleVo> findPaperCompositionByPage(
rt.setName(sa.getName()); FindPaperCompositionPageReqVo req) {
rt.setAccount(sa.getAccount()); PaperCompositionExample pcEx = this.queryExample(req);
rt.setMobile(sa.getMobile()); //
rt.setEmail(sa.getEmail()); //1--创建时间 2--更新时间 3--名称默认值为1
return rt; String orderBy = "create_time";
} switch (req.getOrderBy()) {
return null; case 1:
orderBy = "create_time";
break;
case 2:
orderBy = "update_time";
break;
case 3:
orderBy = "name";
break;
} }
orderBy += (req.getDesc() ? " desc" : "");
//
PageHelper.clearPage();
PageHelper.startPage(req.getPageNum(), req.getPageSize(), orderBy);
Page<PaperComposition> sqlPage = (Page<PaperComposition>) compositionDAO.selectByExample(pcEx);
//
final List<PaperCompositionWithRuleVo> rtList = new ArrayList<>();
if (!CollectionUtils.isEmpty(sqlPage.getResult())) {
for (PaperComposition pc : sqlPage.getResult()) {
List<PaperRule> prList = this.findRuleByPcId(pc.getId());
rtList.add(PaperCompositionConvertor.convert(pc, prList));
}
}
//
PageVO<PaperCompositionWithRuleVo> page = PageVO.convert(sqlPage, rtList);
//
if (!CollectionUtils.isEmpty(page.getList())) {
page.getList().forEach(pc -> {
pc.setCreatorInfo(this.findCreatorInfo(pc.getCreatorId()));
});
}
//
return page;
}
/** private PaperCompositionWithRuleVo.CreatorBasic findCreatorInfo(Long creatorId) {
* 获取试卷完整的蓝图包括规则 SysAccount sa = this.sysAccountDAO.selectByPrimaryKey(creatorId);
* if (null != sa) {
* @param pcId 试卷蓝图id PaperCompositionWithRuleVo.CreatorBasic rt = new PaperCompositionWithRuleVo.CreatorBasic();
*/ rt.setId(sa.getId());
@Transactional(readOnly = true) if (StringUtils.hasText(sa.getName())) {
public PaperCompositionWithRuleVo findPaperComposition(Long pcId, AccountVO user) { rt.setName(sa.getName());
PaperComposition curPc = compositionDAO.selectByPrimaryKey(pcId); } else {
PaperExceptionAssert.PcExisted.assertTrue(null != curPc, "试卷定义不存在id=" + pcId); rt.setName("昵称:" + sa.getNickname());
List<PaperRule> paperRuleList = this.findRuleByPcId(pcId); }
// rt.setAccount(sa.getAccount());
PaperCompositionWithRuleVo rt = PaperCompositionConvertor.convert(curPc, paperRuleList); rt.setMobile(sa.getMobile());
rt.setCreatorInfo(this.findCreatorInfo(rt.getCreatorId())); rt.setEmail(sa.getEmail());
return rt; return rt;
} }
return null;
}
/** /**
* 根据试卷蓝图的项目和名称查找项目 * 获取试卷完整的蓝图包括规则
*/ *
@Transactional(readOnly = true) * @param pcId 试卷蓝图id
public List<PaperComposition> findCompositionByCompanyIdAndName(Long orgId, String name) { */
PaperCompositionExample example = new PaperCompositionExample(); @Transactional(readOnly = true)
example.createCriteria().andOrgIdEqualTo(orgId).andNameEqualTo(name); public PaperCompositionWithRuleVo findPaperComposition(Long pcId, AccountVO user) {
List<PaperComposition> list = compositionDAO.selectByExample(example); PaperComposition curPc = compositionDAO.selectByPrimaryKey(pcId);
return list; PaperExceptionAssert.PcExisted.assertTrue(null != curPc, "试卷定义不存在id=" + pcId);
} List<PaperRule> paperRuleList = this.findRuleByPcId(pcId);
//
PaperCompositionWithRuleVo rt = PaperCompositionConvertor.convert(curPc, paperRuleList);
rt.setCreatorInfo(this.findCreatorInfo(rt.getCreatorId()));
return rt;
}
/** /**
* 查询试卷蓝图的所有规则 * 根据试卷蓝图的项目和名称查找项目
* */
* @param pcId 试卷蓝图的id @Transactional(readOnly = true)
*/ public List<PaperComposition> findCompositionByCompanyIdAndName(Long orgId, String name) {
@Transactional(readOnly = true) PaperCompositionExample example = new PaperCompositionExample();
public List<PaperRule> findRuleByPcId(Long pcId) { example.createCriteria().andOrgIdEqualTo(orgId).andNameEqualTo(name);
PaperRuleExample example = new PaperRuleExample(); List<PaperComposition> list = compositionDAO.selectByExample(example);
example.createCriteria().andPcIdEqualTo(pcId); return list;
return ruleDAO.selectByExample(example); }
}
/** /**
* 校验规则当前规定的总分值是否小于等于试卷蓝图中的满分 * 查询试卷蓝图的所有规则
*/ *
private boolean checkRulesScoreLessOrEqualFull(Long pcId) { * @param pcId 试卷蓝图的id
PaperComposition curPc = compositionDAO.selectByPrimaryKey(pcId); */
PaperExceptionAssert.PcExisted.assertTrue(null != curPc, String.format("试卷定义[id = %s]不存在", pcId)); @Transactional(readOnly = true)
List<PaperRule> ruleList = findRuleByPcId(pcId); public List<PaperRule> findRuleByPcId(Long pcId) {
int ruleScore = 0; PaperRuleExample example = new PaperRuleExample();
if (!CollectionUtils.isEmpty(ruleList)) { example.createCriteria().andPcIdEqualTo(pcId);
ruleScore = ruleList.stream().mapToInt(rule -> { return ruleDAO.selectByExample(example);
return rule.getScore() * rule.getAmount(); }
}).sum();
}
return ruleScore <= curPc.getFullScore();
}
/** public List<CreatorBasic> queryCreatorList(FindPaperCompositionPageReqVo req) {
* 校验规则当前规定的总分值是否等于试卷蓝图中的满分 List<CreatorBasic> creators = new ArrayList<>();
*/ List<PaperCompositionWithRuleVo> rules = findPaperCompositionList(req);
private boolean checkRulesScoreEqualFull(Long pcId) { rules.stream().map(PaperCompositionWithRuleVo::getCreatorId)
PaperComposition curPc = compositionDAO.selectByPrimaryKey(pcId); .distinct()
PaperExceptionAssert.PcExisted.assertTrue(null != curPc, String.format("试卷定义[id = %s]不存在", pcId)); .forEach(creatorId -> creators.add(this.findCreatorInfo(creatorId)));
List<PaperRule> ruleList = findRuleByPcId(pcId); return creators;
int ruleScore = 0; }
if (!CollectionUtils.isEmpty(ruleList)) {
ruleScore = ruleList.stream().mapToInt(rule -> { /**
return rule.getScore() * rule.getAmount(); * 校验规则当前规定的总分值是否等于试卷蓝图中的满分
}).sum(); */
} private boolean checkRulesScoreEqualFull(Long pcId) {
return ruleScore == curPc.getFullScore(); PaperComposition curPc = compositionDAO.selectByPrimaryKey(pcId);
PaperExceptionAssert.PcExisted.assertTrue(null != curPc,
String.format("试卷定义[id = %s]不存在", pcId));
List<PaperRule> ruleList = findRuleByPcId(pcId);
int ruleScore = 0;
if (!CollectionUtils.isEmpty(ruleList)) {
ruleScore = ruleList.stream().mapToInt(rule -> {
return rule.getScore() * rule.getAmount();
}).sum();
} }
return ruleScore == curPc.getFullScore();
}
} }

View File

@ -34,6 +34,8 @@ import club.joylink.rtss.vo.client.project.UDPClientConfigVO;
import club.joylink.rtss.vo.client.project.UDPLowConfigVO; import club.joylink.rtss.vo.client.project.UDPLowConfigVO;
import club.joylink.rtss.vo.client.project.VrIbpConfigVO; import club.joylink.rtss.vo.client.project.VrIbpConfigVO;
import club.joylink.rtss.vo.client.project.VrpsdConfigVO; import club.joylink.rtss.vo.client.project.VrpsdConfigVO;
import club.joylink.rtss.vo.client.project.cgy.CgyPslConfigVO;
import club.joylink.rtss.vo.client.project.cgy.CgySectionConfigVO;
import club.joylink.rtss.vo.client.project.cgy.CgySignalConfigVO; import club.joylink.rtss.vo.client.project.cgy.CgySignalConfigVO;
import club.joylink.rtss.vo.client.project.cgy.CgySwitchConfigVO; import club.joylink.rtss.vo.client.project.cgy.CgySwitchConfigVO;
import club.joylink.rtss.vo.client.project.gzb.GzbSignalConfigVO; import club.joylink.rtss.vo.client.project.gzb.GzbSignalConfigVO;
@ -579,7 +581,7 @@ public class DeviceServiceImpl implements DeviceService {
plcGateway.setType(ProjectDeviceType.PLC_GATEWAY.name()); plcGateway.setType(ProjectDeviceType.PLC_GATEWAY.name());
plcGateway.setCreator(accountVO.getId()); plcGateway.setCreator(accountVO.getId());
plcGateway.setCreateTime(now); plcGateway.setCreateTime(now);
PlcGatewayConfigVO plcGatewayConfigVO = new PlcGatewayConfigVO(0, 16); PlcGatewayConfigVO plcGatewayConfigVO = new PlcGatewayConfigVO(0, 64);
plcGateway.setConfig(plcGatewayConfigVO.toJson()); plcGateway.setConfig(plcGatewayConfigVO.toJson());
list.add(plcGateway); list.add(plcGateway);
//SIGNAL //SIGNAL
@ -589,7 +591,7 @@ public class DeviceServiceImpl implements DeviceService {
signal1.setType(ProjectDeviceType.SIGNAL.name()); signal1.setType(ProjectDeviceType.SIGNAL.name());
signal1.setCreator(accountVO.getId()); signal1.setCreator(accountVO.getId());
signal1.setCreateTime(now); signal1.setCreateTime(now);
signal1.setConfig(new CgySignalConfigVO(null, 2, 3, 4, 11, 12, 13).toJson()); signal1.setConfig(new CgySignalConfigVO("S13289", 0, 1, 2, 3, 4, 5, 16, 17, 18, 19).toJson());
list.add(signal1); list.add(signal1);
ProjectDevice signal2 = new ProjectDevice(); ProjectDevice signal2 = new ProjectDevice();
signal2.setProjectCode(projectCode); signal2.setProjectCode(projectCode);
@ -597,7 +599,7 @@ public class DeviceServiceImpl implements DeviceService {
signal2.setType(ProjectDeviceType.SIGNAL.name()); signal2.setType(ProjectDeviceType.SIGNAL.name());
signal2.setCreator(accountVO.getId()); signal2.setCreator(accountVO.getId());
signal2.setCreateTime(now); signal2.setCreateTime(now);
signal2.setConfig(new CgySignalConfigVO(null, 5, 6, 7, 14, 15, 16).toJson()); signal2.setConfig(new CgySignalConfigVO("X44854", 6, 7, 8, 9, 10, 11, 20, 21, 22, 23).toJson());
list.add(signal2); list.add(signal2);
//SWITCH //SWITCH
ProjectDevice aSwitch = new ProjectDevice(); ProjectDevice aSwitch = new ProjectDevice();
@ -606,17 +608,50 @@ public class DeviceServiceImpl implements DeviceService {
aSwitch.setType(ProjectDeviceType.SWITCH.name()); aSwitch.setType(ProjectDeviceType.SWITCH.name());
aSwitch.setCreator(accountVO.getId()); aSwitch.setCreator(accountVO.getId());
aSwitch.setCreateTime(now); aSwitch.setCreateTime(now);
aSwitch.setConfig(new CgySwitchConfigVO().toJson()); aSwitch.setConfig(new CgySwitchConfigVO("W37779").toJson());
list.add(aSwitch); list.add(aSwitch);
// //SECTION //PSL
// ProjectDevice section = new ProjectDevice(); ProjectDevice psl = new ProjectDevice();
// section.setProjectCode(projectCode); psl.setProjectCode(projectCode);
// section.setCode(prefix + "section"); psl.setCode(prefix + "psl");
// section.setType(ProjectDeviceType.SECTION.name()); psl.setType(ProjectDeviceType.PSL.name());
// section.setCreator(accountVO.getId()); psl.setCreator(accountVO.getId());
// section.setCreateTime(now); psl.setCreateTime(now);
// section.setConfig(new CgySectionConfigVO().toJson()); psl.setConfig(new CgyPslConfigVO("PF59020_PSL").toJson());
// list.add(section); list.add(psl);
//SECTION
ProjectDevice section106 = new ProjectDevice();
section106.setProjectCode(projectCode);
section106.setCode(prefix + "section106");
section106.setType(ProjectDeviceType.SECTION.name());
section106.setCreator(accountVO.getId());
section106.setCreateTime(now);
section106.setConfig(new CgySectionConfigVO(null, 35).toJson());
list.add(section106);
ProjectDevice section104 = new ProjectDevice();
section104.setProjectCode(projectCode);
section104.setCode(prefix + "section104");
section104.setType(ProjectDeviceType.SECTION.name());
section104.setCreator(accountVO.getId());
section104.setCreateTime(now);
section104.setConfig(new CgySectionConfigVO(null, 36).toJson());
list.add(section104);
ProjectDevice section101 = new ProjectDevice();
section101.setProjectCode(projectCode);
section101.setCode(prefix + "section101");
section101.setType(ProjectDeviceType.SECTION.name());
section101.setCreator(accountVO.getId());
section101.setCreateTime(now);
section101.setConfig(new CgySectionConfigVO(null, 37).toJson());
list.add(section101);
ProjectDevice section102 = new ProjectDevice();
section102.setProjectCode(projectCode);
section102.setCode(prefix + "section102");
section102.setType(ProjectDeviceType.SECTION.name());
section102.setCreator(accountVO.getId());
section102.setCreateTime(now);
section102.setConfig(new CgySectionConfigVO(null, 38).toJson());
list.add(section102);
return list; return list;
} }

View File

@ -12,152 +12,166 @@ import club.joylink.rtss.simulation.cbtc.data.map.Stand;
import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealityPsl; import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealityPsl;
import club.joylink.rtss.simulation.cbtc.event.SimulationPslStatusEvent; import club.joylink.rtss.simulation.cbtc.event.SimulationPslStatusEvent;
import club.joylink.rtss.vo.client.psl.PslStatus; import club.joylink.rtss.vo.client.psl.PslStatus;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import java.util.HashMap;
import java.util.Map;
@Service @Service
public class VirtualRealityPslService implements IVirtualRealityPslService { public class VirtualRealityPslService implements IVirtualRealityPslService {
@Autowired @Autowired
private GroupSimulationService groupSimulationService; private GroupSimulationService groupSimulationService;
@Autowired @Autowired
private ApplicationContext applicationContext; private ApplicationContext applicationContext;
@Autowired @Autowired
private CiApiService ciApiService; private CiApiService ciApiService;
@Override @Override
public PslStatus getStatus(String group, String standCode) { public PslStatus getStatus(String group, String standCode) {
Simulation simulation = groupSimulationService.getSimulationByGroup(group); Simulation simulation = groupSimulationService.getSimulationByGroup(group);
SimulationDataRepository repository = simulation.getRepository(); SimulationDataRepository repository = simulation.getRepository();
Map<String, PslStatus> pslStatusMap = repository.getPslStatusMap(); Map<String, PslStatus> pslStatusMap = repository.getPslStatusMap();
PslStatus status = pslStatusMap.get(standCode); PslStatus status = pslStatusMap.get(standCode);
if (status != null) { if (status != null) {
return status; return status;
}
Stand stand = repository.getByCode(standCode, Stand.class);
BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertNotNull(stand.getPsd(),
String.format("%s没有屏蔽门", stand.debugStr()));
VirtualRealityPsl vrPsl = collectStatus(stand);
status = new PslStatus(vrPsl);
pslStatusMap.put(standCode, status);
return status;
}
@Override
public void pressTheButton(Simulation simulation, String standCode,
VirtualRealityPsl.Button button) {
Stand stand = simulation.getRepository().getByCode(standCode, Stand.class);
VirtualRealityPsl vrPsl = collectStatus(stand);
theButtonIsPressed(simulation, vrPsl, button);
}
private void theButtonIsPressed(Simulation simulation, VirtualRealityPsl vrPsl,
VirtualRealityPsl.Button button) {
Stand stand = vrPsl.getStand();
switch (button) {
case YXJZ:
vrPsl.setYxjzKey(!vrPsl.isYxjzKey());
break;
case HSJC:
vrPsl.setHsjcKey(!vrPsl.isHsjcKey());
ciApiService.setOrCancelInterlockRelease(simulation, stand, vrPsl.isHsjcKey());
break;
case KM:
ciApiService.openScreenDoor(simulation, stand.getCode(),
CiStandService.PsdCommandSource.PSL);
break;
case GM:
ciApiService.closeScreenDoor(simulation, stand.getCode(),
CiStandService.PsdCommandSource.PSL);
break;
case SD:
vrPsl.setSdButton(!vrPsl.isSdButton());
break;
}
}
@Override
public void updateStatus(Simulation simulation, VirtualRealityPsl vrPsl,
VirtualRealityPsl.Button button, boolean on) {
switch (button) {
case YXJZ:
vrPsl.setYxjzKey(on);
break;
case HSJC:
vrPsl.setHsjcKey(on);
break;
case KM:
vrPsl.setKmButton(on);
break;
case GM:
vrPsl.setGmButton(on);
break;
case SD:
vrPsl.setSdButton(on);
break;
}
effective(simulation, vrPsl.getStand(), button, on);
}
private void effective(Simulation simulation, Stand stand, VirtualRealityPsl.Button button,
boolean on) {
switch (button) {
case YXJZ:
break;
case HSJC:
ciApiService.setOrCancelInterlockRelease(simulation, stand, on);
break;
case KM:
if (on) {
ciApiService.openScreenDoor(simulation, stand.getCode(),
CiStandService.PsdCommandSource.PSL);
} }
Stand stand = repository.getByCode(standCode, Stand.class); break;
BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertNotNull(stand.getPsd(), case GM:
String.format("%s没有屏蔽门", stand.debugStr())); if (on) {
VirtualRealityPsl vrPsl = collectStatus(stand); ciApiService.closeScreenDoor(simulation, stand.getCode(),
status = new PslStatus(vrPsl); CiStandService.PsdCommandSource.PSL);
pslStatusMap.put(standCode, status);
return status;
}
@Override
public void pressTheButton(Simulation simulation, String standCode, VirtualRealityPsl.Button button) {
Stand stand = simulation.getRepository().getByCode(standCode, Stand.class);
VirtualRealityPsl vrPsl = collectStatus(stand);
theButtonIsPressed(simulation, vrPsl, button);
}
private void theButtonIsPressed(Simulation simulation, VirtualRealityPsl vrPsl, VirtualRealityPsl.Button button) {
Stand stand = vrPsl.getStand();
switch (button) {
case YXJZ:
vrPsl.setYxjzKey(!vrPsl.isYxjzKey());
break;
case HSJC:
vrPsl.setHsjcKey(!vrPsl.isHsjcKey());
ciApiService.setOrCancelInterlockRelease(simulation, stand, vrPsl.isHsjcKey());
break;
case KM:
ciApiService.openScreenDoor(simulation, stand.getCode(), CiStandService.PsdCommandSource.PSL);
break;
case GM:
ciApiService.closeScreenDoor(simulation, stand.getCode(), CiStandService.PsdCommandSource.PSL);
break;
case SD:
vrPsl.setSdButton(!vrPsl.isSdButton());
break;
} }
break;
case SD:
break;
} }
}
@Override @Override
public void updateStatus(Simulation simulation, VirtualRealityPsl vrPsl, VirtualRealityPsl.Button button, boolean on) { public void addJobs(Simulation simulation) {
switch (button) { simulation.addJobIfAbsent(Simulation.JobName.pslStatus,
case YXJZ: () -> this.collectAndDispatcher(simulation), SimulationConstants.PSL_STATUS_COLLECT_RATE);
vrPsl.setYxjzKey(on); }
break;
case HSJC: public void collectAndDispatcher(Simulation simulation) {
vrPsl.setHsjcKey(on); SimulationDataRepository repository = simulation.getRepository();
break; Map<String, PslStatus> ibpStatusMap = repository.getPslStatusMap();
case KM: Map<String, PslStatus> collectionMap = new HashMap<>();
case GM: for (Stand stand : repository.getStandList()) {
break; if (stand.getVrPsl() == null) {
case SD: continue;
vrPsl.setSdButton(on); }
break; VirtualRealityPsl vrPsl = this.collectStatus(stand);
PslStatus pslStatus = ibpStatusMap.get(stand.getCode());
if (pslStatus == null) {
PslStatus newStatus = new PslStatus(vrPsl);
ibpStatusMap.put(stand.getCode(), newStatus);
collectionMap.put(stand.getCode(), newStatus);
} else {
PslStatus difference = pslStatus.collectDifference(vrPsl);
if (difference != null) {
collectionMap.put(stand.getCode(), difference);
} }
effective(simulation, vrPsl.getStand(), button, on); }
} }
if (!CollectionUtils.isEmpty(collectionMap)) {
applicationContext.publishEvent(
new SimulationPslStatusEvent(this, simulation, collectionMap));
}
}
private void effective(Simulation simulation, Stand stand, VirtualRealityPsl.Button button, boolean on) { private VirtualRealityPsl collectStatus(Stand stand) {
switch (button) { VirtualRealityPsl vrPsl = stand.getVrPsl();
case YXJZ: PSD psd = stand.getPsd();
break; vrPsl.setQbgmLight(vrPsl.isSdButton() || psd.isCloseAndLock());
case HSJC: vrPsl.setPslczLight(vrPsl.isSdButton() || vrPsl.isYxjzKey());
ciApiService.setOrCancelInterlockRelease(simulation, stand, on); vrPsl.setHsjcLight(vrPsl.isSdButton() || vrPsl.isHsjcKey());
break; vrPsl.setKmLight(vrPsl.isSdButton() || !psd.isClose());
case KM: vrPsl.setGmLight(vrPsl.isSdButton() || psd.isClose());
if (on) return vrPsl;
ciApiService.openScreenDoor(simulation, stand.getCode(), CiStandService.PsdCommandSource.PSL); }
break;
case GM:
if (on)
ciApiService.closeScreenDoor(simulation, stand.getCode(), CiStandService.PsdCommandSource.PSL);
break;
case SD:
break;
}
}
@Override
public void addJobs(Simulation simulation) {
simulation.addJobIfAbsent(Simulation.JobName.pslStatus,
() -> this.collectAndDispatcher(simulation), SimulationConstants.PSL_STATUS_COLLECT_RATE);
}
public void collectAndDispatcher(Simulation simulation) {
SimulationDataRepository repository = simulation.getRepository();
Map<String, PslStatus> ibpStatusMap = repository.getPslStatusMap();
Map<String, PslStatus> collectionMap = new HashMap<>();
for (Stand stand : repository.getStandList()) {
if (stand.getVrPsl() == null)
continue;
VirtualRealityPsl vrPsl = this.collectStatus(stand);
PslStatus pslStatus = ibpStatusMap.get(stand.getCode());
if (pslStatus == null) {
PslStatus newStatus = new PslStatus(vrPsl);
ibpStatusMap.put(stand.getCode(), newStatus);
collectionMap.put(stand.getCode(), newStatus);
} else {
PslStatus difference = pslStatus.collectDifference(vrPsl);
if (difference != null) {
collectionMap.put(stand.getCode(), difference);
}
}
}
if (!CollectionUtils.isEmpty(collectionMap)) {
applicationContext.publishEvent(new SimulationPslStatusEvent(this, simulation, collectionMap));
}
}
private VirtualRealityPsl collectStatus(Stand stand) {
VirtualRealityPsl vrPsl = stand.getVrPsl();
PSD psd = stand.getPsd();
vrPsl.setQbgmLight(vrPsl.isSdButton() || psd.isCloseAndLock());
vrPsl.setPslczLight(vrPsl.isSdButton() || vrPsl.isYxjzKey());
vrPsl.setHsjcLight(vrPsl.isSdButton() || vrPsl.isHsjcKey());
vrPsl.setKmLight(vrPsl.isSdButton() || !psd.isClose());
vrPsl.setGmLight(vrPsl.isSdButton() || psd.isClose());
return vrPsl;
}
} }

View File

@ -380,9 +380,7 @@ public class Training2PublishService {
if (reqVO.getType() != null) { if (reqVO.getType() != null) {
or.andTypeEqualTo(reqVO.getType().value()); or.andTypeEqualTo(reqVO.getType().value());
} }
// if(reqVO.getOrgId() !=null){ example.setOrderByClause("id desc");
// or.andOrgIdNotEqualTo(reqVO.getOrgId());
// }
List<PublishedTraining2> list = this.publishedDao.selectByExample(example); List<PublishedTraining2> list = this.publishedDao.selectByExample(example);
if (CollectionUtils.isEmpty(list)) { if (CollectionUtils.isEmpty(list)) {
return List.of(); return List.of();

View File

@ -16,8 +16,6 @@ import club.joylink.rtss.simulation.cbtc.GroupSimulationService;
import club.joylink.rtss.simulation.cbtc.Simulation; import club.joylink.rtss.simulation.cbtc.Simulation;
import club.joylink.rtss.simulation.cbtc.SimulationLifeCycleService; import club.joylink.rtss.simulation.cbtc.SimulationLifeCycleService;
import club.joylink.rtss.simulation.cbtc.SimulationService; import club.joylink.rtss.simulation.cbtc.SimulationService;
import club.joylink.rtss.simulation.cbtc.conversation.ConversationGroup;
import club.joylink.rtss.simulation.cbtc.conversation.ConversationMember;
import club.joylink.rtss.simulation.cbtc.data.map.Switch; import club.joylink.rtss.simulation.cbtc.data.map.Switch;
import club.joylink.rtss.simulation.cbtc.data.vo.ConversationMessageVO; import club.joylink.rtss.simulation.cbtc.data.vo.ConversationMessageVO;
import club.joylink.rtss.simulation.cbtc.data.vo.Training2MessageVO; import club.joylink.rtss.simulation.cbtc.data.vo.Training2MessageVO;
@ -317,9 +315,12 @@ public class Training2Service {
Map<Long, Float> scoreMap = new HashMap<>(); Map<Long, Float> scoreMap = new HashMap<>();
if (!CollectionUtils.isEmpty(training2.getScoringRules())) { if (!CollectionUtils.isEmpty(training2.getScoringRules())) {
training2.getScoringRules().stream() training2.getScoringRules().stream()
.filter(score -> Objects.equals(score.getMember().getId(), member.getId())) .flatMap(sr -> sr.getDetails().stream())
.findFirst().ifPresent(scoringRule2 -> scoringRule2.getDetails() .forEach(d -> scoreMap.put(d.getStep().getId(), d.getScore()));
.forEach(d -> scoreMap.put(d.getStep().getId(), d.getScore()))); // training2.getScoringRules().stream()
//// .filter(score -> Objects.equals(score.getMember().getId(), member.getId()))
// .findFirst().ifPresent(scoringRule2 -> scoringRule2.getDetails()
// .forEach(d -> scoreMap.put(d.getStep().getId(), d.getScore())));
} }
// 前端传回的步骤信息 // 前端传回的步骤信息
Map<Long, PaperTrainAnswerDetail> answerDetailMap = new HashMap<>(); Map<Long, PaperTrainAnswerDetail> answerDetailMap = new HashMap<>();
@ -327,20 +328,23 @@ public class Training2Service {
scoreDetailList.forEach(d -> answerDetailMap.put(d.getStepId(), d)); scoreDetailList.forEach(d -> answerDetailMap.put(d.getStepId(), d));
} }
return training2.getSteps().stream() return training2.getSteps().stream()
.filter(s -> Objects.equals(s.getSimulationMember().getId(), member.getId())) // .filter(s -> Objects.equals(s.getSimulationMember().getId(), member.getId()))
.map(step -> { .map(step -> {
PaperTrainAnswerDetail detail = new PaperTrainAnswerDetail(); PaperTrainAnswerDetail detail = new PaperTrainAnswerDetail();
detail.setStepId(step.getId()); detail.setStepId(step.getId());
detail.setHaveRule(scoreMap.containsKey(step.getId())); detail.setHaveRule(scoreMap.containsKey(step.getId()));
if (answerDetailMap.containsKey(step.getId())) { detail.setRuleScore(scoreMap.get(step.getId()));
detail.setSuccess(answerDetailMap.get(step.getId()).isSuccess()); if (!Objects.equals(step.getSimulationMember().getId(), member.getId())) {
detail.setSuccess(true);
detail.setScore(detail.getRuleScore());
} else {
if (answerDetailMap.containsKey(step.getId())) {
detail.setSuccess(answerDetailMap.get(step.getId()).isSuccess());
detail.setClientOperations(answerDetailMap.get(step.getId()).getClientOperations());
detail.setNotExistAppend(true);
}
detail.setScore( detail.setScore(
detail.isHaveRule() && detail.isSuccess() ? scoreMap.get(step.getId()) : 0F); detail.isHaveRule() && detail.isSuccess() ? scoreMap.get(step.getId()) : 0F);
detail.setClientOperations(answerDetailMap.get(step.getId()).getClientOperations());
detail.setNotExistAppend(true);
}
if (detail.isHaveRule()) {
detail.setRuleScore(scoreMap.get(step.getId()));
} }
return detail; return detail;
}).collect(Collectors.toList()); }).collect(Collectors.toList());

View File

@ -5,6 +5,7 @@ import club.joylink.rtss.entity.RtsMapFunction;
import club.joylink.rtss.entity.SysAccount; import club.joylink.rtss.entity.SysAccount;
import club.joylink.rtss.entity.UserSimulationRecord; import club.joylink.rtss.entity.UserSimulationRecord;
import club.joylink.rtss.entity.UserSimulationRecordExample; import club.joylink.rtss.entity.UserSimulationRecordExample;
import club.joylink.rtss.entity.UserSimulationRecordExample.Criteria;
import club.joylink.rtss.event.UserSimulationRecordEvent; import club.joylink.rtss.event.UserSimulationRecordEvent;
import club.joylink.rtss.exception.BusinessExceptionAssertEnum; import club.joylink.rtss.exception.BusinessExceptionAssertEnum;
import club.joylink.rtss.services.IMapService; import club.joylink.rtss.services.IMapService;
@ -13,6 +14,7 @@ import club.joylink.rtss.services.mapFunction.RtsMapFunctionService;
import club.joylink.rtss.simulation.cbtc.message.UserSimulationRecordManager; import club.joylink.rtss.simulation.cbtc.message.UserSimulationRecordManager;
import club.joylink.rtss.util.TimeUnit; import club.joylink.rtss.util.TimeUnit;
import club.joylink.rtss.vo.client.PageVO; import club.joylink.rtss.vo.client.PageVO;
import club.joylink.rtss.vo.client.simulationUsage.SimulationUsageRecordQueryVO;
import club.joylink.rtss.vo.client.simulationUsage.UserSimulationQueryVO; import club.joylink.rtss.vo.client.simulationUsage.UserSimulationQueryVO;
import club.joylink.rtss.vo.client.simulationUsage.UserSimulationRecordVO; import club.joylink.rtss.vo.client.simulationUsage.UserSimulationRecordVO;
import club.joylink.rtss.vo.client.simulationUsage.UserSimulationStatsVO; import club.joylink.rtss.vo.client.simulationUsage.UserSimulationStatsVO;
@ -66,7 +68,8 @@ public class UserSimulationRecordService {
} }
public List<UserSimulationRecord> queryByMapAndUserIds(Long mapId, List<Long> userIds) { public List<UserSimulationRecord> queryByMapAndUserIds(Long mapId, List<Long> userIds) {
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertCollectionNotEmpty(userIds, "用户列表不能为空"); BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertCollectionNotEmpty(userIds,
"用户列表不能为空");
UserSimulationRecordExample example = new UserSimulationRecordExample(); UserSimulationRecordExample example = new UserSimulationRecordExample();
example.createCriteria().andMapIdEqualTo(mapId).andUserIdIn(userIds); example.createCriteria().andMapIdEqualTo(mapId).andUserIdIn(userIds);
return userSimulationRecordDAO.selectByExample(example); return userSimulationRecordDAO.selectByExample(example);
@ -165,6 +168,22 @@ public class UserSimulationRecordService {
return statistic(startTime, endTime, timeUnit, list); return statistic(startTime, endTime, timeUnit, list);
} }
/**
* 查询仿真使用记录
*/
public List<UserSimulationRecord> listSimulationUsageRecords(
SimulationUsageRecordQueryVO queryVO) {
UserSimulationRecordExample example = new UserSimulationRecordExample();
Criteria criteria = example.createCriteria();
if (queryVO.getUid() != null) {
criteria.andUserIdEqualTo(queryVO.getUid());
}
if (queryVO.getFunctionId() != null) {
criteria.andFunctionIdEqualTo(queryVO.getFunctionId());
}
return userSimulationRecordDAO.selectByExample(example);
}
/** /**
* 对使用记录按照时间单位开始结束时间分段统计 * 对使用记录按照时间单位开始结束时间分段统计
*/ */
@ -223,9 +242,12 @@ public class UserSimulationRecordService {
} }
private void checkParam(UserSimulationQueryVO queryVO) { private void checkParam(UserSimulationQueryVO queryVO) {
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotNull(queryVO.getTimeUnit(), "缺少时间单位"); BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotNull(queryVO.getTimeUnit(),
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotNull(queryVO.getStartTime(), "缺少开始时间"); "缺少时间单位");
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotNull(queryVO.getEndTime(), "缺少结束时间"); BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotNull(queryVO.getStartTime(),
"缺少开始时间");
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotNull(queryVO.getEndTime(),
"缺少结束时间");
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue( BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertTrue(
!queryVO.getStartTime().isAfter(queryVO.getEndTime()), "开始时间不能晚于结束时间"); !queryVO.getStartTime().isAfter(queryVO.getEndTime()), "开始时间不能晚于结束时间");
} }

View File

@ -4,6 +4,7 @@ import club.joylink.rtss.vo.client.PageQueryVO;
import club.joylink.rtss.vo.client.PageVO; import club.joylink.rtss.vo.client.PageVO;
import club.joylink.rtss.vo.client.competition.VoiceErrorVO; import club.joylink.rtss.vo.client.competition.VoiceErrorVO;
import club.joylink.rtss.vo.client.voice.VoiceRecognitionResult; import club.joylink.rtss.vo.client.voice.VoiceRecognitionResult;
import club.joylink.rtss.vo.voice.VoiceVerifyResultVO;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
/** /**
@ -11,9 +12,19 @@ import org.springframework.web.multipart.MultipartFile;
*/ */
public interface IVoiceTrainingService { public interface IVoiceTrainingService {
PageVO<VoiceErrorVO> pagedQueryErrorSet(PageQueryVO queryVO); PageVO<VoiceErrorVO> pagedQueryErrorSet(PageQueryVO queryVO);
VoiceRecognitionResult voiceRecognition(MultipartFile file); VoiceRecognitionResult voiceRecognition(MultipartFile file);
VoiceRecognitionResult voiceRecognition(byte[] bytes, String filePath); VoiceRecognitionResult voiceRecognition(byte[] bytes, String filePath);
/**
* 校验语音识别结果
*
* @param contentType
* @param file 需要校验的语音
* @param text 正确的文本
* @return 校验结果
*/
VoiceVerifyResultVO verifyVoice(String contentType, byte[] file, String text);
} }

View File

@ -2,63 +2,118 @@ package club.joylink.rtss.services.voice;
import club.joylink.rtss.dao.CompetitionErrorSetDAO; import club.joylink.rtss.dao.CompetitionErrorSetDAO;
import club.joylink.rtss.entity.CompetitionErrorSet; import club.joylink.rtss.entity.CompetitionErrorSet;
import club.joylink.rtss.exception.BusinessExceptionAssertEnum;
import club.joylink.rtss.simulation.cbtc.conversation.SimulationVoiceHandler; import club.joylink.rtss.simulation.cbtc.conversation.SimulationVoiceHandler;
import club.joylink.rtss.util.StrUtils;
import club.joylink.rtss.vo.client.PageQueryVO; import club.joylink.rtss.vo.client.PageQueryVO;
import club.joylink.rtss.vo.client.PageVO; import club.joylink.rtss.vo.client.PageVO;
import club.joylink.rtss.vo.client.competition.VoiceErrorVO; import club.joylink.rtss.vo.client.competition.VoiceErrorVO;
import club.joylink.rtss.vo.client.voice.VoiceRecognitionResult; import club.joylink.rtss.vo.client.voice.VoiceRecognitionResult;
import club.joylink.rtss.vo.client.voice.VoiceRecognitionVO; import club.joylink.rtss.vo.client.voice.VoiceRecognitionVO;
import club.joylink.rtss.vo.voice.VoiceVerifyResultVO;
import com.github.pagehelper.Page; import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired; import java.io.ByteArrayInputStream;
import org.springframework.beans.factory.annotation.Qualifier; import java.io.ByteArrayOutputStream;
import org.springframework.stereotype.Service; import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service @Service
public class VoiceTrainingService implements IVoiceTrainingService { public class VoiceTrainingService implements IVoiceTrainingService {
@Autowired @Autowired
private CompetitionErrorSetDAO competitionErrorSetDAO; private CompetitionErrorSetDAO competitionErrorSetDAO;
/* @Autowired /* @Autowired
@Qualifier("baiDuVoiceService") @Qualifier("baiDuVoiceService")
private IVoiceService iVoiceService;*/ private IVoiceService iVoiceService;*/
@Autowired @Autowired
// @Qualifier("baiDuVoiceService2") // @Qualifier("baiDuVoiceService2")
private VoiceService iVoiceService; private VoiceService iVoiceService;
@Autowired @Autowired
private SimulationVoiceHandler simulationVoiceHandler; private SimulationVoiceHandler simulationVoiceHandler;
@Override @Override
public PageVO<VoiceErrorVO> pagedQueryErrorSet(PageQueryVO queryVO) { public PageVO<VoiceErrorVO> pagedQueryErrorSet(PageQueryVO queryVO) {
Page<Object> page = PageHelper.startPage(queryVO.getPageNum(), queryVO.getPageSize()); Page<Object> page = PageHelper.startPage(queryVO.getPageNum(), queryVO.getPageSize());
List<CompetitionErrorSet> sets = competitionErrorSetDAO.selectByExample(null); List<CompetitionErrorSet> sets = competitionErrorSetDAO.selectByExample(null);
List<VoiceErrorVO> list = sets.stream().map(VoiceErrorVO::new).collect(Collectors.toList()); List<VoiceErrorVO> list = sets.stream().map(VoiceErrorVO::new).collect(Collectors.toList());
return PageVO.convert(page, list); return PageVO.convert(page, list);
} }
@Override @Override
public VoiceRecognitionResult voiceRecognition(MultipartFile file) { public VoiceRecognitionResult voiceRecognition(MultipartFile file) {
VoiceRecognitionVO vo = VoiceRecognitionVO.load(file); VoiceRecognitionVO vo = VoiceRecognitionVO.load(file);
VoiceRecognitionResult result = this.iVoiceService.voiceRecognition(vo); return voiceRecognition(vo);
}
@Override
public VoiceRecognitionResult voiceRecognition(byte[] bytes, String filePath) {
VoiceRecognitionVO vo = new VoiceRecognitionVO(bytes);
return voiceRecognition(vo);
}
@Override
public VoiceVerifyResultVO verifyVoice(String contentType, byte[] fileData, String text) {
byte[] monoData = convertToMonoChannel(fileData);
VoiceRecognitionResult voiceRecognitionResult = voiceRecognition(
new VoiceRecognitionVO(monoData, contentType));
boolean match = StrUtils.isMatch(text, voiceRecognitionResult.getResult(), 70);
return new VoiceVerifyResultVO(voiceRecognitionResult.getResult(), match);
}
private VoiceRecognitionResult voiceRecognition(VoiceRecognitionVO vo) {
VoiceRecognitionResult result = this.iVoiceService.voiceRecognition(vo);
// VoiceRecognitionResult result = this.iVoiceService.voiceRecognition(file, ""); // VoiceRecognitionResult result = this.iVoiceService.voiceRecognition(file, "");
result.setResult(simulationVoiceHandler.handle(result.getResult())); result.setResult(simulationVoiceHandler.handle(result.getResult()));
return result; return result;
} }
@Override private byte[] convertToMonoChannel(byte[] audioData) {
public VoiceRecognitionResult voiceRecognition(byte[] bytes, String filePath) { try {
VoiceRecognitionVO vo = new VoiceRecognitionVO(bytes); // 假设输入和输出音频都存储在字节数组中
VoiceRecognitionResult result = this.iVoiceService.voiceRecognition(vo); byte[] outputAudioBytes;
// VoiceRecognitionResult result = this.iVoiceService.voiceRecognition(bytes, filePath);
result.setResult(simulationVoiceHandler.handle(result.getResult())); // 将输入音频字节数组转换为音频输入流
return result; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(audioData);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(byteArrayInputStream);
AudioFormat format = audioInputStream.getFormat();
// 确保输入音频是立体声
if (format.getChannels() != 2) {
System.out.println("Input audio is not stereo.");
return audioData;
}
// 创建单声道格式
AudioFormat monoFormat = new AudioFormat(format.getEncoding(), format.getSampleRate(),
format.getSampleSizeInBits(), 1, format.getFrameSize() / 2, format.getFrameRate(), false);
// 从立体声转换为单声道
AudioInputStream monoInputStream = AudioSystem.getAudioInputStream(monoFormat,
audioInputStream);
// 将单声道音频写入字节数组输出流
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
AudioSystem.write(monoInputStream, AudioFileFormat.Type.WAVE, byteArrayOutputStream);
// 获取输出音频的字节数组
return byteArrayOutputStream.toByteArray();
} catch (UnsupportedAudioFileException | IOException e) {
throw BusinessExceptionAssertEnum.SYSTEM_EXCEPTION.exception(
String.format("音频转单声道失败:%s", e));
} }
}
} }

View File

@ -1,78 +0,0 @@
/*
package club.joylink.rtss.services.voice.huawei;
import club.joylink.rtss.exception.BusinessExceptionAssertEnum;
import club.joylink.rtss.services.voice.IVoiceService;
import club.joylink.rtss.util.VoiceFileUtils;
import club.joylink.rtss.vo.client.VoiceRecognitionResult;
import com.huawei.sis.bean.AuthInfo;
import com.huawei.sis.bean.SisConfig;
import com.huawei.sis.bean.request.AsrCustomShortRequest;
import com.huawei.sis.bean.response.AsrCustomShortResponse;
import com.huawei.sis.client.AsrCustomizationClient;
import com.huawei.sis.exception.SisException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Base64;
@Slf4j
@Service("HuaWeiVoiceService")
public class HuaweiVoiceServiceImpl implements IVoiceService {
@Override
public String synthesis(String message, String per) {
throw BusinessExceptionAssertEnum.THIRD_SERVICE_CALL_EXCEPTION.exception("功能暂未实现");
}
@Override
public String synthesis(String message) {
return this.synthesis(message, "0");
}
*/
/**
* 华为语音识别配置
*//*
private final String ak = "YDUXTXRYGAHGPHAIXZCU";
private final String sk = "Kcbm3sTDCYEou8kGeAhKxfBkgWybIn6IjJyGBX3p";
private final String region = "cn-north-4";
private final String projectId = "0aada8176180f28c2f34c0196f5394e8";
@Override
public VoiceRecognitionResult voiceRecognition(MultipartFile file, String lang) {
String filePath = VoiceFileUtils.saveFile(file);
try {
return voiceRecognition(file.getBytes(), filePath);
} catch (IOException e) {
throw BusinessExceptionAssertEnum.SYSTEM_EXCEPTION.exception("第三方服务调用异常");
}
}
@Override
public VoiceRecognitionResult voiceRecognition(byte[] bytes, String filePath) {
AuthInfo authInfo = new AuthInfo(ak, sk, region, projectId);
SisConfig sisConfig = new SisConfig();
AsrCustomizationClient client = new AsrCustomizationClient(authInfo, sisConfig);
String data = Base64.getEncoder().encodeToString(bytes);
try {
AsrCustomShortRequest request = new AsrCustomShortRequest(data, "pcm16k16bit", "chinese_16k_common");
AsrCustomShortResponse response = client.getAsrShortResponse(request);
return new VoiceRecognitionResult(filePath, response.getResult().getText());
} catch (SisException e) {
throw BusinessExceptionAssertEnum.SYSTEM_EXCEPTION.exception("语音识别失败", e);
}
}
@Override
public VoiceRecognitionResult voiceRecognition(String fileBase64) {
String base64 = fileBase64.substring(fileBase64.indexOf("base64,") + "base64,".length());
byte[] bytes = Base64.getDecoder().decode(base64.trim());
String filePath = VoiceFileUtils.saveFile(bytes);
return voiceRecognition(bytes, filePath);
}
}
*/

View File

@ -1,154 +0,0 @@
//package club.joylink.rtss.simulation;
//
//import club.joylink.rtss.simulation.operation.SimulationOperationDispatcher;
//import club.joylink.rtss.simulation.vo.SimulationFaultVO;
//import club.joylink.rtss.simulation.vo.SimulationInfoVO;
//import club.joylink.rtss.simulation.vo.SimulationMemberVO;
//import club.joylink.rtss.simulation.vo.SimulationUserVO;
//import club.joylink.rtss.vo.LoginUserInfoVO;
//import club.joylink.rtss.vo.client.simulationv1.SimulationInfoQueryVO;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.util.StringUtils;
//import org.springframework.web.bind.annotation.*;
//
//import java.util.List;
//import java.util.Map;
//import java.util.Objects;
//import java.util.stream.Collectors;
//import java.util.stream.Stream;
//
//import static club.joylink.rtss.controller.advice.AuthenticateInterceptor.LOGIN_INFO_KEY;
//
///**
// * 仿真通用接口
// */
//@Slf4j
//@RestController
//@RequestMapping("/common/simulation")
//public class SimulationCommonController {
// @Autowired
// private SimulationManager simulationManager;
// @Autowired
// private SimulationOperationDispatcher simulationOperationDispatcher;
//
// /**
// * 监管仿真
// * @param loginUserInfoVO
// * @param queryVO
// * @return
// */
// @GetMapping("/supervise")
// public List<SimulationInfoVO> superviseSimulation(@RequestAttribute(name=LOGIN_INFO_KEY) LoginUserInfoVO loginUserInfoVO, SimulationInfoQueryVO queryVO) {
// List<Simulation> simulationList = this.simulationManager.getSimulationList();
// Stream<Simulation> stream = simulationList.stream();
//
// stream = stream.filter(simulation -> simulation instanceof club.joylink.rtss.simulation.cbtc.Simulation
// && Objects.equals(loginUserInfoVO.getTopOrgId(),((club.joylink.rtss.simulation.cbtc.Simulation)simulation).getBuildParams().getLoginUserInfo().getTopOrgId()));
//
// if (StringUtils.hasText(queryVO.getGroup())) {
// stream = stream.filter(simulation -> simulation.getId().contains(queryVO.getGroup()));
// }
// if (StringUtils.hasText(queryVO.getUserName())) {
// stream = stream.filter(simulation -> simulation.getSimulationUsers().stream().anyMatch(user -> ((SimulationUser) user).getName().contains(queryVO.getUserName())));
// }
// if (StringUtils.hasText(queryVO.getPrdType())) {
// stream = stream.filter(simulation -> simulation instanceof club.joylink.rtss.simulation.cbtc.Simulation
// && queryVO.getPrdType().equals(((club.joylink.rtss.simulation.cbtc.Simulation) simulation).getBuildParams().getProdType().getCode()));
// }
// return stream.map(Simulation::convertToVO).collect(Collectors.toList());
// }
//
// @GetMapping("/list")
// public List<SimulationInfoVO> queryInfo(SimulationInfoQueryVO queryVO) {
// List<Simulation> simulationList = this.simulationManager.getSimulationList();
// Stream<Simulation> stream = simulationList.stream();
// if (StringUtils.hasText(queryVO.getGroup())) {
// stream = stream.filter(simulation -> simulation.getId().contains(queryVO.getGroup()));
// }
// if (StringUtils.hasText(queryVO.getUserName())) {
// stream = stream.filter(simulation -> simulation.getSimulationUsers().stream().anyMatch(user -> ((SimulationUser) user).getName().contains(queryVO.getUserName())));
// }
// if (StringUtils.hasText(queryVO.getPrdType())) {
// stream = stream.filter(simulation -> simulation instanceof club.joylink.rtss.simulation.cbtc.Simulation
// && queryVO.getPrdType().equals(((club.joylink.rtss.simulation.cbtc.Simulation) simulation).getBuildParams().getProdType().getCode()));
// }
// return stream.map(Simulation::convertToVO).collect(Collectors.toList());
// }
//
// @PutMapping("/{id}/pause")
// public void pause(@PathVariable String id) {
// this.simulationManager.pause(id);
// }
//
// @PutMapping("/{id}/start")
// public void start(@PathVariable String id) {
// this.simulationManager.start(id);
// }
//
// @PutMapping("/{id}/init")
// public void init(@PathVariable String id) {
// this.simulationManager.init(id);
// }
//
// @PutMapping("/{id}/updateSpeed/{speed}")
// public void updateSpeed(@PathVariable String id, @PathVariable int speed) {
// this.simulationManager.updateSpeed(id, speed);
// }
//
// @GetMapping("/{id}")
// public SimulationInfoVO getSimulationInfo(@PathVariable String id) {
// return this.simulationManager.getById(id).convertToVO();
// }
//
// @GetMapping("/{id}/users")
// public List<SimulationUserVO> getSimulationUsers(@PathVariable String id) {
// return this.simulationManager.getSimulationUsers(id).stream()
// .map(SimulationUser::convertToVO)
// .collect(Collectors.toList());
// }
//
// @GetMapping("/{id}/members")
// public List<SimulationMemberVO> getSimulationMembers(@PathVariable String id, @RequestParam(required = false) String role) {
// return this.simulationManager.getSimulationMembers(id).stream()
// .map(SimulationMember::convertToVO)
// .filter(member -> StringUtils.hasText(role) ? member.getRole().toString().equals(role) : true)
// .collect(Collectors.toList());
// }
//
// @GetMapping("/{id}/member/playedBy/{userId}")
// public SimulationMemberVO queryUserPlayedMember(@PathVariable String id, @PathVariable String userId) {
// return this.simulationManager.getById(id)
// .getSimulationMemberByUserId(userId).convertToVO();
// }
//
// @PostMapping("/{id}/member/{memberId}/operate/{type}")
// public Object operate(@PathVariable String id, @PathVariable String memberId,
// @PathVariable String type, @RequestBody Map<String, Object> params) {
// return this.simulationOperationDispatcher.doDispatch(id, memberId, type, params);
// }
//
// /**
// * 故障注入
// */
// @PostMapping("/{id}/fault")
// public void injectFault(@PathVariable String id, @RequestBody SimulationFaultVO faultVO) {
// this.simulationManager.injectFault(id, faultVO);
// }
//
// @DeleteMapping("/{id}/device/{deviceId}/fault/{fault}")
// public void removeFault(@PathVariable String id, @PathVariable String deviceId, @PathVariable String fault) {
// this.simulationManager.removeFault(id, deviceId, fault);
// }
//
// @PutMapping("/{id}/member/{memberId}/playby/{userId}")
// public void memberPlay(@PathVariable String id, @PathVariable String memberId, @PathVariable String userId) {
// this.simulationManager.memberPlayedByUser(id, memberId, userId);
// }
//
// @DeleteMapping("/{id}/destroy")
// public void destroy(@PathVariable String id) {
// this.simulationManager.destroy(id);
// log.info(String.format("仿真通用接口销毁仿真[%s]", id));
// }
//}

View File

@ -1,687 +0,0 @@
//package club.joylink.rtss.simulation.cbtc.ATP.ground;
//
//import club.joylink.rtss.exception.BusinessExceptionAssertEnum;
//import club.joylink.rtss.simulation.cbtc.ATS.AtsApiService;
//import club.joylink.rtss.simulation.cbtc.CI.service.RouteService;
//import club.joylink.rtss.simulation.cbtc.Simulation;
//import club.joylink.rtss.simulation.cbtc.constant.RunLevel;
//import club.joylink.rtss.simulation.cbtc.data.CalculateService;
//import club.joylink.rtss.simulation.cbtc.data.SimulationDataRepository;
//import club.joylink.rtss.simulation.cbtc.data.map.*;
//import club.joylink.rtss.simulation.cbtc.data.support.MovementAuthority;
//import club.joylink.rtss.simulation.cbtc.data.support.SectionPosition;
//import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealityTrain;
//import club.joylink.rtss.simulation.cbtc.onboard.ATP.ATPService;
//import club.joylink.rtss.simulation.cbtc.onboard.ATP.OnboardAtpApiService;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//import org.springframework.util.CollectionUtils;
//
//import java.util.*;
//import java.util.stream.Collectors;
//
///**
// * ZC逻辑循环
// */
//@Slf4j
//@Component
//public class ZCLogicLoop {
//
// @Autowired
// private OnboardAtpApiService onboardAtpApiService;
//
// @Autowired
// private ATPService ATPService;
//
// @Autowired
// private AtsApiService atsApiService;
//
// @Autowired
// private MaService maService;
//
// @Autowired
// private RouteService routeService;
//
// public void run(Simulation simulation) {
// List<VirtualRealityTrain> trainList = simulation.getRepository().getOnlineTrainList();
// trainList.forEach(train -> {
// SectionPosition headPosition = train.getHeadPosition();
// Station deviceStation = headPosition.getSection().getDeviceStation();
// RunLevel defaultRunLevel = simulation.getRepository().getConfig().getRunMode();
// if (RunLevel.ITC.equals(defaultRunLevel)) { //如果线路最高运行级别为ITC级别
// if (!Station.Fault.INTERLOCK_MACHINE_FAULT.equals(deviceStation.getFault())) {
// this.calculateMAOfITC(simulation, train);
// }
// } else if (RunLevel.CBTC.equals(defaultRunLevel)) {
// //更新ITC ma
// if (!simulation.getRepository().hasResponder()) {
// if (!Station.Fault.INTERLOCK_MACHINE_FAULT.equals(deviceStation.getFault())) {
// Float distance2NextSignal = train.calculateDistance2NextNormalOpenSignal();
// if (distance2NextSignal != null && distance2NextSignal <= 5) {
// train.setPositioned(true);
// this.calculateMAOfITC(simulation, train);
// }
// }
// } else {
// simulation.getRepository().getSectionRespondersMap().forEach((section, responders) ->
// responders.stream()
// .filter(Responder::isVB)
// .forEach(responder -> {
// if (responder.getSignal().isNormalOpen()) {
// responder.setMa(this.calculateMAOfITC(simulation, responder));
// }
// }));
// }
// //更新CBTC ma
// if (train.isCommunicable()) {
// this.calculateMAOfCBTC(simulation, train, trainList);
// }
// }
// });
// }
//
// private void calculateMAOfCBTC(Simulation simulation, VirtualRealityTrain train,
// List<VirtualRealityTrain> trainList) {
// // 查找移动授权终端列表
// List<MovementAuthority.End> endList = this.findMaEnd(simulation, train, trainList);
// // 根据查找到的授权终端比较并构建最终的移动授权数据
// MovementAuthority ma = this.compareAndBuildMa(train, endList);
// // 通知车载ATP
// this.onboardAtpApiService.updateMA4CBTC(train, ma);
// }
//
// /**
// * 计算移动授权终端
// *
// * @param simulation
// * @param train
// * @param trainList
// * @return
// */
// private List<MovementAuthority.End> findMaEnd(Simulation simulation, VirtualRealityTrain train, List<VirtualRealityTrain> trainList) {
// // 从车尾开始找车尾主要查看是否在站台轨上且站台轨屏蔽门开放
// boolean right = train.isRight();
// SectionPosition headPosition = train.getHeadPosition();
// SectionPosition tailPosition = train.calculateTailPosition();
// Section tailSection = tailPosition.getSection();
// MovementAuthority.End openPsdEnd = checkPsdOpenOrClose(tailSection);
// List<MovementAuthority.End> endList = new ArrayList<>();
// if (openPsdEnd != null)
// endList.add(openPsdEnd);
// MovementAuthority.End ecStandEnd = checkEC(simulation.getRepository().getConfig(), tailSection);
// if (ecStandEnd != null)
// endList.add(ecStandEnd);
// MovementAuthority.End closedSection = checkClosedSection(tailSection);
// if (closedSection != null)
// return List.of(closedSection);
// // 如果车尾正常从车头开始往前查找
// Section section = headPosition.getSection();
// MovementAuthority.End switchEnd = checkSwitch(tailSection, section, right);
// if (switchEnd != null)
// return List.of(switchEnd);
// // 检查列车当前所在进路是否锁闭
//// MovementAuthority.End end1 = this.checkRouteLock(simulation, section, tailSection, right, train);
//// if (Objects.nonNull(end1)) {
//// endList.add(end1);
//// return endList;
//// }
//// // 检查车头区段是否故障
//// if (headPosition.getSection().isFault()) {
//// endList.add(new MovementAuthority.End(headPosition.getSection(), MovementAuthority.EndType.FAULT_SECTION));
//// }
// //非通信车占用区段
// if (section.hasNctOccupy() && !section.isInvalid()) {
// endList.add(new MovementAuthority.End(section, MovementAuthority.EndType.NCT_OCCUPIED_SECTION));
// return endList;
// }
// //通信车占用区段
// List<Section> occupiedLogicSectionList = simulation.getRepository().queryTrainOccupyAtpSectionList(train.getGroupNumber());
// Set<Section> occupiedLogicSectionSet;
// if (!CollectionUtils.isEmpty(occupiedLogicSectionList)) {
// occupiedLogicSectionSet = new HashSet<>(occupiedLogicSectionList);
// } else {
// occupiedLogicSectionSet = new HashSet<>();
// }
// List<Section> logicList = section.getLogicList();
// if (!CollectionUtils.isEmpty(logicList)) {
// Section logicSection = headPosition.getLogicSection();
// int index = logicList.indexOf(logicSection);
// if (right) {
// for (int i = index + 1; i < logicList.size(); i++) {
// MovementAuthority.End end = checkSectionOccupied(logicList.get(i), right, occupiedLogicSectionSet);
// if (end != null)
// endList.add(end);
// }
// } else {
// for (int i = index - 1; i >= 0; i--) {
// MovementAuthority.End end = checkSectionOccupied(logicList.get(i), right, occupiedLogicSectionSet);
// if (end != null)
// endList.add(end);
// }
// }
// }
// int count = 0;
// while (count < 50) {
// ++count;
//// // 区段未进路锁闭或延时解锁中转换轨除外因为出库列车加载到转换轨没有进路
//// if (!section.isTransferTrack()) {
//// if (section.isDelayUnlock()) {
//// deviceEnd = new MovementAuthority.End(section, MovementAuthority.EndType.UNLOCK_SECTION);
//// break;
//// }
//// if (!section.isRouteLock()) {
//// deviceEnd = new MovementAuthority.End(section, MovementAuthority.EndType.UNLOCK_SECTION);
//// break;
//// }
//// }
// // 站台屏蔽门
// MovementAuthority.End psdEnd = checkPsdOpenOrClose(section);
// if (psdEnd != null)
// endList.add(psdEnd);
// // 紧急关闭的站台
// MovementAuthority.End standEnd = checkEC(simulation.getRepository().getConfig(), section);
// if (standEnd != null)
// endList.add(standEnd);
// // 信号机
// MovementAuthority.End signalEnd = checkSignal(section, right);
// if (Objects.nonNull(signalEnd)) {
// endList.add(signalEnd);
// MovementAuthority.End unlockedOverlapEnd = this.checkUnlockedOverlap(simulation, section, right);
// if (Objects.nonNull(unlockedOverlapEnd)) {
// endList.add(unlockedOverlapEnd);
// }
// }
// // 道岔
// MovementAuthority.End end = checkSwitch(section, right);
// if (end != null)
// endList.add(end);
// // 轨道尽头/问题道岔
// Section temp = section.getNextRunningSectionOf(right);
// if (Objects.isNull(temp)) { // 到尽头
// if (!section.isSwitchTrack()) { // 问题道岔
// endList.add(new MovementAuthority.End(section, MovementAuthority.EndType.END_TRACK));
// }
// break;
// }
// //通信车占用区段
// MovementAuthority.End trainEnd = checkSectionOccupied(temp, right, occupiedLogicSectionSet);
// if (trainEnd != null)
// endList.add(trainEnd);
// //非通信车占用区段
// if (temp.hasNctOccupy() && !temp.isInvalid()) {
// endList.add(new MovementAuthority.End(temp, MovementAuthority.EndType.NCT_OCCUPIED_SECTION));
// }
// //检查关闭的区段
// MovementAuthority.End cs = checkClosedSection(section);
// if (cs != null)
// endList.add(cs);
//
// if (endList.stream().anyMatch(end2 -> !MovementAuthority.EndType.CLOSED_SIGNAL.equals(end2.getType()))) {
// break;
// }
// section = temp;
// }
//// // 前方列车
//// VirtualRealityTrain frontTrain = this.queryFrontTrain(train, trainList);
//// if (Objects.nonNull(frontTrain)) {
//// Section baseSection;
//// if (Objects.equals(frontTrain.isRight(), train.isRight())) {
//// baseSection = frontTrain.calculateTailPosition().getSection();
//// } else {
//// baseSection = frontTrain.getHeadPosition().getSection();
//// }
//// endList.add(new MovementAuthority.End(frontTrain,
//// MovementAuthority.EndType.FRONT_TRAIN,
//// baseSection));
//// }
// return endList;
// }
//
// private MovementAuthority.End checkSectionOccupied(Section section, boolean right, Set<Section> occupiedLogicSectionSet) {
// List<Section> logicList = section.getLogicList();
// if (!CollectionUtils.isEmpty(logicList)) {
// if (right) {
// for (Section logic : logicList) {
// if (logic.isCtOccupied() && !occupiedLogicSectionSet.contains(logic)) {
// return new MovementAuthority.End(logic, MovementAuthority.EndType.FRONT_TRAIN, null);
// }
// }
// } else {
// for (int i = logicList.size() - 1; i >= 0; i--) {
// Section logic = logicList.get(i);
// if (logic.isCtOccupied() && !occupiedLogicSectionSet.contains(logic)) {
// return new MovementAuthority.End(logic, MovementAuthority.EndType.FRONT_TRAIN, null);
// }
// }
// }
// } else {
// if (section.isCtOccupied() && !occupiedLogicSectionSet.contains(section)) {
// return new MovementAuthority.End(section, MovementAuthority.EndType.FRONT_TRAIN, null);
// }
// }
// return null;
// }
//
// private MovementAuthority.End checkSwitch(Section tailSection, Section headSection, boolean right) {
// Section section = tailSection;
// for (int i = 0; i < 10; i++) {
// if (section == null || section.equals(headSection))
// break;
// MovementAuthority.End end = checkSwitch(section, right);
// if (end != null)
// return end;
// section = section.getNextRunningSectionOf(right);
// }
// return null;
// }
//
// private MovementAuthority.End checkSwitch(Section section, boolean right) {
// Switch relSwitch = section.getRelSwitch();
// Section nextSection = section.getNextRunningSectionOf(right);
// if (relSwitch != null) { //是道岔区段
// Route route = relSwitch.getRoute();
// Section previousSection = section.getNextRunningSectionOf(!right);
// if (previousSection == null)
// return null;
// if (route != null) { //道岔进路锁闭
// if (relSwitch.isLoss()) { //失表且下个区段
// return new MovementAuthority.End(relSwitch, MovementAuthority.EndType.FAULT_SWITCH, previousSection);
// } else {
// List<RouteFls> flsList = route.getFlsList();
// if (!CollectionUtils.isEmpty(flsList)) {
// List<RouteFls> fls = flsList.stream()
// .filter(routeFls -> routeFls.getBase().getASwitch().equals(relSwitch))
// .collect(Collectors.toList());
// if (!routeService.isFlsCheckPass(fls)) {
// return new MovementAuthority.End(relSwitch, MovementAuthority.EndType.FAULT_SWITCH, previousSection);
// }
// }
// }
// }
// }
// return null;
// }
//
// private MovementAuthority.End checkClosedSection(Section section) {
// if (section.isClosed()) {
// return new MovementAuthority.End(section, MovementAuthority.EndType.CLOSED_SECTION);
// }
// return null;
// }
//
// private MovementAuthority.End checkEC(MapConfig config, Section section) {
// if (section.isNormalStandTrack()) {
// Station station = section.getStation();
// if (config.isSharingECStation(station.getCode())) {
// for (Stand stand : station.getAllStandList()) {
// if (stand.isEmergencyClosed()) {
// return new MovementAuthority.End(stand, MovementAuthority.EndType.EC_STAND, section);
// }
// }
// } else {
// List<Stand> standList = section.getStandList();
// for (Stand stand : standList) {
// if (stand.isEmergencyClosed()) {
// return new MovementAuthority.End(stand, MovementAuthority.EndType.EC_STAND, section);
// }
// }
// }
// }
// return null;
// }
//
// private MovementAuthority.End checkUnlockedOverlap(Simulation simulation, Section section, boolean right) {
// SimulationDataRepository repository = simulation.getRepository();
// // 判断是否已经办理进路的区段
// Route route = null;
// if (section.isRouteLock()) {
// List<Route> settingRoutes = repository.getSettingRoutes();
// for (Route settingRoute : settingRoutes) {
// if (settingRoute.isLastRouteSection(section)) {
// route = settingRoute;
// break;
// }
// }
// }
// if (Objects.nonNull(route) && repository.isOverlapNeedSetting(route)) { // 进路需要办理延续保护
// RouteOverlap overlap = route.getOverlap();
// if (!overlap.isLock()) { // 延续保护未锁闭
// return new MovementAuthority.End(overlap,
// MovementAuthority.EndType.UNLOCKED_OVERLAP, overlap.getSection());
// }
// }
// return null;
// }
//
// public void calculateMAOfITC(Simulation simulation, VirtualRealityTrain train) {
// // 查找移动授权终端列表
// List<MovementAuthority.End> endList = this.findItcMaEnd(train.getHeadPosition(), train.isRight());
// if (CollectionUtils.isEmpty(endList)) { // 未找到授权终点
// return;
// }
// // 根据查找到的授权终端比较并构建最终的移动授权数据
// MovementAuthority ma = this.compareAndBuildMa(train, endList);
// // 通知车载ATP
// this.onboardAtpApiService.updateMA4ITC(train, ma);
// }
//
// public MovementAuthority calculateMAOfITC(Simulation simulation, Responder responder) {
// // 查找移动授权终端列表
// List<MovementAuthority.End> endList = this.findItcMaEnd(responder.getPosition(), responder.getSignal().isRight());
// if (CollectionUtils.isEmpty(endList)) { // 未找到授权终点
// return null;
// }
// // 根据查找到的授权终端比较并构建最终的移动授权数据
// MovementAuthority ma = this.compareAndBuildMa(responder.getSignal().isRight(), endList);
// // 通知车载ATP
// return ma;
// }
//
// private List<MovementAuthority.End> findItcMaEnd(SectionPosition position, boolean right) {
// List<MovementAuthority.End> endList = new ArrayList<>();
// MovementAuthority.End deviceEnd = null;
// Section section = position.getSection();
// int count = 0;
// while (Objects.nonNull(section) && count < 20) {
// if (count > 1 && !CollectionUtils.isEmpty(endList))
// break;
// ++count;
// // 信号机
// MovementAuthority.End signalEnd = checkGroundSignal(section, right);
// if (Objects.nonNull(signalEnd)) {
// endList.add(signalEnd);
//// deviceEnd = signalEnd;
// break;
// }
// // 轨道尽头/问题道岔
// Section temp = section.getNextRunningSectionOf(right);
// if (Objects.isNull(temp)) { // 到尽头
// if (!section.isSwitchTrack()) { // 问题道岔
// endList.add(new MovementAuthority.End(section,
// MovementAuthority.EndType.END_TRACK));
// }
// break;
// }
// }
// if (Objects.nonNull(deviceEnd)) {
// endList.add(deviceEnd);
// }
// return endList;
// }
//
// /**
// * 比较并构建移动授权数据
// *
// * @param train
// * @param endList
// * @return
// */
// private MovementAuthority compareAndBuildMa(VirtualRealityTrain train, List<MovementAuthority.End> endList) {
// return compareAndBuildMa(train.isRight(), endList);
// }
//
// /**
// * 比较并构建移动授权数据
// *
// * @param endList
// * @return
// */
// private MovementAuthority compareAndBuildMa(boolean right, List<MovementAuthority.End> endList) {
// MovementAuthority.End end = null;
// if (endList.size() == 1) { // 只有一个直接构建移动授权
// end = endList.get(0);
// } else {
// for (MovementAuthority.End temp : endList) {
// if (Objects.isNull(end)) {
// end = temp;
// } else {
// if (end.isAheadOf(temp, right)) {
// end = temp;
// }
// }
// }
// }
// BusinessExceptionAssertEnum.SYSTEM_EXCEPTION.assertNotNull(end);
// end.confirmEndPosition(right);
// return new MovementAuthority(end);
// }
//
// private VirtualRealityTrain queryFrontTrain(VirtualRealityTrain train, List<VirtualRealityTrain> trainList) {
// boolean right = train.isRight();
// SectionPosition headPosition = train.getHeadPosition();
// VirtualRealityTrain front = null;
// Float distance = null;
// for (VirtualRealityTrain other : trainList) {
// if (Objects.equals(other, train)) {
// continue;
// }
// SectionPosition otherTrainPosition;
// if (Objects.equals(right, other.isRight())) {
// // 同向列车取车尾
// otherTrainPosition = other.calculateTailPosition();
//
// } else {
// // 反向列车取车头
// otherTrainPosition = other.getHeadPosition();
// }
// Float tempDistance = CalculateService.calculateDistance(headPosition, otherTrainPosition, right);
// if (Objects.isNull(tempDistance) || tempDistance < 0) {
// // 未找到
// continue;
// } else {
// if (Objects.isNull(front) || tempDistance < distance) {
// front = other;
// distance = tempDistance;
// }
// }
// }
//// if (Objects.nonNull(front)) {
//// log.debug(String.format("列车[%s-%s|%s|%s]前方列车为[%s-%s|%s|%s]",
//// train.getGroupNumber(), train.getServiceNumber(),
//// train.getTripNumber(), train.getDestinationCode(),
//// front.getGroupNumber(), front.getServiceNumber(),
//// front.getTripNumber(), front.getDestinationCode()));
//// }
// return front;
// }
//
// private MovementAuthority.End checkRouteLock(Simulation simulation, Section section, Section tailSection, boolean right, VirtualRealityTrain train) {
// if (section.isTransferTrack())
// return null;
// SimulationDataRepository repository = simulation.getRepository();
// // 判断前方是否有信号机(如果存在信号机则不判断进路锁闭以兼容现在列车加载到转换轨没有进路情况)
//// Signal aheadSignal = section.getSignalOf(right);
//// if (Objects.nonNull(aheadSignal)) {
//// return null;
//// }
// // 先查询是否是已排列的锁闭进路
// List<Route> settingRoutes = repository.getSettingRoutes();
// boolean lock = false;
// if (!CollectionUtils.isEmpty(settingRoutes)) {
// for (Route route : settingRoutes) {
// if (route.isRouteSection(section)
//// && !route.isSetting()
// ) {
// Signal signal = section.getSignalOf(right);
// if (route.isRight() == right || (signal == null || signal.isNormalOpen())) {
// lock = true;
// break;
// }
// }
// }
// }
// if (!lock) { // 未找到锁闭进路判断是否自动信号
// Section base = section;
// int count = 0;
// while (Objects.nonNull(base) && count < 20) {
// ++count;
// // 向反方向查找找信号机判断是否自动信号
// Section pre = base.getNextRunningSectionOf(!right);
// if (Objects.nonNull(pre)) {
// Signal signal = pre.getSignalOf(right);
// if (Objects.nonNull(signal)) {
// if (signal.isAutoSignal()) {
// lock = true; // 如果是自动信号也相当于锁闭
// }
// break; // 找到信号机结束
// }
// }
// base = pre;
// }
// }
// if (!lock) {
// // 未锁闭进路中设置移动授权终点
// return new MovementAuthority.End(section, MovementAuthority.EndType.UNLOCK_SECTION);
// }
// return null;
//
//
//// SimulationDataRepository repository = simulation.getRepository();
//// // 判断前方是否有信号机(如果存在信号机则不判断进路锁闭以兼容现在列车加载到转换轨没有进路情况)
//// if (section.isTransferTrack()) {
//// return null;
//// }
////// Signal aheadSignal = section.getSignalOf(right);
////// if (Objects.nonNull(aheadSignal)) {
////// return null;
////// }
//// // 先查询是否是已排列的锁闭进路
//// List<Route> settingRoutes = repository.getSettingRoutes();
//// boolean lock = false;
//// if (!CollectionUtils.isEmpty(settingRoutes)) {
//// boolean headRoute = false;
//// boolean tailRoute = false;
//// for (Route route : settingRoutes) {
//// if (route.isRight() == right && (route.isRouteSection(section) || route.isRouteSection(tailSection))) {
//// if (route.isRouteSection(section))
//// headRoute = true;
//// if (route.isRouteSection(tailSection))
//// tailRoute = true;
//// lock = true;
//// List<Switch> switches = screenSwitchesInFront(route, tailSection);
//// if (!this.checkRouteSwitchPosition(route, switches) || !this.isFlsCheckPass(route.getFlsList(), switches)) {
//// return new MovementAuthority.End(section, MovementAuthority.EndType.ROUTE_INTERLOCK_NOT_MET);
//// }
//// if (headRoute && tailRoute)
//// break;
//// }
//// }
//// }
//// if (!lock) { // 未找到锁闭进路判断是否自动信号
//// Section base = section;
//// int count = 0;
//// while (Objects.nonNull(base) && count < 20) {
//// ++count;
//// // 向反方向查找找信号机判断是否自动信号
//// Section pre = base.getNextRunningSectionOf(!right);
//// if (Objects.nonNull(pre)) {
//// Signal signal = pre.getSignalOf(right);
//// if (Objects.nonNull(signal)) {
//// if (signal.isAutoSignal()) {
//// lock = true; // 如果是自动信号也相当于锁闭
//// }
//// break; // 找到信号机结束
//// }
//// }
//// base = pre;
//// }
//// }
//// if (!lock && section.getSignalOf(right) == null) {
//// // 未锁闭进路中设置移动授权终点
//// return new MovementAuthority.End(section, MovementAuthority.EndType.UNLOCK_SECTION);
//// }
//// return null;
// }
//
// private boolean checkRouteSwitchPosition(Route route, List<Switch> switches) {
// List<SwitchElement> collect = route.getSwitchList().stream()
// .filter(element -> switches.contains(element.getASwitch()))
// .collect(Collectors.toList());
// return routeService.checkRouteSwitchPosition(collect);
// }
//
// private boolean isFlsCheckPass(List<RouteFls> flsList, List<Switch> switches) {
// if (!CollectionUtils.isEmpty(flsList) && !CollectionUtils.isEmpty(switches)) {
// List<RouteFls> collect = flsList.stream().filter(fls -> switches.contains(fls.getBase().getASwitch())).collect(Collectors.toList());
// return routeService.isFlsCheckPass(collect);
// }
// return true;
// }
//
// /**
// * 筛选前方的道岔
// */
// private List<Switch> screenSwitchesInFront(Route route, Section section) {
// boolean right = route.isRight();
// List<Section> sectionList = route.getSectionList();
// List<Switch> sectionRelSwitches = new ArrayList<>();
// for (int i = 0; i < 10; i++) {
// if (sectionList.contains(section))
// break;
// else
// section = section.getNextRunningSectionOf(right);
// }
// while (sectionList.contains(section)) {
// if (section.getRelSwitch() != null)
// sectionRelSwitches.add(section.getRelSwitch());
// section = section.getNextRunningSectionOf(right);
// }
// return sectionRelSwitches;
// }
//
// /**
// * 检查地面真实信号机是否未开放/故障信号机
// *
// * @param section
// * @param right
// * @return
// */
// private MovementAuthority.End checkGroundSignal(Section section, boolean right) {
// Signal signal = section.getSignalOf(right);
// if (Objects.nonNull(signal) && !signal.isVirtual() && !signal.isNormalOpen()) {
// return new MovementAuthority.End(signal,
// MovementAuthority.EndType.CLOSED_SIGNAL);
// }
// return null;
// }
//
// /**
// * 检查是否未开放/故障信号机
// *
// * @param section
// * @param right
// * @return
// */
// private MovementAuthority.End checkSignal(Section section, boolean right) {
// Signal signal = section.getSignalOf(right);
// if (Objects.nonNull(signal) && !signal.isNormalOpen()) {
// return new MovementAuthority.End(signal,
// MovementAuthority.EndType.CLOSED_SIGNAL);
// }
// return null;
// }
//
// /**
// * 检查是否站台屏蔽门开门
// */
// private MovementAuthority.End checkPsdOpenOrClose(Section section) {
// if (section.isStandTrack()) {
// List<Stand> standList = section.getStandList();
// for (Stand stand : standList) {
// if (!stand.isPsdSafe()) {
// return new MovementAuthority.End(stand, MovementAuthority.EndType.OPENED_PSD, section);
// }
// if (stand.isClosed()) {
// return new MovementAuthority.End(stand, MovementAuthority.EndType.CLOSED_STAND, section);
// }
// }
// }
// return null;
// }
//
//// public void addJobs(Simulation simulation) {
////// simulation.addJob(SimulationModule.ZC.name(), () -> this.run(simulation), SimulationConstants.ZC_LOOP_RATE);
//// simulation.addJob("MaCal", () -> this.maService.calculateMaOfCtcTrains(simulation), 1000);
//// }
//}

View File

@ -21,6 +21,7 @@ import club.joylink.rtss.vo.client.WebSocketMessageType;
import club.joylink.rtss.vo.client.factory.SocketMessageFactory; import club.joylink.rtss.vo.client.factory.SocketMessageFactory;
import club.joylink.rtss.websocket.StompMessageService; import club.joylink.rtss.websocket.StompMessageService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -33,14 +34,14 @@ import java.util.stream.Collectors;
@Component @Component
public class ATSMessageCollectAndDispatcher { public class ATSMessageCollectAndDispatcher {
@Autowired @Autowired
private Joylink3DMessageService joylink3DMessageService; private Joylink3DMessageService joylink3DMessageService;
@Autowired @Autowired
private StompMessageService stompMessageService; private StompMessageService stompMessageService;
@Autowired @Autowired
private ApplicationContext applicationContext; private ApplicationContext applicationContext;
// public void run(Simulation simulation) { // public void run(Simulation simulation) {
//// long start = System.currentTimeMillis(); //// long start = System.currentTimeMillis();
@ -62,222 +63,223 @@ public class ATSMessageCollectAndDispatcher {
//// System.out.println(String.format("收集并发送设备状态用时: [%s ms]", (end - start))); //// System.out.println(String.format("收集并发送设备状态用时: [%s ms]", (end - start)));
// } // }
/** /**
* 收集仿真所有设备状态并发送给仿真用户 * 收集仿真所有设备状态并发送给仿真用户
*/ */
public void collectAllAndSend(Simulation simulation) { public void collectAllAndSend(Simulation simulation) {
List<DeviceStatusVO> deviceStatuses = collectAll(simulation); List<DeviceStatusVO> deviceStatuses = collectAll(simulation);
// 构建并发送设备状态消息 // 构建并发送设备状态消息
SocketMessageVO<List<DeviceStatusVO>> deviceStatusMessage = SocketMessageVO<List<DeviceStatusVO>> deviceStatusMessage =
SocketMessageFactory.buildSimulationDeviceStatusesMessage(simulation.getId(), deviceStatuses); SocketMessageFactory.buildSimulationDeviceStatusesMessage(simulation.getId(), deviceStatuses);
Set<String> sessions = simulation.getSimulationUserIds(); Set<String> sessions = simulation.getSimulationUserIds();
stompMessageService.sendToUser(sessions, deviceStatusMessage); stompMessageService.sendToUser(sessions, deviceStatusMessage);
} }
/** /**
* 收集仿真所有设备状态 * 收集仿真所有设备状态
*/ */
public List<DeviceStatusVO> collectAll(Simulation simulation) { public List<DeviceStatusVO> collectAll(Simulation simulation) {
List<DeviceStatusVO> totalList = new ArrayList<>(); List<DeviceStatusVO> totalList = new ArrayList<>();
SimulationDataRepository repository = simulation.getRepository(); SimulationDataRepository repository = simulation.getRepository();
Map<String, ? extends MapElement> deviceMap = repository.getDeviceMap(); Map<String, ? extends MapElement> deviceMap = repository.getDeviceMap();
deviceMap.values().forEach(device -> { deviceMap.values().forEach(device -> {
DeviceStatus deviceStatus = repository.findStatusByCode(device.getCode()); DeviceStatus deviceStatus = repository.findStatusByCode(device.getCode());
if (Objects.isNull(deviceStatus)) { if (Objects.isNull(deviceStatus)) {
deviceStatus = buildDeviceStatus(device); deviceStatus = buildDeviceStatus(device);
if (Objects.nonNull(deviceStatus)) { if (Objects.nonNull(deviceStatus)) {
repository.addDeviceInfo(deviceStatus); repository.addDeviceInfo(deviceStatus);
totalList.add(deviceStatus.convert2VO(device)); totalList.add(deviceStatus.convert2VO(device));
} }
} else { } else {
DeviceStatusVO statusVO = buildDeviceStatusVO(device); DeviceStatusVO statusVO = buildDeviceStatusVO(device);
if (deviceStatus.compareAndChange(device, statusVO)) { if (deviceStatus.compareAndChange(device, statusVO)) {
totalList.add(statusVO); totalList.add(statusVO);
} }
} }
}); });
// 列车状态 // 列车状态
List<TrainInfo> trainList = repository.getSuperviseTrainList(); List<TrainInfo> trainList = repository.getSuperviseTrainList();
trainList.forEach(train -> { trainList.forEach(train -> {
TrainStatus trainStatus = repository.findStatusByCode(train.getGroupNumber(), TrainStatus.class); TrainStatus trainStatus = repository.findStatusByCode(train.getGroupNumber(), TrainStatus.class);
if (Objects.isNull(trainStatus)) { if (Objects.isNull(trainStatus)) {
// if(simulation.getBuildParams().getProdType() == MapPrdTypeEnum.YJDDZH){ // if(simulation.getBuildParams().getProdType() == MapPrdTypeEnum.YJDDZH){
if(Objects.equals(simulation.getProject(),MapPrdTypeEnum.YJDDZH.name())){ if (Objects.equals(simulation.getProject(), MapPrdTypeEnum.YJDDZH.name())) {
trainStatus = new YJDDZHTrainStatus(train); trainStatus = new YJDDZHTrainStatus(train);
}else{ } else {
trainStatus = new TrainStatus(train); trainStatus = new TrainStatus(train);
} }
repository.addDeviceInfo(trainStatus); repository.addDeviceInfo(trainStatus);
totalList.add(trainStatus.convert2VO(train)); totalList.add(trainStatus.convert2VO(train));
} else { } else {
DeviceStatusVO statusVO; DeviceStatusVO statusVO;
// if(simulation.getBuildParams().getProdType() == MapPrdTypeEnum.YJDDZH){ // if(simulation.getBuildParams().getProdType() == MapPrdTypeEnum.YJDDZH){
if(Objects.equals(simulation.getProject(),MapPrdTypeEnum.YJDDZH.name())){ if (Objects.equals(simulation.getProject(), MapPrdTypeEnum.YJDDZH.name())) {
statusVO = new YJDDZHTrainStatusVO(train); statusVO = new YJDDZHTrainStatusVO(train);
}else{ } else {
statusVO = new TrainStatusVO(train); // statusVO = new TrainStatusVO(train);
} statusVO = new TrainStatusVO(trainStatus);
if (trainStatus.compareAndChange(train, statusVO)) {
totalList.add(statusVO);
}
}
});
// 回库删除的列车状态
List<TrainStatus> inboundTrainList = new ArrayList<>();
List<TrainStatus> trainStatusList = repository.getTrainStatusList();
if (!CollectionUtils.isEmpty(trainStatusList)) {
for (TrainStatus trainStatus : trainStatusList) {
TrainInfo trainInfo = repository.findSupervisedTrainByGroup(trainStatus.getGroupNumber());
if (Objects.isNull(trainInfo)) {
totalList.add(TrainStatusVO.buildDispose(trainStatus.getGroupNumber()));
inboundTrainList.add(trainStatus);
repository.deleteDeviceStatus(trainStatus.getCode());
}
}
} }
joylink3DMessageService.handleTrainInbound(simulation, inboundTrainList); if (trainStatus.compareAndChange(train, statusVO)) {
return totalList; totalList.add(statusVO);
}
private DeviceStatus buildDeviceStatus(MapElement device) {
DeviceStatus status = null;
switch (device.getDeviceType()) {
case SECTION:
status = new SectionStatus((Section) device);
break;
case SWITCH:
status = new SwitchStatus((Switch) device);
break;
case SIGNAL:
status = new SignalStatus((Signal) device);
break;
case STATION:
status = new StationStatus((Station) device);
break;
case STAND:
status = new StandStatus((Stand) device);
break;
case PSD:
status = new PSDStatus((PSD) device);
break;
case ZC:
status = new ZCStatus((ZC) device);
break;
case ROUTE:
status = new RouteStatus((Route) device);
break;
case OVERLAP: {
status = new OverlapStatus((RouteOverlap) device);
break;
}
case CYCLE:
status = new CycleStatus((Cycle) device);
break;
case DIRECTION_ROD:
status = new DirectionRodStatus((DirectionRod) device);
break;
case CATENARY:
status = new CatenaryStatus((Catenary) device);
break;
case STATION_DIRECTION:
status = new StationDirectionStatus((StationDirection) device);
break;
} }
return status; }
} });
// 回库删除的列车状态
private DeviceStatusVO buildDeviceStatusVO(MapElement device) { List<TrainStatus> inboundTrainList = new ArrayList<>();
DeviceStatusVO status = null; List<TrainStatus> trainStatusList = repository.getTrainStatusList();
switch (device.getDeviceType()) { if (!CollectionUtils.isEmpty(trainStatusList)) {
case SECTION: for (TrainStatus trainStatus : trainStatusList) {
status = new SectionStatusVO((Section) device); TrainInfo trainInfo = repository.findSupervisedTrainByGroup(trainStatus.getGroupNumber());
break; if (Objects.isNull(trainInfo)) {
case SWITCH: totalList.add(TrainStatusVO.buildDispose(trainStatus.getGroupNumber()));
status = new SwitchStatusVO((Switch) device); inboundTrainList.add(trainStatus);
break; repository.deleteDeviceStatus(trainStatus.getCode());
case SIGNAL:
status = new SignalStatusVO((Signal) device);
break;
case STATION:
status = new StationStatusVO((Station) device);
break;
case STAND:
status = new StandStatusVO((Stand) device);
break;
case PSD:
status = new PSDStatusVO((PSD) device);
break;
case ZC:
status = new ZCStatusVO((ZC) device);
break;
case ROUTE:
status = new RouteStatusVO((Route) device);
break;
case OVERLAP: {
status = new OverlapStatusVO((RouteOverlap) device);
break;
}
case CYCLE:
status = new CycleStatusVO((Cycle) device);
break;
case DIRECTION_ROD:
status = new DirectionRodStatusVO((DirectionRod) device);
break;
case CATENARY:
status = new CatenaryStatusVO((Catenary) device);
break;
case STATION_DIRECTION:
status = new StationDirectionStatusVO((StationDirection) device);
break;
} }
return status; }
} }
joylink3DMessageService.handleTrainInbound(simulation, inboundTrainList);
return totalList;
}
/** private DeviceStatus buildDeviceStatus(MapElement device) {
* 列车运行数据 DeviceStatus status = null;
*/ switch (device.getDeviceType()) {
public void sendTrainRunData(Simulation simulation, RealRun realRun) { case SECTION:
stompMessageService.sendToUser(simulation.getSimulationUserIds(), status = new SectionStatus((Section) device);
SocketMessageFactory.build(WebSocketMessageType.Simulation_RunFact, break;
simulation.getId(), Arrays.asList(realRun))); case SWITCH:
} status = new SwitchStatus((Switch) device);
break;
case SIGNAL:
status = new SignalStatus((Signal) device);
break;
case STATION:
status = new StationStatus((Station) device);
break;
case STAND:
status = new StandStatus((Stand) device);
break;
case PSD:
status = new PSDStatus((PSD) device);
break;
case ZC:
status = new ZCStatus((ZC) device);
break;
case ROUTE:
status = new RouteStatus((Route) device);
break;
case OVERLAP: {
status = new OverlapStatus((RouteOverlap) device);
break;
}
case CYCLE:
status = new CycleStatus((Cycle) device);
break;
case DIRECTION_ROD:
status = new DirectionRodStatus((DirectionRod) device);
break;
case CATENARY:
status = new CatenaryStatus((Catenary) device);
break;
/** case STATION_DIRECTION:
* 仿真设备操作消息 status = new StationDirectionStatus((StationDirection) device);
*/ break;
public void handlerOperateMessage(Simulation simulation, OperationMessage operationMessage) {
SocketMessageVO<OperationMessage> socketMessageVO =
SocketMessageFactory.build(WebSocketMessageType.Simulation_ApplyHandle, simulation.getId(), operationMessage);
Set<SimulationMember> humanMembers = operationMessage.getTargetMembers().stream().filter(m -> !m.isRobot()).collect(Collectors.toSet());
//当在场景实训设计中并且无真人成员时将数据暂存等待后续角色有人扮演时再发送
if (simulation.isInSceneTraining() && CollectionUtils.isEmpty(humanMembers)) {
for (SimulationMember targetMember : operationMessage.getTargetMembers()) {
targetMember.getUnreceivedMessages().offer(socketMessageVO);
}
return;
}
if (CollectionUtils.isEmpty(humanMembers)) {
//目标都是机器人选择一个机器人发送事件处理
applicationContext.publishEvent(new SimulationOperationMessageEvent(this, simulation, operationMessage));
return;
}
//目标成员有真人推送对应真人处理
stompMessageService.sendToUser(humanMembers.stream().map(SimulationMember::getUserId).collect(Collectors.toSet()), socketMessageVO);
} }
return status;
}
/** private DeviceStatusVO buildDeviceStatusVO(MapElement device) {
* 同步仿真系统时间给客户端 DeviceStatusVO status = null;
*/ switch (device.getDeviceType()) {
public void syncTime(Simulation simulation) { case SECTION:
Set<String> sessions = simulation.getSimulationUserIds(); status = new SectionStatusVO((Section) device);
SocketMessageVO<Long> timeSyncMessage = SocketMessageFactory.buildSimulationTimeSyncMessage(simulation); break;
stompMessageService.sendToUser(sessions, timeSyncMessage); case SWITCH:
} status = new SwitchStatusVO((Switch) device);
break;
case SIGNAL:
status = new SignalStatusVO((Signal) device);
break;
case STATION:
status = new StationStatusVO((Station) device);
break;
case STAND:
status = new StandStatusVO((Stand) device);
break;
case PSD:
status = new PSDStatusVO((PSD) device);
break;
case ZC:
status = new ZCStatusVO((ZC) device);
break;
case ROUTE:
status = new RouteStatusVO((Route) device);
break;
case OVERLAP: {
status = new OverlapStatusVO((RouteOverlap) device);
break;
}
case CYCLE:
status = new CycleStatusVO((Cycle) device);
break;
case DIRECTION_ROD:
status = new DirectionRodStatusVO((DirectionRod) device);
break;
case CATENARY:
status = new CatenaryStatusVO((Catenary) device);
break;
public void addJobs(Simulation simulation) { case STATION_DIRECTION:
simulation.addJob(SimulationModule.SYNC_TIME.name(), () -> syncTime(simulation), SimulationConstants.SYNC_TIME_RATE); status = new StationDirectionStatusVO((StationDirection) device);
simulation.addFixedRateJob(SimulationModule.MESSAGE.name(), () -> collectAllAndSend(simulation), SimulationConstants.SEND_CLIENT_RATE); break;
} }
return status;
}
/**
* 列车运行数据
*/
public void sendTrainRunData(Simulation simulation, RealRun realRun) {
stompMessageService.sendToUser(simulation.getSimulationUserIds(),
SocketMessageFactory.build(WebSocketMessageType.Simulation_RunFact,
simulation.getId(), Arrays.asList(realRun)));
}
/**
* 仿真设备操作消息
*/
public void handlerOperateMessage(Simulation simulation, OperationMessage operationMessage) {
SocketMessageVO<OperationMessage> socketMessageVO =
SocketMessageFactory.build(WebSocketMessageType.Simulation_ApplyHandle, simulation.getId(), operationMessage);
Set<SimulationMember> humanMembers = operationMessage.getTargetMembers().stream().filter(m -> !m.isRobot()).collect(Collectors.toSet());
//当在场景实训设计中并且无真人成员时将数据暂存等待后续角色有人扮演时再发送
if (simulation.isInSceneTraining() && CollectionUtils.isEmpty(humanMembers)) {
for (SimulationMember targetMember : operationMessage.getTargetMembers()) {
targetMember.getUnreceivedMessages().offer(socketMessageVO);
}
return;
}
if (CollectionUtils.isEmpty(humanMembers)) {
//目标都是机器人选择一个机器人发送事件处理
applicationContext.publishEvent(new SimulationOperationMessageEvent(this, simulation, operationMessage));
return;
}
//目标成员有真人推送对应真人处理
stompMessageService.sendToUser(humanMembers.stream().map(SimulationMember::getUserId).collect(Collectors.toSet()), socketMessageVO);
}
/**
* 同步仿真系统时间给客户端
*/
public void syncTime(Simulation simulation) {
Set<String> sessions = simulation.getSimulationUserIds();
SocketMessageVO<Long> timeSyncMessage = SocketMessageFactory.buildSimulationTimeSyncMessage(simulation);
stompMessageService.sendToUser(sessions, timeSyncMessage);
}
public void addJobs(Simulation simulation) {
simulation.addJob(SimulationModule.SYNC_TIME.name(), () -> syncTime(simulation), SimulationConstants.SYNC_TIME_RATE);
simulation.addFixedRateJob(SimulationModule.MESSAGE.name(), () -> collectAllAndSend(simulation), SimulationConstants.SEND_CLIENT_RATE);
}
} }

View File

@ -46,7 +46,14 @@ public class SortDiagramStation {
private Station findNotDepotStation(boolean isRight, int index) { private Station findNotDepotStation(boolean isRight, int index) {
Station station = stationList.get(index); Station station = null;
if (index >= stationList.size()) {
station = stationList.get(stationList.size() - 1);
} else if (index <= 0) {
station = stationList.get(0);
} else {
station = stationList.get(index);
}
while (station.isDepot()) { while (station.isDepot()) {
index += isRight ? -1 : 1; index += isRight ? -1 : 1;
station = stationList.get(index); station = stationList.get(index);

View File

@ -32,6 +32,7 @@ public abstract class AtsRouteSelectService {
* 查询需要触发的进路 * 查询需要触发的进路
* *
* @param simulation * @param simulation
* @param targetList 运行计划中的计划区段包含站后折返轨
* @param turnBackSection 站后折返的折返轨 * @param turnBackSection 站后折返的折返轨
* @return * @return
*/ */
@ -63,13 +64,18 @@ public abstract class AtsRouteSelectService {
MapConfig config = repository.getConfig(); MapConfig config = repository.getConfig();
if (!config.isSignalOpenAfterParking() || (headSection.equals(planSection) if (!config.isSignalOpenAfterParking() || (headSection.equals(planSection)
&& trainInfo.isParking())) { //不需要停站就可以开放信号机或者已经在计划区段停站可以继续向前办理进路 && trainInfo.isParking())) { //不需要停站就可以开放信号机或者已经在计划区段停站可以继续向前办理进路
if (nextPlanSection != null) { //计划区段路径未跑完 //根据车站折返策略处理
Station station = planSection.getStation();
if (station.getTbStrategyId() != null && Objects.equals(turnBackSection,
nextPlanSection)) { //有折返策略时按折返策略
return queryTriggerRoutes4TurnBack(simulation, planSection, turnBackSection, trainInfo);
} else if (nextPlanSection != null) { //无折返策略按计划
routePaths = repository.queryRoutePaths(planSection, nextPlanSection); routePaths = repository.queryRoutePaths(planSection, nextPlanSection);
if (!CollectionUtils.isEmpty(routePaths)) { if (!CollectionUtils.isEmpty(routePaths)) {
return this.queryTriggerRoutesOfRoutePath(repository, trainInfo, routePaths, return this.queryTriggerRoutesOfRoutePath(repository, trainInfo, routePaths,
nextPlanSection).getRoute(); nextPlanSection).getRoute();
} }
} else if (turnBackSection != null) { //站后折返 } else if (turnBackSection != null) {
return queryTriggerRoutes4TurnBack(simulation, planSection, turnBackSection, trainInfo); return queryTriggerRoutes4TurnBack(simulation, planSection, turnBackSection, trainInfo);
} }
} }

View File

@ -5,23 +5,26 @@ import club.joylink.rtss.simulation.cbtc.ATS.service.AtsStandService;
import club.joylink.rtss.simulation.cbtc.ATS.service.AtsTrainService; import club.joylink.rtss.simulation.cbtc.ATS.service.AtsTrainService;
import club.joylink.rtss.simulation.cbtc.Simulation; import club.joylink.rtss.simulation.cbtc.Simulation;
import club.joylink.rtss.simulation.cbtc.data.SimulationDataRepository; import club.joylink.rtss.simulation.cbtc.data.SimulationDataRepository;
import club.joylink.rtss.simulation.cbtc.data.map.*; import club.joylink.rtss.simulation.cbtc.data.map.MapConfig;
import club.joylink.rtss.simulation.cbtc.data.map.Route;
import club.joylink.rtss.simulation.cbtc.data.map.Section;
import club.joylink.rtss.simulation.cbtc.data.map.Signal;
import club.joylink.rtss.simulation.cbtc.data.map.Stand;
import club.joylink.rtss.simulation.cbtc.data.plan.StationPlan; import club.joylink.rtss.simulation.cbtc.data.plan.StationPlan;
import club.joylink.rtss.simulation.cbtc.data.plan.TripPlan; import club.joylink.rtss.simulation.cbtc.data.plan.TripPlan;
import club.joylink.rtss.simulation.cbtc.data.support.RoutePath; import club.joylink.rtss.simulation.cbtc.data.support.RoutePath;
import club.joylink.rtss.simulation.cbtc.data.vo.TrainInfo; import club.joylink.rtss.simulation.cbtc.data.vo.TrainInfo;
import club.joylink.rtss.simulation.cbtc.onboard.ATP.OnboardAtpApiService; import club.joylink.rtss.simulation.cbtc.onboard.ATP.OnboardAtpApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.LocalTime; import java.time.LocalTime;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
/** /**
* 计划车阶段处理服务 * 计划车阶段处理服务
@ -29,44 +32,47 @@ import java.util.Objects;
@Slf4j @Slf4j
@Component @Component
public class AtsPlanTrainStageService implements AtsStageService { public class AtsPlanTrainStageService implements AtsStageService {
@Autowired
private AtsRealRunRecordService realRunRecordService;
@Autowired
private AtsStandService atsStandService;
@Autowired
private OnboardAtpApiService onboardAtpApiService;
@Autowired
private AtsTrainService atsTrainService;
@Override @Autowired
public void handleTransferTrackParking(Simulation simulation, TrainInfo trainInfo, Section parkSection) { private AtsRealRunRecordService realRunRecordService;
SimulationDataRepository repository = simulation.getRepository(); @Autowired
TripPlan tripPlan = repository.getTripPlan(trainInfo.getServiceNumber(), trainInfo.getTripNumber()); private AtsStandService atsStandService;
@Autowired
private OnboardAtpApiService onboardAtpApiService;
@Autowired
private AtsTrainService atsTrainService;
@Override
public void handleTransferTrackParking(Simulation simulation, TrainInfo trainInfo,
Section parkSection) {
SimulationDataRepository repository = simulation.getRepository();
TripPlan tripPlan = repository.getTripPlan(trainInfo.getServiceNumber(),
trainInfo.getTripNumber());
// List<RoutePath> routePathList = repository.queryRoutePathsByEnd(parkSection); // List<RoutePath> routePathList = repository.queryRoutePathsByEnd(parkSection);
// if (routePathList.get(0).isRight() == trainInfo.getRight()) { //准备回库 // if (routePathList.get(0).isRight() == trainInfo.getRight()) { //准备回库
// if (!parkSection.isTurnBackTrack()) { //针对上饶沙盘 // if (!parkSection.isTurnBackTrack()) { //针对上饶沙盘
// trainInfo.finishPlanPrepareInbound(); // trainInfo.finishPlanPrepareInbound();
// } // }
// } else 没看懂为啥有这部分逻辑先注掉 // } else 没看懂为啥有这部分逻辑先注掉
if (tripPlan.getEndSection().equals(parkSection) || if (tripPlan.getEndSection().equals(parkSection) ||
tripPlan.getEndSection().getStation().equals(parkSection.getStation())) { tripPlan.getEndSection().getStation().equals(parkSection.getStation())) {
// 列车到达计划终点准备回库 // 列车到达计划终点准备回库
if (simulation.getRepository().getConfig().isHandleDepot()) { if (simulation.getRepository().getConfig().isHandleDepot()) {
trainInfo.finishPlanPrepareEnterDepot(); trainInfo.finishPlanPrepareEnterDepot();
} else { } else {
if (!parkSection.isTurnBackTrack()) { //针对上饶沙盘 if (!parkSection.isTurnBackTrack()) { //针对上饶沙盘
trainInfo.finishPlanPrepareInbound(); trainInfo.finishPlanPrepareInbound();
} }
} }
//转人工车 //转人工车
atsTrainService.setManualTrain(simulation, trainInfo.getGroupNumber()); atsTrainService.setManualTrain(simulation, trainInfo.getGroupNumber());
} else if (tripPlan.getStartSection().equals(parkSection)) { } else if (tripPlan.getStartSection().equals(parkSection)) {
// 出库列车 // 出库列车
if (trainInfo.getPlanStandTrack() != null) { if (trainInfo.getPlanStandTrack() != null) {
return; return;
} }
LocalDateTime systemTime = simulation.getSystemTime(); LocalDateTime systemTime = simulation.getSystemTime();
if (systemTime.toLocalTime().isAfter(tripPlan.getStartTime())) { if (systemTime.toLocalTime().isAfter(tripPlan.getStartTime())) {
// Integer intervalTime = repository.getIntervalTime(); // Integer intervalTime = repository.getIntervalTime();
// LocalDateTime lastDepartTime = repository.getLastDepartTime(); // LocalDateTime lastDepartTime = repository.getLastDepartTime();
// if (intervalTime != null && lastDepartTime != null) { // if (intervalTime != null && lastDepartTime != null) {
@ -74,261 +80,289 @@ public class AtsPlanTrainStageService implements AtsStageService {
// return; // return;
// } // }
// } // }
StationPlan nextPlan = tripPlan.getSecondStationPlan(); StationPlan nextPlan = tripPlan.getSecondStationPlan();
this.updateNextPlan(simulation, trainInfo, tripPlan, nextPlan); this.updateNextPlan(simulation, trainInfo, tripPlan, nextPlan);
// repository.setLastDepartTime(systemTime); // repository.setLastDepartTime(systemTime);
} }
}
} }
}
@Override @Override
public void handleNormalStandParking(Simulation simulation, TrainInfo trainInfo, Section parkSection) { public void handleNormalStandParking(Simulation simulation, TrainInfo trainInfo,
SimulationDataRepository repository = simulation.getRepository(); Section parkSection) {
MapConfig config = repository.getConfig(); SimulationDataRepository repository = simulation.getRepository();
List<Stand> standList = parkSection.getStandList(); MapConfig config = repository.getConfig();
TripPlan tripPlan = repository.getTripPlan(trainInfo.getServiceNumber(), trainInfo.getTripNumber()); List<Stand> standList = parkSection.getStandList();
TripPlan nextTripPlan = null; TripPlan tripPlan = repository.getTripPlan(trainInfo.getServiceNumber(),
StationPlan stationPlan = tripPlan.queryStationPlan(parkSection); trainInfo.getTripNumber());
if (config.isStandTbStrategyIsInvalid()) { TripPlan nextTripPlan = null;
if (stationPlan != null && tripPlan.isLastPlan(stationPlan) && tripPlan.isFrontTurnBack()) { // 到达终点站了判断站前折返还是站后折返 StationPlan stationPlan = tripPlan.queryStationPlan(parkSection);
// 站前折返查询下一车次计划 if (config.isStandTbStrategyIsInvalid()) {
if (stationPlan != null && tripPlan.isLastPlan(stationPlan)
&& tripPlan.isFrontTurnBack()) { // 到达终点站了判断站前折返还是站后折返
// 站前折返查询下一车次计划
nextTripPlan = repository.queryNextTripPlanOf(tripPlan);
} else if (stationPlan == null && tripPlan.isLastPlanStation(parkSection.getStation())) {
if (config.isAtsAutoHandleManualFrontTurnBack()) {
// 人工站前折返
nextTripPlan = repository.queryNextTripPlanOf(tripPlan);
}
}
if (nextTripPlan != null) { // 站前折返更新计划
this.updateTripPlan(simulation, trainInfo, nextTripPlan);
BusinessExceptionAssertEnum.DATA_ERROR.assertEquals(
nextTripPlan.getFirstStationPlan().getSection(), parkSection,
String.format("下一车次计划[%s]第一站台轨和停靠站台轨不相同:[%s]",
nextTripPlan.getStNumber(), parkSection.getName()));
this.updateNextPlan(simulation, trainInfo, nextTripPlan,
nextTripPlan.getFirstStationPlan());
}
} else {
if (!CollectionUtils.isEmpty(standList)) {
Stand stand = standList.get(0);
switch (stand.getTypeStrategy()) {
case NONE:
return;
case AUTO:
if (stationPlan != null && tripPlan.isLastPlan(stationPlan)) { // 当前计划终点站
if (Objects.equals(stand.isRight(), trainInfo.getRight())) {
onboardAtpApiService.startTurnBack(simulation, trainInfo.getGroupNumber(),
parkSection.getCode());
nextTripPlan = repository.queryNextTripPlanOf(tripPlan); nextTripPlan = repository.queryNextTripPlanOf(tripPlan);
} else if (stationPlan == null && tripPlan.isLastPlanStation(parkSection.getStation())) { if (nextTripPlan != null) { // 站前折返更新计划
if (config.isAtsAutoHandleManualFrontTurnBack()) { this.updateTripPlan(simulation, trainInfo, nextTripPlan);
// 人工站前折返 this.updateNextPlan(simulation, trainInfo, nextTripPlan,
nextTripPlan = repository.queryNextTripPlanOf(tripPlan); nextTripPlan.getSecondStationPlan());
} }
}
}
break;
default:
if (stationPlan != null && tripPlan.isLastPlan(stationPlan)
&& tripPlan.isFrontTurnBack()) { // 到达终点站了判断站前折返还是站后折返
// 站前折返查询下一车次计划
nextTripPlan = repository.queryNextTripPlanOf(tripPlan);
} else if (stationPlan == null && tripPlan.isLastPlanStation(
parkSection.getStation())) {
if (config.isAtsAutoHandleManualFrontTurnBack()) {
// 人工站前折返
nextTripPlan = repository.queryNextTripPlanOf(tripPlan);
}
} }
if (nextTripPlan != null) { // 站前折返更新计划 if (nextTripPlan != null) { // 站前折返更新计划
this.updateTripPlan(simulation, trainInfo, nextTripPlan); this.updateTripPlan(simulation, trainInfo, nextTripPlan);
BusinessExceptionAssertEnum.DATA_ERROR.assertEquals(nextTripPlan.getFirstStationPlan().getSection(), parkSection, BusinessExceptionAssertEnum.DATA_ERROR.assertEquals(
String.format("下一车次计划[%s]第一站台轨和停靠站台轨不相同:[%s]", nextTripPlan.getStNumber(), parkSection.getName())); nextTripPlan.getFirstStationPlan().getSection(), parkSection,
this.updateNextPlan(simulation, trainInfo, nextTripPlan, nextTripPlan.getFirstStationPlan()); String.format("下一车次计划[%s]第一站台轨和停靠站台轨不相同:[%s]",
} nextTripPlan.getStNumber(), parkSection.getName()));
} else { this.updateNextPlan(simulation, trainInfo, nextTripPlan,
if (!CollectionUtils.isEmpty(standList)) { nextTripPlan.getFirstStationPlan());
Stand stand = standList.get(0);
switch (stand.getTypeStrategy()) {
case NONE:
return;
case AUTO:
if (stationPlan != null && tripPlan.isLastPlan(stationPlan)) { // 当前计划终点站
if (Objects.equals(stand.isRight(), trainInfo.getRight())) {
onboardAtpApiService.startTurnBack(simulation, trainInfo.getGroupNumber(), parkSection.getCode());
nextTripPlan = repository.queryNextTripPlanOf(tripPlan);
if (nextTripPlan != null) { // 站前折返更新计划
this.updateTripPlan(simulation, trainInfo, nextTripPlan);
this.updateNextPlan(simulation, trainInfo, nextTripPlan, nextTripPlan.getSecondStationPlan());
}
}
}
break;
default:
if (stationPlan != null && tripPlan.isLastPlan(stationPlan) && tripPlan.isFrontTurnBack()) { // 到达终点站了判断站前折返还是站后折返
// 站前折返查询下一车次计划
nextTripPlan = repository.queryNextTripPlanOf(tripPlan);
} else if (stationPlan == null && tripPlan.isLastPlanStation(parkSection.getStation())) {
if (config.isAtsAutoHandleManualFrontTurnBack()) {
// 人工站前折返
nextTripPlan = repository.queryNextTripPlanOf(tripPlan);
}
}
if (nextTripPlan != null) { // 站前折返更新计划
this.updateTripPlan(simulation, trainInfo, nextTripPlan);
BusinessExceptionAssertEnum.DATA_ERROR.assertEquals(nextTripPlan.getFirstStationPlan().getSection(), parkSection,
String.format("下一车次计划[%s]第一站台轨和停靠站台轨不相同:[%s]", nextTripPlan.getStNumber(), parkSection.getName()));
this.updateNextPlan(simulation, trainInfo, nextTripPlan, nextTripPlan.getFirstStationPlan());
}
break;
}
} }
break;
} }
}
} }
}
@Override @Override
public void ready2DepartFromNormalStand(Simulation simulation, TrainInfo trainInfo, Section parkSection) { public void ready2DepartFromNormalStand(Simulation simulation, TrainInfo trainInfo,
SimulationDataRepository repository = simulation.getRepository(); Section parkSection) {
TripPlan tripPlan = repository.getTripPlan(trainInfo.getServiceNumber(), trainInfo.getTripNumber()); SimulationDataRepository repository = simulation.getRepository();
StationPlan stationPlan = tripPlan.queryStationPlan(parkSection); TripPlan tripPlan = repository.getTripPlan(trainInfo.getServiceNumber(),
if (stationPlan == null) { trainInfo.getTripNumber());
// 非计划中的停靠站台轨暂不处理 StationPlan stationPlan = tripPlan.queryStationPlan(parkSection);
return; if (stationPlan == null) {
} else { // 非计划中的停靠站台轨暂不处理
// 计划站台轨停车 return;
if (trainInfo.isTurnBack()) {//准备折返 } else {
return; // 计划站台轨停车
} if (trainInfo.isTurnBack()) {//准备折返
if (!parkSection.isSamePhysical(trainInfo.getPlanStandTrack())) { return;
// 已经更新过计划 }
return; if (!parkSection.isSamePhysical(trainInfo.getPlanStandTrack())) {
} // 已经更新过计划
if (tripPlan.isLastPlan(stationPlan)) { return;
if (tripPlan.isBackup() && parkSection.equals(tripPlan.getEndSection())) { }
return; if (tripPlan.isLastPlan(stationPlan)) {
} if (tripPlan.isBackup() && parkSection.equals(tripPlan.getEndSection())) {
// 到达终点站准备折返 return;
log.debug(String.format("列车[%s]折返初始化", trainInfo.getGroupNumber()));
List<RoutePath> routePaths = repository.getRoutePaths(parkSection, tripPlan.getEndSection());
Signal signal = parkSection.getSignalOf(routePaths.get(0).isRight());
if (signal.isMainAspect() || signal.isGuideAspect()) {
Route lockedRoute = signal.getLockedRoute();
if (lockedRoute != null && lockedRoute.getLastRouteSection().isTurnBackTrack()) {
trainInfo.turnBackInit(lockedRoute.getLastRouteSection());
this.onboardAtpApiService.startTurnBack(simulation, trainInfo.getGroupNumber(),
lockedRoute.getLastRouteSection().getCode());
}
}
} else {
StationPlan nextStationPlan = tripPlan.queryNextStationPlan(parkSection);
this.updateNextPlan(simulation, trainInfo, tripPlan, nextStationPlan);
}
} }
// 到达终点站准备折返
log.debug(String.format("列车[%s]折返初始化", trainInfo.getGroupNumber()));
List<RoutePath> routePaths = repository.getRoutePaths(parkSection,
tripPlan.getEndSection());
Signal signal = parkSection.getSignalOf(routePaths.get(0).isRight());
if (signal.isMainAspect() || signal.isGuideAspect()) {
Route lockedRoute = signal.getLockedRoute();
if (lockedRoute != null && lockedRoute.getLastRouteSection().isTurnBackTrack()) {
trainInfo.turnBackInit(lockedRoute.getLastRouteSection());
this.onboardAtpApiService.startTurnBack(simulation, trainInfo.getGroupNumber(),
lockedRoute.getLastRouteSection().getCode());
}
}
} else {
StationPlan nextStationPlan = tripPlan.queryNextStationPlan(parkSection);
this.updateNextPlan(simulation, trainInfo, tripPlan, nextStationPlan);
}
} }
}
void updateTripPlan(Simulation simulation, TrainInfo trainInfo, TripPlan nextTripPlan) { void updateTripPlan(Simulation simulation, TrainInfo trainInfo, TripPlan nextTripPlan) {
trainInfo.applyNewTripPlan(nextTripPlan); trainInfo.applyNewTripPlan(nextTripPlan);
this.onboardAtpApiService.updateTripPlan(simulation, trainInfo.getGroupNumber(), nextTripPlan); this.onboardAtpApiService.updateTripPlan(simulation, trainInfo.getGroupNumber(), nextTripPlan);
}
public void updateNextPlan(Simulation simulation, TrainInfo trainInfo, TripPlan tripPlan,
StationPlan nextStationPlan) {
if (nextStationPlan == null) {
log.warn(String.format("列车[%s]下一计划到站为null", trainInfo.debugStr()));
return;
} }
trainInfo.updatePlanInfo(nextStationPlan);
public void updateNextPlan(Simulation simulation, TrainInfo trainInfo, TripPlan tripPlan, StationPlan nextStationPlan) { Section nextPlanSection = nextStationPlan.getSection();
if (nextStationPlan == null) { trainInfo.updateEstimatedArriveInfo(nextPlanSection, nextStationPlan.getArriveTime());
log.warn(String.format("列车[%s]下一计划到站为null", trainInfo.debugStr())); int runTime = this.calculateRunTime(simulation, trainInfo, tripPlan, nextStationPlan);
return; boolean park = nextStationPlan.isPark();
} if (tripPlan.isLastPlan(nextStationPlan)) {
trainInfo.updatePlanInfo(nextStationPlan); park = true;
Section nextPlanSection = nextStationPlan.getSection();
trainInfo.updateEstimatedArriveInfo(nextPlanSection, nextStationPlan.getArriveTime());
int runTime = this.calculateRunTime(simulation, trainInfo, tripPlan, nextStationPlan);
boolean park = nextStationPlan.isPark();
if (tripPlan.isLastPlan(nextStationPlan)) {
park = true;
}
boolean jump = this.atsStandService.isJump(nextPlanSection, trainInfo.getGroupNumber());
if (tripPlan.isLastPlan(nextStationPlan) && jump) {
jump = false;
}
this.onboardAtpApiService.updateNextArriveInfo(simulation, trainInfo.getGroupNumber(),
nextPlanSection, park, runTime, jump);
} }
boolean jump = this.atsStandService.isJump(nextPlanSection, trainInfo.getGroupNumber());
private int calculateRunTime(Simulation simulation, TrainInfo trainInfo, if (tripPlan.isLastPlan(nextStationPlan) && jump) {
TripPlan tripPlan, StationPlan nextStationPlan) { jump = false;
MapConfig config = simulation.getRepository().getConfig();
LocalDateTime systemTime = simulation.getSystemTime();
Section start;
Section end = nextStationPlan.getSection();
LocalTime startTime;
LocalTime endTime = nextStationPlan.getArriveTime();
List<StationPlan> planList = tripPlan.getPlanList();
boolean turnBack = true;
boolean outbound = false;
startTime = tripPlan.getStartTime();
start = tripPlan.getStartSection();
for (StationPlan stationPlan : planList) {
if (stationPlan.equals(nextStationPlan)) {
break;
}
turnBack = false;
if (stationPlan.getSection().isTransferTrack()) {
outbound = true;
} else {
outbound = false;
}
startTime = stationPlan.getLeaveTime();
start = stationPlan.getSection();
}
int planRunTime = (int) ChronoUnit.SECONDS.between(startTime, endTime);
int adjustRunTime = planRunTime;
if (!turnBack && !outbound && config.isAdjustOperationAutomatically() && trainInfo.isAtsAutoAdjust()) {
startTime = systemTime.toLocalTime();
adjustRunTime = (int) ChronoUnit.SECONDS.between(startTime, endTime);
}
int runTime = Math.min(adjustRunTime, planRunTime + 30);
if (runTime <= 0) {
runTime = 1;
}
log.debug(String.format("列车[%s]站间[%s->%s]运行时间为:[%s]", trainInfo.getGroupNumber(),
start.debugStr(), end.debugStr(), runTime));
return runTime;
} }
this.onboardAtpApiService.updateNextArriveInfo(simulation, trainInfo.getGroupNumber(),
nextPlanSection, park, runTime, jump);
}
@Override private int calculateRunTime(Simulation simulation, TrainInfo trainInfo,
public void handleTurnBackTrackParking(Simulation simulation, TrainInfo trainInfo, Section parkSection) { TripPlan tripPlan, StationPlan nextStationPlan) {
SimulationDataRepository repository = simulation.getRepository(); MapConfig config = simulation.getRepository().getConfig();
LocalDateTime systemTime = simulation.getSystemTime(); LocalDateTime systemTime = simulation.getSystemTime();
TripPlan tripPlan = repository.getTripPlan(trainInfo.getServiceNumber(), trainInfo.getTripNumber()); Section start;
if (tripPlan.getEndSection().equals(parkSection) Section end = nextStationPlan.getSection();
/*|| tripPlan.getEndSection().getStation().equals(parkSection.getStation())*/) { LocalTime startTime;
// 计划终端折返轨或和计划终端折返轨同站的折返轨,根据车次类型处理 LocalTime endTime = nextStationPlan.getArriveTime();
TripPlan nextTripPlan = repository.queryNextTripPlanOf(tripPlan); List<StationPlan> planList = tripPlan.getPlanList();
if (nextTripPlan == null) { boolean turnBack = true;
return; boolean outbound = false;
} startTime = tripPlan.getStartTime();
if (tripPlan.isBackup()) { start = tripPlan.getStartSection();
// 备用车 for (StationPlan stationPlan : planList) {
if (systemTime.toLocalTime().plusMinutes(5).isAfter(nextTripPlan.getStartTime())) { if (stationPlan.equals(nextStationPlan)) {
this.updateTripPlan(simulation, trainInfo, nextTripPlan); break;
BusinessExceptionAssertEnum.DATA_ERROR.assertNotEquals(parkSection, nextTripPlan.getFirstStationPlan().getSection()); }
this.updateNextPlan(simulation, trainInfo, nextTripPlan, nextTripPlan.getFirstStationPlan()); turnBack = false;
return; if (stationPlan.getSection().isTransferTrack()) {
} outbound = true;
} else if (tripPlan.isTurnBack()) { } else {
// 折返计划 outbound = false;
this.updateTripPlan(simulation, trainInfo, nextTripPlan); }
BusinessExceptionAssertEnum.DATA_ERROR.assertNotEquals(parkSection, nextTripPlan.getFirstStationPlan().getSection()); startTime = stationPlan.getLeaveTime();
this.updateNextPlan(simulation, trainInfo, nextTripPlan, nextTripPlan.getFirstStationPlan()); start = stationPlan.getSection();
return;
}
} else {
// 非终端折返轨更新列车下一计划到达
if (trainInfo.getPlanStandTrack() != null) {
return;
}
// 查询停靠区段能到达的相邻的站台轨取计划中包含的再进行筛选选出下一车站计划
List<RoutePath> routePathList = repository.queryRoutePathsByStart(parkSection);
List<StationPlan> sameDirectionList = new ArrayList<>();
List<StationPlan> reverseDirectionList = new ArrayList<>();
for (RoutePath routePath : routePathList) {
StationPlan stationPlan = tripPlan.queryStationPlan(routePath.getEnd());
if (stationPlan != null) {
if (routePath.isRight() == tripPlan.isRight()) {
sameDirectionList.add(stationPlan);
} else {
reverseDirectionList.add(stationPlan);
}
}
}
StationPlan stationPlan = null;
if (sameDirectionList.size() > 0) {
stationPlan = sameDirectionList.get(0);
} else if (reverseDirectionList.size() > 0) {
stationPlan = reverseDirectionList.get(0);
}
if (stationPlan != null) {
this.updateNextPlan(simulation, trainInfo, tripPlan, stationPlan);
}
}
} }
int planRunTime = (int) ChronoUnit.SECONDS.between(startTime, endTime);
int adjustRunTime = planRunTime;
if (!turnBack && !outbound && config.isAdjustOperationAutomatically()
&& trainInfo.isAtsAutoAdjust()) {
startTime = systemTime.toLocalTime();
adjustRunTime = (int) ChronoUnit.SECONDS.between(startTime, endTime);
}
int runTime = Math.min(adjustRunTime, planRunTime + 30);
if (runTime <= 0) {
runTime = 1;
}
log.debug(String.format("列车[%s]站间[%s->%s]运行时间为:[%s]", trainInfo.getGroupNumber(),
start.debugStr(), end.debugStr(), runTime));
return runTime;
}
@Override @Override
public void handlePassStand(Simulation simulation, TrainInfo trainInfo) { public void handleTurnBackTrackParking(Simulation simulation, TrainInfo trainInfo,
String planStandTrack = trainInfo.getPlanStandTrack(); Section parkSection) {
if (planStandTrack == null) { SimulationDataRepository repository = simulation.getRepository();
return; LocalDateTime systemTime = simulation.getSystemTime();
TripPlan tripPlan = repository.getTripPlan(trainInfo.getServiceNumber(),
trainInfo.getTripNumber());
// 车次计划中的车站计划全部完成并且当前折返轨与计划折返轨属于同一站则认为车次计划完成
boolean completed = tripPlan.getPlanList().stream().allMatch(StationPlan::isFinished)
&& tripPlan.getEndSection().getStation().equals(parkSection.getStation());
if (completed) {
// 计划终端折返轨或和计划终端折返轨同站的折返轨,根据车次类型处理
TripPlan nextTripPlan = repository.queryNextTripPlanOf(tripPlan);
if (nextTripPlan == null) {
return;
}
if (tripPlan.isBackup()) {
// 备用车
if (systemTime.toLocalTime().plusMinutes(5).isAfter(nextTripPlan.getStartTime())) {
this.updateTripPlan(simulation, trainInfo, nextTripPlan);
BusinessExceptionAssertEnum.DATA_ERROR.assertNotEquals(parkSection,
nextTripPlan.getFirstStationPlan().getSection());
this.updateNextPlan(simulation, trainInfo, nextTripPlan,
nextTripPlan.getFirstStationPlan());
return;
} }
SimulationDataRepository repository = simulation.getRepository(); } else if (tripPlan.isTurnBack()) {
TripPlan tripPlan = repository.getTripPlan(trainInfo.getServiceNumber(), trainInfo.getTripNumber()); // 折返计划
StationPlan stationPlan = tripPlan.queryStationPlan(planStandTrack); this.updateTripPlan(simulation, trainInfo, nextTripPlan);
Section section = repository.getByCode(planStandTrack, Section.class); BusinessExceptionAssertEnum.DATA_ERROR.assertNotEquals(parkSection,
//更新离站信息 nextTripPlan.getFirstStationPlan().getSection());
trainInfo.updateLeaveInfo(section, simulation.getSystemTime().toLocalTime()); this.updateNextPlan(simulation, trainInfo, nextTripPlan,
//更新后续计划到站 nextTripPlan.getFirstStationPlan());
return;
}
} else {
// 非终端折返轨更新列车下一计划到达
if (trainInfo.getPlanStandTrack() != null) {
return;
}
// 查询停靠区段能到达的相邻的站台轨取计划中包含的再进行筛选选出下一车站计划
List<RoutePath> routePathList = repository.queryRoutePathsByStart(parkSection);
List<StationPlan> sameDirectionList = new ArrayList<>();
List<StationPlan> reverseDirectionList = new ArrayList<>();
for (RoutePath routePath : routePathList) {
StationPlan stationPlan = tripPlan.queryStationPlan(routePath.getEnd());
if (stationPlan != null) { if (stationPlan != null) {
stationPlan.finish(); if (routePath.isRight() == tripPlan.isRight()) {
this.realRunRecordService.recordTrainRealRun(simulation, trainInfo, stationPlan.getStation(), sameDirectionList.add(stationPlan);
stationPlan.getSection(), false); } else {
StationPlan nextPlan = tripPlan.queryNextStationPlan(stationPlan.getStation()); reverseDirectionList.add(stationPlan);
this.updateNextPlan(simulation, trainInfo, tripPlan, nextPlan); }
} }
}
StationPlan stationPlan = null;
if (sameDirectionList.size() > 0) {
stationPlan = sameDirectionList.get(0);
} else if (reverseDirectionList.size() > 0) {
stationPlan = reverseDirectionList.get(0);
}
if (stationPlan != null) {
this.updateNextPlan(simulation, trainInfo, tripPlan, stationPlan);
}
} }
}
@Override
public void handlePassStand(Simulation simulation, TrainInfo trainInfo) {
String planStandTrack = trainInfo.getPlanStandTrack();
if (planStandTrack == null) {
return;
}
SimulationDataRepository repository = simulation.getRepository();
TripPlan tripPlan = repository.getTripPlan(trainInfo.getServiceNumber(),
trainInfo.getTripNumber());
StationPlan stationPlan = tripPlan.queryStationPlan(planStandTrack);
Section section = repository.getByCode(planStandTrack, Section.class);
//更新离站信息
trainInfo.updateLeaveInfo(section, simulation.getSystemTime().toLocalTime());
//更新后续计划到站
if (stationPlan != null) {
stationPlan.finish();
this.realRunRecordService.recordTrainRealRun(simulation, trainInfo, stationPlan.getStation(),
stationPlan.getSection(), false);
StationPlan nextPlan = tripPlan.queryNextStationPlan(stationPlan.getStation());
this.updateNextPlan(simulation, trainInfo, tripPlan, nextPlan);
}
}
} }

View File

@ -246,11 +246,11 @@ public class CiApiServiceImpl2 implements CiApiService {
@Override @Override
public void humanCancel(Simulation simulation, String routeCode) { public void humanCancel(Simulation simulation, String routeCode) {
Route route = simulation.getRepository().getByCode(routeCode, Route.class); Route route = simulation.getRepository().getByCode(routeCode, Route.class);
// if (simulation.getRepository().getConfig().isRailway()) { if (route.getStart().isGuideAspect()) { // 根据成都三引导解锁逻辑修改
// BusinessExceptionAssertEnum.OPERATION_FAIL.assertTrue(route.isApproachLock(), signalService.closeRoute(simulation, route.getStart());
// "进路未接近锁闭,不能人解"); } else {
// } this.routeService.delayUnlockStart(simulation, route, route.getStart());
this.routeService.delayUnlockStart(simulation, route, route.getStart()); }
} }
@Override @Override
@ -413,6 +413,10 @@ public class CiApiServiceImpl2 implements CiApiService {
throw BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.exception( throw BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.exception(
"signalCode和routeCode不能都为空"); "signalCode和routeCode不能都为空");
} }
//开启联锁自动进路的信号机不能办理引导进路需先解除自动进路成都三操作文档
if (signal.getRouteList().stream().anyMatch(Route::isFleetMode)) {
throw BusinessExceptionAssertEnum.OPERATION_FAIL.exception("需先解除自动进路状态");
}
if (route == null && signal.getRouteList().stream().anyMatch(Route::isAnySwitchMasterLock)) { if (route == null && signal.getRouteList().stream().anyMatch(Route::isAnySwitchMasterLock)) {
openGuideAspect4GuideMasterLock(simulation, signal); openGuideAspect4GuideMasterLock(simulation, signal);
@ -500,6 +504,10 @@ public class CiApiServiceImpl2 implements CiApiService {
signal.guideDelayStart(); signal.guideDelayStart();
} }
} }
if (repository.getConfig().isGuideDelayCloseWhenFirstSectionOccupied()
&& signal.isGuideAspect()) {
signal.guideDelayStart();
}
// if (signal.getGuideRemain() > 0) { // if (signal.getGuideRemain() > 0) {
// signal.setGuideRemain(0); // signal.setGuideRemain(0);
// } else { // } else {

View File

@ -113,7 +113,7 @@ public class CiRouteService {
// return new Route.CheckFailMessage(Route.CheckFailReason.SectionFaultOccupied, section); // return new Route.CheckFailMessage(Route.CheckFailReason.SectionFaultOccupied, section);
// } // }
} }
if (!start.isCbtcMode()) { if (!start.isCbtcMode() && !guide) {
// 后备办理检查 // 后备办理检查
// 区段占用 // 区段占用
for (Section section : sectionList) { for (Section section : sectionList) {
@ -584,9 +584,13 @@ public class CiRouteService {
route.setLock(false); route.setLock(false);
} }
} }
section.faultUnlock(); if (section.isSwitchTrack()) {
if (section.isShowLogic()) { switchFaultUnlock(simulation, section.getRelSwitch(), route);
section.getLogicList().forEach(Section::faultUnlock); } else {
section.faultUnlock();
if (section.isShowLogic()) {
section.getLogicList().forEach(Section::faultUnlock);
}
} }
} }

View File

@ -6,192 +6,204 @@ import club.joylink.rtss.simulation.cbtc.data.map.Switch;
import club.joylink.rtss.simulation.cbtc.data.map.SwitchElement; import club.joylink.rtss.simulation.cbtc.data.map.SwitchElement;
import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealitySwitch; import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealitySwitch;
import club.joylink.rtss.simulation.cbtc.device.virtual.VirtualRealityDeviceService; import club.joylink.rtss.simulation.cbtc.device.virtual.VirtualRealityDeviceService;
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Objects;
@Component @Component
public class CiSwitchControlService { public class CiSwitchControlService {
@Autowired
private VirtualRealityDeviceService virtualRealityDeviceService;
/** @Autowired
* 道岔单锁 private VirtualRealityDeviceService virtualRealityDeviceService;
*
* @param aSwitch /**
*/ * 道岔单锁
public void singleLock(Switch aSwitch) { *
if (!aSwitch.isSingleLock()) { * @param aSwitch
aSwitch.setSingleLock(true); */
} public void singleLock(Switch aSwitch) {
if (!aSwitch.isSingleLock()) {
aSwitch.setSingleLock(true);
} }
}
/** /**
* 道岔单解 * 道岔单解
* *
* @param aSwitch * @param aSwitch
*/ */
public void singleUnlock(Switch aSwitch) { public void singleUnlock(Switch aSwitch) {
if (aSwitch.isSingleLock()) { if (aSwitch.isSingleLock()) {
aSwitch.setSingleLock(false); aSwitch.setSingleLock(false);
}
} }
}
/** /**
* 封锁(封锁后包含道岔的进路不能排列) * 封锁(封锁后包含道岔的进路不能排列)
* *
* @param aSwitch * @param aSwitch
*/ */
public void blockade(Switch aSwitch) { public void blockade(Switch aSwitch) {
if (!aSwitch.isBlockade()) { if (!aSwitch.isBlockade()) {
aSwitch.setBlockade(true); aSwitch.setBlockade(true);
aSwitch.getA().setBlockade(true); aSwitch.getA().setBlockade(true);
aSwitch.getB().setBlockade(true); aSwitch.getB().setBlockade(true);
aSwitch.getC().setBlockade(true); aSwitch.getC().setBlockade(true);
}
aSwitch.setInit(false);
} }
aSwitch.setInit(false);
}
/** /**
* 解封 * 解封
* *
* @param aSwitch * @param aSwitch
*/ */
public void unblock(Switch aSwitch) { public void unblock(Switch aSwitch) {
if (aSwitch.isBlockade()) { if (aSwitch.isBlockade()) {
aSwitch.setBlockade(false); aSwitch.setBlockade(false);
aSwitch.getA().setBlockade(false); aSwitch.getA().setBlockade(false);
aSwitch.getB().setBlockade(false); aSwitch.getB().setBlockade(false);
aSwitch.getC().setBlockade(false); aSwitch.getC().setBlockade(false);
}
} }
}
/** /**
* 强转道岔 * 强转道岔
* *
* @param simulation * @param simulation
* @param aSwitch * @param aSwitch
* @return * @return
*/ */
public SwitchIndication forceTurn(Simulation simulation, Switch aSwitch) { public SwitchIndication forceTurn(Simulation simulation, Switch aSwitch) {
if (!aSwitch.isSectionOccupied()) { if (!aSwitch.isSectionOccupied()) {
return null; return null;
}
if (aSwitch.isLocked()) {
return null;
}
// 设置强扳授权
aSwitch.setForceTurnRemain(120 * 1000);
SwitchIndication pos = this.turn(simulation, aSwitch);
// 手动释放强扳
aSwitch.setForceTurnRemain(0);
return pos;
} }
if (aSwitch.isLocked()) {
return null;
}
// 设置强扳授权
aSwitch.setForceTurnRemain(120 * 1000);
SwitchIndication pos = this.turn(simulation, aSwitch);
// 手动释放强扳
aSwitch.setForceTurnRemain(0);
return pos;
}
/** /**
* 道岔转动 * 道岔转动
* *
* @param simulation * @param simulation
* @param aSwitch * @param aSwitch
* @return * @return
*/ */
public SwitchIndication turn(Simulation simulation, Switch aSwitch) { public SwitchIndication turn(Simulation simulation, Switch aSwitch) {
VirtualRealitySwitch vrSwitch = aSwitch.getVirtualSwitch(); VirtualRealitySwitch vrSwitch = aSwitch.getVirtualSwitch();
boolean lastTurnToN = vrSwitch.isLastTurnToN(); boolean lastTurnToN; //最后转向的方向主要是为了解决失表的情况下每次转动道岔要向不同方向转动
if (simulation.getRepository().getConfig().isSwitchNRTurnChain()) { if (vrSwitch.isPosN()) {
Switch linkedSwitch = aSwitch.queryLinkedSwitch(); lastTurnToN = true;
if (Objects.nonNull(linkedSwitch)) { } else if (vrSwitch.isPosR()) {
if (lastTurnToN) { lastTurnToN = false;
this.turn2ReversePosition(simulation, linkedSwitch); } else {
} else { lastTurnToN = vrSwitch.isLastTurnToN();
this.turn2NormalPosition(simulation, linkedSwitch); }
} if (simulation.getRepository().getConfig().isSwitchNRTurnChain()) {
} Switch linkedSwitch = aSwitch.queryLinkedSwitch();
} if (Objects.nonNull(linkedSwitch)) {
if (lastTurnToN) { if (lastTurnToN) {
if (this.turn2ReversePosition(simulation, aSwitch)) { this.turn2ReversePosition(simulation, linkedSwitch);
return SwitchIndication.R;
}
} else { } else {
if (this.turn2NormalPosition(simulation, aSwitch)) { this.turn2NormalPosition(simulation, linkedSwitch);
return SwitchIndication.N;
}
} }
return null; }
} }
if (lastTurnToN) {
if (this.turn2ReversePosition(simulation, aSwitch)) {
return SwitchIndication.R;
}
} else {
if (this.turn2NormalPosition(simulation, aSwitch)) {
return SwitchIndication.N;
}
}
return null;
}
/** /**
* 道岔定操 * 道岔定操
* *
* @param simulation * @param simulation
* @param aSwitch * @param aSwitch
*/ */
public boolean turn2NormalPosition(Simulation simulation, Switch aSwitch) { public boolean turn2NormalPosition(Simulation simulation, Switch aSwitch) {
if (!this.checkTurnCondition(aSwitch)) { if (!this.checkTurnCondition(aSwitch)) {
return false; return false;
}
VirtualRealitySwitch vrSwitch = aSwitch.getVirtualSwitch();
this.virtualRealityDeviceService.control(simulation, vrSwitch, VirtualRealitySwitch.Operation.NP);
return true;
} }
VirtualRealitySwitch vrSwitch = aSwitch.getVirtualSwitch();
this.virtualRealityDeviceService.control(simulation, vrSwitch,
VirtualRealitySwitch.Operation.NP);
return true;
}
/** /**
* 道岔反操 * 道岔反操
* *
* @param simulation * @param simulation
* @param aSwitch * @param aSwitch
* @return * @return
*/ */
public boolean turn2ReversePosition(Simulation simulation, Switch aSwitch) { public boolean turn2ReversePosition(Simulation simulation, Switch aSwitch) {
if (!this.checkTurnCondition(aSwitch)) { if (!this.checkTurnCondition(aSwitch)) {
return false; return false;
}
VirtualRealitySwitch vrSwitch = aSwitch.getVirtualSwitch();
this.virtualRealityDeviceService.control(simulation, vrSwitch, VirtualRealitySwitch.Operation.RP);
return true;
} }
VirtualRealitySwitch vrSwitch = aSwitch.getVirtualSwitch();
this.virtualRealityDeviceService.control(simulation, vrSwitch,
VirtualRealitySwitch.Operation.RP);
return true;
}
/** /**
* 检查道岔转动条件 * 检查道岔转动条件
* *
* @param aSwitch * @param aSwitch
* @return * @return
*/ */
private boolean checkTurnCondition(Switch aSwitch) { private boolean checkTurnCondition(Switch aSwitch) {
// 道岔锁闭 或者 道岔占用且无强扳授权则不能转动 // 道岔锁闭 或者 道岔占用且无强扳授权则不能转动
return !(aSwitch.isLocked() || (aSwitch.isSectionOccupied() && aSwitch.getForceTurnRemain() <= 0)); return !(aSwitch.isLocked() || (aSwitch.isSectionOccupied()
} && aSwitch.getForceTurnRemain() <= 0));
}
/** /**
* 确保道岔位置正确 * 确保道岔位置正确
*/ */
public boolean ensureSwitchPosCurrent(Simulation simulation, List<SwitchElement> switchElements, boolean guideSetting) { public boolean ensureSwitchPosCurrent(Simulation simulation, List<SwitchElement> switchElements,
boolean allOn = true; boolean guideSetting) {
if (switchElements == null) { boolean allOn = true;
return true; if (switchElements == null) {
} return true;
for (SwitchElement switchElement : switchElements) {
boolean onPos = this.turnRouteSwitch(simulation, switchElement);
if (!onPos && !(guideSetting && switchElement.getASwitch().isLoss() && switchElement.getASwitch().isGuideMasterLock())) { //不在正确位置并且不是办理引导进路中的引导总锁的失表道岔
allOn = false;
}
}
return allOn;
} }
for (SwitchElement switchElement : switchElements) {
boolean onPos = this.turnRouteSwitch(simulation, switchElement);
if (!onPos && !(guideSetting && switchElement.getASwitch().isLoss()
&& switchElement.getASwitch().isGuideMasterLock())) { //不在正确位置并且不是办理引导进路中的引导总锁的失表道岔
allOn = false;
}
}
return allOn;
}
public boolean turnRouteSwitch(Simulation simulation, SwitchElement switchElement) { public boolean turnRouteSwitch(Simulation simulation, SwitchElement switchElement) {
boolean onPos = true; boolean onPos = true;
if (!switchElement.isOnPosition()) { if (!switchElement.isOnPosition()) {
onPos = false; onPos = false;
if (switchElement.isNormal()) { if (switchElement.isNormal()) {
this.turn2NormalPosition(simulation, switchElement.getASwitch()); this.turn2NormalPosition(simulation, switchElement.getASwitch());
} else { } else {
this.turn2ReversePosition(simulation, switchElement.getASwitch()); this.turn2ReversePosition(simulation, switchElement.getASwitch());
} }
}
return onPos;
} }
return onPos;
}
} }

View File

@ -1,59 +0,0 @@
//package club.joylink.rtss.simulation.cbtc.CI.service;
//
//import club.joylink.rtss.simulation.cbtc.Simulation;
//import club.joylink.rtss.simulation.cbtc.data.map.AutoSignal;
//import club.joylink.rtss.simulation.cbtc.data.map.Section;
//import club.joylink.rtss.simulation.cbtc.data.map.Signal;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
//import java.util.List;
//
///**
// * 自动信号服务
// */
//@Slf4j
//@Component
//public class AutoSignalService {
//
// @Autowired
// private SignalService signalService;
//
// /**
// * 根据连锁关系更新信号显示
// * @param simulation
// * @param autoSignal
// */
// public void updateSignalDisplay(Simulation simulation, AutoSignal autoSignal) {
// Signal signal = autoSignal.getSignal();
// if (!signal.isLogicLight()) {
// List<Section> sectionList = autoSignal.getSectionList();
// boolean clear = true; // 所有区段是否出清
// for (Section section : sectionList) {
// if (section.isOccupied()) {
// clear = false;
// break;
// }
// }
// if (clear) { // 全部出清开信号机
// this.signalService.openGreenSignal(simulation, signal);
// } else { // 关信号机
// this.signalService.close(simulation, signal);
// }
// } else {
// if (!signal.isMainAspect()) {
// this.signalService.openGreenSignal(simulation, signal);
// }
// }
//// if (!clear) { // 信号机物理点红灯
//// if (signal.isLogicLight()) {
//// signal.changeLightType(false);
//// }
//// this.signalService.close(simulation, signal);
//// } else { // 信号机开灯
//// this.signalService.openGreenSignal(simulation, signal);
//// }
// }
//
//}

View File

@ -1,120 +0,0 @@
//package club.joylink.rtss.simulation.cbtc.CI.service;
//
//import club.joylink.rtss.simulation.cbtc.Simulation;
//import club.joylink.rtss.simulation.cbtc.constant.SimulationConstants;
//import club.joylink.rtss.simulation.cbtc.data.map.Route;
//import club.joylink.rtss.simulation.cbtc.data.map.Section;
//import club.joylink.rtss.simulation.cbtc.data.map.Signal;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//import org.springframework.util.CollectionUtils;
//
//import java.util.List;
//import java.util.Objects;
//
///**
// * 区段服务
// */
//@Component
//@Slf4j
//public class SectionService {
//
// @Autowired
// private SignalService signalService;
// @Autowired
// private RouteService routeService;
//
// /**
// * 封锁(封锁后包含区段的进路不能排列)
// */
// public void blockade(Section section) {
//// if(section.isRouteLock() || section.isOverlapLock()) {
//// log.info(String.format("区段[%s(%s)]进路锁闭,不能封锁", section.getName(), section.getCode()));
//// return;
//// }
// if (!section.isBlockade()) {
// section.setBlockade(true);
// if (!section.isCross() && !CollectionUtils.isEmpty(section.getLogicList())) {
// section.getLogicList().forEach(logic -> logic.setBlockade(true));
// }
// }
// }
//
// /**
// * 解封
// */
// public void unblock(Section section) {
// if (section.isBlockade()) {
// section.setBlockade(false);
// if (!section.isCross() && !CollectionUtils.isEmpty(section.getLogicList())) {
// section.getLogicList().forEach(logic -> logic.setBlockade(false));
// }
// }
// }
//
// /**
// * 区故解
// */
// public void sectionFaultUnlock(Simulation simulation, Section section, Route route) {
// if (route != null) {
// if (route.isOpenMain()) {
// signalService.close(simulation, route.getStart());
// }
// if (routeService.isApproachLock(simulation.getRepository(), route) || section.isOverlapLock()) {
// // 区段延时解锁
// int delayTime = route.getDelayReleaseTime() * 1000;
// section.delayUnlock(delayTime);
// if (section.isShowLogic()) {
// section.getLogicList().forEach(ls -> ls.delayUnlock(delayTime));
// }
// return;
// } else {
// route.setLock(false);
// Signal start = route.getStart();
// if (start.getLockedRoute() == route) {
// start.setLockedRoute(null);
// }
// }
// }
// section.faultUnlock();
// if (section.isShowLogic()) {
// section.getLogicList().forEach(Section::faultUnlock);
// }
// }
//
// /**
// * 区段延时区故解
// *
// * @param simulation
// * @param section
// */
// public void delayUnlock(Simulation simulation, Section section) {
// int remainTime = section.getDelayTime();
// if (remainTime > 0) {
// remainTime -= SimulationConstants.CI_LOOP_RATE;
// if (remainTime <= 0) {
// List<Route> routeList = simulation.getRepository().queryAllLockedRoute();
// Route lockedRoute = null;
// for (Route route : routeList) {
// if (route.containSection(section)) {
// lockedRoute = route;
// break;
// }
// }
// if (Objects.nonNull(lockedRoute)) {
// lockedRoute.setLock(false);
// Signal start = lockedRoute.getStart();
// this.signalService.close(simulation, start);
// if (start.getLockedRoute() == lockedRoute) {
// start.setLockedRoute(null);
// }
// }
// section.faultUnlock();
// section.setDelayTime(0);
// } else {
// section.setDelayTime(remainTime);
// }
// }
// }
//}

View File

@ -1,180 +0,0 @@
//package club.joylink.rtss.simulation.cbtc.CI.service;
//
//import club.joylink.rtss.simulation.cbtc.Simulation;
//import club.joylink.rtss.simulation.cbtc.data.map.Route;
//import club.joylink.rtss.simulation.cbtc.data.map.Signal;
//import club.joylink.rtss.simulation.cbtc.data.support.SignalApproachMessage;
//import club.joylink.rtss.simulation.cbtc.event.RouteModeChangeEvent;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.ApplicationContext;
//import org.springframework.stereotype.Component;
//import org.springframework.util.CollectionUtils;
//
//import java.util.List;
//import java.util.Objects;
//
///**
// * 信号机服务
// */
//@Component
//@Slf4j
//public class SignalService {
//
// @Autowired
// private VrSignalControlService vrSignalControlService;
//
// @Autowired
// private ApplicationContext applicationContext;
//
// /**
// * 封锁(封锁后包含信号机的进路不能排列)
// * @param signal
// */
// public void blockade(Simulation simulation, Signal signal) {
// if(!signal.isBlockade()) {
// signal.setBlockade(true);
// this.close(simulation, signal);
// if (signal.getLockedRoute() != null) {
// signal.setReblockade(true);
// log.debug(signal.debugStr() + "因信号机封锁且有锁闭的进路而重复封锁");
// }
// }
// }
//
// /**
// * 解封
// * @param signal
// */
// public void unblock(Signal signal) {
// if (signal.isBlockade()) {
// signal.setBlockade(false);
// }
// }
//
// /**
// * 信号关闭
// * @param simulation
// * @param signal
// */
// public void close(Simulation simulation, Signal signal) {
// if (signal.isLogicLight()) {
// signal.apply(false, false, true);
// if (!signal.isVirtual()) {
// this.vrSignalControlService.close(simulation, signal.getVirtualSignal());
// }
// } else {
// if (!signal.isVirtual()) {
// this.vrSignalControlService.openRedSignal(simulation, signal.getVirtualSignal());
// }
// }
// }
//
// /**
// * 控制室外信号机点绿灯
// * @param simulation
// * @param signal
// */
// public void openGreenSignal(Simulation simulation, Signal signal) {
// if (signal.isLogicLight()) {
// signal.apply(true, false, false);
// if (!signal.isVirtual()) {
// this.vrSignalControlService.close(simulation, signal.getVirtualSignal());
// }
// } else {
// if (!signal.isVirtual()) {
// this.vrSignalControlService.openGreenSignal(simulation, signal.getVirtualSignal());
// }
// }
// }
//
// /**
// * 控制室外信号机点黄灯
// * @param simulation
// * @param signal
// */
// public void openYellowSignal(Simulation simulation, Signal signal) {
// if (signal.isLogicLight()) {
// signal.apply(false, true, false);
// if (!signal.isVirtual()) {
// this.vrSignalControlService.close(simulation, signal.getVirtualSignal());
// }
// } else {
// this.vrSignalControlService.openYellowSignal(simulation, signal.getVirtualSignal());
// }
// }
//
// /**
// * 控制室外信号机点黄红灯
// * @param simulation
// * @param signal
// */
// public void openGuideSignal(Simulation simulation, Signal signal) {
// signal.changeLightType(false);
// this.vrSignalControlService.openGuideSignal(simulation, signal.getVirtualSignal());
// signal.apply(false, true, true);
// int guideRemain = signal.getGuideRemain();
// if (guideRemain > 0) {
// signal.guideInfinite();
// } else {
// signal.guideStart();
// }
// signal.setInit(false);
// if (signal.isReblockade()) {
// signal.setReblockade(false);
// }
// }
//
// /**
// * 处理信号机接近消息
// * @param simulation
// * @param signal
// * @param approachMessage
// */
// public void handleApproachMessage(Simulation simulation, Signal signal, SignalApproachMessage approachMessage) {
// if (Objects.equals(signal.getApproachMsg(), approachMessage.getApproachMsg())) {
// return;
// }
// signal.setApproachMsg(approachMessage.getApproachMsg());
// if (signal.isNctApproach()) { // 接近区段非通信车占用
// this.changeRoutesCBTCMode(simulation, signal, false);
// if (signal.isLogicLight()) { // 非通信车占用改为物理点灯
// this.changeSignalLightType(simulation, signal, false);
// }
// } else if (signal.isCbtcApproach()) { // 接近区段通信车占用
// this.changeRoutesCBTCMode(simulation, signal, true);
// if (!signal.isLogicLight()) {
// this.changeSignalLightType(simulation, signal, true);
// }
// }
// }
//
// private void changeSignalLightType(Simulation simulation, Signal signal, boolean logic) {
// if (!Objects.equals(signal.isLogicLight(), logic)) {
// signal.changeLightType(logic);
// if (!signal.isLogicLight()) {
// if (!signal.isVirtual()) {
// if (signal.isGreenOpen()) {
// this.vrSignalControlService.openGreenSignal(simulation, signal.getVirtualSignal());
// } else if (signal.isYellowOpen()) {
// this.vrSignalControlService.openYellowSignal(simulation, signal.getVirtualSignal());
// } else {
// this.vrSignalControlService.openRedSignal(simulation, signal.getVirtualSignal());
// }
// }
// } else {
// if (!signal.isVirtual()) {
// this.vrSignalControlService.close(simulation, signal.getVirtualSignal());
// }
// }
// }
// }
//
// private void changeRoutesCBTCMode(Simulation simulation, Signal signal, boolean cbtc) {
// List<Route> routeList = signal.getRouteList();
// if (!CollectionUtils.isEmpty(routeList)) {
// routeList.forEach(route -> route.setCbtcMode(cbtc));
// applicationContext.publishEvent(new RouteModeChangeEvent(this, simulation, routeList));
// }
// }
//}

View File

@ -1,185 +0,0 @@
//package club.joylink.rtss.simulation.cbtc.CI.service;
//
//import club.joylink.rtss.simulation.cbtc.Simulation;
//import club.joylink.rtss.simulation.cbtc.communication.vo.ControllableDevice;
//import club.joylink.rtss.simulation.cbtc.communication.vo.PsdSwitch;
//import club.joylink.rtss.simulation.cbtc.data.map.*;
//import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealityScreenDoor;
//import club.joylink.rtss.simulation.cbtc.event.SimulationDeviceControlEvent;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.ApplicationContext;
//import org.springframework.stereotype.Component;
//
//import java.util.Objects;
//
///**
// * 屏蔽门服务
// */
//@Component
//@Slf4j
//public class StandService {
//
// @Autowired
// private ApplicationContext applicationContext;
//
// @Autowired
// private SignalService signalService;
//
// @Autowired
// private RouteService routeService;
//
// /**
// * 控制室外屏蔽门开关
// */
// public void controlVrPSD(Simulation simulation, VirtualRealityScreenDoor vrPsd, boolean open) {
// if ((open && (vrPsd.isSettingOpen() || vrPsd.isOpen2End())) ||
// (!open && (vrPsd.isSettingClose() || vrPsd.isLockAndClose()))) {
//// log.debug(String.format("屏蔽门[%s(%s)]已经在对应状态,不需要再控制", vrPsd.getName(), vrPsd.getCode()));
// return;
// }
// vrPsd.startSetting(open);
// ControllableDevice ctrlMsg = new PsdSwitch(vrPsd, open);
// SimulationDeviceControlEvent event = new SimulationDeviceControlEvent(this, simulation, ctrlMsg);
// this.applicationContext.publishEvent(event);
// }
//
// /**
// * 打开屏蔽门
// *
// * @param simulation
// * @param psd
// */
// public void openScreenDoor(Simulation simulation, PSD psd) {
// VirtualRealityScreenDoor vrPsd = psd.getVirtualScreenDoor();
// if (vrPsd.isPslControl()) {
// return;
// }
// this.controlVrPSD(simulation, vrPsd, true);
// }
//
// /**
// * 关闭屏蔽门
// *
// * @param simulation
// * @param psd
// */
// public void closeScreenDoor(Simulation simulation, PSD psd) {
// VirtualRealityScreenDoor vrPsd = psd.getVirtualScreenDoor();
// if (vrPsd.isPslControl()) {
// return;
// }
// this.controlVrPSD(simulation, vrPsd, false);
// }
//
// /**
// * 设置扣车
// *
// * @param simulation
// * @param stand
// * @param center
// */
// public void holdTrain(Simulation simulation, Stand stand, boolean center) {
// if (center) {
// stand.setCenterHoldTrain(true);
// } else {
// stand.setStationHoldTrain(true);
// }
// // 关闭出站信号机
// Signal signal = stand.getSection().getSignalOf(stand.isRight());
// if (Objects.nonNull(signal)) {
// MapConfig config = simulation.getRepository().getConfig();
// if (config.isStandHoldCloseLogicLight()/* || !signal.isLogicLight()*/) {
// this.signalService.close(simulation, signal);
// }
// }
// }
//
// /**系统扣车*/
// public void sysHoldTrain(Simulation simulation, Stand stand) {
// stand.setSysHoldTrain(true);
// // 关闭出站信号机
// Signal signal = stand.getSection().getSignalOf(stand.isRight());
// if (Objects.nonNull(signal)) {
// MapConfig config = simulation.getRepository().getConfig();
// if (config.isStandHoldCloseLogicLight() || !signal.isLogicLight()) {
// this.signalService.close(simulation, signal);
// }
// }
// }
//
// public void cancelSysHoldTrain(Simulation simulation, Stand stand) {
// stand.setSysHoldTrain(false);
// // 如果所有扣车都取消开放出站信号机
// if (!stand.isHoldTrain()) {
// this.reopenSignal(simulation, stand);
// }
// }
//
// public void ibpHoldTrain(Simulation simulation, Stand stand) {
// stand.setIbpHoldTrain(true);
// // 关闭出站信号机
// Signal signal = stand.getSection().getSignalOf(stand.isRight());
// if (Objects.nonNull(signal)) {
// MapConfig config = simulation.getRepository().getConfig();
// if (config.isStandHoldCloseLogicLight() || !signal.isLogicLight()) {
// this.signalService.close(simulation, signal);
// }
// }
// }
//
// public void cancelIbpHoldTrain(Simulation simulation, Stand stand) {
// stand.setIbpHoldTrain(false);
// // 如果所有扣车都取消开放出站信号机
// if (!stand.isHoldTrain()) {
// this.reopenSignal(simulation, stand);
// }
// }
//
// /**
// * 取消扣车
// *
// * @param simulation
// * @param stand
// * @param center
// */
// public void cancelHoldTrain(Simulation simulation, Stand stand, boolean center) {
// if (center) {
// stand.setCenterHoldTrain(false);
// } else {
// stand.setStationHoldTrain(false);
// }
// // 如果所有扣车都取消开放出站信号机
// if (!stand.isHoldTrain()) {
// this.reopenSignal(simulation, stand);
// }
// }
//
// public void cancelAllHoldTrain(Simulation simulation, Stand stand) {
// stand.setCenterHoldTrain(false);
// stand.setStationHoldTrain(false);
// this.reopenSignal(simulation, stand);
// }
//
// private void reopenSignal(Simulation simulation, Stand stand) {
// Signal signal = stand.getSection().getSignalOf(stand.isRight());
// if (Objects.nonNull(signal) && !signal.isMainAspect()) {
// Route lockedRoute = signal.getLockedRoute();
// if (Objects.nonNull(lockedRoute) && this.routeService.isInterlocked(lockedRoute)) { // 锁闭进路存在,开信号机
// this.routeService.routeOpen(simulation, lockedRoute);
// }
// }
// }
//
// /**
// * 设置或取消互锁解除
// * @param release 是否是设置
// */
// public void setOrCancelInterlockRelease(Simulation simulation, Stand stand, boolean release) {
// stand.getPsd().getVirtualScreenDoor().updateIL(release);
// stand.getPsd().setInterlockRelease(release);
// if (release) {
// this.reopenSignal(simulation, stand);
// }
// }
//}

View File

@ -1,263 +0,0 @@
//package club.joylink.rtss.simulation.cbtc.CI.service;
//
//import club.joylink.rtss.simulation.cbtc.Simulation;
//import club.joylink.rtss.simulation.cbtc.communication.vo.ControllableDevice;
//import club.joylink.rtss.simulation.cbtc.communication.vo.SwitchTurn;
//import club.joylink.rtss.simulation.cbtc.constant.SimulationConstants;
//import club.joylink.rtss.simulation.cbtc.data.map.*;
//import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealitySwitch;
//import club.joylink.rtss.simulation.cbtc.event.RouteModeChangeEvent;
//import club.joylink.rtss.simulation.cbtc.event.SimulationDeviceControlEvent;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.ApplicationContext;
//import org.springframework.context.event.EventListener;
//import org.springframework.stereotype.Component;
//import org.springframework.util.CollectionUtils;
//
//import java.util.List;
//import java.util.Objects;
//import java.util.Random;
//import java.util.stream.Collectors;
//
///**
// * 道岔服务
// */
//@Component
//@Slf4j
//public class SwitchService {
//
// @Autowired
// private ApplicationContext applicationContext;
//
// @Autowired
// private SignalService signalService;
//
// @Autowired
// private RouteService routeService;
//
// @Autowired
// private SectionService sectionService;
//
// /**
// * 控制室外道岔转动道岔转动指令下达
// * @param simulation
// * @param aSwitch
// * @param toNormal
// */
// public void controlSwitch(Simulation simulation, Switch aSwitch, boolean toNormal) {
// if (simulation.getRepository().getConfig().isSwitchTurnOperationCanRecoverSplitFault()) {
// if (new Random().nextInt(3) == 0) {
// Switch.SwitchFault.SPLIT.fix(aSwitch);
// Switch.SwitchFault.NORMAL_SPLIT.fix(aSwitch);
// Switch.SwitchFault.REVERSE_SPLIT.fix(aSwitch);
// }
// }
// VirtualRealitySwitch virtualSwitch = aSwitch.getVirtualSwitch();
// if ((virtualSwitch.isNormal() && toNormal) ||
// (virtualSwitch.isReverse() && !toNormal)) {
// log.debug(String.format("道岔[%s]已经在指定位置[%s],无需转动", aSwitch.debugStr(), virtualSwitch.isNormal()?"N":"R"));
// return;
// }
// if (virtualSwitch.isSettingTo(toNormal)) {
// return;
// }
// // 向虚拟室外设备发送转换指令
// virtualSwitch.startSetting(toNormal);
// ControllableDevice ctrlMsg = new SwitchTurn(virtualSwitch, toNormal);
// SimulationDeviceControlEvent event = new SimulationDeviceControlEvent(this, simulation, ctrlMsg);
// this.applicationContext.publishEvent(event);
// }
//
// /**
// * 道岔定操
// * @param simulation
// * @param aSwitch
// */
// public boolean turn2NormalPosition(Simulation simulation, Switch aSwitch) {
// if(aSwitch.isLocked() || aSwitch.isSectionOccupied()) {
// return false;
// }
// this.controlSwitch(simulation, aSwitch, true);
// return true;
// }
//
// /**
// * 道岔反操
// * @param simulation
// * @param aSwitch
// * @return
// */
// public boolean turn2ReversePosition(Simulation simulation, Switch aSwitch) {
// if(aSwitch.isLocked() || aSwitch.isSectionOccupied()) {
// return false;
// }
// this.controlSwitch(simulation, aSwitch, false);
// return true;
// }
//
// /**
// * 道岔单锁
// * @param aSwitch
// */
// public void singleLock(Switch aSwitch) {
// if (!aSwitch.isSingleLock()) {
// aSwitch.setSingleLock(true);
// }
// }
//
// /**
// * 道岔单解
// * @param aSwitch
// */
// public void singleUnlock(Switch aSwitch) {
// if (aSwitch.isSingleLock()) {
// aSwitch.setSingleLock(false);
// }
// }
//
// /**
// * 封锁(封锁后包含道岔的进路不能排列)
// * @param aSwitch
// */
// public void blockade(Switch aSwitch) {
// if(!aSwitch.isBlockade()) {
// aSwitch.setBlockade(true);
// aSwitch.getA().setBlockade(true);
// aSwitch.getB().setBlockade(true);
// aSwitch.getC().setBlockade(true);
// }
// aSwitch.setInit(false);
// }
//
// /**
// * 解封
// * @param aSwitch
// */
// public void unblock(Switch aSwitch) {
// if(aSwitch.isBlockade()) {
// aSwitch.setBlockade(false);
// aSwitch.getA().setBlockade(false);
// aSwitch.getB().setBlockade(false);
// aSwitch.getC().setBlockade(false);
// }
// }
//
// /**
// * 道岔区段故障解锁
// * @param simulation
// * @param aSwitch
// * @param route
// */
// public void switchFaultUnlock(Simulation simulation, Switch aSwitch, Route route) {
// if (route != null) {
// if (route.isOpenMain()) {
// signalService.close(simulation, route.getStart());
// }
// if (routeService.isApproachLock(simulation.getRepository(), route) || aSwitch.isOverlapLock()) {
// // 延时解锁
// aSwitch.setDelayTime(route.getDelayReleaseTime() * 1000);
// aSwitch.getAllSections().forEach(section -> {
// if (section.isLocked())
// sectionService.sectionFaultUnlock(simulation, section, route);
// });
// return;
// } else {
// route.setLock(false);
// Signal start = route.getStart();
// if (start.getLockedRoute() == route) {
// start.setLockedRoute(null);
// }
// }
// }
// this.faultUnlock(aSwitch, route);
// }
//
// public void faultUnlock(Switch aSwitch, Route route) {
// aSwitch.faultUnlock();
// aSwitch.sectionFaultUnlock();
// if (route != null) {
// route.unlockRouteFlsOfSwitch(aSwitch); //进路中该道岔对应的侧防解除锁闭
// RouteOverlap overlap = route.getOverlap();
// if (overlap != null) {
// for (SectionPath sectionPath : overlap.getPathList()) {
// overlap.unlockFlsOfSwitch(sectionPath.getFlsList(), aSwitch); //延续保护中该道岔的侧防解除锁闭
// }
// }
// }
// }
//
// public void delayUnlock(Simulation simulation, Switch aSwitch) {
// int remainTime = aSwitch.getDelayTime();
// if (remainTime > 0) {
// remainTime -= SimulationConstants.CI_LOOP_RATE;
// if (remainTime <= 0) {
// List<Route> routeList = simulation.getRepository().queryAllLockedRoute();
// Route lockedRoute = null;
// if (aSwitch.isRouteLock()) {
// lockedRoute = aSwitch.getRoute();
// } else {
// for (Route route : routeList) {
// if (route.overlapContainSwitch(aSwitch)) {
// lockedRoute = route;
// break;
// }
// }
// }
// if (Objects.nonNull(lockedRoute)) {
// lockedRoute.setLock(false);
// Signal start = lockedRoute.getStart();
// if (start.getLockedRoute() == lockedRoute) {
// start.setLockedRoute(null);
// }
// }
// this.faultUnlock(aSwitch, lockedRoute);
// aSwitch.setDelayTime(0);
// } else {
// aSwitch.setDelayTime(remainTime);
// }
// }
// }
//
// @EventListener
// public void handle(RouteModeChangeEvent event) {
// this.switchStatusUpdate(event.getSimulation(), event.getRoutes());
// }
//
// /**
// * 道岔的封锁失效状态更新
// */
// private void switchStatusUpdate(Simulation simulation, List<Route> routes) {
// if (!simulation.getRepository().getConfig().isBlockadeCommandOnlyValidInStandbyMode()) {
// return;
// }
// if (!CollectionUtils.isEmpty(routes)) {
// if (!routes.get(0).isCbtcMode()) { //进路的状态被设为非cbtc
// routes.forEach(route -> {
// route.getSwitchList().forEach(switchElement -> {
// Switch aSwitch = switchElement.getASwitch();
// if (aSwitch.isBlockade()) {
// aSwitch.setBlockadeInvalid(false);
// }
// });
// });
// } else {
// List<Switch> switches = routes.stream()
// .flatMap(route -> route.getSwitchList()
// .stream()
// .map(SwitchElement::getASwitch)
// .filter(aSwitch -> aSwitch.isBlockade() && !aSwitch.isBlockadeInvalid()))
// .collect(Collectors.toList()); //进路下所有处于封锁且封锁有效状态的道岔
// for (Route route : simulation.getRepository().getRouteList()) {
// if (!route.isCbtcMode()) {
// switches.removeIf(route::isRouteSwitch);
// if (switches.isEmpty()) {
// break;
// }
// }
// }
// switches.forEach(aSwitch -> aSwitch.setBlockadeInvalid(true));
// }
// }
// }
//}

View File

@ -1,100 +0,0 @@
//package club.joylink.rtss.simulation.cbtc.CI.service;
//
//import club.joylink.rtss.simulation.cbtc.Simulation;
//import club.joylink.rtss.simulation.cbtc.communication.vo.ControllableDevice;
//import club.joylink.rtss.simulation.cbtc.communication.vo.SignalLight;
//import club.joylink.rtss.simulation.cbtc.data.map.Signal;
//import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealitySignal;
//import club.joylink.rtss.simulation.cbtc.event.SimulationDeviceControlEvent;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.ApplicationContext;
//import org.springframework.stereotype.Component;
//
//import java.util.Objects;
//
///**
// * 信号机服务
// */
//@Component
//@Slf4j
//public class VrSignalControlService {
//
// @Autowired
// private ApplicationContext applicationContext;
//
// /**
// * 控制室外信号机灭灯
// * @param simulation
// * @param vrSignal
// */
// public void close(Simulation simulation, VirtualRealitySignal vrSignal) {
// if (!vrSignal.isBlack()) {
// this.controlRealSignal(simulation, vrSignal, false, false, false);
// }
// }
//
// /**
// * 控制室外信号机点绿灯
// * @param simulation
// * @param vrSignal
// */
// public void openGreenSignal(Simulation simulation, VirtualRealitySignal vrSignal) {
// controlRealSignal(simulation, vrSignal, true, false, false);
// }
//
// /**
// * 控制室外信号机点黄灯
// * @param simulation
// * @param vrSignal
// */
// public void openYellowSignal(Simulation simulation, VirtualRealitySignal vrSignal) {
// controlRealSignal(simulation, vrSignal, false, true, false);
// }
//
// /**
// * 控制室外信号机点红灯
// * @param simulation
// * @param vrSignal
// */
// public void openRedSignal(Simulation simulation, VirtualRealitySignal vrSignal) {
// controlRealSignal(simulation, vrSignal, false, false, true);
// }
//
// /**
// * 控制室外信号机点黄红灯
// * @param simulation
// * @param vrSignal
// */
// public void openGuideSignal(Simulation simulation, VirtualRealitySignal vrSignal) {
// this.controlRealSignal(simulation, vrSignal, false, true, true);
// }
//
// /**
// * 控制室外信号灯显示
// * @param simulation
// * @param vrSignal
// * @param greenOpen
// * @param yellowOpen
// * @param redOpen
// */
// private void controlRealSignal(Simulation simulation, VirtualRealitySignal vrSignal,
// boolean greenOpen, boolean yellowOpen, boolean redOpen) {
// // 根据点灯类型和要开放信号下达信号机控制指令
// if(Objects.isNull(vrSignal)){
// return;
// }
// if (!vrSignal.isSame(greenOpen, yellowOpen, redOpen)) {
// Signal signal = simulation.getRepository().getByCode(vrSignal.getCode(), Signal.class);
// if (signal.isFault()) {
// vrSignal.apply(false, false, true);
// } else {
// vrSignal.apply(greenOpen, yellowOpen, redOpen);
// }
// ControllableDevice ctrlMsg = new SignalLight(vrSignal);
// SimulationDeviceControlEvent event = new SimulationDeviceControlEvent(this, simulation, ctrlMsg);
// this.applicationContext.publishEvent(event);
// }
// }
//
//}

View File

@ -189,8 +189,8 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
Simulation.FunctionalType functionalType) { Simulation.FunctionalType functionalType) {
Objects.requireNonNull(mapId, "地图id不能为空"); Objects.requireNonNull(mapId, "地图id不能为空");
Objects.requireNonNull(functionalType, "仿真功能类型不能为空"); Objects.requireNonNull(functionalType, "仿真功能类型不能为空");
SimulationBuildParams params = this.prepareSimulationParams(loginUserInfoVO, mapId, SimulationBuildParams params = this.prepareSimulationParams(loginUserInfoVO, mapId, prdType,
prdType, functionalType); functionalType);
String group = SimulationIdGenerator.generateGroup(loginUserInfoVO.getAccountVO().getId(), String group = SimulationIdGenerator.generateGroup(loginUserInfoVO.getAccountVO().getId(),
mapId); mapId);
Simulation simulation = this.simulationLifeCycleService.create(params, group); Simulation simulation = this.simulationLifeCycleService.create(params, group);
@ -212,17 +212,13 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
List<RunPlanParkingTimeVO> parkTimeList = this.prepareParkTimeData(mapVO, loginUserInfoVO, List<RunPlanParkingTimeVO> parkTimeList = this.prepareParkTimeData(mapVO, loginUserInfoVO,
mapId); mapId);
// 获取操作定义数据 // 获取操作定义数据
List<CommandDefinitionVO> operationDefinitionList = this.iCommandService List<CommandDefinitionVO> operationDefinitionList = this.iCommandService.queryDefinitionsByLineCode(
.queryDefinitionsByLineCode(mapVO.getLineCode()); mapVO.getLineCode());
SimulationBuildParams.SimulationBuildParamsBuilder builder = SimulationBuildParams.builder(); SimulationBuildParams.SimulationBuildParamsBuilder builder = SimulationBuildParams.builder();
// 都有的属性构造 // 都有的属性构造
builder.loginUserInfo(loginUserInfoVO) builder.loginUserInfo(loginUserInfoVO).createTime(LocalDateTime.now()).map(mapVO)
.createTime(LocalDateTime.now()) .userRunLevelList(runLevelList).userParkTimeList(parkTimeList)
.map(mapVO) .operationDefinitionList(operationDefinitionList).prodType(prdType)
.userRunLevelList(runLevelList)
.userParkTimeList(parkTimeList)
.operationDefinitionList(operationDefinitionList)
.prodType(prdType)
.functionalType(functionalType); .functionalType(functionalType);
//运行图选择性构造 //运行图选择性构造
LocalDate runPlanDate = SimulationConstants.getRunPlanDate(); LocalDate runPlanDate = SimulationConstants.getRunPlanDate();
@ -236,9 +232,8 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
schedulingPlanNewVO = this.schedulingService.queryCommonSchedulingPlanOfDay(mapId, schedulingPlanNewVO = this.schedulingService.queryCommonSchedulingPlanOfDay(mapId,
runPlanDate); runPlanDate);
} else { } else {
schedulingPlanNewVO = this.schedulingService schedulingPlanNewVO = this.schedulingService.querySchedulingPlanUserFirst(
.querySchedulingPlanUserFirst(loginUserInfoVO.getAccountVO().getId(), runPlanVO.getId(), loginUserInfoVO.getAccountVO().getId(), runPlanVO.getId(), runPlanDate);
runPlanDate);
} }
builder.schedulingPlan(schedulingPlanNewVO); builder.schedulingPlan(schedulingPlanNewVO);
} }
@ -294,15 +289,12 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
// 获取地图数据 // 获取地图数据
MapVO mapVO = this.iMapService.getMapDetail(mapId); MapVO mapVO = this.iMapService.getMapDetail(mapId);
// 获取操作定义数据 // 获取操作定义数据
List<CommandDefinitionVO> operationDefinitionList = this.iCommandService List<CommandDefinitionVO> operationDefinitionList = this.iCommandService.queryDefinitionsByLineCode(
.queryDefinitionsByLineCode(mapVO.getLineCode()); mapVO.getLineCode());
SimulationBuildParams.SimulationBuildParamsBuilder builder = SimulationBuildParams.builder(); SimulationBuildParams.SimulationBuildParamsBuilder builder = SimulationBuildParams.builder();
// 都有的属性构造 // 都有的属性构造
builder.loginUserInfo(loginUserInfoVO) builder.loginUserInfo(loginUserInfoVO).createTime(LocalDateTime.now()).map(mapVO)
.createTime(LocalDateTime.now()) .operationDefinitionList(operationDefinitionList).prodType(prdType)
.map(mapVO)
.operationDefinitionList(operationDefinitionList)
.prodType(prdType)
.functionalType(functionalType); .functionalType(functionalType);
//运行图选择性构造 //运行图选择性构造
LocalDate runPlanDate = SimulationConstants.getRunPlanDate(); LocalDate runPlanDate = SimulationConstants.getRunPlanDate();
@ -314,9 +306,8 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
schedulingPlanNewVO = this.schedulingService.queryCommonSchedulingPlanOfDay(mapId, schedulingPlanNewVO = this.schedulingService.queryCommonSchedulingPlanOfDay(mapId,
runPlanDate); runPlanDate);
} else { } else {
schedulingPlanNewVO = this.schedulingService schedulingPlanNewVO = this.schedulingService.querySchedulingPlanUserFirst(
.querySchedulingPlanUserFirst(loginUserInfoVO.getAccountVO().getId(), runPlanVO.getId(), loginUserInfoVO.getAccountVO().getId(), runPlanVO.getId(), runPlanDate);
runPlanDate);
} }
builder.schedulingPlan(schedulingPlanNewVO); builder.schedulingPlan(schedulingPlanNewVO);
} }
@ -368,8 +359,7 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
confirmHasPermission(loginUserInfoVO.getAccountVO(), mapId, prodCode); confirmHasPermission(loginUserInfoVO.getAccountVO(), mapId, prodCode);
MapPrdTypeEnum prdType = MapPrdTypeEnum.getMapPrdTypeEnumByCode(prodCode); MapPrdTypeEnum prdType = MapPrdTypeEnum.getMapPrdTypeEnumByCode(prodCode);
Simulation simulation = this.create(loginUserInfoVO, mapId, Simulation simulation = this.create(loginUserInfoVO, mapId, prdType,
prdType,
Simulation.FunctionalType.SIMULATION); Simulation.FunctionalType.SIMULATION);
if (Objects.equals(MapPrdTypeEnum.BIG_SCREEN, prdType)) { if (Objects.equals(MapPrdTypeEnum.BIG_SCREEN, prdType)) {
@ -573,8 +563,7 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
Simulation simulation = this.groupSimulationCache.getSimulationByGroup(group); Simulation simulation = this.groupSimulationCache.getSimulationByGroup(group);
this.simulationLifeCycleService.checkErrorThrow(simulation); this.simulationLifeCycleService.checkErrorThrow(simulation);
List<TripPlan> tripPlanList = simulation.getRepository().getAllTripPlanList(); List<TripPlan> tripPlanList = simulation.getRepository().getAllTripPlanList();
List<String> tripNumberList = tripPlanList.stream() List<String> tripNumberList = tripPlanList.stream().map(TripPlan::getTripNumber)
.map(TripPlan::getTripNumber)
.collect(Collectors.toList()); .collect(Collectors.toList());
return tripNumberList; return tripNumberList;
} }
@ -652,8 +641,8 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
RunPlanVO runPlan = this.iRunPlanTemplateService.getRunPlan(templateId); RunPlanVO runPlan = this.iRunPlanTemplateService.getRunPlan(templateId);
// 重新加载运行计划匹配的派班计划 // 重新加载运行计划匹配的派班计划
Long userId = simulation.getBuildParams().getUser().getId(); Long userId = simulation.getBuildParams().getUser().getId();
SchedulingPlanNewVO schedulingPlan = this.schedulingService SchedulingPlanNewVO schedulingPlan = this.schedulingService.querySchedulingPlanUserFirst(userId,
.querySchedulingPlanUserFirst(userId, templateId, SimulationConstants.getRunPlanDate()); templateId, SimulationConstants.getRunPlanDate());
this.simulationLifeCycleService.reloadRunPlan(simulation, runPlan, schedulingPlan); this.simulationLifeCycleService.reloadRunPlan(simulation, runPlan, schedulingPlan);
simulation.getRepository().clearChangeTrips(); //清除掉之前的车次计划变化信息 simulation.getRepository().clearChangeTrips(); //清除掉之前的车次计划变化信息
} }
@ -673,8 +662,7 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
ScriptBO scriptBO = iScriptService.getScriptBOById(scriptId, simulation); ScriptBO scriptBO = iScriptService.getScriptBOById(scriptId, simulation);
iScriptSimulationService.scriptCoverSimulation(simulation, scriptBO); iScriptSimulationService.scriptCoverSimulation(simulation, scriptBO);
SocketMessageVO<Boolean> message = SocketMessageFactory.build( SocketMessageVO<Boolean> message = SocketMessageFactory.build(
WebSocketMessageType.Simulation_Script_Loaded, WebSocketMessageType.Simulation_Script_Loaded, simulation.getId(), true);
simulation.getId(), true);
Set<String> userIds = simulation.getSimulationUserIds(); Set<String> userIds = simulation.getSimulationUserIds();
stompMessageService.sendToUser(userIds, message); stompMessageService.sendToUser(userIds, message);
} }
@ -851,11 +839,9 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
@Override @Override
public List<SimulationVO> queryJointSimulationByUser(LoginUserInfoVO loginUserInfoVO) { public List<SimulationVO> queryJointSimulationByUser(LoginUserInfoVO loginUserInfoVO) {
List<Simulation> jointSimulationList = this.groupSimulationCache.queryAllJointSimulation(); List<Simulation> jointSimulationList = this.groupSimulationCache.queryAllJointSimulation();
List<Simulation> userJointSimulationList = jointSimulationList.stream() List<Simulation> userJointSimulationList = jointSimulationList.stream().filter(
.filter(simulation -> simulation -> simulation.isSame(loginUserInfoVO.getProject()) && simulation.containsUser(
simulation.isSame(loginUserInfoVO.getProject()) && loginUserInfoVO.getAccountVO().getId())).collect(Collectors.toList());
simulation.containsUser(loginUserInfoVO.getAccountVO().getId()))
.collect(Collectors.toList());
List<SimulationVO> simulationVOList = SimulationVO.convert2VOList(userJointSimulationList); List<SimulationVO> simulationVOList = SimulationVO.convert2VOList(userJointSimulationList);
return simulationVOList; return simulationVOList;
@ -864,13 +850,11 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
@Override @Override
public void kickOut(String group, Long userId, AccountVO user) { public void kickOut(String group, Long userId, AccountVO user) {
Simulation simulation = this.getSimulationByGroup(group); Simulation simulation = this.getSimulationByGroup(group);
BusinessExceptionAssertEnum.INSUFFICIENT_PERMISSIONS BusinessExceptionAssertEnum.INSUFFICIENT_PERMISSIONS.assertTrue(simulation.isAdmin(user));
.assertTrue(simulation.isAdmin(user));
SimulationUser simulationUser = simulation.querySimulationUserById(userId); SimulationUser simulationUser = simulation.querySimulationUserById(userId);
if (Objects.nonNull(simulationUser)) { if (Objects.nonNull(simulationUser)) {
ProjectDeviceVO projectDevice = simulationUser.getProjectDevice(); ProjectDeviceVO projectDevice = simulationUser.getProjectDevice();
BusinessExceptionAssertEnum.OPERATION_NOT_SUPPORTED BusinessExceptionAssertEnum.OPERATION_NOT_SUPPORTED.assertNull(projectDevice);
.assertNull(projectDevice);
this.kickOut(simulation, simulationUser); this.kickOut(simulation, simulationUser);
} }
} }
@ -903,12 +887,12 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
Simulation simulation = this.getSimulationByGroup(group); Simulation simulation = this.getSimulationByGroup(group);
List<RealDeviceConfig> realDeviceList = simulation.getRealDeviceList(); List<RealDeviceConfig> realDeviceList = simulation.getRealDeviceList();
if (!CollectionUtils.isEmpty(realDeviceList)) { if (!CollectionUtils.isEmpty(realDeviceList)) {
Set<ProjectDeviceType> displayDeviceTypes = Set<ProjectDeviceType> displayDeviceTypes = new HashSet<>(
new HashSet<>( List.of(ProjectDeviceType.PSD, ProjectDeviceType.SWITCH, ProjectDeviceType.SIGNAL,
List.of(ProjectDeviceType.PSD, ProjectDeviceType.SWITCH, ProjectDeviceType.SIGNAL, ProjectDeviceType.PLC_GATEWAY, ProjectDeviceType.IBP, ProjectDeviceType.SECTION,
ProjectDeviceType.PLC_GATEWAY, ProjectDeviceType.IBP, ProjectDeviceType.SECTION)); ProjectDeviceType.PSL));
realDeviceList = realDeviceList realDeviceList = realDeviceList.stream()
.stream().filter(device -> displayDeviceTypes.contains(device.getDeviceType())) .filter(device -> displayDeviceTypes.contains(device.getDeviceType()))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
// List<RealDevice> showList = null; // List<RealDevice> showList = null;
@ -953,8 +937,8 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
//校验目标成员类型 //校验目标成员类型
SimulationMember targetMember = simulation.getSimulationMemberById( SimulationMember targetMember = simulation.getSimulationMemberById(
initiateVO.getTargetMemberId()); initiateVO.getTargetMemberId());
BusinessExceptionAssertEnum.SYSTEM_EXCEPTION BusinessExceptionAssertEnum.SYSTEM_EXCEPTION.assertEquals(targetMember.getType(),
.assertEquals(targetMember.getType(), commandType.getMemberType(), "目标成员不正确"); commandType.getMemberType(), "目标成员不正确");
ScriptBO script = simulation.getScript(); ScriptBO script = simulation.getScript();
if (script != null && script.isBgSet()) { //剧本背景已经保存 if (script != null && script.isBgSet()) { //剧本背景已经保存
@ -1008,15 +992,13 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
public void alarmConfirm(String group, List<String> codes, AccountVO accountVO) { public void alarmConfirm(String group, List<String> codes, AccountVO accountVO) {
Simulation simulation = groupSimulationCache.getSimulationByGroup(group); Simulation simulation = groupSimulationCache.getSimulationByGroup(group);
simulation.getRepository().getAlarmList().stream() simulation.getRepository().getAlarmList().stream()
.filter(atsAlarm -> codes.contains(atsAlarm.getCode())) .filter(atsAlarm -> codes.contains(atsAlarm.getCode())).filter(atsAlarm -> {
.filter(atsAlarm -> {
if (atsAlarm.isConfirmed()) { if (atsAlarm.isConfirmed()) {
codes.remove(atsAlarm.getCode()); codes.remove(atsAlarm.getCode());
return false; return false;
} }
return true; return true;
}) }).forEach(atsAlarm -> atsAlarm.confirm(accountVO, simulation.getCorrectSystemTime()));
.forEach(atsAlarm -> atsAlarm.confirm(accountVO, simulation.getCorrectSystemTime()));
this.applicationContext.publishEvent(new SimulationAlarmConfirmEvent(this, simulation, codes)); this.applicationContext.publishEvent(new SimulationAlarmConfirmEvent(this, simulation, codes));
} }
@ -1057,20 +1039,15 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
int end = pageNum * queryVO.getPageSize(); int end = pageNum * queryVO.getPageSize();
start = Math.min(start, logs.size() - 1); start = Math.min(start, logs.size() - 1);
end = Math.min(end, logs.size()); end = Math.min(end, logs.size());
logs = logs.stream() logs = logs.stream().filter(log -> {
.filter(log -> { if (queryVO.getStartTime() != null && log.getTime().isBefore(queryVO.getStartTime())) {
if (queryVO.getStartTime() != null && log.getTime() return false;
.isBefore(queryVO.getStartTime())) { }
return false; if (queryVO.getEndTime() != null && log.getTime().isAfter(queryVO.getEndTime())) {
} return false;
if (queryVO.getEndTime() != null && log.getTime().isAfter(queryVO.getEndTime())) { }
return false; return true;
} }).skip(start).limit(end - start).collect(Collectors.toList());
return true;
})
.skip(start)
.limit(end - start)
.collect(Collectors.toList());
pageVO.setList(logs); pageVO.setList(logs);
} else { } else {
pageVO.setPageNum(1); pageVO.setPageNum(1);
@ -1173,23 +1150,21 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
Long mapId, String prdType) { Long mapId, String prdType) {
if (accountVO.isThirdChildAccount()) { if (accountVO.isThirdChildAccount()) {
List<LoginUserInfoVO> loginInfos = this.loginSessionManager.getAllLoginUserInfos(); List<LoginUserInfoVO> loginInfos = this.loginSessionManager.getAllLoginUserInfos();
Set<LoginUserInfoVO> thirdLoginList = loginInfos.stream() Set<LoginUserInfoVO> thirdLoginList = loginInfos.stream().filter(
.filter(loginUserInfoVO -> loginUserInfoVO.getAccountVO().isThirdChildAccount() loginUserInfoVO -> loginUserInfoVO.getAccountVO().isThirdChildAccount()
&& loginUserInfoVO.getAccountVO().getParentAccount() && loginUserInfoVO.getAccountVO().getParentAccount()
.equals(accountVO.getParentAccount())) .equals(accountVO.getParentAccount())).collect(Collectors.toSet());
.collect(Collectors.toSet());
Set<String> thirdLoginAccountIdList = thirdLoginList.stream() Set<String> thirdLoginAccountIdList = thirdLoginList.stream()
.map(loginUserInfoVO -> loginUserInfoVO.getAccountVO().getId().toString()) .map(loginUserInfoVO -> loginUserInfoVO.getAccountVO().getId().toString())
.collect(Collectors.toSet()); .collect(Collectors.toSet());
long count = this.simulationManager.getSimulationList().stream() long count = this.simulationManager.getSimulationList().stream()
.filter(simulation -> simulation instanceof Simulation) .filter(simulation -> simulation instanceof Simulation)
.map(simulation -> ((Simulation) simulation)) .map(simulation -> ((Simulation) simulation)).filter(simulation -> {
.filter(simulation -> {
if (simulation.getBuildParams().getMap().getId().equals(mapId)) { if (simulation.getBuildParams().getMap().getId().equals(mapId)) {
if (!((MapPrdTypeEnum.JOINT.getCode().equals(prdType) && if (!((MapPrdTypeEnum.JOINT.getCode().equals(prdType) && MapPrdTypeEnum.JOINT.equals(
MapPrdTypeEnum.JOINT.equals(simulation.getBuildParams().getProdType())) || simulation.getBuildParams().getProdType())) || (
(!MapPrdTypeEnum.JOINT.getCode().equals(prdType) && !MapPrdTypeEnum.JOINT.getCode().equals(prdType) && !MapPrdTypeEnum.JOINT.equals(
!MapPrdTypeEnum.JOINT.equals(simulation.getBuildParams().getProdType())))) { simulation.getBuildParams().getProdType())))) {
return false; return false;
} }
for (String accountId : simulation.getSimulationUserIds()) { for (String accountId : simulation.getSimulationUserIds()) {
@ -1199,11 +1174,8 @@ public class GroupSimulationServiceImpl implements GroupSimulationService {
} }
} }
return false; return false;
}) }).count();
.count(); int sum = ups.stream().mapToInt(userPermissionVO -> userPermissionVO.getRemains()).sum();
int sum = ups.stream()
.mapToInt(userPermissionVO -> userPermissionVO.getRemains())
.sum();
if (sum <= count) { if (sum <= count) {
return false; return false;
} else { } else {

View File

@ -1,39 +0,0 @@
//package club.joylink.rtss.simulation.cbtc.ISCS;
//
//import club.joylink.rtss.services.voice.VoiceService;
//import club.joylink.rtss.simulation.cbtc.Simulation;
//import club.joylink.rtss.simulation.cbtc.data.SimulationDataRepository;
//import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealityTrain;
//import club.joylink.rtss.vo.client.iscs.Ats2PisMsg;
//import club.joylink.rtss.vo.client.voice.BaseVoiceSynthesisVO;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
///**
// * PIS系统逻辑服务
// */
//@Component
//public class OnBoardPisService {
// /*@Autowired
// @Qualifier("baiDuVoiceService")
// private IVoiceService iVoiceService;*/
//
// @Autowired
//// @Qualifier("baiDuVoiceService2")
// private VoiceService iVoiceService;
// public void play(Simulation simulation, Ats2PisMsg msg) {
// String content;
// if (msg.isArrivalMsg()) {
// String direction = msg.getStand().isInside() ? "" : "";
// content = msg.getStation().getName() + "站到了,下车的乘客请从列车运行方向的" + direction + "侧车门下车";
// } else {
// content = "本次列车开往" + msg.getTerminalStation().getName() + "方向,下一站" + msg.getStation().getName();
// }
// BaseVoiceSynthesisVO vo = new BaseVoiceSynthesisVO(content);
// String path = iVoiceService.synthesis(vo).getFilePath();
//// String path = iVoiceService.synthesis(content);
// SimulationDataRepository repository = simulation.getRepository();
// VirtualRealityTrain train = repository.getOnlineTrainBy(msg.getGroupNumber());
// train.getVrAudio().updateUrl(path);
// }
//}

View File

@ -8,78 +8,82 @@ import club.joylink.rtss.vo.LoginUserInfoVO;
import club.joylink.rtss.vo.client.PageVO; import club.joylink.rtss.vo.client.PageVO;
import club.joylink.rtss.vo.client.simulationv1.RunAsPlanParam; import club.joylink.rtss.vo.client.simulationv1.RunAsPlanParam;
import club.joylink.rtss.vo.client.simulationv1.SimulationInfoQueryVO; import club.joylink.rtss.vo.client.simulationv1.SimulationInfoQueryVO;
import lombok.NonNull;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import lombok.NonNull;
public interface SimulationService { public interface SimulationService {
/**
* 创建仿真
*/
String createSimulation(long mapId, SimulationWorkParamVO workParamVO, @NonNull LoginUserInfoVO loginUserInfoVO);
/** /**
* 给仿真添加功能 * 创建仿真
*/ */
void addItems(String simulationId, Map<SimulationWorkParamVO.Item, String> itemMap); String createSimulation(long mapId, SimulationWorkParamVO workParamVO,
@NonNull LoginUserInfoVO loginUserInfoVO);
/** /**
* 从仿真中移除功能 * 给仿真添加功能
*/ */
void removeItems(String simulationId, List<SimulationWorkParamVO.Item> items, LoginUserInfoVO loginInfo); void addItems(String simulationId, Map<SimulationWorkParamVO.Item, String> itemMap);
/** /**
* 按计划行车 * 从仿真中移除功能
*/ */
void runAsPlan(String simulationId, RunAsPlanParam param); void removeItems(String simulationId, List<SimulationWorkParamVO.Item> items,
LoginUserInfoVO loginInfo);
/** /**
* 重置仿真 * 按计划行车
*/ */
void reset(String simulationId); void runAsPlan(String simulationId, RunAsPlanParam param);
/** /**
* 根据地图和功能ID获取仿真GroupId * 重置仿真
* */
* @param mapId 地图ID void reset(String simulationId);
* @param mapFunctionId 功能ID
* @return 仿真GroupId /**
*/ * 根据地图和功能ID获取仿真GroupId
String querySimulationByMapIdAndMapFunction(long mapId, long mapFunctionId); *
* @param mapId 地图ID
* @param mapFunctionId 功能ID
* @return 仿真GroupId
*/
String querySimulationByMapIdAndMapFunction(long mapId, long mapFunctionId);
/** /**
* 根据地图和功能ID获取仿真GroupId返回仿真对象 * 根据地图和功能ID获取仿真GroupId返回仿真对象
* *
* @param mapId 地图ID * @param mapId 地图ID
* @param mapFunctionId 功能ID * @param mapFunctionId 功能ID
* @return 仿真GroupId * @return 仿真GroupId
*/ */
Simulation querySimulation(long mapId, long mapFunctionId); Simulation querySimulation(long mapId, long mapFunctionId);
/** /**
* 监控仿真 * 监控仿真
*/ */
void monitor(String simulationId, AccountVO user); void monitor(String simulationId, AccountVO user);
/** /**
* 后台创建仿真 * 后台创建仿真
* *
* @param mapFunctionId mapFunctionId 功能ID * @param mapFunctionId mapFunctionId 功能ID
* @param loginInfo 登录信息 * @param loginInfo 登录信息
* @param checkAuth 是否检查权限 * @param checkAuth 是否检查权限
* @return 仿真对象 * @return 仿真对象
*/ */
Simulation createSimulation(Long mapFunctionId, LoginUserInfoVO loginInfo, boolean checkAuth); Simulation createSimulation(Long mapFunctionId, LoginUserInfoVO loginInfo, boolean checkAuth);
void loadDraftRunPlan(String simulationId, long draftRunPlanId); void loadDraftRunPlan(String simulationId, long draftRunPlanId);
SimulationVO querySimulationJoinedByUser(long userId); SimulationVO querySimulationJoinedByUser(long userId);
List<SimulationInfoVO> listSimulationByOrg(Long topOrgId, SimulationInfoQueryVO queryVO); List<SimulationInfoVO> listSimulationByOrg(Long topOrgId, SimulationInfoQueryVO queryVO);
PageVO<SimulationInfoVO> pagedSimulationByOrg(Long topOrgId, SimulationInfoQueryVO queryVO); PageVO<SimulationInfoVO> pagedSimulationByOrg(Long topOrgId, SimulationInfoQueryVO queryVO);
void sendUnreceivedMessages(String simulationId, String memberId); void sendUnreceivedMessages(String simulationId, String memberId);
List<SimulationInfoVO> listAllSimulation(SimulationInfoQueryVO queryVO);
} }

View File

@ -34,6 +34,15 @@ import club.joylink.rtss.vo.permission.subject.PermissionSubjectVO;
import club.joylink.rtss.websocket.StompMessageService; import club.joylink.rtss.websocket.StompMessageService;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.NonNull; import lombok.NonNull;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -42,58 +51,58 @@ import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Service @Service
@Slf4j @Slf4j
public class SimulationServiceImpl implements SimulationService { public class SimulationServiceImpl implements SimulationService {
@Autowired
private SimulationManager simulationManager;
@Autowired
private SimulationWorkServiceManager simulationWorkServiceManager;
@Autowired
private GroupSimulationService groupSimulationService;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private DefaultMessageSender defaultMessageSender;
@Autowired
private RtsMapFunctionService rtsMapFunctionService;
@Autowired
private StompMessageService stompMessageService;
@Autowired
private RunPlanDraftService runPlanDraftService;
@Autowired
private SimulationLifeCycleService simulationLifeCycleService;
@Autowired @Autowired
private PermissionSubjectService subjectService; private SimulationManager simulationManager;
@Autowired
private SimulationWorkServiceManager simulationWorkServiceManager;
@Autowired
private GroupSimulationService groupSimulationService;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private DefaultMessageSender defaultMessageSender;
@Autowired
private RtsMapFunctionService rtsMapFunctionService;
@Autowired
private StompMessageService stompMessageService;
@Autowired
private RunPlanDraftService runPlanDraftService;
@Autowired
private SimulationLifeCycleService simulationLifeCycleService;
@Autowired @Autowired
private ISysUserService iSysUserService; private PermissionSubjectService subjectService;
@Autowired @Autowired
private IVoiceDiscriminateRule discriminateRule; private ISysUserService iSysUserService;
@Autowired
private IVoiceDiscriminateRule discriminateRule;
@Override @Override
public String createSimulation(long mapId, SimulationWorkParamVO workParamVO, @NonNull LoginUserInfoVO loginUserInfoVO) { public String createSimulation(long mapId, SimulationWorkParamVO workParamVO,
BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotTrue(workParamVO.containsRealDeviceItem(), "此途径创建的仿真不能连接真实设备"); @NonNull LoginUserInfoVO loginUserInfoVO) {
return createSimulation(mapId, null, workParamVO, loginUserInfoVO, null).getId(); BusinessExceptionAssertEnum.ARGUMENT_ILLEGAL.assertNotTrue(workParamVO.containsRealDeviceItem(),
} "此途径创建的仿真不能连接真实设备");
return createSimulation(mapId, null, workParamVO, loginUserInfoVO, null).getId();
}
//只获取所有与该功能相关的权限信息 //只获取所有与该功能相关的权限信息
private List<PermissionSubjectVO> filterUserPermission(List<PermissionSubjectVO> subjectVOList, MapFunctionVO functionVO, LoginUserInfoVO loginUserInfoVO) { private List<PermissionSubjectVO> filterUserPermission(List<PermissionSubjectVO> subjectVOList,
List<PermissionSubjectVO> newVoList = Lists.newArrayList(); MapFunctionVO functionVO, LoginUserInfoVO loginUserInfoVO) {
for (PermissionSubjectVO subjectVO : subjectVOList) { List<PermissionSubjectVO> newVoList = Lists.newArrayList();
if (subjectVO.getStartTime().isAfter(LocalDateTime.now())) { for (PermissionSubjectVO subjectVO : subjectVOList) {
log.info("权限主体id:[{}] 用户id:[{}] 开始时间:[{}]未到时间", subjectVO.getId(), subjectVO.getSubjectId(), subjectVO.getStartTime()); if (subjectVO.getStartTime().isAfter(LocalDateTime.now())) {
continue; log.info("权限主体id:[{}] 用户id:[{}] 开始时间:[{}]未到时间", subjectVO.getId(),
} subjectVO.getSubjectId(), subjectVO.getStartTime());
if (!CollectionUtils.isEmpty(subjectVO.getSystemAbilityList())) { continue;
}
if (!CollectionUtils.isEmpty(subjectVO.getSystemAbilityList())) {
/* if(Objects.equals(PermissionTypeEnum.PROJECT.getValue(),subjectVO.getPermissionType())){ /* if(Objects.equals(PermissionTypeEnum.PROJECT.getValue(),subjectVO.getPermissionType())){
if(Objects.equals(subjectVO.getPermissionProjectCode(),loginUserInfoVO.getProject().toLowerCase())){ if(Objects.equals(subjectVO.getPermissionProjectCode(),loginUserInfoVO.getProject().toLowerCase())){
newVoList.add(subjectVO); newVoList.add(subjectVO);
@ -104,285 +113,339 @@ public class SimulationServiceImpl implements SimulationService {
newVoList.add(subjectVO); newVoList.add(subjectVO);
} }
}else{*/ }else{*/
for (PermissionSystemAbilityVO permissionSystemAbilityVO : subjectVO.getSystemAbilityList()) { for (PermissionSystemAbilityVO permissionSystemAbilityVO : subjectVO.getSystemAbilityList()) {
if (Objects.equals(permissionSystemAbilityVO.getAbilityId(), functionVO.getId())) { if (Objects.equals(permissionSystemAbilityVO.getAbilityId(), functionVO.getId())) {
newVoList.add(subjectVO); newVoList.add(subjectVO);
break; break;
} }
} }
// } // }
} else { } else {
log.error("权限主体对应的功能是空 主体id:[{}],subjectId:[{}],subjectType:[{}]", subjectVO.getId(), subjectVO.getSubjectId(), subjectVO.getSubjectType()); log.error("权限主体对应的功能是空 主体id:[{}],subjectId:[{}],subjectType:[{}]",
} subjectVO.getId(), subjectVO.getSubjectId(), subjectVO.getSubjectType());
} }
return newVoList; }
return newVoList;
}
/**
* 检测用户对应的权限是否满足
*
* @param functionVO
* @param loginInfo
*/
private Map<String, Boolean> checkUserPermission(MapFunctionVO functionVO,
LoginUserInfoVO loginInfo) {
if (loginInfo.getAccountVO().isAdmin()) {
return Collections.emptyMap();
}
LoginUserInfoVO newLoginUser = loginInfo;
if (loginInfo.getAccountVO().isThirdChildAccount()) {
AccountVO user = this.iSysUserService.queryUserByAccountForMaster(
loginInfo.getAccountVO().getParentAccount());
BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertTrue(Objects.nonNull(user),
"未找到主账号相关权限");
newLoginUser = new LoginUserInfoVO();
user.setCompanyId(loginInfo.getAccountVO().getCompanyId());
newLoginUser.setAccountVO(user);
newLoginUser.setProjectInfo(loginInfo.getProjectInfo());
} }
/** List<PermissionSubjectVO> subjectVOList = this.subjectService.findPermissionWithMapIdAndUserInfo(
* 检测用户对应的权限是否满足 functionVO.getMapId(), newLoginUser);
*
* @param functionVO
* @param loginInfo
*/
private Map<String, Boolean> checkUserPermission(MapFunctionVO functionVO, LoginUserInfoVO loginInfo) {
if (loginInfo.getAccountVO().isAdmin()) {
return Collections.emptyMap();
}
LoginUserInfoVO newLoginUser = loginInfo;
if (loginInfo.getAccountVO().isThirdChildAccount()) {
AccountVO user = this.iSysUserService.queryUserByAccountForMaster(loginInfo.getAccountVO().getParentAccount());
BusinessExceptionAssertEnum.DATA_NOT_EXIST.assertTrue(Objects.nonNull(user), "未找到主账号相关权限");
newLoginUser = new LoginUserInfoVO();
user.setCompanyId(loginInfo.getAccountVO().getCompanyId());
newLoginUser.setAccountVO(user);
newLoginUser.setProjectInfo(loginInfo.getProjectInfo());
}
List<PermissionSubjectVO> subjectVOList = this.subjectService.findPermissionWithMapIdAndUserInfo(functionVO.getMapId(), newLoginUser); List<PermissionSubjectVO> newVOLIst = this.filterUserPermission(subjectVOList, functionVO,
newLoginUser);
List<PermissionSubjectVO> newVOLIst = this.filterUserPermission(subjectVOList, functionVO, newLoginUser); if (CollectionUtils.isEmpty(newVOLIst)) {
if (CollectionUtils.isEmpty(newVOLIst)) { log.error("未找到对应的权限数据mapId[{}],functionId[{}],userId[{}]", functionVO.getMapId(),
log.error("未找到对应的权限数据mapId[{}],functionId[{}],userId[{}]", functionVO.getMapId(), functionVO.getId(), newLoginUser.getAccountVO().getId()); functionVO.getId(), newLoginUser.getAccountVO().getId());
BusinessExceptionAssertEnum.INSUFFICIENT_PERMISSIONS.assertNotTrue(true, "未找到该权限"); BusinessExceptionAssertEnum.INSUFFICIENT_PERMISSIONS.assertNotTrue(true, "未找到该权限");
}
Map<String, Boolean> resultMap2 = Maps.newHashMap();
Map<String, List<PermissionSubjectVO>> subjectMapList = newVOLIst.stream().collect(Collectors.groupingBy(PermissionSubjectVO::getSubjectType));
for (PermissionSubjectTypeEnum st : PermissionSubjectTypeEnum.SORT_ENUM) {
List<PermissionSubjectVO> tmpSubjectVOList = subjectMapList.get(st.name());
if (CollectionUtils.isEmpty(tmpSubjectVOList)) {
continue;
}
List<PermissionSubjectVO> canUseSubjectList = this.findCanUsedPermission(tmpSubjectVOList, functionVO, loginInfo);
BusinessExceptionAssertEnum.INSUFFICIENT_PERMISSIONS.assertNotTrue(CollectionUtils.isEmpty(canUseSubjectList), "该权限过期");
for (PermissionSubjectVO subjectVO : canUseSubjectList) {
String key = String.format("%s-%s", st.name(), subjectVO.getId());
List<Simulation> findSimList = this.simulationManager.finder(key);
resultMap2.put(key, false);
if (findSimList.size() + 1 <= subjectVO.getAmount()) {
resultMap2.put(key, true);
break;
}
}
if (resultMap2.values().stream().anyMatch(d -> Objects.equals(true, d))) {
break;
}
}
BusinessExceptionAssertEnum.INSUFFICIENT_PERMISSIONS.assertNotTrue(resultMap2.values().stream().allMatch(d -> Objects.equals(false, d)), "仿真生成数量过载");
return resultMap2;
} }
Map<String, Boolean> resultMap2 = Maps.newHashMap();
private List<PermissionSubjectVO> findCanUsedPermission(List<PermissionSubjectVO> newVOLIst, MapFunctionVO functionVO, LoginUserInfoVO loginInfo) { Map<String, List<PermissionSubjectVO>> subjectMapList = newVOLIst.stream()
List<PermissionSubjectVO> canUseSubjectList = newVOLIst.stream().filter(d -> Objects.equals(true, d.getForever())).collect(Collectors.toList()); .collect(Collectors.groupingBy(PermissionSubjectVO::getSubjectType));
if (CollectionUtils.isEmpty(canUseSubjectList)) { for (PermissionSubjectTypeEnum st : PermissionSubjectTypeEnum.SORT_ENUM) {
List<Long> timeOverIdList = newVOLIst.stream().filter(d -> Objects.nonNull(d.getEndTime()) && d.getEndTime().isAfter(LocalDateTime.now())) List<PermissionSubjectVO> tmpSubjectVOList = subjectMapList.get(st.name());
.map(d -> d.getId()) if (CollectionUtils.isEmpty(tmpSubjectVOList)) {
.collect(Collectors.toList()); continue;
if (CollectionUtils.isEmpty(timeOverIdList)) { }
log.error("mapId[{}],functionId[{}] userId[{}] 权限过期", functionVO.getMapId(), functionVO.getId(), loginInfo.getAccountVO().getId()); List<PermissionSubjectVO> canUseSubjectList = this.findCanUsedPermission(tmpSubjectVOList,
return Collections.emptyList(); functionVO, loginInfo);
} BusinessExceptionAssertEnum.INSUFFICIENT_PERMISSIONS.assertNotTrue(
canUseSubjectList = newVOLIst.stream().filter(d -> timeOverIdList.contains(d.getId())).collect(Collectors.toList()); CollectionUtils.isEmpty(canUseSubjectList), "该权限过期");
for (PermissionSubjectVO subjectVO : canUseSubjectList) {
String key = String.format("%s-%s", st.name(), subjectVO.getId());
List<Simulation> findSimList = this.simulationManager.finder(key);
resultMap2.put(key, false);
if (findSimList.size() + 1 <= subjectVO.getAmount()) {
resultMap2.put(key, true);
break;
} }
return canUseSubjectList; }
if (resultMap2.values().stream().anyMatch(d -> Objects.equals(true, d))) {
break;
}
} }
BusinessExceptionAssertEnum.INSUFFICIENT_PERMISSIONS.assertNotTrue(
resultMap2.values().stream().allMatch(d -> Objects.equals(false, d)), "仿真生成数量过载");
return resultMap2;
}
@Override private List<PermissionSubjectVO> findCanUsedPermission(List<PermissionSubjectVO> newVOLIst,
public void addItems(@NonNull String simulationId, Map<SimulationWorkParamVO.Item, String> itemMap) { MapFunctionVO functionVO, LoginUserInfoVO loginInfo) {
if (!CollectionUtils.isEmpty(itemMap)) { List<PermissionSubjectVO> canUseSubjectList = newVOLIst.stream()
Simulation simulation = simulationManager.getById(simulationId, Simulation.class); .filter(d -> Objects.equals(true, d.getForever())).collect(Collectors.toList());
Simulation.Type simulationType = simulation.getType(); if (CollectionUtils.isEmpty(canUseSubjectList)) {
SimulationWorkService initService = simulationWorkServiceManager.getWorkService(simulationType); List<Long> timeOverIdList = newVOLIst.stream().filter(
d -> Objects.nonNull(d.getEndTime()) && d.getEndTime().isAfter(LocalDateTime.now()))
.map(d -> d.getId())
.collect(Collectors.toList());
if (CollectionUtils.isEmpty(timeOverIdList)) {
log.error("mapId[{}],functionId[{}] userId[{}] 权限过期", functionVO.getMapId(),
functionVO.getId(), loginInfo.getAccountVO().getId());
return Collections.emptyList();
}
canUseSubjectList = newVOLIst.stream().filter(d -> timeOverIdList.contains(d.getId()))
.collect(Collectors.toList());
}
return canUseSubjectList;
}
@Override
public void addItems(@NonNull String simulationId,
Map<SimulationWorkParamVO.Item, String> itemMap) {
if (!CollectionUtils.isEmpty(itemMap)) {
Simulation simulation = simulationManager.getById(simulationId, Simulation.class);
Simulation.Type simulationType = simulation.getType();
SimulationWorkService initService = simulationWorkServiceManager.getWorkService(
simulationType);
// if (StringUtils.hasText(simulation.getCreatorId())) { // if (StringUtils.hasText(simulation.getCreatorId())) {
// BusinessExceptionAssertEnum.OPERATION_NOT_SUPPORTED.assertEquals(loginInfo.getAccountVO().getIdStr(), simulation.getCreatorId(), // BusinessExceptionAssertEnum.OPERATION_NOT_SUPPORTED.assertEquals(loginInfo.getAccountVO().getIdStr(), simulation.getCreatorId(),
// "非仿真创建者不能使用该功能"); // "非仿真创建者不能使用该功能");
// } // }
initService.addItems(simulation, itemMap); initService.addItems(simulation, itemMap);
SocketMessageVO<SimulationWorkParamVO> workParamMessage = SocketMessageFactory SocketMessageVO<SimulationWorkParamVO> workParamMessage = SocketMessageFactory
.buildSimulationWorkParamMessage(simulationId, simulation.getBuildParams().getWorkParamVO()); .buildSimulationWorkParamMessage(simulationId,
Set<String> users = simulation.getSimulationUserIds(); simulation.getBuildParams().getWorkParamVO());
stompMessageService.sendToUser(users, workParamMessage); Set<String> users = simulation.getSimulationUserIds();
} stompMessageService.sendToUser(users, workParamMessage);
} }
}
@Override @Override
public void removeItems(@NonNull String simulationId, List<SimulationWorkParamVO.Item> items, LoginUserInfoVO loginInfo) { public void removeItems(@NonNull String simulationId, List<SimulationWorkParamVO.Item> items,
if (!CollectionUtils.isEmpty(items)) { LoginUserInfoVO loginInfo) {
Simulation simulation = simulationManager.getById(simulationId, Simulation.class); if (!CollectionUtils.isEmpty(items)) {
Simulation.Type simulationType = simulation.getType(); Simulation simulation = simulationManager.getById(simulationId, Simulation.class);
SimulationWorkService initService = simulationWorkServiceManager.getWorkService(simulationType); Simulation.Type simulationType = simulation.getType();
SimulationWorkService initService = simulationWorkServiceManager.getWorkService(
simulationType);
// if (StringUtils.hasText(simulation.getCreatorId())) { // if (StringUtils.hasText(simulation.getCreatorId())) {
// BusinessExceptionAssertEnum.OPERATION_NOT_SUPPORTED.assertEquals(loginInfo.getAccountVO().getIdStr(), simulation.getCreatorId(), // BusinessExceptionAssertEnum.OPERATION_NOT_SUPPORTED.assertEquals(loginInfo.getAccountVO().getIdStr(), simulation.getCreatorId(),
// "非仿真创建者不能使用该功能"); // "非仿真创建者不能使用该功能");
// } // }
initService.removeFunctions(simulation, items); initService.removeFunctions(simulation, items);
} }
}
@Override
public void runAsPlan(String simulationId, RunAsPlanParam param) {
Simulation simulation = simulationManager.getById(simulationId, Simulation.class);
SimulationWorkService initService = simulationWorkServiceManager.getWorkService(
simulation.getType());
initService.runAsPlan(simulation, param);
}
@Override
public void reset(String simulationId) {
Simulation simulation = simulationManager.getById(simulationId, Simulation.class);
SimulationWorkService initService = simulationWorkServiceManager.getWorkService(
simulation.getType());
initService.reset(simulation);
}
/**
* 根据地图功能ID获取仿真ID
*
* @param mapId 地图ID
* @param mapFunctionId 功能ID
* @return 仿真ID
*/
@Override
public String querySimulationByMapIdAndMapFunction(long mapId, long mapFunctionId) {
return querySimulation(mapId, mapFunctionId).getId();
}
/**
* 根据地图功能ID获取仿真信息获取实体
*/
public Simulation querySimulation(long mapId, long mapFunctionId) {
Simulation targetSimulation = simulationManager.getSimulationList().stream().filter(s -> {
Simulation simulation = (Simulation) s;
return simulation.getMapFunctionId() != null && simulation.getMapFunctionId() == mapFunctionId
&& simulation.getBuildParams().getMap().getId() == mapId;
}).findFirst().map(s -> (Simulation) s).orElse(null);
if (targetSimulation != null) {
return targetSimulation;
}
throw new SimulationException(SimulationExceptionType.Simulation_Not_Exist);
}
@Override
public void monitor(String simulationId, AccountVO user) {
Simulation simulation = simulationManager.getById(simulationId, Simulation.class);
SimulationUser simulationUser = new SimulationUser(simulation, user,
club.joylink.rtss.simulation.SimulationUser.Type.TEACHER);
simulationWorkServiceManager.addSimulationUser(simulation, simulationUser);
}
private Simulation createSimulation(long mapId, MapFunctionVO mapFunctionVO,
@NonNull SimulationWorkParamVO workParamVO,
@NonNull LoginUserInfoVO loginUserInfoVO, Map<String, Boolean> createUserType) {
//获取仿真工作服务
SimulationWorkService initService = simulationWorkServiceManager.getWorkService(
workParamVO.getType());
//创建仿真
String simulationId = SimulationIdGenerator.generateGroup(
loginUserInfoVO.getAccountVO().getId(), mapId);
Simulation simulation = initService.create(mapId, workParamVO, loginUserInfoVO, simulationId);
//语音配置数据
List<VoiceDiscriminateRule> ruleList = this.discriminateRule.findRuleByMapId(mapId);
simulation.setVoiceRuleList(ruleList);
simulation.setMapFunctionVO(mapFunctionVO);
simulation.setCreateUserType(createUserType);
LoginUserInfoVO loginUserInfo = simulation.getBuildParams().getLoginUserInfo();
if (Objects.nonNull(loginUserInfo)) {
simulation.setCreatorId(loginUserInfo.getAccountVO().getIdStr());
simulation.setProject(loginUserInfo.getProject());
simulation.setProjectVO(loginUserInfo.getProjectInfo());
}
// 删除旧仿真保存新仿真
simulation.setMessageSender(this.defaultMessageSender); // 设置默认的消息发布器
simulation.loadModule(); // 加载通用模块
groupSimulationService.clearSimulation(simulation.getId());
simulationManager.saveNew(simulation);
initService.loadData(simulation);
initService.addJobs(simulation);
initService.addMessagePublisher(simulation);
initService.init(simulation);
if (!CollectionUtils.isEmpty(workParamVO.getItemMap())) {
initService.addItems(simulation, workParamVO.getItemMap());
}
applicationContext.publishEvent(new SimulationCreateSuccessEvent(this, simulation));
// 群组配置信息
simulation.initDefaultConversationGroupMap();
// 仿真开始运行
simulationManager.start(simulation.getId());
return simulation;
}
@Override
public Simulation createSimulation(Long mapFunctionId, LoginUserInfoVO loginInfo,
boolean checkAuth) {
MapFunctionVO mapFunctionVO = rtsMapFunctionService.get(mapFunctionId);
Long mapId = mapFunctionVO.getMapId();
Map<String, Boolean> createUserType = Maps.newHashMap();
if (checkAuth) {
createUserType = this.checkUserPermission(mapFunctionVO, loginInfo);
}
SimulationWorkParamVO workParamVO = mapFunctionVO.getParamVO();
if (workParamVO.containsRealDeviceItem()) {
//有实体设备加载项的地图功能实训室同时只能存在一个
Stream<Simulation> stream = simulationManager.getSimulationStream(Simulation.class);
Optional<Simulation> oldSimulationOptional = stream
.filter(sim -> Objects.equals(sim.getMapFunctionId(), mapFunctionId))
.findFirst();
oldSimulationOptional.ifPresent(simulation -> simulationManager.destroy(simulation.getId()));
} }
@Override return createSimulation(mapId, mapFunctionVO, mapFunctionVO.getParamVO(), loginInfo,
public void runAsPlan(String simulationId, RunAsPlanParam param) { createUserType);
Simulation simulation = simulationManager.getById(simulationId, Simulation.class); }
SimulationWorkService initService = simulationWorkServiceManager.getWorkService(simulation.getType());
initService.runAsPlan(simulation, param); @Override
public void loadDraftRunPlan(String simulationId, long draftRunPlanId) {
Simulation simulation = simulationManager.getById(simulationId, Simulation.class);
if (simulation.isPlanRunning()) {
throw new SimulationException(SimulationExceptionType.Operation_Cannot_handed,
String.format("计划运行中,无法重新加载运行计划"));
} }
RunPlanVO runPlanVO = runPlanDraftService.getById(draftRunPlanId);
// 重新加载运行计划匹配的派班计划
this.simulationLifeCycleService.reloadRunPlan(simulation, runPlanVO, null);
simulation.getRepository().clearChangeTrips(); //清除掉之前的车次计划变化信息
}
@Override @Override
public void reset(String simulationId) { public SimulationVO querySimulationJoinedByUser(long userId) {
Simulation simulation = simulationManager.getById(simulationId, Simulation.class); Optional<club.joylink.rtss.simulation.Simulation> optional = simulationManager.getSimulationStream(
SimulationWorkService initService = simulationWorkServiceManager.getWorkService(simulation.getType()); null)
initService.reset(simulation); .filter(simulation -> simulation.querySimulationUserById(String.valueOf(userId)) != null)
.findFirst();
return optional.map(
simulation -> groupSimulationService.getSimulationBasicInfo(simulation.getId()))
.orElse(null);
}
@Override
public List<SimulationInfoVO> listSimulationByOrg(Long topOrgId, SimulationInfoQueryVO queryVO) {
Stream<Simulation> stream = this.simulationManager.getSimulationStream(Simulation.class);
stream = stream.filter(simulation -> Objects.equals(topOrgId,
simulation.getBuildParams().getLoginUserInfo().getTopOrgId()));
if (StringUtils.hasText(queryVO.getGroup())) {
stream = stream.filter(simulation -> simulation.getId().contains(queryVO.getGroup()));
} }
if (StringUtils.hasText(queryVO.getUserName())) {
/** stream = stream.filter(simulation -> simulation.getSimulationUsers().stream()
* 根据地图功能ID获取仿真ID .anyMatch(user -> user.getName().contains(queryVO.getUserName())));
*
* @param mapId 地图ID
* @param mapFunctionId 功能ID
* @return 仿真ID
*/
@Override
public String querySimulationByMapIdAndMapFunction(long mapId, long mapFunctionId) {
return querySimulation(mapId, mapFunctionId).getId();
} }
return stream.map(Simulation::convertToVO).collect(Collectors.toList());
}
/** @Override
* 根据地图功能ID获取仿真信息获取实体 public PageVO<SimulationInfoVO> pagedSimulationByOrg(Long topOrgId,
*/ SimulationInfoQueryVO queryVO) {
public Simulation querySimulation(long mapId, long mapFunctionId) { List<SimulationInfoVO> list = listSimulationByOrg(topOrgId, queryVO);
Simulation targetSimulation = simulationManager.getSimulationList().stream().filter(s -> { Stream<SimulationInfoVO> stream = list.stream();
Simulation simulation = (Simulation) s; int skipNum = (queryVO.getPageNum() - 1) * queryVO.getPageSize();
return simulation.getMapFunctionId() != null && simulation.getMapFunctionId() == mapFunctionId List<SimulationInfoVO> collect = stream.skip(skipNum).limit(queryVO.getPageSize())
&& simulation.getBuildParams().getMap().getId() == mapId; .collect(Collectors.toList());
}).findFirst().map(s -> (Simulation) s).orElse(null); return new PageVO<>(queryVO.getPageNum(), queryVO.getPageSize(), list.size(), collect);
if (targetSimulation != null) { }
return targetSimulation;
} @Override
throw new SimulationException(SimulationExceptionType.Simulation_Not_Exist); public void sendUnreceivedMessages(String simulationId, String memberId) {
Simulation simulation = simulationManager.getById(simulationId, Simulation.class);
SimulationMember member = simulation.getSimulationMemberById(memberId);
while (true) {
SocketMessageVO<?> message = member.getUnreceivedMessages().poll();
if (message == null) {
break;
}
stompMessageService.sendToUser(member.getUserId(), message);
} }
}
@Override @Override
public void monitor(String simulationId, AccountVO user) { public List<SimulationInfoVO> listAllSimulation(SimulationInfoQueryVO queryVO) {
Simulation simulation = simulationManager.getById(simulationId, Simulation.class); List<Simulation> simulationList = this.simulationManager.getSimulationList();
SimulationUser simulationUser = new SimulationUser(simulation, user, club.joylink.rtss.simulation.SimulationUser.Type.TEACHER); Stream<Simulation> stream = simulationList.stream();
simulationWorkServiceManager.addSimulationUser(simulation, simulationUser); if (StringUtils.hasText(queryVO.getGroup())) {
stream = stream.filter(simulation -> simulation.getId().contains(queryVO.getGroup()));
} }
if (StringUtils.hasText(queryVO.getUserName())) {
private Simulation createSimulation(long mapId, MapFunctionVO mapFunctionVO, @NonNull SimulationWorkParamVO workParamVO, stream = stream.filter(simulation -> simulation.getSimulationUsers().stream()
@NonNull LoginUserInfoVO loginUserInfoVO, Map<String, Boolean> createUserType) { .anyMatch(user -> user.getName().contains(queryVO.getUserName())));
//获取仿真工作服务
SimulationWorkService initService = simulationWorkServiceManager.getWorkService(workParamVO.getType());
//创建仿真
String simulationId = SimulationIdGenerator.generateGroup(loginUserInfoVO.getAccountVO().getId(), mapId);
Simulation simulation = initService.create(mapId, workParamVO, loginUserInfoVO, simulationId);
//语音配置数据
List<VoiceDiscriminateRule> ruleList = this.discriminateRule.findRuleByMapId(mapId);
simulation.setVoiceRuleList(ruleList);
simulation.setMapFunctionVO(mapFunctionVO);
simulation.setCreateUserType(createUserType);
LoginUserInfoVO loginUserInfo = simulation.getBuildParams().getLoginUserInfo();
if (Objects.nonNull(loginUserInfo)) {
simulation.setCreatorId(loginUserInfo.getAccountVO().getIdStr());
simulation.setProject(loginUserInfo.getProject());
simulation.setProjectVO(loginUserInfo.getProjectInfo());
}
// 删除旧仿真保存新仿真
simulation.setMessageSender(this.defaultMessageSender); // 设置默认的消息发布器
simulation.loadModule(); // 加载通用模块
groupSimulationService.clearSimulation(simulation.getId());
simulationManager.saveNew(simulation);
initService.loadData(simulation);
initService.addJobs(simulation);
initService.addMessagePublisher(simulation);
initService.init(simulation);
if (!CollectionUtils.isEmpty(workParamVO.getItemMap())) {
initService.addItems(simulation, workParamVO.getItemMap());
}
applicationContext.publishEvent(new SimulationCreateSuccessEvent(this, simulation));
// 群组配置信息
simulation.initDefaultConversationGroupMap();
// 仿真开始运行
simulationManager.start(simulation.getId());
return simulation;
} }
if (queryVO.getFunctionId() != null) {
@Override stream = stream.filter(
public Simulation createSimulation(Long mapFunctionId, LoginUserInfoVO loginInfo, boolean checkAuth) { simulation -> Objects.equals(queryVO.getFunctionId(), simulation.getMapFunctionId()));
MapFunctionVO mapFunctionVO = rtsMapFunctionService.get(mapFunctionId);
Long mapId = mapFunctionVO.getMapId();
Map<String, Boolean> createUserType = Maps.newHashMap();
if (checkAuth) {
createUserType = this.checkUserPermission(mapFunctionVO, loginInfo);
}
SimulationWorkParamVO workParamVO = mapFunctionVO.getParamVO();
if (workParamVO.containsRealDeviceItem()) {
//有实体设备加载项的地图功能实训室同时只能存在一个
Stream<Simulation> stream = simulationManager.getSimulationStream(Simulation.class);
Optional<Simulation> oldSimulationOptional = stream
.filter(sim -> Objects.equals(sim.getMapFunctionId(), mapFunctionId))
.findFirst();
oldSimulationOptional.ifPresent(simulation -> simulationManager.destroy(simulation.getId()));
}
return createSimulation(mapId, mapFunctionVO, mapFunctionVO.getParamVO(), loginInfo, createUserType);
}
@Override
public void loadDraftRunPlan(String simulationId, long draftRunPlanId) {
Simulation simulation = simulationManager.getById(simulationId, Simulation.class);
if (simulation.isPlanRunning()) {
throw new SimulationException(SimulationExceptionType.Operation_Cannot_handed,
String.format("计划运行中,无法重新加载运行计划"));
}
RunPlanVO runPlanVO = runPlanDraftService.getById(draftRunPlanId);
// 重新加载运行计划匹配的派班计划
this.simulationLifeCycleService.reloadRunPlan(simulation, runPlanVO, null);
simulation.getRepository().clearChangeTrips(); //清除掉之前的车次计划变化信息
}
@Override
public SimulationVO querySimulationJoinedByUser(long userId) {
Optional<club.joylink.rtss.simulation.Simulation> optional = simulationManager.getSimulationStream(null)
.filter(simulation -> simulation.querySimulationUserById(String.valueOf(userId)) != null)
.findFirst();
return optional.map(simulation -> groupSimulationService.getSimulationBasicInfo(simulation.getId())).orElse(null);
}
@Override
public List<SimulationInfoVO> listSimulationByOrg(Long topOrgId, SimulationInfoQueryVO queryVO) {
Stream<Simulation> stream = this.simulationManager.getSimulationStream(Simulation.class);
stream = stream.filter(simulation -> Objects.equals(topOrgId, simulation.getBuildParams().getLoginUserInfo().getTopOrgId()));
if (StringUtils.hasText(queryVO.getGroup())) {
stream = stream.filter(simulation -> simulation.getId().contains(queryVO.getGroup()));
}
if (StringUtils.hasText(queryVO.getUserName())) {
stream = stream.filter(simulation -> simulation.getSimulationUsers().stream().anyMatch(user -> user.getName().contains(queryVO.getUserName())));
}
return stream.map(Simulation::convertToVO).collect(Collectors.toList());
}
@Override
public PageVO<SimulationInfoVO> pagedSimulationByOrg(Long topOrgId, SimulationInfoQueryVO queryVO) {
List<SimulationInfoVO> list = listSimulationByOrg(topOrgId, queryVO);
Stream<SimulationInfoVO> stream = list.stream();
int skipNum = (queryVO.getPageNum() - 1) * queryVO.getPageSize();
List<SimulationInfoVO> collect = stream.skip(skipNum).limit(queryVO.getPageSize()).collect(Collectors.toList());
return new PageVO<>(queryVO.getPageNum(), queryVO.getPageSize(), list.size(), collect);
}
@Override
public void sendUnreceivedMessages(String simulationId, String memberId) {
Simulation simulation = simulationManager.getById(simulationId, Simulation.class);
SimulationMember member = simulation.getSimulationMemberById(memberId);
while (true) {
SocketMessageVO<?> message = member.getUnreceivedMessages().poll();
if (message == null) {
break;
}
stompMessageService.sendToUser(member.getUserId(), message);
}
} }
return stream.map(Simulation::convertToVO).collect(Collectors.toList());
}
} }

View File

@ -1,22 +0,0 @@
//package club.joylink.rtss.simulation.cbtc.communication.vo;
//
//import com.fasterxml.jackson.databind.annotation.JsonSerialize;
//import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealityScreenDoor;
//import club.joylink.rtss.util.jsonSerialize.Boolean2NumSerializer;
//import lombok.Getter;
//
///**
// * 站台屏蔽门开/关门控制消息
// */
//@Getter
//public class PsdSwitch extends ControllableDevice {
//
// /** true-开门 false-关门 */
// @JsonSerialize(using = Boolean2NumSerializer.class)
// private boolean open;
//
// public PsdSwitch(VirtualRealityScreenDoor psd, boolean open) {
// super(psd.getCode(), psd.getDeviceType());
// this.open = open;
// }
//}

View File

@ -1,25 +0,0 @@
//package club.joylink.rtss.simulation.cbtc.communication.vo;
//
//import club.joylink.rtss.simulation.cbtc.constant.SignalAspect;
//import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealitySignal;
//import lombok.Getter;
//
///**
// * 信号机点灯状态
// */
//@Getter
//public class SignalLight extends ControllableDevice {
// /**
// * 信号显示
// */
// private SignalAspect aspect;
//
// public SignalLight(VirtualRealitySignal signal) {
// super(signal.getCode(), signal.getDeviceType());
// if (signal.getCommand() != null) {
// this.aspect = signal.getCommand();
// } else {
// this.aspect = signal.getAspect();
// }
// }
//}

View File

@ -1,22 +0,0 @@
//package club.joylink.rtss.simulation.cbtc.communication.vo;
//
//import com.fasterxml.jackson.databind.annotation.JsonSerialize;
//import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealitySwitch;
//import club.joylink.rtss.util.jsonSerialize.Boolean2NumSerializer;
//import lombok.Getter;
//
///**
// * 道岔开始转动消息
// */
//@Getter
//public class SwitchTurn extends ControllableDevice {
//
// /** true-转到定位 false-转到反位 */
// @JsonSerialize(using = Boolean2NumSerializer.class)
// private boolean normal;
//
// public SwitchTurn(VirtualRealitySwitch vrSwitch, boolean normal) {
// super(vrSwitch.getCode(), vrSwitch.getDeviceType());
// this.normal = normal;
// }
//}

View File

@ -1,20 +1,22 @@
package club.joylink.rtss.simulation.cbtc.data.map; package club.joylink.rtss.simulation.cbtc.data.map;
import static club.joylink.rtss.simulation.cbtc.member.SimulationMember.Type.DISPATCHER;
import static club.joylink.rtss.simulation.cbtc.member.SimulationMember.Type.ELECTRIC_DISPATCHER;
import static club.joylink.rtss.simulation.cbtc.member.SimulationMember.Type.MAINTAINER;
import static club.joylink.rtss.simulation.cbtc.member.SimulationMember.Type.STATION_SUPERVISOR;
import club.joylink.rtss.simulation.cbtc.constant.RunLevel; import club.joylink.rtss.simulation.cbtc.constant.RunLevel;
import club.joylink.rtss.simulation.cbtc.member.SimulationMember; import club.joylink.rtss.simulation.cbtc.member.SimulationMember;
import club.joylink.rtss.vo.map.MapFunctionConfig; import club.joylink.rtss.vo.map.MapFunctionConfig;
import club.joylink.rtss.vo.map.RealLineConfigVO; import club.joylink.rtss.vo.map.RealLineConfigVO;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import lombok.Getter;
import static club.joylink.rtss.simulation.cbtc.member.SimulationMember.Type.*; import lombok.Setter;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/** /**
* 地图配置 * 地图配置
@ -23,379 +25,420 @@ import static club.joylink.rtss.simulation.cbtc.member.SimulationMember.Type.*;
@Setter @Setter
public class MapConfig { public class MapConfig {
/** /**
* 上行方向是否向右 * 上行方向是否向右
*/ */
private boolean upRight; private boolean upRight;
/** /**
* 信号封锁下进路是否可以办理 * 信号封锁下进路是否可以办理
*/ */
private boolean signalBlockRouteSettable; private boolean signalBlockRouteSettable;
/** /**
* 进路办理是否先锁闭开始办理直接先锁闭区段如福州一号线 * 进路办理是否先锁闭开始办理直接先锁闭区段如福州一号线
*/ */
private boolean lockFirst; private boolean lockFirst;
/** /**
* 进路办理不失败一直尝试办理 * 进路办理不失败一直尝试办理
*/ */
private boolean routeSettingNoFail; private boolean routeSettingNoFail;
/** /**
* 列车停站开门后才办理出站进路开放出站信号机 * 列车停站开门后才办理出站进路开放出站信号机
*/ */
private boolean signalOpenAfterParking; private boolean signalOpenAfterParking;
/** /**
* 站台扣车是否关闭逻辑点灯的信号机 * 站台扣车是否关闭逻辑点灯的信号机
*/ */
private boolean standHoldCloseLogicLight; private boolean standHoldCloseLogicLight;
/** /**
* ATS是否自动处理人工设置的站前折返自动更新车次 * ATS是否自动处理人工设置的站前折返自动更新车次
*/ */
private boolean atsAutoHandleManualFrontTurnBack; private boolean atsAutoHandleManualFrontTurnBack;
/** /**
* CTC列车进路延续保护仅折返站处锁闭 * CTC列车进路延续保护仅折返站处锁闭
*/ */
private boolean ctcOverlapOnlyTurnBackStationLock; private boolean ctcOverlapOnlyTurnBackStationLock;
/** /**
* 引导办理是否需要先排列进路 * 引导办理是否需要先排列进路
*/ */
private boolean guideNeedRouteSettingFirst; private boolean guideNeedRouteSettingFirst;
/** /**
* 进路是否分为ATP信号地面信号引导信号 * 进路是否分为ATP信号地面信号引导信号
*/ */
private boolean routeLikeHa1; private boolean routeLikeHa1;
/** /**
* 道岔区段是否单独占用对于两个相连的道岔情况 * 道岔区段是否单独占用对于两个相连的道岔情况
*/ */
private boolean switchSingleHandle; private boolean switchSingleHandle;
/** /**
* 进路延续保护设置通过触发设置 * 进路延续保护设置通过触发设置
*/ */
private boolean overlapSettingByTrigger; private boolean overlapSettingByTrigger;
/** /**
* 道岔正/反操是否联动 * 道岔正/反操是否联动
*/ */
private boolean switchNRTurnChain; private boolean switchNRTurnChain;
/** /**
* 道岔单解/锁是否联动 * 道岔单解/锁是否联动
*/ */
private boolean switchSingleLockChain; private boolean switchSingleLockChain;
/** /**
* 道岔失表联动 * 道岔失表联动
*/ */
private boolean switchLossChain; private boolean switchLossChain;
/** /**
* 取消进路命令能否取消引导或接近锁闭的进路 * 取消进路命令能否取消引导或接近锁闭的进路
*/ */
private ApproachLockCancel singleApproachLockCancelRoute; private ApproachLockCancel singleApproachLockCancelRoute;
/** /**
* 列车控制模式/级别 * 列车控制模式/级别
*/ */
private RunLevel runMode; private RunLevel runMode;
/** /**
* 初始加载设备时是否默认单锁正线道岔 * 初始加载设备时是否默认单锁正线道岔
*/ */
private boolean initSingleLockSwitch; private boolean initSingleLockSwitch;
/** /**
* 不停站头码车服务号列表:010-999 * 不停站头码车服务号列表:010-999
*/ */
private String noParkingSM = ""; private String noParkingSM = "";
/** /**
* 停站头码车服务号列表:010-999 * 停站头码车服务号列表:010-999
*/ */
private String parkingSM = ""; private String parkingSM = "";
/** /**
* RM模式下ATP防护速度单位m/s * RM模式下ATP防护速度单位m/s
*/ */
private float rmAtpSpeed; private float rmAtpSpeed;
/** /**
* URM下ATP防护速度单位m/s * URM下ATP防护速度单位m/s
*/ */
private float urmAtpSpeed; private float urmAtpSpeed;
/** /**
* 当取消进路/人解进路时将该进路始端信号机下所有进路设为自排关 * 当取消进路/人解进路时将该进路始端信号机下所有进路设为自排关
*/ */
private boolean cancelAtsControlOfAllRoutesWhenCancelRoute; private boolean cancelAtsControlOfAllRoutesWhenCancelRoute;
/** /**
* 在设置自排开或自动触发之前信号机需处于人工控状态 * 在设置自排开或自动触发之前信号机需处于人工控状态
*/ */
private boolean signalHumanControlBeforeSetAtsControlOrCIAutoTrigger; private boolean signalHumanControlBeforeSetAtsControlOrCIAutoTrigger;
/** /**
* 扣车时是否允许提前发车 * 扣车时是否允许提前发车
*/ */
private boolean allowEarlyDepartureWhenHoldTrain; private boolean allowEarlyDepartureWhenHoldTrain;
/** /**
* 取消进路时列车紧急制动 * 取消进路时列车紧急制动
*/ */
private boolean EBWhenCancelRoute; private boolean EBWhenCancelRoute;
/** /**
* ATS自动调整运行 * ATS自动调整运行
*/ */
private boolean adjustOperationAutomatically; private boolean adjustOperationAutomatically;
/** /**
* 在办理车队进路前是否要先排列进路 * 在办理车队进路前是否要先排列进路
*/ */
private boolean setRouteBeforeSetFlt; private boolean setRouteBeforeSetFlt;
/** /**
* 在取消车队进路时同时取消进路 * 在取消车队进路时同时取消进路
*/ */
private boolean cancelRouteWhenCancelFlt; private boolean cancelRouteWhenCancelFlt;
/** /**
* 办理引导前需要信号机接近锁闭 * 办理引导前需要信号机接近锁闭
*/ */
private boolean needApproachLockBeforeSetGuide; private boolean needApproachLockBeforeSetGuide;
/** /**
* 封锁命令状态仅在后备模式下有效 * 封锁命令状态仅在后备模式下有效
*/ */
private boolean blockadeCommandOnlyValidInStandbyMode; private boolean blockadeCommandOnlyValidInStandbyMode;
/** /**
* 计轴预复位前需要车站预复位 * 计轴预复位前需要车站预复位
*/ */
private boolean stationPreResetBeforeAxlePreReset; private boolean stationPreResetBeforeAxlePreReset;
/** /**
* 道岔转动操作可以使失表故障恢复 * 道岔转动操作可以使失表故障恢复
*/ */
private boolean switchTurnOperationCanRecoverSplitFault; private boolean switchTurnOperationCanRecoverSplitFault;
/** /**
* 扣车命令不区分控制模式 * 扣车命令不区分控制模式
*/ */
private boolean holdCommandIgnoreControlMode; private boolean holdCommandIgnoreControlMode;
/** 共享紧急关闭效果的车站 */ /**
private Set<String> sharingECStations; * 共享紧急关闭效果的车站
*/
private Set<String> sharingECStations;
/** 取消联锁条件不满足的进路时需要延时解锁 */ /**
private boolean delayWhenCancelRouteWithAbnormalInterlock; * 取消联锁条件不满足的进路时需要延时解锁
*/
private boolean delayWhenCancelRouteWithAbnormalInterlock;
/** 车次号的位数 */ /**
private int figuresOfTripNumber; * 车次号的位数
*/
private int figuresOfTripNumber;
/** 服务号的位数 */ /**
private int figuresOfServiceNumber; * 服务号的位数
*/
private int figuresOfServiceNumber;
/** 设置头码车时检查方向 */ /**
private boolean checkDirectionWhenSetHead; * 设置头码车时检查方向
*/
private boolean checkDirectionWhenSetHead;
/** 转换轨进路只能通过故障解锁来取消 */ /**
private boolean transferRouteCanOnlyFaultUnlock; * 转换轨进路只能通过故障解锁来取消
*/
private boolean transferRouteCanOnlyFaultUnlock;
/** 头码车抵达目的地后变为人工车 */ /**
private boolean setManualWhenHeadTrainArriveTarget; * 头码车抵达目的地后变为人工车
*/
private boolean setManualWhenHeadTrainArriveTarget;
/** 进路默认开启冲突检测 */ /**
private boolean routeDefaultCheckConflict; * 进路默认开启冲突检测
*/
private boolean routeDefaultCheckConflict;
/** 处理停车场/车辆段逻辑 */ /**
private boolean handleDepot; * 处理停车场/车辆段逻辑
*/
private boolean handleDepot;
/** 运行图中车次号是否唯一 */ /**
private boolean tripNumberIsUnique; * 运行图中车次号是否唯一
*/
private boolean tripNumberIsUnique;
/** 站台折返策略不生效 */ /**
private boolean standTbStrategyIsInvalid; * 站台折返策略不生效
*/
private boolean standTbStrategyIsInvalid;
/** 根据服务号更新车次计划(西安三提出,抽线之后,后续列车还跑原来的服务,不会自动顶上) */ /**
private boolean updateTripPlanByServiceNumber; * 根据服务号更新车次计划西安三提出抽线之后后续列车还跑原来的服务不会自动顶上
*/
private boolean updateTripPlanByServiceNumber;
/** /**
* 大铁线路 * 大铁线路
*/ */
private boolean railway; private boolean railway;
/** /**
* 对信号机封锁操作是否影响信号显示 * 对信号机封锁操作是否影响信号显示
* <p> * <p>
* true-封锁信号机会使信号机显示禁止色<br> * true-封锁信号机会使信号机显示禁止色<br> false-封锁信号机不会影响信号机显示
* false-封锁信号机不会影响信号机显示 */
*/ private boolean signalBolckOptReflectSignal;
private boolean signalBolckOptReflectSignal;
/** /**
* 区故解只能应用于故障锁闭区段 * 区故解只能应用于故障锁闭区段
*/ */
private boolean SFUCanOnlyApplyForFaultLockSection; private boolean SFUCanOnlyApplyForFaultLockSection;
private boolean hasCTC; private boolean hasCTC;
private boolean hasTDCS; private boolean hasTDCS;
/** /**
* 道岔失表/挤岔时可以办理进路由远及近锁闭到失表/挤岔处终止并且可以开放引导信号 * 道岔失表/挤岔时可以办理进路由远及近锁闭到失表/挤岔处终止并且可以开放引导信号
*/ */
private boolean routeCanSetWhenSwitchFault; private boolean routeCanSetWhenSwitchFault;
/** /**
* 人工驾驶模式CM/RM/NRM下的列车默认是停车等待命令状态 * 人工驾驶模式CM/RM/NRM下的列车默认是停车等待命令状态
*/ */
private boolean manualTrainDefaultStop; private boolean manualTrainDefaultStop;
private Set<SimulationMember.Type> needConfirmConnectMembers = /**
Stream.of(DISPATCHER, STATION_SUPERVISOR, MAINTAINER, ELECTRIC_DISPATCHER).collect(Collectors.toSet()); * 办理引导进路时如果进路首区段占用引导信号15秒后关闭
*/
private boolean guideDelayCloseWhenFirstSectionOccupied;
public MapConfig() { private Set<SimulationMember.Type> needConfirmConnectMembers =
this.lockFirst = false; Stream.of(DISPATCHER, STATION_SUPERVISOR, MAINTAINER, ELECTRIC_DISPATCHER)
this.runMode = RunLevel.CBTC; .collect(Collectors.toSet());
}
public void copyConfigBy(RealLineConfigVO configVO) { public MapConfig() {
if (Objects.nonNull(configVO)) { this.lockFirst = false;
setUpRight(configVO.getUpRight()); this.runMode = RunLevel.CBTC;
this.setSignalBlockRouteSettable(configVO.isSignalBlockRouteSettable()); }
setLockFirst(configVO.getLockFirst());
setRouteSettingNoFail(configVO.isRouteSettingNoFail()); public void copyConfigBy(RealLineConfigVO configVO) {
setSignalOpenAfterParking(configVO.isSignalOpenAfterParking()); if (Objects.nonNull(configVO)) {
this.setStandHoldCloseLogicLight(configVO.isStandHoldCloseLogicLight()); setUpRight(configVO.getUpRight());
this.setAtsAutoHandleManualFrontTurnBack(configVO.isAtsAutoHandleManualFrontTurnBack()); this.setSignalBlockRouteSettable(configVO.isSignalBlockRouteSettable());
setCtcOverlapOnlyTurnBackStationLock(configVO.isCtcOverlapOnlyTurnBackStationLock()); setLockFirst(configVO.getLockFirst());
this.setGuideNeedRouteSettingFirst(configVO.isGuideNeedRouteSettingFirst()); setRouteSettingNoFail(configVO.isRouteSettingNoFail());
setSwitchSingleHandle(configVO.getSwitchSingleHandle()); setSignalOpenAfterParking(configVO.isSignalOpenAfterParking());
setSwitchNRTurnChain(configVO.getSwitchNRTurnChain()); this.setStandHoldCloseLogicLight(configVO.isStandHoldCloseLogicLight());
setSwitchSingleLockChain(configVO.getSwitchSingleLockChain()); this.setAtsAutoHandleManualFrontTurnBack(configVO.isAtsAutoHandleManualFrontTurnBack());
setSwitchLossChain(configVO.getSwitchLossChain()); setCtcOverlapOnlyTurnBackStationLock(configVO.isCtcOverlapOnlyTurnBackStationLock());
setSingleApproachLockCancelRoute(configVO.getSingleApproachLockCancelRoute()); this.setGuideNeedRouteSettingFirst(configVO.isGuideNeedRouteSettingFirst());
setRunMode(RunLevel.valueOf(configVO.getRunMode())); setSwitchSingleHandle(configVO.getSwitchSingleHandle());
setInitSingleLockSwitch(configVO.isInitSingleLockSwitch()); setSwitchNRTurnChain(configVO.getSwitchNRTurnChain());
setNoParkingSM(configVO.getNoParkingSM()); setSwitchSingleLockChain(configVO.getSwitchSingleLockChain());
setParkingSM(configVO.getParkingSM()); setSwitchLossChain(configVO.getSwitchLossChain());
setRmAtpSpeed(configVO.getRmAtpSpeed() / 3.6f); setSingleApproachLockCancelRoute(configVO.getSingleApproachLockCancelRoute());
setUrmAtpSpeed(configVO.getUrmAtpSpeed() / 3.6f); setRunMode(RunLevel.valueOf(configVO.getRunMode()));
setCancelAtsControlOfAllRoutesWhenCancelRoute(configVO.isCancelAtsControlOfAllRoutesWhenCancelRoute()); setInitSingleLockSwitch(configVO.isInitSingleLockSwitch());
setSignalHumanControlBeforeSetAtsControlOrCIAutoTrigger(configVO.isSignalHumanControlBeforeSetAtsControlOrCIAutoTrigger()); setNoParkingSM(configVO.getNoParkingSM());
setAllowEarlyDepartureWhenHoldTrain(configVO.isAllowEarlyDepartureWhenHoldTrain()); setParkingSM(configVO.getParkingSM());
setEBWhenCancelRoute(configVO.isEBWhenCancelRoute()); setRmAtpSpeed(configVO.getRmAtpSpeed() / 3.6f);
setAdjustOperationAutomatically(configVO.isAdjustOperationAutomatically()); setUrmAtpSpeed(configVO.getUrmAtpSpeed() / 3.6f);
setSetRouteBeforeSetFlt(configVO.isSetRouteBeforeSetFlt()); setCancelAtsControlOfAllRoutesWhenCancelRoute(
setCancelRouteWhenCancelFlt(configVO.isCancelRouteWhenCancelFlt()); configVO.isCancelAtsControlOfAllRoutesWhenCancelRoute());
setNeedApproachLockBeforeSetGuide(configVO.isNeedApproachLockBeforeSetGuide()); setSignalHumanControlBeforeSetAtsControlOrCIAutoTrigger(
configVO.isSignalHumanControlBeforeSetAtsControlOrCIAutoTrigger());
setAllowEarlyDepartureWhenHoldTrain(configVO.isAllowEarlyDepartureWhenHoldTrain());
setEBWhenCancelRoute(configVO.isEBWhenCancelRoute());
setAdjustOperationAutomatically(configVO.isAdjustOperationAutomatically());
setSetRouteBeforeSetFlt(configVO.isSetRouteBeforeSetFlt());
setCancelRouteWhenCancelFlt(configVO.isCancelRouteWhenCancelFlt());
setNeedApproachLockBeforeSetGuide(configVO.isNeedApproachLockBeforeSetGuide());
// setStandSkipSetTrainOnlyOnce(configVO.isStandSkipSetTrainOnlyOnce()); // setStandSkipSetTrainOnlyOnce(configVO.isStandSkipSetTrainOnlyOnce());
setBlockadeCommandOnlyValidInStandbyMode(configVO.isBlockadeCommandOnlyValidInStandbyMode()); setBlockadeCommandOnlyValidInStandbyMode(configVO.isBlockadeCommandOnlyValidInStandbyMode());
// setSomeCommandNeedInit(configVO.isSwitchBlockadeCommandNeedInit()); // setSomeCommandNeedInit(configVO.isSwitchBlockadeCommandNeedInit());
setStationPreResetBeforeAxlePreReset(configVO.isStationPreResetBeforeAxlePreReset()); setStationPreResetBeforeAxlePreReset(configVO.isStationPreResetBeforeAxlePreReset());
setSwitchTurnOperationCanRecoverSplitFault(configVO.isSwitchTurnOperationCanRecoverSplitFault()); setSwitchTurnOperationCanRecoverSplitFault(
setHoldCommandIgnoreControlMode(configVO.isHoldCommandIgnoreControlMode()); configVO.isSwitchTurnOperationCanRecoverSplitFault());
setDelayWhenCancelRouteWithAbnormalInterlock(configVO.isDelayWhenCancelRouteWithAbnormalInterlock()); setHoldCommandIgnoreControlMode(configVO.isHoldCommandIgnoreControlMode());
setFiguresOfTripNumber(configVO.getFiguresOfTripNumber()); setDelayWhenCancelRouteWithAbnormalInterlock(
setFiguresOfServiceNumber(configVO.getFiguresOfServiceNumber()); configVO.isDelayWhenCancelRouteWithAbnormalInterlock());
setCheckDirectionWhenSetHead(configVO.isCheckDirectionWhenSetHead()); setFiguresOfTripNumber(configVO.getFiguresOfTripNumber());
setTransferRouteCanOnlyFaultUnlock(configVO.isTransferRouteCanOnlyFaultUnlock()); setFiguresOfServiceNumber(configVO.getFiguresOfServiceNumber());
setSetManualWhenHeadTrainArriveTarget(configVO.isSetManualWhenHeadTrainArriveTarget()); setCheckDirectionWhenSetHead(configVO.isCheckDirectionWhenSetHead());
setRouteDefaultCheckConflict(configVO.isRouteDefaultCheckConflict()); setTransferRouteCanOnlyFaultUnlock(configVO.isTransferRouteCanOnlyFaultUnlock());
setTripNumberIsUnique(configVO.isTripNumberIsUnique()); setSetManualWhenHeadTrainArriveTarget(configVO.isSetManualWhenHeadTrainArriveTarget());
setStandTbStrategyIsInvalid(configVO.isStandTbStrategyIsInvalid()); setRouteDefaultCheckConflict(configVO.isRouteDefaultCheckConflict());
setUpdateTripPlanByServiceNumber(configVO.isUpdateTripPlanByServiceNumber()); setTripNumberIsUnique(configVO.isTripNumberIsUnique());
setRailway(configVO.isRailway()); setStandTbStrategyIsInvalid(configVO.isStandTbStrategyIsInvalid());
setSignalBolckOptReflectSignal(configVO.isSignalBolckOptReflectSignal()); setUpdateTripPlanByServiceNumber(configVO.isUpdateTripPlanByServiceNumber());
setSFUCanOnlyApplyForFaultLockSection(configVO.isSFUCanOnlyApplyForFaultLockSection()); setRailway(configVO.isRailway());
setRouteCanSetWhenSwitchFault(configVO.isRouteCanSetWhenSwitchFault()); setSignalBolckOptReflectSignal(configVO.isSignalBolckOptReflectSignal());
setManualTrainDefaultStop(configVO.isManualTrainDefaultStop()); setSFUCanOnlyApplyForFaultLockSection(configVO.isSFUCanOnlyApplyForFaultLockSection());
setRouteCanSetWhenSwitchFault(configVO.isRouteCanSetWhenSwitchFault());
setManualTrainDefaultStop(configVO.isManualTrainDefaultStop());
setGuideDelayCloseWhenFirstSectionOccupied(
configVO.isGuideDelayCloseWhenFirstSectionOccupied());
}
}
public void copyConfigBy(MapFunctionConfig mapFunctionConfig) {
if (mapFunctionConfig == null) {
return;
}
this.hasCTC = mapFunctionConfig.isHasCTC();
this.hasTDCS = mapFunctionConfig.isHasTDCS();
}
public boolean isNoParkingServiceNumber(String serviceNumber) {
if (StringUtils.hasText(noParkingSM)) {
if (noParkingSM.contains("-")) {
String[] split = noParkingSM.split("-");
if (split.length == 2) {
return Integer.parseInt(serviceNumber) >= Integer.parseInt(split[0])
&& Integer.parseInt(serviceNumber) <= Integer.parseInt(split[1]);
} }
}
} }
return false;
}
public void copyConfigBy(MapFunctionConfig mapFunctionConfig) { public boolean isParkingServiceNumber(String serviceNumber) {
if (mapFunctionConfig == null) if (StringUtils.hasText(parkingSM)) {
return; if (parkingSM.contains("-")) {
this.hasCTC = mapFunctionConfig.isHasCTC(); String[] split = parkingSM.split("-");
this.hasTDCS = mapFunctionConfig.isHasTDCS(); if (split.length == 2) {
} return Integer.parseInt(serviceNumber) >= Integer.parseInt(split[0])
&& Integer.parseInt(serviceNumber) <= Integer.parseInt(split[1]);
public boolean isNoParkingServiceNumber(String serviceNumber) {
if (StringUtils.hasText(noParkingSM)) {
if (noParkingSM.contains("-")) {
String[] split = noParkingSM.split("-");
if (split.length == 2) {
return Integer.parseInt(serviceNumber) >= Integer.parseInt(split[0]) && Integer.parseInt(serviceNumber) <= Integer.parseInt(split[1]);
}
}
} }
return false; }
} }
return false;
}
public boolean isParkingServiceNumber(String serviceNumber) { /**
if (StringUtils.hasText(parkingSM)) { * 是否向右根据上/下行
if (parkingSM.contains("-")) { *
String[] split = parkingSM.split("-"); * @param up 是否上行
if (split.length == 2) { * @return
return Integer.parseInt(serviceNumber) >= Integer.parseInt(split[0]) && Integer.parseInt(serviceNumber) <= Integer.parseInt(split[1]); */
} public boolean isRight(boolean up) {
} if ((this.isUpRight() && up) || (!this.isUpRight() && !up)) {
} return true;
return false; } else {
return false;
} }
}
/**
* 是否是上行根据左/右行
*/
public boolean isUp(boolean right) {
return this.upRight == right;
}
public boolean isSharingECStation(String stationCode) {
if (CollectionUtils.isEmpty(this.sharingECStations)) {
return false;
}
for (String code : sharingECStations) {
if (code.equals(stationCode)) {
return true;
}
}
return false;
}
public enum ApproachLockCancel {
/** /**
* 是否向右根据上/下行 * 不能取消
*
* @param up 是否上行
* @return
*/ */
public boolean isRight(boolean up) { NOT,
if ((this.isUpRight() && up) || (!this.isUpRight() && !up)) {
return true;
} else {
return false;
}
}
/** /**
* 是否是上行根据左/右行 * 延时取消
*/ */
public boolean isUp(boolean right) { DELAY,
return this.upRight == right; /**
} * 直接取消
*/
public boolean isSharingECStation(String stationCode) { DIRECT,
if (CollectionUtils.isEmpty(this.sharingECStations)) ;
return false; }
for (String code : sharingECStations) {
if (code.equals(stationCode))
return true;
}
return false;
}
public enum ApproachLockCancel {
/**
* 不能取消
*/
NOT,
/**
* 延时取消
*/
DELAY,
/**
* 直接取消
*/
DIRECT,;
}
} }

View File

@ -1,22 +0,0 @@
//package club.joylink.rtss.simulation.cbtc.data.support;
//
//import club.joylink.rtss.simulation.cbtc.data.map.Section;
//import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealityTrain;
//import lombok.Getter;
//
///**
// * 列车停稳消息
// */
//@Getter
//public class TrainStopMessage {
//
// private VirtualRealityTrain train;
//
// private Section section;
//
// public TrainStopMessage(VirtualRealityTrain train) {
// this.train = train;
// this.section = train.getHeadPosition().getSection();
// }
//
//}

View File

@ -9,79 +9,85 @@ import lombok.Setter;
*/ */
@Getter @Getter
@Setter @Setter
public class VirtualRealityScreenDoor extends ControllableVrDevice<VirtualRealityScreenDoor.Operation> { public class VirtualRealityScreenDoor extends
ControllableVrDevice<VirtualRealityScreenDoor.Operation> {
public boolean isCommandOpen() { public boolean isCommandOpen() {
return Operation.K.equals(this.getCommand()); return Operation.K.equals(this.getCommand());
} }
/** /**
* 道岔支持的操作 * 道岔支持的操作
*/ */
public enum Operation { public enum Operation {
/** 开门 */ /**
K, * 开门
/** 关门 */ */
G, K,
} /**
* 关门
/** */
* 是否关闭 G,
*/ }
private boolean close;
/**
/** * 是否关闭
* 是否开门到位 */
*/ private boolean close;
private boolean open2End;
/**
/** * 是否开门到位
* 是否锁闭 */
*/ private boolean open2End;
private boolean lock;
/**
/** * 是否锁闭
* psl盘互锁解除 */
*/ private boolean lock;
private boolean pslInterlockRelease;
/**
/** * psl盘互锁解除
* ibp盘互锁解除 */
*/ private boolean pslInterlockRelease;
private boolean ibpInterlockRelease;
/**
private Fault fault; * ibp盘互锁解除
*/
public VirtualRealityScreenDoor(String code, String name) { private boolean ibpInterlockRelease;
super(code, name, MapElement.DeviceType.PSD, 3*1000);
this.close = true; private Fault fault;
this.lock = true;
} public VirtualRealityScreenDoor(String code, String name) {
super(code, name, MapElement.DeviceType.PSD, 3 * 1000);
@Override this.close = true;
public void reset() { this.lock = true;
super.reset(); }
this.close = true;
this.lock = true; @Override
this.open2End = false; public void reset() {
this.pslInterlockRelease = false; super.reset();
this.ibpInterlockRelease = false; this.close = true;
this.fault = null; this.lock = true;
} this.open2End = false;
this.pslInterlockRelease = false;
@Override this.ibpInterlockRelease = false;
protected boolean checkConditionBeforeControl(Operation command) { this.fault = null;
if (command == null) }
return false;
switch (command) { @Override
case K: protected boolean checkConditionBeforeControl(Operation command) {
return !open2End; if (command == null) {
case G: return false;
return !isLockAndClose(); }
default: switch (command) {
throw new IllegalStateException("Unexpected value: " + command); case K:
} return !open2End;
case G:
return !isLockAndClose();
default:
throw new IllegalStateException("Unexpected value: " + command);
} }
}
// @Override // @Override
// protected boolean checkConditionBeforeControl(Operation command) { // protected boolean checkConditionBeforeControl(Operation command) {
@ -101,148 +107,153 @@ public class VirtualRealityScreenDoor extends ControllableVrDevice<VirtualRealit
// return true; // return true;
// } // }
@Override @Override
protected void doTurn() { protected void doTurn() {
Operation command = getCommand(); Operation command = getCommand();
if (command == null) { if (command == null) {
return; return;
}
switch (command) {
case K:{
if (this.isOpen2End())
setRemain(0);
else
setClose(false);
break;
}
case G: {
if (this.isLockAndClose())
setRemain(0);
else
setOpen2End(false);
break;
}
default:
throw new IllegalStateException("Unexpected value: " + command);
}
} }
switch (command) {
case K: {
if (this.isOpen2End()) {
setRemain(0);
} else {
setClose(false);
}
break;
}
case G: {
if (this.isLockAndClose()) {
setRemain(0);
} else {
setOpen2End(false);
}
break;
}
default:
throw new IllegalStateException("Unexpected value: " + command);
}
}
@Override @Override
protected void doFinish(Operation command) { protected void doFinish(Operation command) {
switch (command) { switch (command) {
case K:{ case K: {
this.setClose(false); this.setClose(false);
this.open2End = true; this.open2End = true;
break; break;
} }
case G: { case G: {
this.open2End = false; this.open2End = false;
this.setClose(true); this.setClose(true);
this.setLock(true); this.setLock(true);
break; break;
} }
}
} }
}
public boolean isInterlockRelease() { public boolean isInterlockRelease() {
return pslInterlockRelease || ibpInterlockRelease; return pslInterlockRelease || ibpInterlockRelease;
} }
public void setClose(boolean close) { public void setClose(boolean close) {
if ((Fault.CANNOT_BE_CLOSED.equals(this.fault) && close)|| if ((Fault.CANNOT_BE_CLOSED.equals(this.fault) && close) ||
(Fault.CANNOT_BE_OPENED.equals(this.fault) && !close)) (Fault.CANNOT_BE_OPENED.equals(this.fault) && !close)) {
return; return;
this.close = close; }
} this.close = close;
}
public void setLock(boolean lock) { public void setLock(boolean lock) {
if (Fault.NO_CLOSE_AND_LOCK.equals(this.fault) && lock) if (Fault.NO_CLOSE_AND_LOCK.equals(this.fault) && lock) {
return; return;
this.lock = lock; }
} this.lock = lock;
}
// public void updateIL(boolean il) { // public void updateIL(boolean il) {
// this.interlockRelease = il; // this.interlockRelease = il;
// } // }
public boolean isLockAndClose() { public boolean isLockAndClose() {
return this.lock && this.close; return this.lock && this.close;
} }
/** /**
* 全部关门 * 全部关门
*/ */
public void updateLockAndClose(boolean close, boolean lock) { public void updateLockAndClose(boolean close, boolean lock) {
this.open2End = false; this.open2End = false;
this.close = close; this.close = close;
this.setLock(lock); this.setLock(lock);
if (close && lock && this.isSettingClose()) { if (close && lock && this.isSettingClose()) {
this.finish(); this.finish();
} }
} }
public void updateOpen2End(boolean end) { public void updateOpen2End(boolean end) {
this.setLock(false); this.setLock(false);
this.close = false; this.close = false;
this.open2End = end; this.open2End = end;
if (end && this.isSettingOpen()) { if (end && this.isSettingOpen()) {
this.finish(); this.finish();
} }
} }
public boolean isSettingOpen() { public boolean isSettingOpen() {
return Operation.K.equals(this.getCommand()) && this.getRemain() > 0; return Operation.K.equals(this.getCommand()) && this.getRemain() > 0;
} }
public boolean isSettingClose() { public boolean isSettingClose() {
return Operation.G.equals(this.getCommand()) && this.getRemain() > 0; return Operation.G.equals(this.getCommand()) && this.getRemain() > 0;
} }
/** /**
* 开关门进行中 * 开关门进行中
*/ */
public void turning() { public void turning() {
if (this.lock) { if (this.lock) {
this.setLock(false); this.setLock(false);
} }
if (this.close) { if (this.close) {
this.close = false; this.close = false;
} }
if (this.open2End) { if (this.open2End) {
this.open2End = false; this.open2End = false;
} }
} }
public enum Fault { public enum Fault {
CANNOT_BE_CLOSED { CANNOT_BE_CLOSED {
@Override @Override
public void apply(VirtualRealityScreenDoor door) { public void apply(VirtualRealityScreenDoor door) {
door.setFault(null); // door.setFault(null);
door.control(Operation.K); // door.control(Operation.K);
door.setFault(this); door.setFault(this);
} }
}, },
CANNOT_BE_OPENED { CANNOT_BE_OPENED {
@Override @Override
public void apply(VirtualRealityScreenDoor door) { public void apply(VirtualRealityScreenDoor door) {
door.setFault(null); // door.setFault(null);
door.control(Operation.G); // door.control(Operation.G);
door.setFault(this); door.setFault(this);
} }
}, },
NO_CLOSE_AND_LOCK { NO_CLOSE_AND_LOCK {
@Override @Override
public void apply(VirtualRealityScreenDoor door) { public void apply(VirtualRealityScreenDoor door) {
door.setLock(false); door.setLock(false);
door.setFault(this); door.setFault(this);
} }
}; };
public abstract void apply(VirtualRealityScreenDoor door); public abstract void apply(VirtualRealityScreenDoor door);
public void fix(VirtualRealityScreenDoor vrPSD) { public void fix(VirtualRealityScreenDoor vrPSD) {
if (this.equals(vrPSD.getFault())) if (this.equals(vrPSD.getFault())) {
vrPSD.setFault(null); vrPSD.setFault(null);
} }
} }
}
} }

View File

@ -13,141 +13,147 @@ import lombok.Setter;
@Setter @Setter
public class VirtualRealitySwitch extends ControllableVrDevice<VirtualRealitySwitch.Operation> { public class VirtualRealitySwitch extends ControllableVrDevice<VirtualRealitySwitch.Operation> {
private SwitchIndication p; private SwitchIndication p;
// -------------运行逻辑控制参数------------- // -------------运行逻辑控制参数-------------
private Fault fault; private Fault fault;
private Operation lastOperation; private Operation lastOperation;
@Override @Override
public boolean control(Operation command) { public boolean control(Operation command) {
boolean control = super.control(command); boolean control = super.control(command);
if (control && command != null) { if (control && command != null) {
this.lastOperation = command; this.lastOperation = command;
}
return control;
} }
return control;
}
@Override @Override
protected boolean checkConditionBeforeControl(Operation command) { protected boolean checkConditionBeforeControl(Operation command) {
switch (command) { switch (command) {
case NP: case NP:
return !(SwitchIndication.N == this.p); return !(SwitchIndication.N == this.p);
case RP: case RP:
return !(SwitchIndication.R == this.p); return !(SwitchIndication.R == this.p);
}
return true;
} }
return true;
}
@Override @Override
protected void doTurn() { protected void doTurn() {
this.p = SwitchIndication.NO; this.p = SwitchIndication.NO;
}
@Override
protected void doFinish(Operation command) {
BusinessExceptionAssertEnum.SYSTEM_EXCEPTION.assertNotNull(command);
if (Fault.SQUEEZE.equals(this.getFault()) || Fault.SPLIT.equals(this.getFault())) {
return;
} }
switch (command) {
@Override case NP:
protected void doFinish(Operation command) { this.p = SwitchIndication.N;
BusinessExceptionAssertEnum.SYSTEM_EXCEPTION.assertNotNull(command); break;
if (Fault.SQUEEZE.equals(this.getFault()) || Fault.SPLIT.equals(this.getFault())) { case RP:
return; this.p = SwitchIndication.R;
} break;
switch (command) {
case NP:
this.p = SwitchIndication.N;
break;
case RP:
this.p = SwitchIndication.R;
break;
}
} }
}
public boolean isPosN() { public boolean isPosN() {
return SwitchIndication.N.equals(this.p); return SwitchIndication.N.equals(this.p);
} }
public boolean isPosR() { public boolean isPosR() {
return SwitchIndication.R.equals(this.p); return SwitchIndication.R.equals(this.p);
} }
public boolean isCommandNp() { public boolean isCommandNp() {
return Operation.NP.equals(this.getCommand()); return Operation.NP.equals(this.getCommand());
} }
/**
* 道岔支持的操作
*/
public enum Operation {
/** /**
* 道岔支持的操作 * 定操
*/ */
public enum Operation { NP,
/** 定操 */ /**
NP, * 反操
/** 反操 */ */
RP, RP,
} }
public VirtualRealitySwitch(String code, String name, int turnTime) { public VirtualRealitySwitch(String code, String name, int turnTime) {
super(code, name, MapElement.DeviceType.SWITCH, turnTime * 1000); super(code, name, MapElement.DeviceType.SWITCH, turnTime * 1000);
this.p = SwitchIndication.N; this.p = SwitchIndication.N;
} }
@Override @Override
public void reset() { public void reset() {
super.reset(); super.reset();
this.p = SwitchIndication.N; this.p = SwitchIndication.N;
this.fault = null; this.fault = null;
this.lastOperation = Operation.NP; this.lastOperation = Operation.NP;
} }
public void apply(boolean normalPosition, boolean reversePosition) { public void apply(boolean normalPosition, boolean reversePosition) {
if (normalPosition) { if (normalPosition) {
this.p = SwitchIndication.N; this.p = SwitchIndication.N;
} else if (reversePosition) { } else if (reversePosition) {
this.p = SwitchIndication.R; this.p = SwitchIndication.R;
} else { } else {
this.p = SwitchIndication.NO; this.p = SwitchIndication.NO;
}
if ((Operation.NP.equals(this.getCommand()) && SwitchIndication.N.equals(this.p)) ||
(Operation.RP.equals(this.getCommand()) && SwitchIndication.R.equals(this.p))) {
this.finish();
}
}
//最后一次是否是转向定位
public boolean isLastTurnToN() {
return this.lastOperation == Operation.NP;
}
public enum Fault {
SPLIT {
@Override
public boolean apply(VirtualRealitySwitch vrSwitch) {
if (this.equals(vrSwitch.getFault())) {
return false;
} }
if ((Operation.NP.equals(this.getCommand()) && SwitchIndication.N.equals(this.p)) || vrSwitch.setFault(this);
(Operation.RP.equals(this.getCommand()) && SwitchIndication.R.equals(this.p))) { vrSwitch.setP(SwitchIndication.NO);
this.finish(); return true;
} }
} },
/**
//最后一次是否是转向定位 * 挤岔
public boolean isLastTurnToN() { */
return this.lastOperation == Operation.NP; SQUEEZE {
} @Override
public boolean apply(VirtualRealitySwitch vrSwitch) {
public enum Fault { if (this.equals(vrSwitch.getFault())) {
SPLIT { return false;
@Override
public boolean apply(VirtualRealitySwitch vrSwitch) {
if (this.equals(vrSwitch.getFault()))
return false;
vrSwitch.setFault(this);
vrSwitch.setP(SwitchIndication.NO);
return true;
}
},
/**
* 挤岔
*/
SQUEEZE {
@Override
public boolean apply(VirtualRealitySwitch vrSwitch) {
if (this.equals(vrSwitch.getFault()))
return false;
vrSwitch.setFault(this);
vrSwitch.setP(SwitchIndication.EX);
return true;
}
};
public abstract boolean apply(VirtualRealitySwitch vrSwitch);
public void fix(VirtualRealitySwitch vrSwitch) {
if (this.equals(vrSwitch.getFault())) {
vrSwitch.setFault(null);
}
} }
vrSwitch.setFault(this);
vrSwitch.setP(SwitchIndication.EX);
return true;
}
};
public abstract boolean apply(VirtualRealitySwitch vrSwitch);
public void fix(VirtualRealitySwitch vrSwitch) {
if (this.equals(vrSwitch.getFault())) {
vrSwitch.setFault(null);
}
} }
}
} }

View File

@ -0,0 +1,26 @@
package club.joylink.rtss.simulation.cbtc.device.real.modbustcp.cgy;
import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.common.RealDeviceConfig;
import club.joylink.rtss.util.JsonUtils;
import club.joylink.rtss.vo.client.project.ProjectDeviceVO;
import club.joylink.rtss.vo.client.project.cgy.CgyPslConfigVO;
import club.joylink.rtss.vo.client.project.sdy.SdyPslConfigVO;
import lombok.Getter;
@Getter
public class CgyPslConfig extends RealDeviceConfig {
private CgyPslConfigVO configVO;
public CgyPslConfig(ProjectDeviceVO projectDevice) {
super(projectDevice);
if (projectDevice != null) {
this.configVO = JsonUtils.read(projectDevice.getConfig(), CgyPslConfigVO.class);
}
}
@Override
public String findDeviceCode() {
return configVO.findDeviceCode();
}
}

View File

@ -0,0 +1,86 @@
package club.joylink.rtss.simulation.cbtc.device.real.modbustcp.cgy;
import club.joylink.rtss.services.psl.IVirtualRealityPslService;
import club.joylink.rtss.simulation.cbtc.Simulation;
import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealityPsl;
import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealityPsl.Button;
import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.PlcGatewayService;
import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.RealDeviceService;
import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.common.PlcGateway;
import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.common.RealDeviceConfig;
import club.joylink.rtss.vo.client.project.cgy.CgyPslConfigVO;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@Slf4j
@Component
public class CgyPslServiceImpl implements RealDeviceService {
@Autowired
private PlcGatewayService plcGatewayService;
@Autowired
private IVirtualRealityPslService virtualRealityPslService;
@Override
public boolean canHandle(RealDeviceConfig deviceConfig) {
return deviceConfig instanceof CgyPslConfig;
}
@Override
public void init(Simulation simulation, RealDeviceConfig deviceConfig) {
// PlcGateway plcGateway = simulation.getPlcGateway();
// CgyPslConfigVO configVO = ((CgyPslConfig) deviceConfig).getConfigVO();
// Channel channel = plcGateway.getChannel();
// int baseAddr = plcGateway.getConfig().getAddr() + configVO.getAddr();
// plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_gm_light(), false, channel);
// plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_km_light(), false, channel);
// plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_psl_light(), false, channel);
// plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_gbsj_light(), false, channel);
}
@Override
public void handle(Simulation simulation, RealDeviceConfig deviceConfig, ByteBuf byteBuf) {
PlcGateway plcGateway = simulation.queryPlcGatewayDevice();
if (plcGateway == null) {
return;
}
CgyPslConfig config = (CgyPslConfig) deviceConfig;
CgyPslConfigVO configVO = config.getConfigVO();
if (!StringUtils.hasText(configVO.getPslCode())) {
return;
}
VirtualRealityPsl vrPsl = simulation.getRepository()
.getByCode(configVO.getPslCode(), VirtualRealityPsl.class);
ByteBuf deviceStatus = RealDeviceConfig.getDeviceCoilStatus(byteBuf, configVO.getAddr(),
configVO.getQuantity());
boolean r_km_btn = RealDeviceConfig.getBitOf(deviceStatus, configVO.getR_km_btn());
boolean r_gm_btn = RealDeviceConfig.getBitOf(deviceStatus, configVO.getR_gm_btn());
boolean r_yxjz_btn = RealDeviceConfig.getBitOf(deviceStatus, configVO.getR_yxjz_btn());
boolean r_hsjc_key = RealDeviceConfig.getBitOf(deviceStatus, configVO.getR_hsjc_key());
boolean r_xy_btn = RealDeviceConfig.getBitOf(deviceStatus, configVO.getR_xy_btn());
boolean w_km_light = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_km_light());
boolean w_gm_light = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_gm_light());
boolean w_yxcz_light = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_yxcz_light());
boolean w_gbsj_light = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_gbsj_light());
//向vrPSL同步操作
virtualRealityPslService.updateStatus(simulation, vrPsl, Button.KM, r_km_btn);
virtualRealityPslService.updateStatus(simulation, vrPsl, Button.GM, r_gm_btn);
virtualRealityPslService.updateStatus(simulation, vrPsl, Button.YXJZ, r_yxjz_btn);
virtualRealityPslService.updateStatus(simulation, vrPsl, Button.HSJC, r_hsjc_key);
//向实体PSL同步状态
int baseAddr = plcGateway.getConfig().getAddr() + configVO.getAddr();
Channel channel = plcGateway.getChannel();
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_km_light(),
w_km_light, vrPsl.isKmLight(), channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_gm_light(),
w_gm_light, vrPsl.isGmLight(), channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_yxcz_light(),
w_yxcz_light, vrPsl.isYxjzKey(), channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_gbsj_light(),
w_gbsj_light, vrPsl.isQbgmLight(), channel);
}
}

View File

@ -1,44 +1,43 @@
//package club.joylink.rtss.simulation.cbtc.device.real.modbustcp.cgy; package club.joylink.rtss.simulation.cbtc.device.real.modbustcp.cgy;
//
//import club.joylink.rtss.simulation.cbtc.Simulation; import club.joylink.rtss.simulation.cbtc.Simulation;
//import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealitySectionAxleCounter; import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealitySectionAxleCounter;
//import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.RealDeviceService; import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.RealDeviceService;
//import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.common.PlcGateway; import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.common.PlcGateway;
//import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.common.RealDeviceConfig; import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.common.RealDeviceConfig;
//import club.joylink.rtss.vo.client.project.cgy.CgySectionConfigVO; import club.joylink.rtss.vo.client.project.cgy.CgySectionConfigVO;
//import club.joylink.rtss.vo.client.project.say.SaySectionConfigVO; import io.netty.buffer.ByteBuf;
//import io.netty.buffer.ByteBuf; import org.springframework.stereotype.Service;
//import org.springframework.stereotype.Service;
// @Service
//@Service public class CgySectionServiceImpl implements RealDeviceService {
//public class CgySectionServiceImpl implements RealDeviceService {
// @Override
// @Override public boolean canHandle(RealDeviceConfig deviceConfig) {
// public boolean canHandle(RealDeviceConfig deviceConfig) { return deviceConfig instanceof CgySectionConfig;
// return deviceConfig instanceof CgySectionConfig; }
// }
// @Override
// @Override public void init(Simulation simulation, RealDeviceConfig deviceConfig) {
// public void init(Simulation simulation, RealDeviceConfig deviceConfig) {
// }
// }
// @Override
// @Override public void handle(Simulation simulation, RealDeviceConfig deviceConfig, ByteBuf byteBuf) {
// public void handle(Simulation simulation, RealDeviceConfig deviceConfig, ByteBuf byteBuf) { PlcGateway plcGateway = simulation.queryPlcGatewayDevice();
// PlcGateway plcGateway = simulation.queryPlcGatewayDevice(); if (plcGateway == null) {
// if (plcGateway == null) { return;
// return; }
// } CgySectionConfig config = (CgySectionConfig) deviceConfig;
// CgySectionConfig config = (CgySectionConfig) deviceConfig; VirtualRealitySectionAxleCounter vrAxleCounter = (VirtualRealitySectionAxleCounter) config.getMapElement();
// VirtualRealitySectionAxleCounter vrAxleCounter = (VirtualRealitySectionAxleCounter) config.getMapElement(); if (vrAxleCounter == null) {
// if (vrAxleCounter == null) { return;
// return; }
// } CgySectionConfigVO configVO = config.getConfigVO();
// CgySectionConfigVO configVO = config.getConfigVO(); ByteBuf deviceStatus = RealDeviceConfig.getDeviceCoilStatus(byteBuf, configVO.getAddr(),
// ByteBuf deviceStatus = RealDeviceConfig.getDeviceCoilStatus(byteBuf, configVO.getAddr(), configVO.getQuantity());
// configVO.getQuantity());
// boolean r_occupied = RealDeviceConfig.getBitOf(deviceStatus, configVO.getR_occupied());
// boolean r_clear = RealDeviceConfig.getBitOf(deviceStatus, configVO.getR_clear()); vrAxleCounter.setOccupy(r_occupied);
// vrAxleCounter.setOccupy(!r_clear); }
// } }
//}

View File

@ -46,29 +46,34 @@ public class CgySignalServiceImpl implements RealDeviceService {
Channel channel = plcGateway.getChannel(); Channel channel = plcGateway.getChannel();
switch (aspect) { switch (aspect) {
case No: case No:
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_red(), false, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_ddj(), true, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_green(), false, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_lxj(), false, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_yellow(), false, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_yxj(), false, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_zxj(), false, channel);
break; break;
case R: case R:
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_red(), true, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_ddj(), false, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_green(), false, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_lxj(), false, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_yellow(), false, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_yxj(), false, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_zxj(), false, channel);
break; break;
case G: case G:
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_red(), false, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_ddj(), true, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_green(), true, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_lxj(), true, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_yellow(), false, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_yxj(), false, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_zxj(), true, channel);
break; break;
case Y: case Y:
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_red(), false, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_ddj(), true, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_green(), false, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_lxj(), true, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_yellow(), true, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_yxj(), false, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_zxj(), false, channel);
break; break;
case RY: case RY:
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_red(), true, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_ddj(), false, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_green(), false, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_lxj(), false, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_yellow(), true, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_yxj(), true, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_zxj(), false, channel);
break; break;
default: default:
log.error("不支持的显示:{}", aspect); log.error("不支持的显示:{}", aspect);
@ -91,84 +96,83 @@ public class CgySignalServiceImpl implements RealDeviceService {
ByteBuf deviceStatus = RealDeviceConfig.getDeviceCoilStatus(byteBuf, configVO.getAddr(), ByteBuf deviceStatus = RealDeviceConfig.getDeviceCoilStatus(byteBuf, configVO.getAddr(),
configVO.getQuantity()); configVO.getQuantity());
boolean r_r = RealDeviceConfig.getBitOf(deviceStatus, configVO.getR_red()); //同步信号显示
boolean r_g = RealDeviceConfig.getBitOf(deviceStatus, configVO.getR_green()); SignalAspect aspect = getAspect(deviceStatus, configVO);
boolean r_y = RealDeviceConfig.getBitOf(deviceStatus, configVO.getR_yellow()); vrSignal.apply(aspect);
//驱动信号显示
SignalAspect aspect = null;
if (!r_r && !r_g && !r_y) {
aspect = SignalAspect.No;
} else if (r_r && !r_g && !r_y) {
aspect = SignalAspect.R;
} else if (!r_r && r_g && !r_y) {
aspect = SignalAspect.G;
} else if (!r_r && !r_g && r_y) {
aspect = SignalAspect.Y;
} else if (r_r && !r_g && r_y) {
aspect = SignalAspect.RY;
}
if (aspect == null) {
log.error("未知的信号组合[红:%s][绿:%s][黄:%s]", r_r, r_g, r_y);
} else {
vrSignal.apply(aspect);
}
if (vrSignal.isTurning()) { if (vrSignal.isTurning()) {
boolean w_r = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_red()); boolean w_ddj = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_ddj());
boolean w_g = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_green()); boolean w_lxj = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_lxj());
boolean w_y = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_yellow()); boolean w_yxj = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_yxj());
boolean w_zxj = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_zxj());
int baseAddr = plcGateway.getConfig().getAddr() + configVO.getAddr(); int baseAddr = plcGateway.getConfig().getAddr() + configVO.getAddr();
Channel channel = plcGateway.getChannel(); Channel channel = plcGateway.getChannel();
SignalAspect command = vrSignal.getCommand(); SignalAspect command = vrSignal.getCommand();
switch (command) { switch (command) {
case No: case No:
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_red(), w_r, false, plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_ddj(), w_ddj, true,
channel); channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_green(), w_g, plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_lxj(), w_lxj,
false, false,
channel); channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_yellow(), w_y, plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_yxj(), w_yxj,
false,
channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_zxj(), w_zxj,
false, false,
channel); channel);
break; break;
case R: case R:
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_red(), w_r, true, plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_ddj(), w_ddj,
channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_green(), w_g,
false, false,
channel); channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_yellow(), w_y, plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_lxj(), w_lxj,
false,
channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_yxj(), w_yxj,
false,
channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_zxj(), w_zxj,
false, false,
channel); channel);
break; break;
case G: case G:
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_red(), w_r, false, plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_ddj(), w_ddj,
channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_green(), w_g, true,
channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_yellow(), w_y,
false, false,
channel); channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_lxj(), w_lxj, true,
channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_yxj(), w_yxj,
false,
channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_zxj(), w_zxj, true,
channel);
break; break;
case Y: case Y:
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_red(), w_r, false, plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_ddj(), w_ddj,
channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_green(), w_g,
false, false,
channel); channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_yellow(), w_y, plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_lxj(), w_lxj, true,
true, channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_yxj(), w_yxj,
false,
channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_zxj(), w_zxj,
false,
channel); channel);
break; break;
case RY: case RY:
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_red(), w_r, true, plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_ddj(), w_ddj,
channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_green(), w_g,
false, false,
channel); channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_yellow(), w_y, plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_lxj(), w_lxj,
true, false,
channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_yxj(), w_yxj, true,
channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_zxj(), w_zxj,
false,
channel); channel);
break; break;
default: default:
@ -177,4 +181,22 @@ public class CgySignalServiceImpl implements RealDeviceService {
} }
} }
} }
private SignalAspect getAspect(ByteBuf deviceStatus, CgySignalConfigVO configVO) {
boolean r_ddj = RealDeviceConfig.getBitOf(deviceStatus, configVO.getR_ddj());
boolean r_lxj = RealDeviceConfig.getBitOf(deviceStatus, configVO.getR_lxj());
boolean r_yxj = RealDeviceConfig.getBitOf(deviceStatus, configVO.getR_yxj());
boolean r_zxj = RealDeviceConfig.getBitOf(deviceStatus, configVO.getR_zxj());
if (r_yxj) {
return SignalAspect.RY;
} else if (r_lxj && r_zxj) {
return SignalAspect.G;
} else if (r_lxj) {
return SignalAspect.Y;
} else if (!r_ddj) {
return SignalAspect.R;
} else {
return SignalAspect.No;
}
}
} }

View File

@ -35,7 +35,7 @@ public class CgySwitchServiceImpl implements RealDeviceService {
CgySwitchConfigVO configVO = config.getConfigVO(); CgySwitchConfigVO configVO = config.getConfigVO();
int baseAddr = plcGateway.getConfig().getAddr() + configVO.getAddr(); int baseAddr = plcGateway.getConfig().getAddr() + configVO.getAddr();
Channel channel = plcGateway.getChannel(); Channel channel = plcGateway.getChannel();
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_sj(), false, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_js(), false, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_dc(), false, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_dc(), false, channel);
plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_fc(), false, channel); plcGatewayService.writeSingleCoil(baseAddr, configVO.getW_fc(), false, channel);
} }
@ -63,7 +63,7 @@ public class CgySwitchServiceImpl implements RealDeviceService {
boolean r_fb = RealDeviceConfig.getBitOf(deviceStatus, configVO.getR_fb()); boolean r_fb = RealDeviceConfig.getBitOf(deviceStatus, configVO.getR_fb());
vrSwitch.apply(r_db, r_fb); vrSwitch.apply(r_db, r_fb);
//以下操作实体设备的逻辑中防止继电器长期接通的逻辑将定反操视为技能共用3秒冷却技能持续时间也是3秒 //以下操作实体设备的逻辑中防止继电器长期接通的逻辑将定反操视为技能共用3秒冷却技能持续时间也是3秒
if (config.isEnd()) { //此判断既可视为操作是否冷却也可视为持续时间是否耗尽 if (config.isEnd()) { //此判断既可视为操作是否冷却也可视为持续时间是否耗尽
config.sync(r_db, r_fb); config.sync(r_db, r_fb);
release(deviceStatus, baseAddr, configVO, channel); //操作持续时间耗尽后断开所有继电器 release(deviceStatus, baseAddr, configVO, channel); //操作持续时间耗尽后断开所有继电器
@ -87,10 +87,10 @@ public class CgySwitchServiceImpl implements RealDeviceService {
private void turnToN(ByteBuf deviceStatus, int baseAddr, CgySwitchConfigVO configVO, private void turnToN(ByteBuf deviceStatus, int baseAddr, CgySwitchConfigVO configVO,
Channel channel) { Channel channel) {
boolean w_sb = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_sj()); boolean w_sb = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_js());
boolean w_dc = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_dc()); boolean w_dc = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_dc());
boolean w_fc = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_fc()); boolean w_fc = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_fc());
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_sj(), w_sb, true, plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_js(), w_sb, true,
channel); channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_dc(), w_dc, true, plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_dc(), w_dc, true,
channel); channel);
@ -100,10 +100,10 @@ public class CgySwitchServiceImpl implements RealDeviceService {
private void turnToP(ByteBuf deviceStatus, int baseAddr, CgySwitchConfigVO configVO, private void turnToP(ByteBuf deviceStatus, int baseAddr, CgySwitchConfigVO configVO,
Channel channel) { Channel channel) {
boolean w_sb = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_sj()); boolean w_js = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_js());
boolean w_dc = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_dc()); boolean w_dc = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_dc());
boolean w_fc = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_fc()); boolean w_fc = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_fc());
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_sj(), w_sb, true, plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_js(), w_js, true,
channel); channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_dc(), w_dc, false, plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_dc(), w_dc, false,
channel); channel);
@ -113,10 +113,10 @@ public class CgySwitchServiceImpl implements RealDeviceService {
private void release(ByteBuf deviceStatus, int baseAddr, CgySwitchConfigVO configVO, private void release(ByteBuf deviceStatus, int baseAddr, CgySwitchConfigVO configVO,
Channel channel) { Channel channel) {
boolean w_sj = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_sj()); boolean w_sj = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_js());
boolean w_dc = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_dc()); boolean w_dc = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_dc());
boolean w_fc = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_fc()); boolean w_fc = RealDeviceConfig.getBitOf(deviceStatus, configVO.getW_fc());
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_sj(), w_sj, false, plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_js(), w_sj, false,
channel); channel);
plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_dc(), w_dc, false, plcGatewayService.checkEqualAndWriteSingleCoil(baseAddr, configVO.getW_dc(), w_dc, false,
channel); channel);

View File

@ -10,119 +10,124 @@ import club.joylink.rtss.simulation.cbtc.data.map.Signal;
import club.joylink.rtss.simulation.cbtc.data.support.SectionPosition; import club.joylink.rtss.simulation.cbtc.data.support.SectionPosition;
import club.joylink.rtss.simulation.cbtc.data.vo.TrainInfo; import club.joylink.rtss.simulation.cbtc.data.vo.TrainInfo;
import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealityTrain; import club.joylink.rtss.simulation.cbtc.data.vr.VirtualRealityTrain;
import org.springframework.stereotype.Component;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import org.springframework.stereotype.Component;
@Component @Component
public class TrainTargetUpdateService { public class TrainTargetUpdateService {
public static final String Model_Name = "TrainTargetUpdate";
public static final int Rate = 5000;
public void addJobs(Simulation simulation) { public static final String Model_Name = "TrainTargetUpdate";
simulation.addJob(Model_Name, () -> this.run(simulation), Rate); public static final int Rate = 5000;
public void addJobs(Simulation simulation) {
simulation.addJob(Model_Name, () -> this.run(simulation), Rate);
}
public void run(Simulation simulation) {
SimulationDataRepository repository = simulation.getRepository();
List<VirtualRealityTrain> onlineTrain = repository.getOnlineTrainList();
for (VirtualRealityTrain train : onlineTrain) {
TrainInfo trainInfo = repository.findSupervisedTrainByGroup(train.getGroupNumber());
if (trainInfo == null) {
continue;
}
Section target = train.getTarget();
Section newTarget = this.queryArriveTarget(train, trainInfo);
if (newTarget != null && !Objects.equals(target, newTarget)) {
train.setTarget(newTarget);
}
} }
}
public void run(Simulation simulation) { private Section queryArriveTarget4Manual(VirtualRealityTrain train, TrainInfo trainInfo,
SimulationDataRepository repository = simulation.getRepository(); Section target) {
List<VirtualRealityTrain> onlineTrain = repository.getOnlineTrainList(); SectionPosition headPosition = train.getHeadPosition();
for (VirtualRealityTrain train : onlineTrain) { boolean right = train.isRight();
TrainInfo trainInfo = repository.getSupervisedTrainByGroup(train.getGroupNumber()); Section newTarget = target;
// if (!trainInfo.isManualTrain()) { Section temp = headPosition.getSection();
// continue; for (int i = 0; i < 50; i++) {
// } if (temp == null) {
Section target = train.getTarget(); break;
Section newTarget = this.queryArriveTarget(train, trainInfo);
if (newTarget != null && !Objects.equals(target, newTarget)) {
train.setTarget(newTarget);
}
} }
} if (!temp.isFunctionTrack()) {
temp = temp.findNextRunningSectionBaseRealSwitch(right);
private Section queryArriveTarget4Manual(VirtualRealityTrain train, TrainInfo trainInfo, Section target) { continue;
SectionPosition headPosition = train.getHeadPosition(); }
boolean right = train.isRight(); Signal signal = temp.getSignalOf(right);
Section newTarget = target; if (signal != null && !signal.isMainAspect()) {
Section temp = headPosition.getSection(); newTarget = temp;
for (int i = 0; i < 50; i++) { if (temp.isFunctionTrack()) {
if (temp == null) break;
break; }
if (!temp.isFunctionTrack()) { }
temp = temp.findNextRunningSectionBaseRealSwitch(right); if (temp.isNormalStandTrack() || temp.isTransferTrack()) {
continue; if (temp.isNormalStandTrack()) {
} if (temp.getStandList().stream()
Signal signal = temp.getSignalOf(right); .anyMatch(stand -> stand.isJumpStop(train.getGroupNumber()))) { //该列车应在站台跳停
if (signal != null && !signal.isMainAspect()) {
newTarget = temp;
if (temp.isFunctionTrack())
break;
}
if (temp.isNormalStandTrack() || temp.isTransferTrack()) {
if (temp.isNormalStandTrack()) {
if (temp.getStandList().stream().anyMatch(stand -> stand.isJumpStop(train.getGroupNumber()))) { //该列车应在站台跳停
temp = temp.findNextRunningSectionBaseRealSwitch(right);
continue;
}
}
if (!temp.equals(headPosition.getSection())) { //列车还未到达该区段
newTarget = temp;
break;
} else {
if (!temp.getCode().equals(trainInfo.getActualArriveStandTrack())) { //列车未在该区段停车
SectionPosition maxStopPosition = CalculateService
.calculateNextPositionByStartAndLen(temp.buildStopPointPosition(right),
right, SimulationConstants.PARK_POINT_MAX_OFFSET, false); //最远停车点
if (maxStopPosition.isAheadOf(headPosition, right)) { //该区段最远停车点在车头前方
newTarget = temp;
break;
}
}
}
}
temp = temp.findNextRunningSectionBaseRealSwitch(right); temp = temp.findNextRunningSectionBaseRealSwitch(right);
continue;
}
} }
return newTarget; if (!temp.equals(headPosition.getSection())) { //列车还未到达该区段
newTarget = temp;
break;
} else {
if (!temp.getCode().equals(trainInfo.getActualArriveStandTrack())) { //列车未在该区段停车
SectionPosition maxStopPosition = CalculateService
.calculateNextPositionByStartAndLen(temp.buildStopPointPosition(right),
right, SimulationConstants.PARK_POINT_MAX_OFFSET, false); //最远停车点
if (maxStopPosition.isAheadOf(headPosition, right)) { //该区段最远停车点在车头前方
newTarget = temp;
break;
}
}
}
}
temp = temp.findNextRunningSectionBaseRealSwitch(right);
} }
return newTarget;
}
private Section queryArriveTarget(VirtualRealityTrain train, TrainInfo trainInfo) { private Section queryArriveTarget(VirtualRealityTrain train, TrainInfo trainInfo) {
Section newTarget = null; Section newTarget = null;
MaService.Ma ma = train.getMa2(); MaService.Ma ma = train.getMa2();
if (ma == null) if (ma == null) {
return null; return null;
SectionPosition eoaPosition = ma.getEoaPosition(); }
Section eoaSection = eoaPosition.getSection(); SectionPosition eoaPosition = ma.getEoaPosition();
SectionPosition headPosition = train.getHeadPosition(); Section eoaSection = eoaPosition.getSection();
boolean right = train.isRight(); SectionPosition headPosition = train.getHeadPosition();
Section headSection = headPosition.getSection(); boolean right = train.isRight();
Section section = headSection; Section headSection = headPosition.getSection();
for (int i = 0; i < 100; i++) { Section section = headSection;
if (section.equals(eoaSection) && newTarget == null) { //已经遍历到移动授权终点区段且中途未找到功能轨 for (int i = 0; i < 100; i++) {
newTarget = section; if (section.equals(eoaSection) && newTarget == null) { //已经遍历到移动授权终点区段且中途未找到功能轨
break; newTarget = section;
} break;
if (section.isFunctionTrack()) { }
if (section.isNormalStandTrack()) { if (section.isFunctionTrack()) {
if (train.isHold()) { if (section.isNormalStandTrack()) {
newTarget = section; if (train.isHold()) {
break; newTarget = section;
} break;
if (!section.getCode().equals(trainInfo.getActualArriveStandTrack())) { //列车没有抵达该站台轨的信息 }
newTarget = section; if (!section.getCode().equals(trainInfo.getActualArriveStandTrack())) { //列车没有抵达该站台轨的信息
break; newTarget = section;
} break;
} else { }
newTarget = section; } else {
} newTarget = section;
}
section = section.findNextRunningSectionBaseRealSwitch(right);
if (section == null) {
break;
} else {
continue;
}
} }
return newTarget; }
section = section.findNextRunningSectionBaseRealSwitch(right);
if (section == null) {
break;
} else {
continue;
}
} }
return newTarget;
}
} }

View File

@ -1,356 +0,0 @@
//package club.joylink.rtss.simulation.cbtc.passenger.strategy.service;
//
//import club.joylink.rtss.exception.BusinessExceptionAssertEnum;
//import club.joylink.rtss.simulation.cbtc.data.map.Stand;
//import club.joylink.rtss.simulation.cbtc.data.plan.RealRun;
//import club.joylink.rtss.simulation.cbtc.data.plan.StationPlan;
//import club.joylink.rtss.simulation.cbtc.data.plan.TripPlan;
//import club.joylink.rtss.simulation.cbtc.passenger.strategy.Config;
//import club.joylink.rtss.simulation.cbtc.passenger.strategy.data.*;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//import org.springframework.util.CollectionUtils;
//
//import java.time.LocalDateTime;
//import java.time.LocalTime;
//import java.util.*;
//
//@Slf4j
//@Component
//public class JumpAndParkTimeStrategyServiceImpl implements StrategyService<JumpAndParkTimeStrategy> {
//
// @Override
// public List<JumpAndParkTimeStrategy> generateStrategy(StrategyCalculateData data) {
// List<JumpAndParkTimeStrategy> list = new ArrayList<>();
// List<StandPassenger> lpfList = data.queryLpfList();
// if (CollectionUtils.isEmpty(lpfList)) {
// return null;
// }
// // 暂时按一个站大客流处理
// StandPassenger standPassenger = lpfList.get(0);
// Stand stand = standPassenger.getStand();
// Map<String, List<TripPlan>> planMap = data.getPlanMap();
// int planParkTime = 0; // 计划停站时间
// for (List<TripPlan> planList : planMap.values()) {
// for (TripPlan tripPlan : planList) {
// List<StationPlan> stationPlanList = tripPlan.getPlanList();
// for (StationPlan stationPlan : stationPlanList) {
// if (Objects.equals(stationPlan.getSection(), stand.getSection()) &&
// stationPlan.getParkTime() > 0) {
// planParkTime = stationPlan.getParkTime();
// break;
// }
// }
// }
// if (planParkTime > 0) {
// break;
// }
// }
// if (planParkTime <= 0) {
// throw new IllegalArgumentException(String.format("计划或站台[%s]数据异常,找到的计划停站时间异常:为[%s]", stand.debugStr(), planParkTime));
// }
// // 最大停站时间内每隔5秒生成一个策略策略的停站时间为计划停站时间+5*i
// int iter = (Config.STAND_MAX_STOP_TIME - planParkTime) / 5;
// for (int i = 1; i <= iter; i++) {
// list.add(new JumpAndParkTimeStrategy(stand, planParkTime + i * 5));
// }
// List<Stand> leftStandList = data.getLeftStandList();
// List<Stand> rightStandList = data.getRightStandList();
// boolean right = false;
// int index = leftStandList.indexOf(stand);
// if (index < 0) {
// // 不是左向站台
// right = true;
// index = rightStandList.indexOf(stand);
// }
// BusinessExceptionAssertEnum.DATA_ERROR.assertTrue(index >= 0, String.format("未找到站台[%s]", stand.debugStr()));
// log.debug(String.format("[%s]第[%s]个站台大客流", right?"右向":"左向", (index+1)));
//
// boolean hasJump = false;
// if (index == 0) {
// // 第一站不生成跳停策略
// log.debug(String.format("第一个站,不生成跳停策略"));
// }
// List<Stand> jumpableStandList;
// if (right) {
// jumpableStandList = rightStandList.subList(0, index);
// } else {
// jumpableStandList = leftStandList.subList(0, index);
// }
// List<TrainPassenger> trainPassengerList = data.getTrainPassengerList();
// for (int i = jumpableStandList.size()-1; i > 0; i--) { // 起始站不跳停
// Stand s = jumpableStandList.get(i);
// // 该站台人数是否支持跳停
// StandPassenger sp = data.getStandPassengerByStand(s);
// if (sp.getWait() >= Config.STAND_JUMP_MAX) {
// log.debug(String.format("站台[%s]客流数[%s]>=站台跳停最大客流量[%s],不能跳停",
// s.debugStr(), sp.getWait(), Config.STAND_JUMP_MAX));
// continue;
// }
// // 该站是否被前列车跳过
// RealRun jumpRun = this.isJustJumped(data, s);
// if (jumpRun != null) {
// log.debug(String.format("站台[%s]刚被跳停,不生成", s.debugStr()));
// continue;
// }
// // 前一站是否刚跳停
// if (i - 1 > 0) {
// Stand pre = jumpableStandList.get(i - 1);
// jumpRun = this.isJustJumped(data, pre);
// if (jumpRun != null) {
// boolean jump = false;
// List<RealRun> realRuns = data.queryRealRuns(jumpRun.getGroupNumber());
// int i1 = realRuns.indexOf(jumpRun);
// for (int j = i1; j < realRuns.size(); j++) {
// RealRun realRun = realRuns.get(j);
// if (Objects.equals(realRun.getSectionCode(), s.getSection().getCode())) {
// if (!realRun.isArrive()) {
// jump = true;
// }
// break;
// }
// }
// if (jump) {
// log.debug(String.format("站台[%s]的前一站台[%s]刚被跳停,不生成", s.debugStr(), pre.debugStr()));
// continue;
// }
// }
// }
// hasJump = true;
// for (JumpAndParkTimeStrategy jumpAndParkTimeStrategy : list) {
// jumpAndParkTimeStrategy.setJumpStand(s);
// }
// }
// if (!hasJump) {
// list.clear();
// }
// log.debug(String.format("生成跳停+停站时间策略[%s]个", list.size()));
// return list;
// }
//
// private RealRun isJustJumped(StrategyCalculateData data, Stand stand) {
// List<TrainPassenger> trainPassengerList = data.getTrainPassengerList();
// StationPlan plan = null;
// boolean jump = false;
// RealRun standLastRun = null;
// for (TrainPassenger trainPassenger : trainPassengerList) {
// String groupNumber = trainPassenger.getGroupNumber();
// TripPlan tripPlan = data.queryTripPlan(trainPassenger.getServiceNumber(), trainPassenger.getTripNumber());
// if (tripPlan == null) {
// log.warn(String.format("列车[%s-%s|%s]没有找到车次计划",
// groupNumber, trainPassenger.getServiceNumber(), trainPassenger.getTripNumber()));
// continue;
// }
// int index = tripPlan.getPlanIndex(stand.getSection());
// if (index < 0) { // 没有对应站台计划无需判断跳停
// continue;
// }
// List<RealRun> realRunList = data.queryRealRuns(groupNumber);
// if (!CollectionUtils.isEmpty(realRunList)) {
// realRunList.sort(Comparator.comparing(RealRun::getTime));
// RealRun last = realRunList.get(realRunList.size() - 1);
// int lastRunIndex = tripPlan.getPlanIndex(last.getSectionCode());
// if (lastRunIndex < index) { // 列车实际运行未过站台
// StationPlan stationPlan = tripPlan.getPlanList().get(index);
// if (plan == null || plan.getArriveTime().isAfter(stationPlan.getArriveTime())) {
// plan = stationPlan;
// }
// continue;
// }
// for (int i = realRunList.size() - 1; i >= 0; i--) {
// RealRun realRun = realRunList.get(i);
// if (!Objects.equals(realRun.getServiceNumber(), trainPassenger.getServiceNumber()) ||
// !Objects.equals(realRun.getTripNumber(), trainPassenger.getTripNumber())) {
// break;
// }
// if (Objects.equals(realRun.getSectionCode(), stand.getSection().getCode())) {
// if (!realRun.isArrive() && i > 0) {
// RealRun pre = realRunList.get(i - 1);
// if (pre.isArrive() &&
// Objects.equals(pre.getSectionCode(), stand.getSection().getCode())) {
// if (standLastRun == null || standLastRun.getTime().isAfter(pre.getTime())) {
// jump = false;
// standLastRun = pre;
// }
// } else {
// if (standLastRun == null || standLastRun.getTime().isAfter(realRun.getTime())) {
// jump = true;
// standLastRun = realRun;
// }
// }
// }
// }
// }
// }
// }
// if (jump) {
// return standLastRun;
// }
// return null;
// }
//
// @Override
// public void calculate(StrategyCalculateData data, JumpAndParkTimeStrategy strategy) {
// List<TrainPassenger> trainPassengerList = data.getTrainPassengerList();
// LocalDateTime systemTime = data.getSystemTime();
// LocalDateTime startTime = systemTime;
// LocalDateTime endTime = systemTime.plusMinutes(Config.STRATEGY_CAL_TIME);
// boolean jump = false;
// int i = 0;
// while (startTime.isBefore(endTime) && i < 1000) {
// ++i;
// LocalDateTime nextTime = null;
// for (TrainPassenger trainPassenger : trainPassengerList) {
// String groupNumber = trainPassenger.getGroupNumber();
// List<RealRun> realRunList = data.queryRealRuns(groupNumber);
// if (CollectionUtils.isEmpty(realRunList)) {
// TripPlan tripPlan = data.queryTripPlan(trainPassenger.getServiceNumber(), trainPassenger.getTripNumber());
// if (tripPlan == null) {
// log.warn(String.format("列车[%s-%s|%s]没有找到车次计划",
// groupNumber, trainPassenger.getServiceNumber(), trainPassenger.getTripNumber()));
// continue;
// }
// if (tripPlan.isBackup()) {
// continue;
// }
// List<StationPlan> planList = tripPlan.getPlanList();
// for (StationPlan stationPlan : planList) {
// if (stationPlan.getArriveTime().compareTo(systemTime.toLocalTime()) >= 0) {
// this.handleTrainRun(data, strategy, trainPassenger, tripPlan, stationPlan);
// break;
// }
// }
// realRunList = data.queryRealRuns(groupNumber);
// if (CollectionUtils.isEmpty(realRunList)) {
// log.error(String.format("列车[%s-%s|%s],车次[%s],时间[%s]",
// groupNumber, trainPassenger.getServiceNumber(), trainPassenger.getTripNumber(),
// tripPlan.debugStr(), systemTime.toString()));
// }
// } else {
// RealRun lastRun = realRunList.get(realRunList.size() - 1);
// TripPlan tripPlan = data.queryTripPlan(lastRun.getServiceNumber(), lastRun.getTripNumber());
// StationPlan stationPlan = tripPlan.queryStationPlanByStationCode(lastRun.getStationCode());
// BusinessExceptionAssertEnum.SYSTEM_EXCEPTION.assertNotNull(stationPlan);
// if (lastRun.isArrive()) {
// this.handleTrainRun(data, strategy, trainPassenger, tripPlan, stationPlan);
// } else {
// if (tripPlan.isLastPlan(stationPlan)) {
// TripPlan nextTripPlan = data.queryNextTripPlan(tripPlan);
// if (nextTripPlan != null) {
// StationPlan nextStationPlan = nextTripPlan.getFirstStationPlan();
// this.handleTrainRun(data, strategy, trainPassenger, nextTripPlan, nextStationPlan);
// }
// } else {
// StationPlan nextStationPlan = tripPlan.queryNextStationPlan(stationPlan.getStation());
// this.handleTrainRun(data, strategy, trainPassenger, tripPlan, nextStationPlan);
// }
// }
// }
// // 更新nextTime
// if (!CollectionUtils.isEmpty(realRunList)) {
// RealRun last = realRunList.get(realRunList.size() - 1);
// if (nextTime == null || nextTime.isAfter(last.getTime())) {
// nextTime = last.getTime();
// }
// }
// }
// systemTime = nextTime;
// }
// }
//
// private void handleTrainRun(StrategyCalculateData data,
// JumpAndParkTimeStrategy strategy,
// TrainPassenger trainPassenger,
// TripPlan tripPlan, StationPlan stationPlan) {
// Stand stand = strategy.getJumpStand();
// String groupNumber = trainPassenger.getGroupNumber();
// List<RealRun> realRunList = data.queryRealRuns(groupNumber);
// RealRun lastRun = null;
// int offset = 0;
// if (!CollectionUtils.isEmpty(realRunList)) {
// // 获取上一个实际运行并计算时间偏移
// lastRun = realRunList.get(realRunList.size() - 1);
// TripPlan lastTripPlan = data.queryTripPlan(lastRun.getServiceNumber(), lastRun.getTripNumber());
// StationPlan lastStationPlan = lastTripPlan.queryStationPlanByStationCode(lastRun.getStationCode());
// if (lastRun.isArrive()) {
// offset = lastRun.getTime().toLocalTime().toSecondOfDay() - lastStationPlan.getArriveTime().toSecondOfDay();
// } else {
// offset = lastRun.getTime().toLocalTime().toSecondOfDay() - lastStationPlan.getLeaveTime().toSecondOfDay();
// }
// }
// if (Objects.equals(stand.getSection(), stationPlan.getSection()) && !strategy.isJumped()) { // 跳停站台计划
// // 跳停策略指定的跳停站台构建跳停运行并更新策略
// RealRun passing = this.buildRealRun(groupNumber, tripPlan, stationPlan, false,
// stationPlan.getArriveTime(), offset, data.getSystemTime());
// data.addRealRun(passing);
// strategy.jumpedByTrain(groupNumber, tripPlan);
// strategy.addOffset(-Config.TRAIN_PASS_SAVE_TIME);
// StandPassenger standPassenger = data.getStandPassengerByStand(stand);
// strategy.addEffectTrain(groupNumber);
// strategy.addExtraNum(standPassenger.getWait());
// return;
// }
// // 非跳停根据计划更新预测运行
// if (lastRun == null ||
// !Objects.equals(stationPlan.getStation().getCode(), lastRun.getStationCode())) {
// RealRun arrive = this.buildRealRun(groupNumber, tripPlan, stationPlan, true,
// stationPlan.getArriveTime(), offset, data.getSystemTime());
// data.addRealRun(arrive);
// }
// int parkTime = stationPlan.getParkTime();
// // 列车到站乘客上车更新列车上人数
// if (stationPlan.getSection().getStandList().size() == 0) {
// return;
// }
// Stand parkStand = strategy.getParkStand();
// LocalTime arriveTime = stationPlan.getArriveTime();
// LocalTime leaveTime = stationPlan.getLeaveTime();
// // 列车到站乘客上车更新列车上人数
// StandPassenger standPassenger = data.getStandPassengerByStand(stationPlan.getSection().getStandList().get(0));
// int wait = standPassenger.getWait(); // 站台等待乘客数
// int normal = (parkTime - Config.INVALID_BOARD_TIME) * Config.PASSENGER_BOARD_SPEED; // 根据停站预测的可上车人数
// int remain = Config.TRAIN_CAPACITY - trainPassenger.getNum(); // 列车上剩余可载人数
// // 大客流站计算指标
// if (Objects.equals(stationPlan.getSection(), parkStand.getSection())) {
// // 时刻表偏差
// parkTime = strategy.getTime();
// leaveTime = arriveTime.plusSeconds(parkTime);
//// strategy.addTarget1(parkTime - stationPlan.getParkTime());
//// // 乘客等待时间(按人数统计不考虑时间)
//// strategy.addTarget2(standPassenger.getWait());
// //
// strategy.addEffectTrain(groupNumber);
// int extraTime = strategy.getTime() - stationPlan.getParkTime();
// strategy.addOffset(extraTime);
// int extraNum = extraTime * Config.PASSENGER_BOARD_SPEED;
// int extra = extraNum;
// if (normal + extraNum > remain) {
// if (normal < remain) {
// extra = remain - normal;
// } else {
// extra = 0;
// }
// }
// strategy.addExtraNum(extra);
// normal += extraNum;
// }
// float min = Math.min(Math.min(wait, normal), remain); // 实际上车人数
// standPassenger.minus(min);
// trainPassenger.plus(min);
//// // 大客流站计算指标
//// if (data.isLpfStand(stationPlan.getSection())) {
//// // 乘客等待时间(按人数统计不考虑时间)
//// strategy.addTarget2(standPassenger.getWait());
//// }
// // 生成预测实际运行图
// RealRun leave = this.buildRealRun(trainPassenger.getGroupNumber(), tripPlan, stationPlan, false,
// leaveTime, offset, data.getSystemTime());
// data.addRealRun(leave);
// }
//
// @Override
// public String getName() {
// return "跳停策略服务";
// }
//
//}

View File

@ -345,10 +345,15 @@ public class SimulationRobotService {
|| Objects.equals(vrSignal.getAspect(), signal.getGuideAspect())) { //引导信号 || Objects.equals(vrSignal.getAspect(), signal.getGuideAspect())) { //引导信号
if (!Objects.equals(signal, throughSignal) || !Objects.equals(vrSignal.getAspect(), if (!Objects.equals(signal, throughSignal) || !Objects.equals(vrSignal.getAspect(),
throughAspect)) { throughAspect)) {
SectionPosition noPassPosition = CalculateService.calculateNextPositionByStartAndLen( SectionPosition tempPosition;
signalPosition, !right, 2, true); if (section.isFunctionTrack()) { //解决福州一列车从车辆段开出来时在转换轨停车位置有误导致无法发车的问题
if (targetPosition == null || noPassPosition.isAheadOf(targetPosition, right)) { tempPosition = new SectionPosition(section, section.getStopPointByDirection(right));
targetPosition = noPassPosition; } else {
tempPosition = CalculateService.calculateNextPositionByStartAndLen(
signalPosition, !right, 2, true);
}
if (targetPosition == null || tempPosition.isAheadOf(targetPosition, right)) {
targetPosition = tempPosition;
} }
} }
} }

View File

@ -222,7 +222,7 @@ public class MetroSimulationWorkServiceImpl implements SimulationWorkService {
faultGenerator.addJobs(simulation); faultGenerator.addJobs(simulation);
atsMessageCollectAndDispatcher.addJobs(simulation); atsMessageCollectAndDispatcher.addJobs(simulation);
nccAlarmService.addJobs(simulation); nccAlarmService.addJobs(simulation);
trainMessageDiagram.addJobs(simulation); // trainMessageDiagram.addJobs(simulation); 逻辑报错暂时注掉
} }
@Override @Override

View File

@ -7,18 +7,17 @@ import club.joylink.rtss.vo.client.org.OrgVO;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import javax.validation.constraints.NotBlank;
import java.io.Serializable; import java.io.Serializable;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import javax.validation.constraints.NotBlank;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/** /**
* 账户对象 * 账户对象
@ -28,307 +27,316 @@ import java.util.List;
@Setter @Setter
@EqualsAndHashCode @EqualsAndHashCode
public class AccountVO implements Serializable { public class AccountVO implements Serializable {
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
/** @JsonSerialize(using = ToStringSerializer.class)
* 登录账户名线下登录账户名 private Long id;
*/
private String account;
/**
* 父账户
*/
private String parentAccount;
/**
* 账户类型
*/
private String type;
public static final String Type_1 = "1"; // 个人账户
public static final String Type_2 = "2"; // 第三方企业账户
public static final String Type_3 = "3"; // 第三方企业子账户
/** /**
* 账号所属的组织是账号表里的字段 * 登录账户名线下登录账户名
*/ */
private Long orgId; private String account;
/**
* 父账户
*/
private String parentAccount;
/**
* 账户类型
*/
private String type;
public static final String Type_1 = "1"; // 个人账户
public static final String Type_2 = "2"; // 第三方企业账户
public static final String Type_3 = "3"; // 第三方企业子账户
/** /**
* 真实姓名 * 账号所属的组织是账号表里的字段
*/ */
@NotBlank(message = "姓名不能为空") private Long orgId;
private String name;
/** /**
* 昵称 * 真实姓名
*/ */
@NotBlank(message = "昵称不能为空") @NotBlank(message = "姓名不能为空")
private String nickname; private String name;
/** /**
* 头像资源地址 * 昵称
*/ */
private String avatarPath; @NotBlank(message = "昵称不能为空")
private String nickname;
/** /**
* 手机号 * 头像资源地址
*/ */
@NotBlank(message = "手机号码不能为空") private String avatarPath;
private String mobile;
/** /**
* 国家码 * 手机号
*/ */
private String nationcode; @NotBlank(message = "手机号码不能为空")
private String mobile;
private String password; /**
* 国家码
*/
private String nationcode;
/** private String password;
* 微信openId
*/
@NotBlank(message = "微信OPENID不能为空")
private String wxId;
/** /**
* 微信unionId * 微信openId
*/ */
private String wxUnionId; @NotBlank(message = "微信OPENID不能为空")
private String wxId;
/** /**
* 微信小程序openId * 微信unionId
*/ */
private String wmOpenId; private String wxUnionId;
/** /**
* 数据库的roles字段 * 微信小程序openId
*/ */
@JsonIgnore private String wmOpenId;
private String dbRoles;
/** /**
* 角色 * 数据库的roles字段
*/ */
private List<String> roles; @JsonIgnore
private String dbRoles;
/** /**
* 账号来源最初的目的是给cgy做注册人数变化曲线 * 角色
*/ */
private String source; private List<String> roles;
/** /**
* email邮箱 * 账号来源最初的目的是给cgy做注册人数变化曲线
*/ */
private String email; private String source;
/** /**
* 状态1-可用 * email邮箱
*/ */
private String status; private String email;
/** /**
* 创建时间 * 状态1-可用
*/ */
private LocalDateTime createTime; private String status;
//单位信息 /**
private Long companyId; * 创建时间
*/
private LocalDateTime createTime;
private String companyName; /**
private Boolean companyAdmin; * 更新时间
/** */
* 用户所属组织关联的项目 private LocalDateTime updateTime;
*/
private List<String> projectCodes; //单位信息
private Long companyId;
private String companyName;
private Boolean companyAdmin;
/**
* 用户所属组织关联的项目
*/
private List<String> projectCodes;
public AccountVO() { public AccountVO() {
}
public AccountVO(SysAccount account) {
this.id = account.getId();
this.account = account.getAccount();
this.parentAccount = account.getParentAccount();
this.type = account.getType();
this.orgId = account.getOrgId();
this.name = account.getName();
this.nickname = account.getNickname();
this.avatarPath = account.getAvatarPath();
this.mobile = account.getMobile();
this.nationcode = account.getNationcode();
this.password = account.getPassword();
this.wxId = account.getWxId();
this.wxUnionId = account.getWxUnionId();
this.wmOpenId = account.getWmOpenId();
this.setRolesByString(account.getRoles());
this.source = account.getSource();
this.email = account.getEmail();
this.status = account.getStatus();
this.createTime = account.getCreateTime();
this.updateTime = account.getUpdateTime();
}
public static AccountVO system() {
AccountVO accountVO = new AccountVO();
accountVO.setId(0L);
accountVO.setName("系统");
return accountVO;
}
public static SysAccount fromVO(AccountVO accountVo) {
SysAccount account = new SysAccount();
account.setId(accountVo.getId());
account.setName(accountVo.getName());
account.setNickname(accountVo.getNickname());
account.setNationcode(accountVo.getNationcode());
account.setMobile(accountVo.getMobile());
account.setWxId(accountVo.getWxId());
account.setWxUnionId(accountVo.getWxUnionId());
account.setRoles(accountVo.getRolesStr());
account.setEmail(accountVo.getEmail());
account.setStatus(accountVo.getStatus());
account.setCreateTime(accountVo.getCreateTime());
return account;
}
@JsonIgnore
public String getIdStr() {
return String.valueOf(this.id);
}
@JsonIgnore
public String getRolesStr() {
if (!CollectionUtils.isEmpty(this.roles)) {
return String.join(",", this.roles.toArray(new String[]{}));
} }
return null;
}
public AccountVO(SysAccount account) { public void setRolesByString(String roles) {
this.id = account.getId(); if (StringUtils.hasText(roles)) {
this.account = account.getAccount(); String[] splits = roles.split(",");
this.parentAccount = account.getParentAccount(); this.roles = new ArrayList<>();
this.type = account.getType(); Collections.addAll(this.roles, splits);
this.orgId = account.getOrgId();
this.name = account.getName();
this.nickname = account.getNickname();
this.avatarPath = account.getAvatarPath();
this.mobile = account.getMobile();
this.nationcode = account.getNationcode();
this.password = account.getPassword();
this.wxId = account.getWxId();
this.wxUnionId = account.getWxUnionId();
this.wmOpenId = account.getWmOpenId();
this.setRolesByString(account.getRoles());
this.source = account.getSource();
this.email = account.getEmail();
this.status = account.getStatus();
this.createTime = account.getCreateTime();
} }
}
public static AccountVO system() { public void setRolesByString() {
if (StringUtils.hasText(dbRoles)) {
String[] splits = dbRoles.split(",");
this.roles = new ArrayList<>();
Collections.addAll(this.roles, splits);
}
}
@Override
public String toString() {
return "UserVO [id=" + id + ", name=" + name + ", nickname=" + nickname + ", mobile=" + mobile
+ ", email=" + email + ", nationcode="
+ nationcode + ", wxId=" + wxId + "]";
}
public static List<AccountVO> convertFromDB(List<SysAccount> list) {
List<AccountVO> voList = new ArrayList<>();
if (!CollectionUtils.isEmpty(list)) {
list.forEach(account -> voList.add(new AccountVO(account)));
}
return voList;
}
public static List<AccountVO> convert2BaseInfoVO(List<SysAccount> list) {
List<AccountVO> voList = new ArrayList<>();
if (!CollectionUtils.isEmpty(list)) {
list.forEach(account -> {
AccountVO accountVO = new AccountVO(); AccountVO accountVO = new AccountVO();
accountVO.setId(0L); accountVO.setId(account.getId());
accountVO.setName("系统"); accountVO.setName(account.getName());
return accountVO; accountVO.setNickname(account.getNickname());
accountVO.setMobile(account.getMobile());
voList.add(accountVO);
});
} }
return voList;
}
public static SysAccount fromVO(AccountVO accountVo) { public static List<SysAccount> convert2UnionIdInfoVOs(List<AccountVO> voList) {
SysAccount account = new SysAccount(); List<SysAccount> list = new ArrayList<>();
account.setId(accountVo.getId()); if (!CollectionUtils.isEmpty(voList)) {
account.setName(accountVo.getName()); voList.forEach(userVO -> {
account.setNickname(accountVo.getNickname()); if (StringUtils.hasText(userVO.getWxUnionId())) {
account.setNationcode(accountVo.getNationcode()); SysAccount account = new SysAccount();
account.setMobile(accountVo.getMobile()); account.setId(userVO.getId());
account.setWxId(accountVo.getWxId()); account.setWxUnionId(userVO.getWxUnionId());
account.setWxUnionId(accountVo.getWxUnionId()); list.add(account);
account.setRoles(accountVo.getRolesStr());
account.setEmail(accountVo.getEmail());
account.setStatus(accountVo.getStatus());
account.setCreateTime(accountVo.getCreateTime());
return account;
}
@JsonIgnore
public String getIdStr() {
return String.valueOf(this.id);
}
@JsonIgnore
public String getRolesStr() {
if (!CollectionUtils.isEmpty(this.roles)) {
return String.join(",", this.roles.toArray(new String[]{}));
} }
return null; });
} }
return list;
}
public void setRolesByString(String roles) { /**
if (StringUtils.hasText(roles)) { * 是否管理员
String[] splits = roles.split(","); *
this.roles = new ArrayList<>(); * @return
Collections.addAll(this.roles, splits); */
} @JsonIgnore
} public boolean isAdmin() {
return !CollectionUtils.isEmpty(this.roles)
&& (this.roles.contains(BusinessConsts.ROLE_04) || this.roles.contains(
BusinessConsts.ROLE_05));
}
public void setRolesByString() { /**
if (StringUtils.hasText(dbRoles)) { * 是否超级管理员
String[] splits = dbRoles.split(","); *
this.roles = new ArrayList<>(); * @return
Collections.addAll(this.roles, splits); */
} @JsonIgnore
} public boolean isSuperAdmin() {
return !CollectionUtils.isEmpty(this.roles)
&& (this.roles.contains(BusinessConsts.ROLE_05));
}
@Override public void filter4Client() {
public String toString() { this.password = null;
return "UserVO [id=" + id + ", name=" + name + ", nickname=" + nickname + ", mobile=" + mobile + ", email=" + email + ", nationcode=" this.wxUnionId = null;
+ nationcode + ", wxId=" + wxId + "]"; this.wxId = null;
} this.wmOpenId = null;
this.createTime = null;
}
public static List<AccountVO> convertFromDB(List<SysAccount> list) { public void forClient() {
List<AccountVO> voList = new ArrayList<>(); if (StringUtils.hasText(dbRoles)) {
if (!CollectionUtils.isEmpty(list)) { this.roles = List.of(dbRoles.split(","));
list.forEach(account -> voList.add(new AccountVO(account)));
}
return voList;
} }
}
public static List<AccountVO> convert2BaseInfoVO(List<SysAccount> list) { public void setOrgInfo(Org org, Boolean companyAdmin, List<String> projectCodes) {
List<AccountVO> voList = new ArrayList<>(); this.companyId = org.getId();
if (!CollectionUtils.isEmpty(list)) { this.companyName = org.getName();
list.forEach(account -> { this.companyAdmin = companyAdmin;
AccountVO accountVO = new AccountVO(); this.projectCodes = projectCodes;
accountVO.setId(account.getId()); }
accountVO.setName(account.getName());
accountVO.setNickname(account.getNickname());
accountVO.setMobile(account.getMobile());
voList.add(accountVO);
});
}
return voList;
}
public static List<SysAccount> convert2UnionIdInfoVOs(List<AccountVO> voList) { public void copyOrgInfo(AccountVO accountVO) {
List<SysAccount> list = new ArrayList<>(); if (accountVO != null) {
if (!CollectionUtils.isEmpty(voList)) { this.companyId = accountVO.getCompanyId();
voList.forEach(userVO -> { this.companyName = accountVO.getCompanyName();
if (StringUtils.hasText(userVO.getWxUnionId())) { this.companyAdmin = accountVO.getCompanyAdmin();
SysAccount account = new SysAccount(); this.projectCodes = accountVO.getProjectCodes();
account.setId(userVO.getId());
account.setWxUnionId(userVO.getWxUnionId());
list.add(account);
}
});
}
return list;
} }
}
/** @JsonIgnore
* 是否管理员 public boolean isThirdChildAccount() {
* return Type_3.equalsIgnoreCase(this.type) && StringUtils.hasText(this.parentAccount);
* @return }
*/
@JsonIgnore
public boolean isAdmin() {
return !CollectionUtils.isEmpty(this.roles)
&& (this.roles.contains(BusinessConsts.ROLE_04) || this.roles.contains(BusinessConsts.ROLE_05));
}
/** public void setOrgProjectVO(OrgVO orgVO, boolean orgAdmin) {
* 是否超级管理员 if (orgVO != null) {
* this.companyId = orgVO.getId();
* @return this.companyName = orgVO.getName();
*/ this.companyAdmin = orgAdmin;
@JsonIgnore this.projectCodes = orgVO.getProjectCodes();
public boolean isSuperAdmin() { } else {
return !CollectionUtils.isEmpty(this.roles) this.companyId = null;
&& (this.roles.contains(BusinessConsts.ROLE_05)); this.companyName = null;
} this.companyAdmin = false;
this.projectCodes = List.of();
public void filter4Client() {
this.password = null;
this.wxUnionId = null;
this.wxId = null;
this.wmOpenId = null;
this.createTime = null;
}
public void forClient() {
if (StringUtils.hasText(dbRoles)) {
this.roles = List.of(dbRoles.split(","));
}
}
public void setOrgInfo(Org org, Boolean companyAdmin, List<String> projectCodes) {
this.companyId = org.getId();
this.companyName = org.getName();
this.companyAdmin = companyAdmin;
this.projectCodes = projectCodes;
}
public void copyOrgInfo(AccountVO accountVO) {
if (accountVO != null) {
this.companyId = accountVO.getCompanyId();
this.companyName = accountVO.getCompanyName();
this.companyAdmin = accountVO.getCompanyAdmin();
this.projectCodes = accountVO.getProjectCodes();
}
}
@JsonIgnore
public boolean isThirdChildAccount() {
return Type_3.equalsIgnoreCase(this.type) && StringUtils.hasText(this.parentAccount);
}
public void setOrgProjectVO(OrgVO orgVO, boolean orgAdmin) {
if (orgVO != null) {
this.companyId = orgVO.getId();
this.companyName = orgVO.getName();
this.companyAdmin = orgAdmin;
this.projectCodes = orgVO.getProjectCodes();
} else {
this.companyId = null;
this.companyName = null;
this.companyAdmin = false;
this.projectCodes = List.of();
}
} }
}
} }

View File

@ -0,0 +1,23 @@
package club.joylink.rtss.vo.client.cgy;
import javax.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class CgyThirdPartyLoginInfoVO {
@NotEmpty(message = "appId不能为空")
private String appId;
private String sessionId;
private Long timeStamp;
@NotEmpty(message = "账号不能为空")
private String account;
@NotEmpty(message = "用户名不能为空")
private String name;
private String parentAccount;
}

View File

@ -4,6 +4,7 @@ import club.joylink.rtss.constants.ProjectCode;
import club.joylink.rtss.constants.ProjectDeviceType; import club.joylink.rtss.constants.ProjectDeviceType;
import club.joylink.rtss.entity.ProjectDevice; import club.joylink.rtss.entity.ProjectDevice;
import club.joylink.rtss.exception.BusinessExceptionAssertEnum; import club.joylink.rtss.exception.BusinessExceptionAssertEnum;
import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.cgy.CgyPslConfig;
import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.cgy.CgySectionConfig; import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.cgy.CgySectionConfig;
import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.cgy.CgySignalConfig; import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.cgy.CgySignalConfig;
import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.cgy.CgySwitchConfig; import club.joylink.rtss.simulation.cbtc.device.real.modbustcp.cgy.CgySwitchConfig;
@ -175,6 +176,9 @@ public class ProjectDeviceVO {
case SECTION: case SECTION:
list.add(new CgySectionConfig(deviceVO)); list.add(new CgySectionConfig(deviceVO));
break; break;
case PSL:
list.add(new CgyPslConfig(deviceVO));
break;
} }
} }
return list; return list;

View File

@ -0,0 +1,71 @@
package club.joylink.rtss.vo.client.project.cgy;
import club.joylink.rtss.vo.client.project.RealConfigVO;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class CgyPslConfigVO extends RealConfigVO {
private String pslCode;
/**
* 开门按钮
*/
private Integer r_km_btn = 32;
/**
* 关门按钮
*/
private Integer r_gm_btn = 33;
/**
* 就地允许/禁止按钮
*/
private Integer r_yxjz_btn = 34;
/**
* 互锁解除钥匙true-互锁解除
*/
private Integer r_hsjc_key = 46;
/**
* 消音按钮不知道消的啥音
*/
private Integer r_xy_btn = 47;
/**
* 控制-开门指示灯
*/
private Integer w_km_light = 48;
/**
* 控制-关门指示灯
*/
private Integer w_gm_light = 49;
/**
* 控制-psl允许操作指示灯
*/
private Integer w_yxcz_light = 50;
/**
* 控制-关闭锁紧指示灯
*/
private Integer w_gbsj_light = 55;
public CgyPslConfigVO(String pslCode) {
this();
this.pslCode = pslCode;
}
public CgyPslConfigVO() {
super(0, 64);
}
@Override
public String findDeviceCode() {
return pslCode;
}
}

View File

@ -11,10 +11,16 @@ public class CgySectionConfigVO extends RealConfigVO {
/** /**
* 出清 * 出清
*/ */
private Integer r_occupied = 6; private Integer r_occupied;
public CgySectionConfigVO(String sectionCode, Integer r_occupied) {
this();
this.sectionCode = sectionCode;
this.r_occupied = r_occupied;
}
public CgySectionConfigVO() { public CgySectionConfigVO() {
super(0, 32); super(0, 64);
} }
@Override @Override

View File

@ -1,46 +1,62 @@
package club.joylink.rtss.vo.client.project.cgy; package club.joylink.rtss.vo.client.project.cgy;
import club.joylink.rtss.vo.client.project.RealConfigVO; import club.joylink.rtss.vo.client.project.RealConfigVO;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
/**
* 红灯常亮DDJ吸起红灯灭 Lxj吸起黄灯 YxJ红黄 LXJZXJ吸起绿灯
*/
@Getter @Getter
@Setter @Setter
public class CgySignalConfigVO extends RealConfigVO { public class CgySignalConfigVO extends RealConfigVO {
private String signalCode; private String signalCode;
/** private Integer r_ddj;
*
*/ private Integer r_lxj;
private Integer r_red;
/** /**
* 绿 * 主灯丝报警
*/ */
private Integer r_green; private Integer r_dj;
private Integer r_zxj;
private Integer r_yxj;
/** /**
* * 副灯丝报警
*/ */
private Integer r_yellow; private Integer r_dj2;
private Integer w_red; private Integer w_ddj;
private Integer w_green; private Integer w_lxj;
private Integer w_yellow; private Integer w_zxj;
public CgySignalConfigVO(String signalCode, Integer r_red, private Integer w_yxj;
Integer r_green, Integer r_yellow, Integer w_red, Integer w_green, Integer w_yellow) {
super(0, 24); public CgySignalConfigVO(String signalCode, Integer r_ddj,
Integer r_lxj, Integer r_dj, Integer r_zxj, Integer r_yxj, Integer r_dj2, Integer w_ddj,
Integer w_lxj, Integer w_zxj, Integer w_yxj) {
this();
this.signalCode = signalCode; this.signalCode = signalCode;
this.r_red = r_red; this.r_ddj = r_ddj;
this.r_green = r_green; this.r_lxj = r_lxj;
this.r_yellow = r_yellow; this.r_dj = r_dj;
this.w_red = w_red; this.r_zxj = r_zxj;
this.w_green = w_green; this.r_yxj = r_yxj;
this.w_yellow = w_yellow; this.r_dj2 = r_dj2;
this.w_ddj = w_ddj;
this.w_lxj = w_lxj;
this.w_zxj = w_zxj;
this.w_yxj = w_yxj;
} }
public CgySignalConfigVO() { public CgySignalConfigVO() {

View File

@ -10,30 +10,39 @@ public class CgySwitchConfigVO extends RealConfigVO {
private String switchCode; private String switchCode;
/**
* 解锁表示
*/
private Integer r_js = 12;
/** /**
* 定表 * 定表
*/ */
private Integer r_db = 0; private Integer r_db = 13;
/** /**
* 反表 * 反表
*/ */
private Integer r_fb = 1; private Integer r_fb = 14;
/** /**
* *
*/ */
private Integer w_sj = 8; private Integer w_js = 24;
/** /**
* 定操 * 定操
*/ */
private Integer w_dc = 9; private Integer w_dc = 25;
/** /**
* 反操 * 反操
*/ */
private Integer w_fc = 10; private Integer w_fc = 26;
public CgySwitchConfigVO(String switchCode) {
this();
this.switchCode = switchCode;
}
public CgySwitchConfigVO() { public CgySwitchConfigVO() {
super(0, 32); super(0, 32);

View File

@ -0,0 +1,16 @@
package club.joylink.rtss.vo.client.simulationUsage;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class SimulationUsageRecordQueryVO {
private Long uid;
private Long functionId;
}

View File

@ -9,9 +9,12 @@ import lombok.Setter;
@Setter @Setter
@NoArgsConstructor @NoArgsConstructor
public class SimulationInfoQueryVO extends PageQueryVO { public class SimulationInfoQueryVO extends PageQueryVO {
private String project;
private String group; private String project;
private String userName; private String group;
private String userName;
private Long functionId;
} }

View File

@ -1,140 +1,145 @@
package club.joylink.rtss.vo.map; package club.joylink.rtss.vo.map;
import lombok.Getter;
import lombok.Setter;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import lombok.Getter;
import lombok.Setter;
@Getter @Getter
@Setter @Setter
public class MapCiGenerateConfig { public class MapCiGenerateConfig {
//--------------------联锁数据生成配置start------------------- //--------------------联锁数据生成配置start-------------------
/** /**
*是否类似哈尔滨一号线联锁分为ATP信号地面信号引导信号 * 是否类似哈尔滨一号线联锁分为ATP信号地面信号引导信号
*/ */
private boolean likeHa1; private boolean likeHa1;
/** /**
*是否生成侧防true-生成侧防不要联动道岔false-不生成侧防用联动道岔 * 是否生成侧防true-生成侧防不要联动道岔false-不生成侧防用联动道岔
*/ */
private boolean generateFls; private boolean generateFls;
/** /**
*信号机接近区段只取最近的一个 * 信号机接近区段只取最近的一个
*/ */
private boolean signalApproachOnlyOne; private boolean signalApproachOnlyOne;
/** /**
*信号机接近区段仅考虑定位道岔 * 信号机接近区段仅考虑定位道岔
*/ */
private boolean signalApproachOnlyNpSwitch; private boolean signalApproachOnlyNpSwitch;
/** /**
*信号机接近区段不跨过前方同向信号机 * 信号机接近区段不跨过前方同向信号机
*/ */
private boolean signalApproachNotPassPreSignal = true; private boolean signalApproachNotPassPreSignal = true;
/** /**
*进路名称使用终端信号机同区段反向信号机名称命名true-使用反向如果存在的话false-使用终端信号机命名 * 进路名称使用终端信号机同区段反向信号机名称命名true-使用反向如果存在的话false-使用终端信号机命名
*/ */
private boolean routeNameUseEndOppositeSignalName; private boolean routeNameUseEndOppositeSignalName;
/** /**
*是否生成折返进路 * 是否生成折返进路
*/ */
private boolean generateTbRoute; private boolean generateTbRoute;
/** /**
*折返进路名称使用终端信号机反向信号机名称 * 折返进路名称使用终端信号机反向信号机名称并且终端按钮亦使用反向信号机-成都三联锁
*/ */
private boolean tbRouteNameUseEndOppositeSignalName; private boolean tbRouteNameUseEndOppositeSignalName;
/** /**
*进路始端防护信号机是否总是绿灯true-总是开绿灯false-根据进路中有无反位道岔生成绿灯或黄灯 * 进路始端防护信号机是否总是绿灯true-总是开绿灯false-根据进路中有无反位道岔生成绿灯或黄灯
*/ */
private boolean routeSignalAlwaysGreen; private boolean routeSignalAlwaysGreen;
/** /**
*多个延续保护路径生成多条进路:true-生成多条进路false-生成一条进路 * 多个延续保护路径生成多条进路:true-生成多条进路false-生成一条进路
*/ */
private boolean routeApartByOverlap; private boolean routeApartByOverlap;
/** /**
*延续保护是否只构建道岔 * 延续保护是否只构建道岔
*/ */
private boolean overlapOnlySwitch; private boolean overlapOnlySwitch;
// //
// @ApiModelProperty(value = "延续保护构建是否只考虑一个道岔计轴") // @ApiModelProperty(value = "延续保护构建是否只考虑一个道岔计轴")
// private boolean overlapOnlyOneSwitch; // private boolean overlapOnlyOneSwitch;
/** /**
* 延续保护最小长度 * 延续保护最小长度
*/ */
private float overlapMinLen = 55; private float overlapMinLen = 55;
/** /**
*延续保护道岔是否只构建定位道岔 * 延续保护道岔是否只构建定位道岔
*/ */
private boolean overlapSwitchNpOnly; private boolean overlapSwitchNpOnly;
/** /**
*延续保护道岔在防护信号机与所属区段方向相反时只构建定位道岔 * 延续保护道岔在防护信号机与所属区段方向相反时只构建定位道岔
*/ */
private boolean overlapSignalOppositeSwitchNpOnly; private boolean overlapSignalOppositeSwitchNpOnly;
/** /**
*延续保护的建立方式true-通过触发建立false-随进路建立 * 延续保护的建立方式true-通过触发建立false-随进路建立
*/ */
private boolean overlapSettingByTrigger; private boolean overlapSettingByTrigger;
/** /**
*默认延续保护解锁时间 * 默认延续保护解锁时间
*/ */
private int overlapReleaseTime = 60; private int overlapReleaseTime = 60;
/** /**
*默认进路解锁时间 * 默认进路解锁时间
*/ */
private int routeReleaseTime = 45; private int routeReleaseTime = 45;
/** /**
*是否生成自动折返 * 是否生成自动折返
*/ */
private boolean generateCycle; private boolean generateCycle;
/** /**
*是否生成进路信号按钮 * 是否生成进路信号按钮
*/ */
private boolean routeButton; private boolean routeButton;
/** /**
*若生成进路信号按钮进路信号按钮是否取最近的一个信号机 * 若生成进路信号按钮进路信号按钮是否取最近的一个信号机
*/ */
private boolean getNearlySignal; private boolean getNearlySignal;
/** /**
*是否生成目的地码定义泰雷兹式 * 是否生成目的地码定义泰雷兹式
*/ */
private boolean generateDestination; private boolean generateDestination;
/** 上下行站台共享紧急关闭效果的车站 */ /**
private Set<String> sharingECStations = new HashSet<>(); * 上下行站台共享紧急关闭效果的车站
*/
private Set<String> sharingECStations = new HashSet<>();
/** 进路联锁不包含站台扣车 */ /**
private boolean routeInterlockDoNotIncludeStandHoldTrain; * 进路联锁不包含站台扣车
*/
private boolean routeInterlockDoNotIncludeStandHoldTrain;
// @ApiModelProperty(value = "是否分开生成ATP联锁和地面信号联锁") // @ApiModelProperty(value = "是否分开生成ATP联锁和地面信号联锁")
// private boolean apartGroundAndAtp; // private boolean apartGroundAndAtp;
/** 是否处理停车场/车辆段逻辑 */ /**
private boolean handleDepot; * 是否处理停车场/车辆段逻辑
*/
private boolean handleDepot;
/** /**
* 是大铁线路 * 是大铁线路
*/ */
private boolean railway; private boolean railway;
//--------------------联锁数据生成配置end------------------- //--------------------联锁数据生成配置end-------------------
} }

View File

@ -10,251 +10,275 @@ import lombok.Setter;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
*地图线路公共配置项 * 地图线路公共配置项
*/ */
@Getter @Getter
@Setter @Setter
@NoArgsConstructor @NoArgsConstructor
public class RealLineConfigVO { public class RealLineConfigVO {
/** /**
*上行是否右方向 * 上行是否右方向
*/ */
private Boolean upRight = true; private Boolean upRight = true;
/** /**
*进路办理是否先锁闭开始办理直接先锁闭区段如福州一号线 * 进路办理是否先锁闭开始办理直接先锁闭区段如福州一号线
*/ */
private Boolean lockFirst = false; private Boolean lockFirst = false;
/** /**
* 信号封锁下进路是否可以办理 * 信号封锁下进路是否可以办理
*/ */
private boolean signalBlockRouteSettable = false; private boolean signalBlockRouteSettable = false;
/** /**
* 进路办理不失败 * 进路办理不失败
*/ */
private boolean routeSettingNoFail = false; private boolean routeSettingNoFail = false;
/** /**
*是否列车停站开门后才办理出站进路开放出站信号机 * 是否列车停站开门后才办理出站进路开放出站信号机
*/ */
private boolean signalOpenAfterParking = false; private boolean signalOpenAfterParking = false;
/** /**
*站台扣车是否关闭逻辑点灯的信号机 * 站台扣车是否关闭逻辑点灯的信号机
*/ */
private boolean standHoldCloseLogicLight = false; private boolean standHoldCloseLogicLight = false;
/** /**
*ATS是否自动处理人工设置的站前折返自动更新车次 * ATS是否自动处理人工设置的站前折返自动更新车次
*/ */
private boolean atsAutoHandleManualFrontTurnBack = false; private boolean atsAutoHandleManualFrontTurnBack = false;
/** /**
*CTC列车进路延续保护仅折返站处锁闭 * CTC列车进路延续保护仅折返站处锁闭
*/ */
private boolean ctcOverlapOnlyTurnBackStationLock = false; private boolean ctcOverlapOnlyTurnBackStationLock = false;
/** /**
*引导办理是否需要先排列进路 * 引导办理是否需要先排列进路
*/ */
private boolean guideNeedRouteSettingFirst = true; private boolean guideNeedRouteSettingFirst = true;
/** /**
*道岔区段状态改变按单个道岔处理 * 道岔区段状态改变按单个道岔处理
*/ */
private Boolean switchSingleHandle = true; private Boolean switchSingleHandle = true;
/** /**
*道岔正/反操是否联动 * 道岔正/反操是否联动
*/ */
private Boolean switchNRTurnChain = false; private Boolean switchNRTurnChain = false;
/** /**
*道岔单解/锁是否联动 * 道岔单解/锁是否联动
*/ */
private Boolean switchSingleLockChain = false; private Boolean switchSingleLockChain = false;
/** /**
*道岔故障失表是否联动 * 道岔故障失表是否联动
*/ */
private Boolean switchLossChain = false; private Boolean switchLossChain = false;
/** /**
*是否强制取消进路/在接近区段占用时是否依旧强制执行取消进路 * 是否强制取消进路/在接近区段占用时是否依旧强制执行取消进路
*/ */
private MapConfig.ApproachLockCancel singleApproachLockCancelRoute = MapConfig.ApproachLockCancel.NOT; private MapConfig.ApproachLockCancel singleApproachLockCancelRoute = MapConfig.ApproachLockCancel.NOT;
/** /**
*列车控制模式/级别 * 列车控制模式/级别
*/ */
private String runMode = RunLevel.CBTC.name(); private String runMode = RunLevel.CBTC.name();
/** /**
*不停站头码车服务号列表 * 不停站头码车服务号列表
*/ */
private String noParkingSM=""; private String noParkingSM = "";
/** /**
*停站头码车服务号列表 * 停站头码车服务号列表
*/ */
private String parkingSM=""; private String parkingSM = "";
/** /**
*RM模式下ATP防护速度单位km/h * RM模式下ATP防护速度单位km/h
*/ */
private float rmAtpSpeed = 25f; private float rmAtpSpeed = 25f;
/** /**
*URM模式下ATP防护速度单位km/h * URM模式下ATP防护速度单位km/h
*/ */
private float urmAtpSpeed = 45f; private float urmAtpSpeed = 45f;
/** /**
* 初始加载设备时是否默认单锁正线道岔 * 初始加载设备时是否默认单锁正线道岔
*/ */
private boolean initSingleLockSwitch = false; private boolean initSingleLockSwitch = false;
/** /**
* 当取消进路/人解进路时将该进路始端信号机下所有进路设为自排关 * 当取消进路/人解进路时将该进路始端信号机下所有进路设为自排关
*/ */
private boolean cancelAtsControlOfAllRoutesWhenCancelRoute; private boolean cancelAtsControlOfAllRoutesWhenCancelRoute;
/** /**
* 在设置自排开或自动触发之前信号机需处于人工控状态 * 在设置自排开或自动触发之前信号机需处于人工控状态
*/ */
private boolean signalHumanControlBeforeSetAtsControlOrCIAutoTrigger; private boolean signalHumanControlBeforeSetAtsControlOrCIAutoTrigger;
/** /**
* 扣车时是否允许提前发车 * 扣车时是否允许提前发车
*/ */
private boolean allowEarlyDepartureWhenHoldTrain; private boolean allowEarlyDepartureWhenHoldTrain;
/** /**
* 取消进路时列车紧急制动 * 取消进路时列车紧急制动
*/ */
private boolean EBWhenCancelRoute; private boolean EBWhenCancelRoute;
/** /**
* ATS自动调整运行 * ATS自动调整运行
*/ */
private boolean adjustOperationAutomatically = true; private boolean adjustOperationAutomatically = true;
/** /**
* 在办理车队进路前是否要先排列进路 * 在办理车队进路前是否要先排列进路
*/ */
private boolean setRouteBeforeSetFlt = true; private boolean setRouteBeforeSetFlt = true;
/** /**
* 在取消车队进路时同时取消进路 * 在取消车队进路时同时取消进路
*/ */
private boolean cancelRouteWhenCancelFlt; private boolean cancelRouteWhenCancelFlt;
/** /**
* 办理引导前需要信号机接近锁闭 * 办理引导前需要信号机接近锁闭
*/ */
private boolean needApproachLockBeforeSetGuide = true; private boolean needApproachLockBeforeSetGuide = true;
// /** // /**
// * 站台指定列车跳停仅跳停一次 // * 站台指定列车跳停仅跳停一次
// */ // */
// private boolean standSkipSetTrainOnlyOnce; // private boolean standSkipSetTrainOnlyOnce;
/** /**
* 封锁命令状态仅在后备模式下有效 * 封锁命令状态仅在后备模式下有效
*/ */
private boolean blockadeCommandOnlyValidInStandbyMode; private boolean blockadeCommandOnlyValidInStandbyMode;
// /** // /**
// * 道岔封锁命令需要初始化 // * 道岔封锁命令需要初始化
// */ // */
// private boolean switchBlockadeCommandNeedInit; // private boolean switchBlockadeCommandNeedInit;
/** /**
* 计轴预复位前需要车站预复位 * 计轴预复位前需要车站预复位
*/ */
private boolean stationPreResetBeforeAxlePreReset; private boolean stationPreResetBeforeAxlePreReset;
/** /**
* 道岔转动操作可以使失表故障恢复 * 道岔转动操作可以使失表故障恢复
*/ */
private boolean switchTurnOperationCanRecoverSplitFault; private boolean switchTurnOperationCanRecoverSplitFault;
/** /**
* 扣车命令不区分控制模式 * 扣车命令不区分控制模式
*/ */
private boolean holdCommandIgnoreControlMode; private boolean holdCommandIgnoreControlMode;
/** 取消联锁条件不满足的进路时需要延时解锁 */ /**
private boolean delayWhenCancelRouteWithAbnormalInterlock; * 取消联锁条件不满足的进路时需要延时解锁
*/
private boolean delayWhenCancelRouteWithAbnormalInterlock;
/** 车次号的位数 */ /**
private int figuresOfTripNumber = 4; * 车次号的位数
*/
private int figuresOfTripNumber = 4;
/** 服务号的位数 */ /**
private int figuresOfServiceNumber = 3; * 服务号的位数
*/
private int figuresOfServiceNumber = 3;
/** 设置头码车时检查方向 */ /**
private boolean checkDirectionWhenSetHead; * 设置头码车时检查方向
*/
private boolean checkDirectionWhenSetHead;
/** 转换轨进路只能通过故障解锁来取消 */ /**
private boolean transferRouteCanOnlyFaultUnlock; * 转换轨进路只能通过故障解锁来取消
*/
private boolean transferRouteCanOnlyFaultUnlock;
/** 头码车抵达目的地后变为人工车 */ /**
private boolean setManualWhenHeadTrainArriveTarget; * 头码车抵达目的地后变为人工车
*/
private boolean setManualWhenHeadTrainArriveTarget;
/** 进路默认开启冲突检测 */ /**
private boolean routeDefaultCheckConflict; * 进路默认开启冲突检测
*/
private boolean routeDefaultCheckConflict;
/** 运行图中车次号是否唯一 */ /**
private boolean tripNumberIsUnique; * 运行图中车次号是否唯一
*/
private boolean tripNumberIsUnique;
/** 站台折返策略不生效 */ /**
private boolean standTbStrategyIsInvalid; * 站台折返策略不生效
*/
private boolean standTbStrategyIsInvalid;
/** 根据服务号更新车次计划 */ /**
private boolean updateTripPlanByServiceNumber; * 根据服务号更新车次计划
*/
private boolean updateTripPlanByServiceNumber;
/** /**
* 大铁线路 * 大铁线路
*/ */
private boolean railway; private boolean railway;
/** /**
* 对信号机封锁操作是否影响信号显示 * 对信号机封锁操作是否影响信号显示
* <p> * <p>
* true-封锁信号机会使信号机显示禁止色<br> * true-封锁信号机会使信号机显示禁止色<br> false-封锁信号机不会影响信号机显示
* false-封锁信号机不会影响信号机显示 */
*/ private boolean signalBolckOptReflectSignal = true;
private boolean signalBolckOptReflectSignal=true;
/**
* 区故解只能应用于故障锁闭区段
*/
@JsonProperty(value = "SFUCanOnlyApplyForFaultLockSection")
private boolean SFUCanOnlyApplyForFaultLockSection;
/** /**
* 道岔故障时可以办理进路由远及近锁闭到故障处终止 * 区故解只能应用于故障锁闭区段
*/ */
private boolean routeCanSetWhenSwitchFault; @JsonProperty(value = "SFUCanOnlyApplyForFaultLockSection")
private boolean SFUCanOnlyApplyForFaultLockSection;
/** /**
* 人工驾驶模式CM/RM/NRM下的列车默认是停车等待命令状态 * 道岔故障时可以办理进路由远及近锁闭到故障处终止
*/ */
private boolean manualTrainDefaultStop; private boolean routeCanSetWhenSwitchFault;
public static RealLineConfigVO parseJsonStr(String configData) { /**
if (StringUtils.hasText(configData)) { * 人工驾驶模式CM/RM/NRM下的列车默认是停车等待命令状态
return JsonUtils.read(configData, RealLineConfigVO.class); */
} private boolean manualTrainDefaultStop;
return new RealLineConfigVO();
/**
* 办理引导进路时如果进路首区段占用引导信号15秒后关闭
*/
private boolean guideDelayCloseWhenFirstSectionOccupied;
public static RealLineConfigVO parseJsonStr(String configData) {
if (StringUtils.hasText(configData)) {
return JsonUtils.read(configData, RealLineConfigVO.class);
} }
return new RealLineConfigVO();
}
public boolean isUp(boolean right) { public boolean isUp(boolean right) {
return right == upRight; return right == upRight;
} }
} }

View File

@ -21,63 +21,63 @@ import java.util.Map;
@Setter @Setter
@NoArgsConstructor @NoArgsConstructor
public class FindPaperCompositionPageReqVo extends PageQueryVO { public class FindPaperCompositionPageReqVo extends PageQueryVO {
/**
* 组织id<br>
* 选填<br>
*/
@JsonSerialize(using = ToStringSerializer.class)
private Long orgId;
/**
* 线路id
*/
private Long mapId;
/**
* 试卷蓝图名称<br>
* 选填<br>
*/
private String name;
/**
* 试卷蓝图名称--是否模糊查询默认true<br>
* 选填<br>
*/
private Boolean nameLike = true;
/**
* 试卷蓝图简介<br>
* 选填<br>
*/
private String profile;
/**
* 试卷蓝图简介--是否模糊查询,默认true<br>
* 选填<br>
*/
private Boolean profileLike = true;
/**
* 根据试卷蓝图的状态查找,默认值FindPcType.All<br>
* All(1)-所有,Editing(2)-正在编辑的,CanUse(3)-可以用于生成试卷的,Locked(4)-封存,Used(5)-已经被使用过<br>
* 选填<br>
*/
private FindPcType findState = FindPcType.All;
/**
* 以什么来排序
* <p>
* 1--创建时间 2--更新时间 3--名称默认值为1
* <p>
* 选填
*/
private Integer orderBy = 1;
/** /**
* 是否降序true-降序false-升序默认值为true; * 组织id<br> 选填<br>
* <p> */
* 选填 @JsonSerialize(using = ToStringSerializer.class)
*/ private Long orgId;
private Boolean desc = true; /**
/** * 线路id
* 试卷蓝图状态1-正在编辑2-封存(不能修改)3-已经被使用(不能修改删除)<br> */
* 选填<br> private Long mapId;
*/ /**
public List<PaperCompositionState> stateList(){ * 试卷蓝图名称<br> 选填<br>
return FindPcType.stateList(findState); */
} private String name;
/**
* 试卷蓝图名称--是否模糊查询默认true<br> 选填<br>
*/
private Boolean nameLike = true;
/**
* 试卷蓝图简介<br> 选填<br>
*/
private String profile;
/**
* 试卷蓝图简介--是否模糊查询,默认true<br> 选填<br>
*/
private Boolean profileLike = true;
/**
* 根据试卷蓝图的状态查找,默认值FindPcType.All<br>
* All(1)-所有,Editing(2)-正在编辑的,CanUse(3)-可以用于生成试卷的,Locked(4)-封存,Used(5)-已经被使用过<br> 选填<br>
*/
private FindPcType findState = FindPcType.All;
/**
* 以什么来排序
* <p>
* 1--创建时间 2--更新时间 3--名称默认值为1
* <p>
* 选填
*/
private Integer orderBy = 1;
/**
* 是否降序true-降序false-升序默认值为true;
* <p>
* 选填
*/
private Boolean desc = true;
/**
* 试卷创建者的ID
*/
private Long creatorId;
/**
* 试卷蓝图状态1-正在编辑2-封存(不能修改)3-已经被使用(不能修改删除)<br> 选填<br>
*/
public List<PaperCompositionState> stateList() {
return FindPcType.stateList(findState);
}
} }

View File

@ -1,48 +1,46 @@
package club.joylink.rtss.vo.paper; package club.joylink.rtss.vo.paper;
import club.joylink.rtss.vo.client.training2.Operation2VO; import club.joylink.rtss.vo.client.training2.Operation2VO;
import java.util.List;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import java.util.List;
@Data @Data
@NoArgsConstructor @NoArgsConstructor
public class PaperTrainAnswerDetail { public class PaperTrainAnswerDetail {
/** /**
* 实训步骤id * 实训步骤id
*/ */
private Long stepId; private Long stepId;
/** /**
* 实训是否成功 * 实训是否成功
*/ */
private boolean success; private boolean success;
/** /**
* 获得的分数 * 获得的分数
*/ */
private Float score; private Float score;
/** /**
* 规则设置的分数 * 规则设置的分数
*/ */
private Float ruleScore; private Float ruleScore;
/** /**
* 是否有打分规则 * 是否有打分规则
*/ */
private boolean haveRule; private boolean haveRule;
private boolean notExistAppend; private boolean notExistAppend;
/** /**
* 客户端操作的实训,对应的id必须要传 * 客户端操作的实训,对应的id必须要传
*/ */
private List<TrainOperations> clientOperations; private List<TrainOperations> clientOperations;
public static class TrainOperations extends Operation2VO.ClientOperation2VO {
public static class TrainOperations extends Operation2VO.ClientOperation2VO{ }
}
} }

View File

@ -1,27 +0,0 @@
/*
package club.joylink.rtss.vo.permission;
import club.joylink.rtss.vo.permission.subject.PermissionSubjectVO;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PermissionRefParamVO {
private Long distributeId;
private Long permissionId;
public static List<PermissionRefParamVO> convert(List<PermissionSubjectVO> vo){
List<PermissionRefParamVO> list = Lists.newArrayList();
for (PermissionSubjectVO subjectVO : vo) {
list.add(new PermissionRefParamVO(subjectVO.getDistributeId(),subjectVO.getPermissionId()));
}
return list;
}
}
*/

View File

@ -0,0 +1,13 @@
package club.joylink.rtss.vo.voice;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class VoiceVerifyResultVO {
private String text;
private boolean match;
}

View File

@ -0,0 +1,204 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="club.joylink.rtss.dao.CgyViewDAO">
<resultMap id="BaseResultMap" type="club.joylink.rtss.entity.CgyView">
<id column="app_id" jdbcType="VARCHAR" property="appId" />
<result column="app_secret" jdbcType="VARCHAR" property="appSecret" />
<result column="function_id" jdbcType="BIGINT" property="functionId" />
<result column="view_count" jdbcType="BIGINT" property="viewCount" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
app_id, app_secret, function_id, view_count
</sql>
<select id="selectByExample" parameterType="club.joylink.rtss.entity.CgyViewExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from cgy_view
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
<if test="limit != null">
<if test="offset != null">
limit ${offset}, ${limit}
</if>
<if test="offset == null">
limit ${limit}
</if>
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from cgy_view
where app_id = #{appId,jdbcType=VARCHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String">
delete from cgy_view
where app_id = #{appId,jdbcType=VARCHAR}
</delete>
<delete id="deleteByExample" parameterType="club.joylink.rtss.entity.CgyViewExample">
delete from cgy_view
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="club.joylink.rtss.entity.CgyView">
insert into cgy_view (app_id, app_secret, function_id,
view_count)
values (#{appId,jdbcType=VARCHAR}, #{appSecret,jdbcType=VARCHAR}, #{functionId,jdbcType=BIGINT},
#{viewCount,jdbcType=BIGINT})
</insert>
<insert id="insertSelective" parameterType="club.joylink.rtss.entity.CgyView">
insert into cgy_view
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="appId != null">
app_id,
</if>
<if test="appSecret != null">
app_secret,
</if>
<if test="functionId != null">
function_id,
</if>
<if test="viewCount != null">
view_count,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="appId != null">
#{appId,jdbcType=VARCHAR},
</if>
<if test="appSecret != null">
#{appSecret,jdbcType=VARCHAR},
</if>
<if test="functionId != null">
#{functionId,jdbcType=BIGINT},
</if>
<if test="viewCount != null">
#{viewCount,jdbcType=BIGINT},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="club.joylink.rtss.entity.CgyViewExample" resultType="java.lang.Long">
select count(*) from cgy_view
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update cgy_view
<set>
<if test="record.appId != null">
app_id = #{record.appId,jdbcType=VARCHAR},
</if>
<if test="record.appSecret != null">
app_secret = #{record.appSecret,jdbcType=VARCHAR},
</if>
<if test="record.functionId != null">
function_id = #{record.functionId,jdbcType=BIGINT},
</if>
<if test="record.viewCount != null">
view_count = #{record.viewCount,jdbcType=BIGINT},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update cgy_view
set app_id = #{record.appId,jdbcType=VARCHAR},
app_secret = #{record.appSecret,jdbcType=VARCHAR},
function_id = #{record.functionId,jdbcType=BIGINT},
view_count = #{record.viewCount,jdbcType=BIGINT}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="club.joylink.rtss.entity.CgyView">
update cgy_view
<set>
<if test="appSecret != null">
app_secret = #{appSecret,jdbcType=VARCHAR},
</if>
<if test="functionId != null">
function_id = #{functionId,jdbcType=BIGINT},
</if>
<if test="viewCount != null">
view_count = #{viewCount,jdbcType=BIGINT},
</if>
</set>
where app_id = #{appId,jdbcType=VARCHAR}
</update>
<update id="updateByPrimaryKey" parameterType="club.joylink.rtss.entity.CgyView">
update cgy_view
set app_secret = #{appSecret,jdbcType=VARCHAR},
function_id = #{functionId,jdbcType=BIGINT},
view_count = #{viewCount,jdbcType=BIGINT}
where app_id = #{appId,jdbcType=VARCHAR}
</update>
</mapper>