commit e90e11527dce1e5b6d6c5453cf7ba47dd650ecd4 Author: Timer <@> Date: Thu Jan 29 17:06:01 2026 +0800 initial diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..ccf5566 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,10 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml +# 基于编辑器的 HTTP 客户端请求 +/httpRequests/ +# 依赖于环境的 Maven 主目录路径 +/mavenHomeManager.xml +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..d227fcd --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,14 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/sipaiis_datacollector.iml b/.idea/sipaiis_datacollector.iml new file mode 100644 index 0000000..d6ebd48 --- /dev/null +++ b/.idea/sipaiis_datacollector.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.trae/documents/鍦℅IS_Job涓姞鍏ュ拰杈炬祦閲忚璁$畻鐐逛綅鎺ㄩ.md b/.trae/documents/鍦℅IS_Job涓姞鍏ュ拰杈炬祦閲忚璁$畻鐐逛綅鎺ㄩ.md new file mode 100644 index 0000000..8a3a177 --- /dev/null +++ b/.trae/documents/鍦℅IS_Job涓姞鍏ュ拰杈炬祦閲忚璁$畻鐐逛綅鎺ㄩ.md @@ -0,0 +1,55 @@ +## 鍙樻洿鐩爣 + +* 鍦 `com.sipai.schedule.GIS_Job.jobGIS` 鐨 SQL WHERE 杩囨护涓紝鍔犲叆 6 涓柊璁$畻鐐逛綅鐨勭簿纭尮閰嶏紝浣垮叾闅忔棦鏈夌偣浣嶄竴璧蜂笅鍙戝埌绠$綉骞冲彴銆 + +* 鏂板鐐逛綅锛歚KCGW_53564_A8`銆乣KCGW_53564_A7`銆乣KCGW_53564_P1`銆乣KCGW_53581_A8`銆乣KCGW_53581_A7`銆乣KCGW_53581_P1`銆 + +## 浠g爜浣嶇疆 + +* 鏂囦欢锛歚src/main/java/com/sipai/schedule/GIS_Job.java` + +* 鏂规硶锛歚jobGIS` + +* 鐜版湁 SQL 鎷兼帴鍖洪棿锛歚GIS_Job.java:427-436` + +## 鍏蜂綋鏀瑰姩 + +* 鍦ㄧ幇鏈変袱鏉″拰杈捐澶囧墠缂杩囨护涔嬪悗銆佸垎鍙蜂箣鍓嶏紝鎸夋棦鏈夋牸寮忚拷鍔犱互涓嬫潯浠讹細 + +``` +" OR id = 'KCGW_53564_A8'\n" + +" OR id = 'KCGW_53564_A7'\n" + +" OR id = 'KCGW_53564_P1'\n" + +" OR id = 'KCGW_53581_A8'\n" + +" OR id = 'KCGW_53581_A7'\n" + +" OR id = 'KCGW_53581_P1'\n" + +``` + +* 淇濇寔鍘熸湁 `LIKE 'KCGW_22008_53564_%'` 涓 `LIKE 'KCGW_22029_53581_%'` 涓嶅彉锛岄伩鍏嶅奖鍝嶆棦鏈夎疆璇㈢偣浣嶆帹閫併 + +## 瀹炵幇姝ラ + +* 缂栬緫 `sql` 瀛楃涓诧紝杩藉姞涓婅堪 6 琛 `OR id = '...'` 鏉′欢锛屼繚鐣欐湯灏惧垎鍙枫 + +* 涓嶆敼鍔ㄥ叾浠栭昏緫锛堟煡璇€佺粍瑁 JSON銆丮QTT 鍙戦侊級銆 + +## 鏍¢獙涓庨獙璇 + +* 鍦ㄦ湰鍦拌繍琛 `jobGIS` 瀹氭椂浠诲姟鎴栨墜鍔ㄨЕ鍙戝悓璺緞鏌ヨ锛岀‘璁 `mPointService.selectListByWhere(sql)` 杩斿洖闆嗗悎鍖呭惈鏂板 6 鐐逛綅锛堝彲鍦ㄦ棩蹇楁垨璋冭瘯涓瑙嗭級銆 + +* 瑙傚療 MQTT 鎺ㄩ佸唴瀹癸紙涓婚 `CommString.Mqtt_Topic_DATA`锛夋槸鍚﹀寘鍚搴 `mpcode` 涓庢渶鏂板/鏃堕棿銆 + +* 鍏虫敞鏃ュ織杈撳嚭涓庡紓甯稿爢鏍堬紝纭繚鏃 SQL 鎷兼帴鏍煎紡閿欒銆 + +## 鍏煎鎬т笌鍛藉悕涓鑷存 + +* 鏂板 ID 涓 `HD_Job` 涓绠楃偣浣嶇紪鐮佷竴鑷达細`KCGW__`銆 + +* 涓嶅奖鍝嶆棦鏈 `SignalTag`銆乣P1_DAY/HOUR`銆乣KCGW_15001_A1_*` 绛夎繃婊ゃ + +## 椋庨櫓涓庡洖閫 + +* 鑻ュ悗缁绠楃偣浣嶅懡鍚嶈鑼冭皟鏁达紝闇鍚屾鏇存柊姝ゅ绮剧‘鍖归厤銆 + +* 鑻ョ缃戝钩鍙颁笉闇瑕佽繖 6 涓偣浣嶏紝鍙洿鎺ョЩ闄ゆ柊澧炵殑 `OR id = '...'` 鏉′欢鍥為銆 + diff --git a/README.md b/README.md new file mode 100644 index 0000000..ff90759 --- /dev/null +++ b/README.md @@ -0,0 +1,92 @@ +# SIPAIIS_DataCollector + + + +## Getting started + +To make it easy for you to get started with GitLab, here's a list of recommended next steps. + +Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! + +## Add your files + +- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files +- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: + +``` +cd existing_repo +git remote add origin http://localhost/backend/sipaiis_datacollector.git +git branch -M main +git push -uf origin main +``` + +## Integrate with your tools + +- [ ] [Set up project integrations](http://localhost/backend/sipaiis_datacollector/-/settings/integrations) + +## Collaborate with your team + +- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) +- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) +- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) +- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) +- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) + +## Test and Deploy + +Use the built-in continuous integration in GitLab. + +- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) +- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) +- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) +- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) +- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) + +*** + +# Editing this README + +When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. + +## Suggestions for a good README +Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. + +## Name +Choose a self-explaining name for your project. + +## Description +Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. + +## Badges +On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. + +## Visuals +Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. + +## Installation +Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. + +## Usage +Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. + +## Support +Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. + +## Roadmap +If you have ideas for releases in the future, it is a good idea to list them in the README. + +## Contributing +State if you are open to contributions and what your requirements are for accepting them. + +For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. + +You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. + +## Authors and acknowledgment +Show your appreciation to those who have contributed to the project. + +## License +For open source projects, say how it is licensed. + +## Project status +If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..88d7d16 --- /dev/null +++ b/pom.xml @@ -0,0 +1,284 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.0.RELEASE + + + com.sipai + springboot + 0.0.1-SNAPSHOT + jar + springboot + Demo project for Spring Boot + + 1.8 + 4.1.86.Final + 2.3.7.RELEASE + + + + org.springframework.boot + spring-boot-starter-web + + + logback-core + ch.qos.logback + + + logback-classic + ch.qos.logback + + + spring-boot-starter-logging + org.springframework.boot + + + log4j-to-slf4j + org.apache.logging.log4j + + + + + + org.springframework.boot + spring-boot-starter-data-elasticsearch + + + + org.projectlombok + lombok + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + + org.mybatis.generator + mybatis-generator-core + 1.3.5 + + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 2.0.0 + + + com.alibaba + druid-spring-boot-starter + 1.1.10 + + + + com.microsoft.sqlserver + mssql-jdbc + runtime + + + + mysql + mysql-connector-java + 8.0.11 + + + org.eclipse.paho + org.eclipse.paho.client.mqttv3 + 1.1.0 + + + + com.fasterxml.uuid + java-uuid-generator + 4.0.1 + + + + com.alibaba + fastjson + 1.2.75 + + + org.aspectj + aspectjweaver + 1.9.4 + + + + org.springframework + spring-jdbc + + + + + com.google.code.gson + gson + 2.8.5 + + + + org.springframework + springloaded + 1.2.8.RELEASE + + + + org.springframework.boot + spring-boot-starter-amqp + + + + + io.springfox + springfox-swagger2 + 2.9.2 + + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + + org.apache.commons + commons-collections4 + 4.4 + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + + org.redisson + redisson + 3.13.3 + + + + io.netty + netty-all + ${netty.version} + + + + + org.eclipse.milo + sdk-client + 0.6.10 + + + com.google.guava + guava + + + + + + org.eclipse.milo + stack-core + 0.6.10 + + + + + com.google.guava + guava + 31.1-jre + + + + + org.springframework.kafka + spring-kafka + ${spring-kafka.version} + + + + + com.github.ben-manes.caffeine + caffeine + 2.9.3 + + + + com.github.pagehelper + pagehelper-spring-boot-starter + 1.4.6 + + + + + org.springframework.boot + spring-boot-starter-log4j2 + + + + + org.apache.httpcomponents + httpclient + 4.5.13 + + + org.apache.httpcomponents + httpmime + 4.5.13 + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.sipai.DataApplication + + + + + org.mybatis.generator + mybatis-generator-maven-plugin + 1.3.2 + + ${basedir}/src/main/resources/generatior-config.xml + true + true + + + + + + src/main/webapp + META-INF/resources + + **/** + + + + src/main/resources + + **/** + + + + + + \ No newline at end of file diff --git a/src/main/java/com/sipai/DataApplication.java b/src/main/java/com/sipai/DataApplication.java new file mode 100644 index 0000000..cf2cebd --- /dev/null +++ b/src/main/java/com/sipai/DataApplication.java @@ -0,0 +1,47 @@ +package com.sipai; + +import com.sipai.tools.DataSourceAspect; +import com.sipai.tools.DataSourceContextHolder; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration; +import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration; +import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.ImportResource; +import org.springframework.context.annotation.PropertySource; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +//@SpringBootApplication + +/** + * @SpringBootApplication 涓 + * @Configuration銆丂EnableAutoConfiguration銆丂ComponentScan 涓変釜娉ㄨВ鐨勭粍鍚 + */ + +@SpringBootApplication(exclude = { + DataSourceAutoConfiguration.class +}) +@EnableTransactionManagement //寮鍚簨鍔″姛鑳 +@EnableAsync//寮鍚紓姝 +@EnableScheduling +@MapperScan("src/main/resources/mybatis/mapper") +//@PropertySource("classpath:application-pro.yml")//yml閲岄潰鎸囧畾pro澶辨晥锛屽彧鑳藉湪杩欏己鍒舵寚瀹 +public class DataApplication { + + static{ + System.setProperty("es.set.netty.runtime.available.processors", "false"); + } + + public static void main(String[] args) { + SpringApplication app = new SpringApplication(DataApplication.class); + app.setAllowBeanDefinitionOverriding(false); // 妫鏌ユ槸鍚︽湁姝よ缃 + app.run(args); + } + +} diff --git a/src/main/java/com/sipai/config/AppConfig.java b/src/main/java/com/sipai/config/AppConfig.java new file mode 100644 index 0000000..a29e6cd --- /dev/null +++ b/src/main/java/com/sipai/config/AppConfig.java @@ -0,0 +1,18 @@ +package com.sipai.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "app") +public class AppConfig { + private int maxPoints; + + public int getMaxPoints() { + return maxPoints; + } + + public void setMaxPoints(int maxPoints) { + this.maxPoints = maxPoints; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/config/MockOpcUaClient.java b/src/main/java/com/sipai/config/MockOpcUaClient.java new file mode 100644 index 0000000..ecffa7f --- /dev/null +++ b/src/main/java/com/sipai/config/MockOpcUaClient.java @@ -0,0 +1,38 @@ +package com.sipai.config; + +import org.eclipse.milo.opcua.sdk.client.OpcUaClient; +import org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig; +import org.eclipse.milo.opcua.stack.client.UaStackClient; +import org.eclipse.milo.opcua.stack.core.types.builtin.*; +import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; + +public class MockOpcUaClient extends OpcUaClient { + public MockOpcUaClient(OpcUaClientConfig config) throws Exception { + super(config, (UaStackClient) Executors.newSingleThreadExecutor()); // 鎻愪緵鎵鏈夊繀闇鐨勫弬鏁 + } + + private static OpcUaClientConfig createMockConfig() { + return OpcUaClientConfig.builder() + .setEndpoint(null) // 妯℃嫙绔偣 + .setApplicationName(LocalizedText.english("Mock OPC UA Client")) + .build(); + } + + public static MockOpcUaClient createMockClient() throws Exception { + return new MockOpcUaClient(createMockConfig()); + } + + @Override + public CompletableFuture readValue(double timeout, TimestampsToReturn timestamps, NodeId nodeId) { + DataValue dataValue = new DataValue( + new Variant(0), // 妯℃嫙鍊 + StatusCode.GOOD, + null, + null + ); + return CompletableFuture.completedFuture(dataValue); + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/config/OpcUaConfig.java b/src/main/java/com/sipai/config/OpcUaConfig.java new file mode 100644 index 0000000..fa24e73 --- /dev/null +++ b/src/main/java/com/sipai/config/OpcUaConfig.java @@ -0,0 +1,76 @@ +package com.sipai.config; + +import org.eclipse.milo.opcua.sdk.client.OpcUaClient; +import org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig; +import org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider; +import org.eclipse.milo.opcua.sdk.client.api.identity.IdentityProvider; +import org.eclipse.milo.opcua.sdk.client.api.identity.UsernameProvider; +import org.eclipse.milo.opcua.stack.client.DiscoveryClient; +import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy; +import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger; +import org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.List; + +@Configuration +public class OpcUaConfig { + @Autowired + private OpcUaProperties properties; + + @Bean + @ConditionalOnProperty(prefix = "opcua", name = "enabled", havingValue = "true") + public OpcUaClient opcUaClient() throws Exception { + return createClient(properties); + } + + /*@Bean + public OpcUaClient opcUaClient(OpcUaProperties properties) throws Exception { + if (!properties.isEnabled()) { + // 濡傛灉 OPC UA 鍔熻兘鏈惎鐢紝杩斿洖 null 鎴栨姏鍑鸿嚜瀹氫箟寮傚父 + return null; // 鎴栬呮姏鍑轰竴涓嚜瀹氫箟寮傚父 + } + return createClient(properties); + }*/ + + private OpcUaClient createClient(OpcUaProperties properties) throws Exception { + // 1. 鍙戠幇绔偣 + List endpoints = DiscoveryClient + .getEndpoints(properties.getServerUrl()) + .get(); + + // 2. 鏍规嵁閰嶇疆閫夋嫨绔偣 + EndpointDescription endpoint = endpoints.stream() + .filter(e -> e.getSecurityPolicyUri().equals(SecurityPolicy.None.getUri())) + .findFirst() + .orElseThrow(() -> new Exception("鏈壘鍒板尶鍚嶈闂鐐")); + + // 3. 鍒涘缓韬唤璁よ瘉鎻愪緵鑰 + IdentityProvider identityProvider; + if (properties.getUsername() != null && !properties.getUsername().isEmpty()) { + // 浣跨敤鐢ㄦ埛鍚/瀵嗙爜璁よ瘉 + identityProvider = new UsernameProvider( + properties.getUsername(), + properties.getPassword() + ); + } else { + // 浣跨敤鍖垮悕璁よ瘉 + identityProvider = new AnonymousProvider(); + } + + // 4. 鍒涘缓瀹㈡埛绔厤缃 + OpcUaClientConfig config = OpcUaClientConfig.builder() + .setEndpoint(endpoint) + .setRequestTimeout(UInteger.valueOf(5000)) + .setIdentityProvider(identityProvider) + .build(); + + // 5. 鍒涘缓骞惰繛鎺ュ鎴风 + OpcUaClient client = OpcUaClient.create(config); + client.connect().get(); + return client; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/config/OpcUaProperties.java b/src/main/java/com/sipai/config/OpcUaProperties.java new file mode 100644 index 0000000..9762bbd --- /dev/null +++ b/src/main/java/com/sipai/config/OpcUaProperties.java @@ -0,0 +1,66 @@ +package com.sipai.config; + +import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy; +import org.eclipse.milo.opcua.stack.core.types.enumerated.MessageSecurityMode; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "opcua") +public class OpcUaProperties { + private String serverUrl; + private SecurityPolicy securityPolicy = SecurityPolicy.None; + private MessageSecurityMode securityMode = MessageSecurityMode.None; + private String username; + private String password; + private boolean enabled = false;//鏄惁鍚敤opc瀹㈡埛绔 + + // Getters and Setters + public String getServerUrl() { + return serverUrl; + } + + public void setServerUrl(String serverUrl) { + this.serverUrl = serverUrl; + } + + public SecurityPolicy getSecurityPolicy() { + return securityPolicy; + } + + public void setSecurityPolicy(SecurityPolicy securityPolicy) { + this.securityPolicy = securityPolicy; + } + + public MessageSecurityMode getSecurityMode() { + return securityMode; + } + + public void setSecurityMode(MessageSecurityMode securityMode) { + this.securityMode = securityMode; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/config/RedissonConfig.java b/src/main/java/com/sipai/config/RedissonConfig.java new file mode 100644 index 0000000..e61c62b --- /dev/null +++ b/src/main/java/com/sipai/config/RedissonConfig.java @@ -0,0 +1,75 @@ +package com.sipai.config; + + +import org.redisson.Redisson; +import org.redisson.api.RedissonClient; +import org.redisson.client.codec.Codec; +import org.redisson.codec.JsonJacksonCodec; +import org.redisson.config.Config; +import org.redisson.config.SingleServerConfig; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @Author : YYJ + * @CreateTime : 2021/9/13 + * @Description : + **/ +@Configuration +public class RedissonConfig { + private static String MODE_SINGLE = "single"; + private static String MODE_CLUSTER = "cluster"; + @Value("${spring.redis.mode}") + public String mode; + + @Value("${spring.redis.cluster.nodes}") + public String cluster; + + @Value("${spring.redis.password}") + public String password; + + @Value("${spring.redis.host}") + public String host; + + @Value("${spring.redis.port}") + public String port; + + @Value("${spring.redis.timeout}") + public Integer timeout; + +// @Value("${redis.database}") +// public String database; + + @Bean + public RedissonClient redissonClient(){ + RedissonClient redisson = null; + Config conf = new Config(); + + if(MODE_SINGLE.equals(mode)) {//鍗曟満 + //鍗曡妭鐐规ā寮 + SingleServerConfig singleServerConfig = conf.useSingleServer(); + //璁剧疆杩炴帴鍦板潃锛歳edis://127.0.0.1:6379 + singleServerConfig.setAddress("redis://" + host + ":" + port); + //璁剧疆杩炴帴瀵嗙爜 + singleServerConfig.setPassword(password); +// singleServerConfig.setDatabase(Integer.valueOf(database)); + }else if(MODE_CLUSTER.equals(mode)){//闆嗙兢 + String[] nodes = cluster.split(","); + for (int i = 0; i < nodes.length; i++) { + nodes[i] = "redis://" + nodes[i]; + } + conf.useClusterServers() + .setScanInterval(2000) + .addNodeAddress(nodes) + .setTimeout(timeout) + .setPassword(password); + } + + //浣跨敤json搴忓垪鍖栨柟寮 + Codec codec = new JsonJacksonCodec(); + conf.setCodec(codec); + redisson = Redisson.create(conf); + return redisson; + } +} diff --git a/src/main/java/com/sipai/config/StartupLogger.java b/src/main/java/com/sipai/config/StartupLogger.java new file mode 100644 index 0000000..925a90e --- /dev/null +++ b/src/main/java/com/sipai/config/StartupLogger.java @@ -0,0 +1,20 @@ +package com.sipai.config; + +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +import java.net.InetAddress; +import java.net.UnknownHostException; + +@Component +public class StartupLogger { + + @EventListener(ApplicationReadyEvent.class) + public void onStartup() throws UnknownHostException { + String ip = InetAddress.getLocalHost().getHostAddress(); + String port = System.getProperty("server.port");//bat鑴氭湰浼犺繃鏉ョ殑绔彛 + String url = ip + ":" + port; + System.out.println("Spring Boot 鏈嶅姟宸插惎鍔ㄥ畬鎴愶紒" + (url != null ? "寮鍙戠幆澧" : url)); + } +} diff --git a/src/main/java/com/sipai/config/UDPClient.java b/src/main/java/com/sipai/config/UDPClient.java new file mode 100644 index 0000000..ccd0989 --- /dev/null +++ b/src/main/java/com/sipai/config/UDPClient.java @@ -0,0 +1,80 @@ +package com.sipai.config; + +import org.springframework.beans.factory.annotation.Value; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; + +/** + * 鐢ㄤ簬娴嬭瘯 - 鍗楁槍椤圭洰 + * sj 2025-05-21 + */ +public class UDPClient { + +// @Value("${udp.server.port}") +// private static int serverPort; + + public static void main(String[] args) { + +// 绠$綉鐩戞祴璁惧閲囬泦 +// 192.168.10.18:5006 +// 223.84.61.83:5006 + +// String serverHost = "116.236.176.248"; +// String serverHost = "127.0.0.1"; + String serverHost = "223.84.61.83"; + int serverPort = 5006; + + //鏅鸿兘浜曠洊 + String hexString = "AB CD 00 4D 2A FB 25 07 20 12 00 01 A0 01 68 00 02 08 48 4B 33 35 2D 49 49 3B 56 31 2E 31 3B 56 31 2E 30 2E 30 36 00 00 00 00 00 00 00 00 04 01 C2 D2 00 00 04 02 40 E0 00 00 04 03 3F EC 7D AF 04 04 47 C3 50 00 04 05 47 C3 50 00 05 01 00 00 D3 0D 0A"; + //娴侀噺璁 +// String hexString = "AB CD 00 71 56 03 25 07 08 09 15 01 0F 02 D8 00 FD 12 48 38 36 45 3B 31 2E 33 3B 31 2E 30 2E 33 35 20 20 20 20 20 00 00 00 00 00 00 00 00 01 01 DC 02 00 00 25 A8 00 00 01 02 00 00 00 00 03 00 00 00 01 03 DC 02 00 00 22 A8 00 00 04 01 3C A3 D7 0A 04 02 3D A3 D7 0A 04 03 41 A0 00 00 04 04 41 C4 7A E1 04 07 41 2C CC CD 04 08 3E 45 A1 CB 05 01 00 00 A2 0D 0A"; + //娑蹭綅璁 +// String hexString = "AB CD 00 B7 59 F7 25 07 08 09 05 03 05 01 6D 00 C0 06 48 4B 31 39 52 3B 33 2E 31 3B 31 2E 30 2E 30 30 00 00 00 00 00 00 00 00 00 00 00 00 04 01 42 E0 00 00 42 E0 00 00 42 E0 00 00 04 02 40 00 00 00 40 00 00 00 40 00 00 00 04 03 43 E8 80 00 43 E8 80 00 43 E8 80 00 04 04 3F C0 6A 32 40 0A 7D B4 3F C0 6A 32 04 05 40 69 D8 88 40 69 D8 88 40 69 D8 88 04 06 00 00 00 00 00 00 00 00 00 00 00 00 04 07 00 00 00 00 00 00 00 00 00 00 00 00 04 08 40 65 E3 55 40 65 D2 F2 40 65 B2 2E 04 09 3D DD 2F 00 3D DF 3B 60 3D E3 53 E0 04 0A 3D DD 2F 00 3D DF 3B 60 3D E3 53 E0 34 0D 0A"; + //鐢靛 +// String hexString = "AB CD 00 A3 36 B1 25 06 21 18 15 08 0F 02 DC 00 D2 0D 48 38 36 45 3B 31 2E 33 3B 31 2E 30 2E 33 35 20 20 20 20 20 00 00 00 00 00 00 00 00 04 03 41 40 00 00 41 40 00 00 41 40 00 00 41 40 00 00 41 40 00 00 41 40 00 00 41 40 00 00 41 40 00 00 04 07 00 00 00 00 3A 83 12 6F 3A 83 12 6F 3A 83 12 6F 3A 83 12 6F 3A 83 12 6F 3A 83 12 6F 3A 83 12 6F 04 08 41 C8 CC CD 41 CA 66 66 41 CB 33 33 41 CC CC CD 41 D0 CC CD 41 D3 33 33 41 D4 CC CD 41 D5 99 9A 05 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 A1 0D 0A"; + //闆ㄩ噺璁 +// String hexString = "AB CD 00 8B 3A 99 25 06 21 13 33 02 01 04 64 00 A5 15 48 38 31 45 2D 3B 31 2E 34 3B 35 2E 30 2E 30 34 20 20 20 20 00 00 00 00 00 00 00 00 01 01 00 00 00 00 00 00 00 00 00 00 00 00 01 02 00 00 00 00 00 00 00 00 00 00 00 00 01 04 00 00 00 00 00 00 00 00 00 00 00 00 01 05 00 00 00 00 00 00 00 00 00 00 00 00 04 01 43 37 66 66 43 37 66 66 04 02 00 00 00 00 00 00 00 00 04 04 40 E8 80 00 40 F0 00 00 04 05 00 00 00 00 00 00 00 00 EE 0D 0A"; + //鍐呮稘鈥 +// String hexString = "AB CD 00 6A 3E 81 25 06 21 13 33 01 01 05 6A 00 05 19 56 38 38 20 53 6D 61 72 74 20 20 20 20 20 20 20 20 20 20 20 00 00 00 00 00 00 00 00 01 01 00 00 00 00 00 00 00 00 01 02 00 00 00 00 00 00 00 00 02 03 01 02 04 01 02 09 00 02 0A 00 02 0B 00 04 01 00 00 00 00 04 02 00 00 00 00 04 0D 00 00 00 00 01 0E 00 00 00 00 00 00 00 00 70 0D 0A"; + + + hexString = hexString.replaceAll("\\s+", ""); // Remove all whitespace + byte[] data = hexStringToByteArray(hexString); + + try (DatagramSocket socket = new DatagramSocket()) { + InetAddress serverAddress = InetAddress.getByName(serverHost); + + // 鍙戦佹暟鎹寘 + DatagramPacket packet = new DatagramPacket( + data, data.length, serverAddress, serverPort); + socket.send(packet); + System.out.println("宸插彂閫佹暟鎹寘鍒版湇鍔″櫒"); + + // 鎺ユ敹鍝嶅簲 + byte[] buffer = new byte[1024]; + DatagramPacket response = new DatagramPacket(buffer, buffer.length); + socket.receive(response); + + String responseStr = new String( + response.getData(), 0, response.getLength()); + System.out.println("鏈嶅姟鍣ㄥ搷搴: " + responseStr); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + // 鍗佸叚杩涘埗瀛楃涓茶浆瀛楄妭鏁扮粍鐨勬柟娉 + private static byte[] hexStringToByteArray(String s) { + int len = s.length(); + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + + Character.digit(s.charAt(i + 1), 16)); + } + return data; + } +} diff --git a/src/main/java/com/sipai/config/UDPFilePollingClient.java b/src/main/java/com/sipai/config/UDPFilePollingClient.java new file mode 100644 index 0000000..07be833 --- /dev/null +++ b/src/main/java/com/sipai/config/UDPFilePollingClient.java @@ -0,0 +1,135 @@ +package com.sipai.config; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.*; +import java.util.concurrent.TimeUnit; + +/** + * 鐢ㄤ簬娴嬭瘯 - 鍗楁槍椤圭洰 + * 淇敼涓鸿疆璇xt鏂囦欢骞跺彂閫佸唴瀹 + * sj 2025-05-21 + * 淇敼涓轰粎杞涓娆 + */ +public class UDPFilePollingClient { + + private static final String SERVER_HOST = "223.84.61.83"; // 榛樿鏈湴 + private static final int SERVER_PORT = 5006; + private static final String WATCH_DIRECTORY = "D:\\data_logs\\yewei"; // 鐩戞帶褰撳墠鐩綍 + private static final Set processedFiles = Collections.synchronizedSet(new HashSet<>()); + + public static void main(String[] args) { + System.out.println("鍚姩UDP鏂囦欢杞鏈嶅姟(鍗曟杩愯)锛岀洃鎺х洰褰: " + WATCH_DIRECTORY); + pollAndProcessFiles(); + System.out.println("鏂囦欢杞澶勭悊瀹屾垚"); + } + + private static void pollAndProcessFiles() { + try { + List txtFiles = new ArrayList<>(); + + // 鏀堕泦鎵鏈塼xt鏂囦欢 + Files.walkFileTree(Paths.get(WATCH_DIRECTORY), new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { + if (file.toString().toLowerCase().endsWith(".txt")) { + txtFiles.add(file); + } + return FileVisitResult.CONTINUE; + } + }); + + // 鎸変慨鏀规椂闂存帓搴(浠庢棫鍒版柊) + txtFiles.sort(Comparator.comparing(path -> { + try { + return Files.getLastModifiedTime(path).toMillis(); + } catch (IOException e) { + return 0L; + } + })); + + // 澶勭悊鏈鐞嗚繃鐨勬枃浠 + for (Path file : txtFiles) { + if (!processedFiles.contains(file)) { + processFile(file); + processedFiles.add(file); + } + } + } catch (IOException e) { + System.err.println("鐩綍杞閿欒: " + e.getMessage()); + } + } + + private static void processFile(Path file) { + try { + // 姝g‘璇诲彇鏂囦欢鍐呭涓哄瓧绗︿覆 + String fileContent = new String(Files.readAllBytes(file)).trim(); + + if (fileContent.isEmpty()) { + System.out.println("鏂囦欢鍐呭涓虹┖锛岃烦杩: " + file.getFileName()); + return; + } + + // 鍙戦乁DP璇锋眰 + sendUdpRequest(fileContent); + + // 鍙: 鍙戦佹垚鍔熷悗绉诲姩鎴栧垹闄ゆ枃浠 + Files.delete(file); + // 鎴栫Щ鍔ㄥ埌宸插鐞嗙洰褰 + // Files.move(file, Paths.get("processed", file.getFileName())); + + } catch (IOException e) { + System.err.println("澶勭悊鏂囦欢閿欒 " + file.getFileName() + ": " + e.getMessage()); + } + } + + private static void sendUdpRequest(String hexString) { + hexString = hexString.replaceAll("\\s+", ""); // 绉婚櫎鎵鏈夌┖鐧藉瓧绗 + + try (DatagramSocket socket = new DatagramSocket()) { + InetAddress serverAddress = InetAddress.getByName(SERVER_HOST); + byte[] data = hexStringToByteArray(hexString); + + // 鍙戦佹暟鎹寘 + DatagramPacket packet = new DatagramPacket( + data, data.length, serverAddress, SERVER_PORT); + socket.send(packet); + System.out.println("宸插彂閫乁DP鏁版嵁鍖呭埌 " + SERVER_HOST + ":" + SERVER_PORT); + + // 鎺ユ敹鍝嶅簲(鍙) + byte[] buffer = new byte[1024]; + DatagramPacket response = new DatagramPacket(buffer, buffer.length); + socket.setSoTimeout(1000); // 3绉掕秴鏃 + try { + socket.receive(response); + String responseStr = new String( + response.getData(), 0, response.getLength()); + System.out.println("鏈嶅姟鍣ㄥ搷搴: " + responseStr); + } catch (IOException e) { + System.out.println("鏈敹鍒版湇鍔″櫒鍝嶅簲(瓒呮椂)"); + } + + } catch (IOException e) { + System.err.println("UDP閫氫俊閿欒: " + e.getMessage()); + } + } + + // 鍗佸叚杩涘埗瀛楃涓茶浆瀛楄妭鏁扮粍鐨勬柟娉 + private static byte[] hexStringToByteArray(String s) { + int len = s.length(); + if (len % 2 != 0) { + throw new IllegalArgumentException("鍗佸叚杩涘埗瀛楃涓查暱搴﹀繀椤讳负鍋舵暟"); + } + + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + + Character.digit(s.charAt(i + 1), 16)); + } + return data; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/config/UDPServer.java b/src/main/java/com/sipai/config/UDPServer.java new file mode 100644 index 0000000..44e9e71 --- /dev/null +++ b/src/main/java/com/sipai/config/UDPServer.java @@ -0,0 +1,859 @@ +package com.sipai.config; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.sipai.entity.data.DeviceData; +import com.sipai.entity.data.PipelineEquipment; +import com.sipai.entity.data.PipelineEquipmentMpoint; +import com.sipai.entity.data.SensorData; +import com.sipai.entity.mqtt.MqttConfig; +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointES; +import com.sipai.entity.scada.MPointHistory; +import com.sipai.service.data.PipelineEquipmentMpointService; +import com.sipai.service.data.PipelineEquipmentService; +import com.sipai.service.mqtt.MqttConfigService; +import com.sipai.service.scada.MPointHistoryService; +import com.sipai.service.scada.MPointService; +import com.sipai.tools.AlarmType; +import com.sipai.tools.CommString; +import com.sipai.tools.CommUtil; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import org.redisson.api.RBatch; +import org.redisson.api.RMapCache; +import org.redisson.api.RedissonClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.math.BigDecimal; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; + +/** + * 鍗楁槍椤圭洰upd鎺ユ敹鏁版嵁澶勭悊 + * sj 2025-05-21 + */ +@Component +public class UDPServer implements CommandLineRunner { + + @Value("${udp.server.port}") //绔彛 + private int port; + @Value("${udp.server.enabled:true}") // 榛樿鍊间负true + private boolean enabled; + private static final int BUFFER_SIZE = 1024; + + @Autowired + private PipelineEquipmentService pipelineEquipmentService; + @Autowired + private PipelineEquipmentMpointService pipelineEquipmentMpointService; + @Autowired + private MPointService mPointService; + @Autowired + private MPointHistoryService mPointHistoryService; + @Autowired + private MqttConfigService mqttConfigService; + + //缂撳瓨鐐逛綅 + private static final Map dataCache = new ConcurrentHashMap<>(); + + @Override + public void run(String... args) throws Exception { + + if (!enabled) { + System.out.println("UDP鏈嶅姟鏈惎鐢"); + return; + } + + try (DatagramSocket socket = new DatagramSocket(port)) { + System.out.println("UDP鏈嶅姟绔惎鍔紝鐩戝惉绔彛: " + port); + byte[] buffer = new byte[BUFFER_SIZE]; + DatagramPacket packet = new DatagramPacket(buffer, buffer.length); + while (true) { + socket.receive(packet); +// System.out.println(CommUtil.nowDate() + "======鏀跺埌鏉ヨ嚜 " + packet.getAddress() + ":" + packet.getPort() + " 鐨勬暟鎹"); + + // 鍙戦佸簲绛 + String response = "@222\r\n"; + byte[] responseData = response.getBytes(StandardCharsets.UTF_8); + DatagramPacket responsePacket = new DatagramPacket( + responseData, responseData.length, + packet.getAddress(), packet.getPort()); + socket.send(responsePacket); + + // 瑙f瀽鏁版嵁鍖 + byte[] receivedData = new byte[packet.getLength()]; + System.arraycopy(packet.getData(), 0, receivedData, 0, packet.getLength()); + // 鎵撳嵃鍘熷瀛楄妭鏁扮粍锛堝崄鍏繘鍒舵牸寮忥級 +// System.out.println("鍘熷鏁版嵁鍖咃紙鍗佸叚杩涘埗锛: " + bytesToHex(receivedData)); + + DeviceData data = parseDeviceData(Unpooled.wrappedBuffer(receivedData)); + if (data != null) { + String jsonData = CommUtil.toJson(data); + JSONObject jsonObject = JSON.parseObject(jsonData); + System.out.println("绔欏彿鏀跺埌鏁版嵁锛" + jsonObject.get("stationId")+"锛"+jsonObject.get("startTime")); + JSONArray jsonArray = JSONArray.parseArray(jsonObject.get("sensorDataList").toString()); + if (jsonArray != null && !jsonArray.isEmpty()) { + processSensorData(jsonObject, jsonArray, bytesToHex(receivedData)); + } + } + } + } catch (IOException e) { + Logger logger = LoggerFactory.getLogger(UDPServer.class); + logger.error("UDP鏈嶅姟绔惎鍔ㄥ紓甯", e); + e.printStackTrace(); + } + } + + //姣忔鏀跺埌鐨勬姤鏂囧瓨鍒癉鐩樹笅 - 鐢ㄤ簬璋冭瘯 + private void logs(String type, String bytes, String path) { + try { + // 鑾峰彇褰撳墠鏃堕棿 + LocalDateTime now = LocalDateTime.now(); + + // 瀹氫箟鏂囦欢鍚嶏紙淇濇寔鍘熸潵鐨勬牸寮忥級 + String fileName = DateTimeFormatter + .ofPattern("yyyyMMdd_HHmmss") + .format(now) + "_" + type + ".txt"; + + // 瀹氫箟鏂囦欢璺緞锛圖:/data_logs/骞-鏈-鏃/鑷畾涔夎矾寰/锛 + String dateDir = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(now); + Path dirPath = Paths.get("D:/data_logs_new/" + dateDir + "/" + path + "/"); + + if (!Files.exists(dirPath)) { + Files.createDirectories(dirPath); // 濡傛灉鐩綍涓嶅瓨鍦紝鍒欏垱寤 + } + + Path filePath = dirPath.resolve(fileName); // 瀹屾暣璺緞 + Files.write(filePath, bytes.getBytes()); // 鍐欏叆鍐呭鍒版枃浠 + } catch (IOException e) { + e.printStackTrace(); + } + } + + //鍒嗗彂鍒板悇涓笟鍔″鐞 + private void processSensorData(JSONObject jsonObject, JSONArray jsonArray, String bytes) { + String stationId = jsonObject.get("stationId").toString(); + switch (stationId.charAt(1)) { + case '1'://浜曠洊 + logs(stationId, bytes, "jinggai"); + processManholeCoverData(jsonObject, jsonArray); + break; + case '2'://娴侀噺璁 + logs(stationId, bytes, "liuliang"); + processFlowMeterData(jsonObject, jsonArray); + break; + case '3'://娑蹭綅璁 + logs(stationId, bytes, "yewei"); + processLevelMeterData(jsonObject, jsonArray); + break; + case '4'://鐢靛鐜 + logs(stationId, bytes, "diandao"); + processConductivityMeterData(jsonObject, jsonArray); + break; + case '5'://闆ㄩ噺璁 + logs(stationId, bytes, "yuliang"); + processRainGaugeData(jsonObject, jsonArray); + break; + case '6'://鍐呮稘鐩戞祴 + logs(stationId, bytes, "neilao"); + processWaterloggingMonitoringData(jsonObject, jsonArray); + break; + default: + System.out.println("鏈煡璁惧绫诲瀷"); + } + } + + // 浜曠洊澶勭悊閫昏緫 + private void processManholeCoverData(JSONObject jsonObject, JSONArray jsonArray) { +// System.out.println("寮濮嬪鐞嗕簳鐩栨暟鎹=============================================="); + int dataCount = jsonObject.getIntValue("dataCount"); + String startTimeStr = jsonObject.getString("startTime"); + int intervalMinutes = jsonObject.getIntValue("intervalMinutes"); + String stationId = jsonObject.getString("stationId"); + double batteryVoltage = jsonObject.getDouble("batteryVoltage"); // 鑾峰彇鐢垫睜鐢靛帇 + +// System.out.println("鏁版嵁涓暟锛" + dataCount); +// System.out.println("寮濮嬫椂闂达細" + startTimeStr); +// System.out.println("闂撮殧鍒嗛挓锛" + intervalMinutes); + + //鍗曠嫭澶勭悊鐢靛帇 + String channelName = stationId + "_V1"; + String mpcode = getMpcodeFromCacheOrDB(stationId, channelName, "V1"); + if (!mpcode.equals("鏈厤缃")) { + //鎺ㄩ乲afka + mPointService.sendKafka4UDP("",mpcode, batteryVoltage, startTimeStr, 0, 1); + //鎺ㄩ乵qtt + JSONArray jsonArray_mqtt = new JSONArray(); + JSONObject jsonObject_mqtt = new JSONObject(); + jsonObject_mqtt.put("mpcode", mpcode); + jsonObject_mqtt.put("value", batteryVoltage); + jsonObject_mqtt.put("time", startTimeStr); + jsonArray_mqtt.add(jsonObject_mqtt); + mqttConfigService.doSendView(jsonArray_mqtt,CommString.Mqtt_Topic_DATA); + } + + // 鐢熸垚鏃堕棿鐐瑰簭鍒 + List timePoints = generateTimePoints(startTimeStr, dataCount, intervalMinutes); + + // 澶勭悊妯℃嫙閲忔暟鎹 (type=4) +// System.out.println("\n妯℃嫙閲忔暟鎹:"); + Map analogMappings = new HashMap<>(); + analogMappings.put(1, "A1"); // 淇″彿寮哄害 + analogMappings.put(2, "A2"); // 鍩虹珯搴忓彿 + analogMappings.put(3, "A3"); // 浜曠洊瑙掑害 + analogMappings.put(4, "A4"); // 鐢甸樆鍊1 + analogMappings.put(5, "A5"); // 鐢甸樆鍊2 + processSensorData(stationId, jsonArray, 4, analogMappings, "analogValues", timePoints); + + // 鍒涘缓鏂扮殑JSONArray鏉ュ瓨鍌ㄥ鐞嗗悗鐨勬姤璀︽暟鎹 + JSONArray processedAlarmData = new JSONArray(); + + // 澶勭悊鎶ヨ閲忔暟鎹 (type=5) +// System.out.println("\n鎶ヨ閲忔暟鎹:"); + for (Object obj : jsonArray) { + JSONObject sensorData = (JSONObject) obj; + if (sensorData.getIntValue("type") == 5) { + int qValue = sensorData.getIntValue("qValue"); + + // 鎻愬彇鍚勬姤璀︿綅鐘舵(0/1) + int voltageAlarm = (qValue & 0x0001) != 0 ? 1 : 0; // Q10 + int waterAlarm = (qValue & 0x0002) != 0 ? 1 : 0; // Q11 + int coverAlarm = (qValue & 0x0004) != 0 ? 1 : 0; // Q12 + + // 涓烘瘡涓姤璀︿綅鍒涘缓鍗曠嫭鐨勬暟鎹璞 + JSONObject voltageAlarmData = new JSONObject(); + voltageAlarmData.put("type", 5); + voltageAlarmData.put("channel", 0); // Q10瀵瑰簲channel 0 + voltageAlarmData.put("qValues", Collections.nCopies(dataCount, voltageAlarm)); + + JSONObject waterAlarmData = new JSONObject(); + waterAlarmData.put("type", 5); + waterAlarmData.put("channel", 1); // Q11瀵瑰簲channel 1 + waterAlarmData.put("qValues", Collections.nCopies(dataCount, waterAlarm)); + + JSONObject coverAlarmData = new JSONObject(); + coverAlarmData.put("type", 5); + coverAlarmData.put("channel", 2); // Q12瀵瑰簲channel 2 + coverAlarmData.put("qValues", Collections.nCopies(dataCount, coverAlarm)); + + // 娣诲姞鍒板鐞嗗悗鐨勬姤璀︽暟鎹暟缁 + processedAlarmData.add(voltageAlarmData); + processedAlarmData.add(waterAlarmData); + processedAlarmData.add(coverAlarmData); + } else { + // 闈炴姤璀︽暟鎹洿鎺ヤ繚鐣 + processedAlarmData.add(sensorData); + } + } + + // 澶勭悊鎶ヨ鏁版嵁瀛樺偍 + Map alarmMappings = new HashMap<>(); + alarmMappings.put(0, "Q10"); // 鐢靛帇鎶ヨ + alarmMappings.put(1, "Q11"); // 姘存蹈鎶ヨ + alarmMappings.put(2, "Q12"); // 寮鐩栨姤璀 + processSensorData(stationId, processedAlarmData, 5, alarmMappings, "qValues", timePoints); + } + + // 娴侀噺璁″鐞嗛昏緫 + private void processFlowMeterData(JSONObject jsonObject, JSONArray jsonArray) { +// System.out.println("寮濮嬪鐞嗘祦閲忚鏁版嵁=============================================="); + int dataCount = jsonObject.getIntValue("dataCount"); + String startTimeStr = jsonObject.getString("startTime"); + int intervalMinutes = jsonObject.getIntValue("intervalMinutes"); + String stationId = jsonObject.getString("stationId"); + +// System.out.println("鏁版嵁涓暟锛" + dataCount); +// System.out.println("寮濮嬫椂闂达細" + startTimeStr); +// System.out.println("闂撮殧鍒嗛挓锛" + intervalMinutes); + + // 鐢熸垚鏃堕棿鐐瑰簭鍒 + List timePoints = generateTimePoints(startTimeStr, dataCount, intervalMinutes); + + // 澶勭悊鑴夊啿閲忔暟鎹 (type=1) +// System.out.println("\n鑴夊啿閲忔暟鎹:"); + Map pulseMappings = new HashMap<>(); + pulseMappings.put(1, "P1"); + pulseMappings.put(2, "P2"); + pulseMappings.put(3, "P3"); + processSensorData(stationId, jsonArray, 1, pulseMappings, "accumulatedFlows", timePoints); + + // 澶勭悊妯℃嫙閲忔暟鎹 (type=4) +// System.out.println("\n妯℃嫙閲忔暟鎹:"); + Map analogMappings = new HashMap<>(); + analogMappings.put(1, "A1"); + analogMappings.put(2, "A2"); + analogMappings.put(4, "A4"); + analogMappings.put(7, "A7"); + analogMappings.put(8, "A8"); + processSensorData(stationId, jsonArray, 4, analogMappings, "analogValues", timePoints); + } + + // 娑蹭綅璁″鐞嗛昏緫 + private void processLevelMeterData(JSONObject jsonObject, JSONArray jsonArray) { +// System.out.println("寮濮嬪鐞嗘恫浣嶈鏁版嵁=============================================="); + int dataCount = jsonObject.getIntValue("dataCount"); + String startTimeStr = jsonObject.getString("startTime"); + int intervalMinutes = jsonObject.getIntValue("intervalMinutes"); + String stationId = jsonObject.getString("stationId"); + +// System.out.println("鏁版嵁涓暟锛" + dataCount); +// System.out.println("寮濮嬫椂闂达細" + startTimeStr); +// System.out.println("闂撮殧鍒嗛挓锛" + intervalMinutes); + + // 鐢熸垚鏃堕棿鐐瑰簭鍒 + List timePoints = generateTimePoints(startTimeStr, dataCount, intervalMinutes); + + // 澶勭悊妯℃嫙閲忔暟鎹 (type=4) +// System.out.println("\n娑蹭綅璁℃ā鎷熼噺鏁版嵁:"); + Map analogMappings = new HashMap<>(); + analogMappings.put(1, "A1"); // 淇″彿鎺ユ敹鍔熺巼(dBm) + analogMappings.put(2, "A2"); // 淇″櫔姣 + analogMappings.put(3, "A3"); // 灏忓尯ID + analogMappings.put(4, "A4"); // 鍊炬枩瑙掑害(掳) + analogMappings.put(5, "A5"); // 鐢垫睜鐢靛帇(V) + analogMappings.put(6, "A6"); // 鎶曞叆寮忔恫浣(m) + analogMappings.put(8, "A8"); // 闆疯揪姘翠綅(m) + analogMappings.put(10, "A10"); // 缁煎悎娑蹭綅(m) + + processSensorData(stationId, jsonArray, 4, analogMappings, "analogValues", timePoints); + } + + // 鐢靛鐜囦华澶勭悊閫昏緫 + private void processConductivityMeterData(JSONObject jsonObject, JSONArray jsonArray) { +// System.out.println("寮濮嬪鐞嗙數瀵肩巼浠暟鎹=============================================="); + int dataCount = jsonObject.getIntValue("dataCount"); + String startTimeStr = jsonObject.getString("startTime"); + int intervalMinutes = jsonObject.getIntValue("intervalMinutes"); + String stationId = jsonObject.getString("stationId"); + double batteryVoltage = jsonObject.getDouble("batteryVoltage"); +// System.out.println("鏁版嵁涓暟锛" + dataCount); +// System.out.println("寮濮嬫椂闂达細" + startTimeStr); +// System.out.println("闂撮殧鍒嗛挓锛" + intervalMinutes); + + //鍗曠嫭澶勭悊鐢靛帇 + String channelName = stationId + "_V"; + String mpcode = getMpcodeFromCacheOrDB(stationId, channelName, "V"); + if (!mpcode.equals("鏈厤缃")) { + mPointService.sendKafka4UDP("",mpcode, batteryVoltage, startTimeStr, 0, 1); + //鎺ㄩ乵qtt + JSONArray jsonArray_mqtt = new JSONArray(); + JSONObject jsonObject_mqtt = new JSONObject(); + jsonObject_mqtt.put("mpcode", mpcode); + jsonObject_mqtt.put("value", batteryVoltage); + jsonObject_mqtt.put("time", startTimeStr); + jsonArray_mqtt.add(jsonObject_mqtt); + mqttConfigService.doSendView(jsonArray_mqtt,CommString.Mqtt_Topic_DATA); + } + + // 鐢熸垚鏃堕棿鐐瑰簭鍒 + List timePoints = generateTimePoints(startTimeStr, dataCount, intervalMinutes); + + // 澶勭悊妯℃嫙閲忔暟鎹 (type=4) +// System.out.println("\n鐢靛鐜囦华鏁版嵁:"); + Map analogMappings = new HashMap<>(); + analogMappings.put(7, "A7"); // 鐢靛鐜囧 + analogMappings.put(8, "A8"); // 娓╁害鍊 + processSensorData(stationId, jsonArray, 4, analogMappings, "analogValues", timePoints); + } + + // 闆ㄩ噺璁″鐞嗛昏緫 + private void processRainGaugeData(JSONObject jsonObject, JSONArray jsonArray) { +// System.out.println("寮濮嬪鐞嗛洦閲忚鏁版嵁=============================================="); + int dataCount = jsonObject.getIntValue("dataCount"); + String startTimeStr = jsonObject.getString("startTime"); + int intervalMinutes = jsonObject.getIntValue("intervalMinutes"); + String stationId = jsonObject.getString("stationId"); + +// System.out.println("鏁版嵁涓暟锛" + dataCount); +// System.out.println("寮濮嬫椂闂达細" + startTimeStr); +// System.out.println("闂撮殧鍒嗛挓锛" + intervalMinutes); + + // 鐢熸垚鏃堕棿鐐瑰簭鍒 + List timePoints = generateTimePoints(startTimeStr, dataCount, intervalMinutes); + + // 澶勭悊妯℃嫙閲忔暟鎹 (type=4) +// System.out.println("\n闆ㄩ噺璁℃暟鎹:"); + Map analogMappings = new HashMap<>(); + analogMappings.put(1, "A1"); // 闆ㄩ噺鍊 + processSensorData(stationId, jsonArray, 4, analogMappings, "analogValues", timePoints); + } + + // 鍐呮稘鐩戞祴澶勭悊閫昏緫 + private void processWaterloggingMonitoringData(JSONObject jsonObject, JSONArray jsonArray) { +// System.out.println("寮濮嬪鐞嗗唴娑濈洃娴嬫暟鎹=============================================="); + int dataCount = jsonObject.getIntValue("dataCount"); + String startTimeStr = jsonObject.getString("startTime"); + int intervalMinutes = jsonObject.getIntValue("intervalMinutes"); + String stationId = jsonObject.getString("stationId"); + +// System.out.println("鏁版嵁涓暟锛" + dataCount); +// System.out.println("寮濮嬫椂闂达細" + startTimeStr); +// System.out.println("闂撮殧鍒嗛挓锛" + intervalMinutes); + + // 鐢熸垚鏃堕棿鐐瑰簭鍒 + List timePoints = generateTimePoints(startTimeStr, dataCount, intervalMinutes); + + // 澶勭悊妯℃嫙閲忔暟鎹 (type=4) +// System.out.println("\n姘翠綅鏁版嵁:"); + Map analogMappings = new HashMap<>(); + analogMappings.put(13, "A13"); // 姘翠綅鍊(0x0D) +// analogMappings.put(14, "A14"); // 鐘舵佸(0x0D) + processSensorData(stationId, jsonArray, 4, analogMappings, "analogValues", timePoints); + + // 澶勭悊鑴夊啿閲忔暟鎹 (type=1) +// System.out.println("\n鐘舵佹暟鎹:"); + Map pulseMappings = new HashMap<>(); + pulseMappings.put(14, "P14"); // 鐘舵佸(0x0E) + processSensorData(stationId, jsonArray, 1, pulseMappings, "accumulatedFlows", timePoints); + } + + private DeviceData parseDeviceData(ByteBuf buf) { + // 鏌ユ壘璧峰绗︿綅缃 + int startIndex = -1; + for (int i = 0; i < buf.readableBytes() - 1; i++) { + if (buf.getByte(i) == (byte) 0xAB && buf.getByte(i + 1) == (byte) 0xCD) { + startIndex = i; + break; + } + } + if (startIndex == -1) { + // 娌℃壘鍒拌捣濮嬬锛屼涪寮冩墍鏈夋暟鎹 + buf.skipBytes(buf.readableBytes()); + return null; + } + // 璺宠繃璧峰绗﹀墠鐨勬墍鏈夊瓧鑺 + buf.skipBytes(startIndex); + // 鏍囪褰撳墠浣嶇疆 + buf.markReaderIndex(); + // 楠岃瘉璧峰绗 + byte b1 = buf.readByte(); + byte b2 = buf.readByte(); + if (b1 != (byte) 0xAB || b2 != (byte) 0xCD) { + buf.resetReaderIndex(); + buf.skipBytes(1); + return null; + } + // 纭繚鏈夎冻澶熸暟鎹鍙栭暱搴 + if (buf.readableBytes() < 2) { + buf.resetReaderIndex(); + return null; + } + // 璇诲彇闀垮害 + int dataLength = buf.readUnsignedShort(); + // 璁$畻瀹屾暣鍖呴暱搴 + int totalLength = 2 + 2 + dataLength + 2; // AB CD + len + data + 缁撴潫绗 + // 纭繚鏈夊畬鏁存暟鎹寘 + if (buf.readableBytes() < dataLength + 2) { + buf.resetReaderIndex(); + return null; + } + // 璇诲彇瀹屾暣鏁版嵁鍖 + ByteBuf frame = buf.readRetainedSlice(dataLength + 2); + DeviceData data = new DeviceData(); + // 1. 鍩虹淇℃伅瑙f瀽 + data.setStationId(frame.readUnsignedShort()); + byte[] timeBytes = new byte[5]; + frame.readBytes(timeBytes); + data.setStartTime(parseBcdTime(timeBytes)); + data.setDataCount(frame.readUnsignedByte()); + data.setIntervalMinutes(frame.readUnsignedByte()); + data.setBatteryVoltage(frame.readUnsignedShort() / 100.0f); + data.setUploadCount(frame.readUnsignedShort()); + //璁惧淇℃伅澶勭悊 + int infoLength = frame.readUnsignedByte(); + // 璇诲彇瀹為檯璁惧淇℃伅锛堝浐瀹20瀛楄妭锛 + byte[] deviceInfo = new byte[20]; + frame.readBytes(deviceInfo); + data.setDeviceInfo(new String(deviceInfo, StandardCharsets.US_ASCII).trim()); + int bytesToSkip = 8; // 璺宠繃棰勭暀鐨8瀛楄妭 + frame.skipBytes(bytesToSkip); + //瑙f瀽浼犳劅鍣ㄦ暟鎹 + List sensorDataList = new ArrayList<>(); + while (frame.readableBytes() >= 2) { + int type = frame.readUnsignedByte(); + int channel = frame.readUnsignedByte(); +// System.out.printf("Parsing sensor: type=%02X, channel=%02X at pos=%d%n", type, channel, frame.readerIndex() - 2); + SensorData sensor = new SensorData(); + sensor.setType(type); + sensor.setChannel(channel); + try { + switch (type) { + case 0x01: // 鑴夊啿閲 + long yesterdayFlow = frame.readUnsignedIntLE(); + sensor.setYesterdayFlow(yesterdayFlow); + List flows = new ArrayList<>(); + for (int j = 0; j < data.getDataCount(); j++) { + if (frame.readableBytes() < 4) { + break; + } + flows.add(frame.readUnsignedIntLE()); + } + sensor.setAccumulatedFlows(flows); + break; + + case 0x02: // 寮鍏抽噺/鎶ヨ閲 + // 姣忎釜閫氶亾鍙鍙1瀛楄妭鐘舵佸 + if (frame.readableBytes() >= 1) { + int status = frame.readUnsignedByte(); + List statusList = new ArrayList<>(); + statusList.add(status); + sensor.setDescription("寮鍏抽噺鐘舵"); + } + break; + case 0x41: // 涓嶇煡閬撳暐绫诲瀷 + // 涓嶇煡閬撳暐绫诲瀷 + if (frame.readableBytes() >= 1) { + + } + break; + + case 0x42: // 涓嶇煡閬撳暐绫诲瀷 + // 涓嶇煡閬撳暐绫诲瀷 + if (frame.readableBytes() >= 1) { + + } + break; + + case 0x43: // 涓嶇煡閬撳暐绫诲瀷 + // 涓嶇煡閬撳暐绫诲瀷 + if (frame.readableBytes() >= 1) { + + } + break; + + case 0x04: // 妯℃嫙閲 + List analogs = new ArrayList<>(); + for (int j = 0; j < data.getDataCount(); j++) { + if (frame.readableBytes() < 4) { + break; + } + float value = 0.0f; + try { + // 鏅鸿兘浜曠洊 + if (String.valueOf(data.getStationId()).charAt(1) == '1') { + // 灏濊瘯涓嶅悓鐨勮В鏋愭柟寮忥紝鏍规嵁閫氶亾绫诲瀷閫夋嫨鍚堥傜殑瑙f瀽鏂规硶 + switch (channel) { + case 1: // A1 淇″彿寮哄害 (dBm) + byte signalByte = frame.readByte(); + frame.skipBytes(3); // 璺宠繃鍓╀綑3瀛楄妭 + value = (float) signalByte; + break; + case 2: // A2 鍩虹珯搴忓彿 + value = (float) frame.readUnsignedIntLE(); + break; + case 3: // A3 浜曠洊瑙掑害 + int angleInt = frame.readInt(); // 浣跨敤readInt()璇诲彇澶х搴 + value = Float.intBitsToFloat(angleInt); + // 楠岃瘉鏄惁涓哄悎鐞嗙殑瑙掑害鍊 + if (value < 0 || value > 360) { + frame.resetReaderIndex(); + frame.skipBytes(j * 4); + int angleFixed = frame.readUnsignedShort(); + frame.skipBytes(2); + value = (float) angleFixed / 100.0f; + } + break; + case 4: // A4 鐢甸樆鍊1 + case 5: // A5 鐢甸樆鍊2 + case 7: // + case 8: // + int resistanceInt1 = frame.readInt(); // 浣跨敤readInt()璇诲彇澶х搴 + value = Float.intBitsToFloat(resistanceInt1); + break; + default: // 鍏朵粬妯℃嫙閲忥紝榛樿浣跨敤娴偣鏁拌В鏋 + int intValue = frame.readIntLE(); + value = Float.intBitsToFloat(intValue); + break; + } + } + // 娴侀噺璁 + if (String.valueOf(data.getStationId()).charAt(1) == '2') { + // 缁熶竴浣跨敤澶х搴忚鍙朓EEE754娴偣鏁 + int intValue = frame.readInt(); // 鏀逛负readInt()鑰屼笉鏄痳eadIntLE() + value = Float.intBitsToFloat(intValue); + // 淇濈暀3浣嶅皬鏁 + value = (float) (Math.round(value * 1000) / 1000.0); + // 鏍煎紡鍖栦负3浣嶅皬鏁帮紝涓嶈冻琛ラ浂 + String formattedValue = String.format("%.3f", value); // 渚嬪 7.4 鈫 "7.400" + value = Float.parseFloat(formattedValue); // 杞洖float锛堝彲閫夛級 + } + // 娑蹭綅璁 + if (String.valueOf(data.getStationId()).charAt(1) == '3') { + // 缁熶竴浣跨敤澶х搴忚鍙朓EEE754娴偣鏁 + int intValue = frame.readInt(); // 鏀逛负readInt()鑰屼笉鏄痳eadIntLE() + value = Float.intBitsToFloat(intValue); + // 淇濈暀3浣嶅皬鏁 + value = (float) (Math.round(value * 1000) / 1000.0); + // 鏍煎紡鍖栦负3浣嶅皬鏁帮紝涓嶈冻琛ラ浂 + String formattedValue = String.format("%.3f", value); // 渚嬪 7.4 鈫 "7.400" + value = Float.parseFloat(formattedValue); // 杞洖float锛堝彲閫夛級 + } + // 鐢靛鐜 + /*if (String.valueOf(data.getStationId()).charAt(1) == '4') { + int intValue = frame.readIntLE(); + value = Float.intBitsToFloat(intValue); + // 淇濈暀2浣嶅皬鏁 + value = (float) (Math.round(value * 100) / 100.0); + }*/ + // 鐢靛鐜 + if (String.valueOf(data.getStationId()).charAt(1) == '4') { + // 鏀逛负浣跨敤澶х搴忚鍙 + int intValue = frame.readInt(); // 鏀逛负readInt()鑰屼笉鏄痳eadIntLE() + value = Float.intBitsToFloat(intValue); + // 淇濈暀2浣嶅皬鏁 + value = (float) (Math.round(value * 100) / 100.0); + } + // 闆ㄩ噺璁 + if (String.valueOf(data.getStationId()).charAt(1) == '5') { + // 鏀逛负浣跨敤澶х搴忚鍙 + int intValue = frame.readInt(); // 鏀逛负readInt()鑰屼笉鏄痳eadIntLE() + value = Float.intBitsToFloat(intValue); + // 淇濈暀2浣嶅皬鏁 + value = (float) (Math.round(value * 100) / 100.0); + } + // 鍐呮稘鐩戞祴璁惧 + if (String.valueOf(data.getStationId()).charAt(1) == '6') { + // 鏀逛负浣跨敤澶х搴忚鍙 + int intValue = frame.readInt(); // 鏀逛负readInt()鑰屼笉鏄痳eadIntLE() + value = Float.intBitsToFloat(intValue); + // 淇濈暀2浣嶅皬鏁 + value = (float) (Math.round(value * 100) / 100.0); + } + // 杩囨护寮傚父鍊 + if (Float.isNaN(value) || Float.isInfinite(value) || value < -1000000.0f || value > 1000000.0f) { + value = 0.0f; + } + } catch (Exception e) { + frame.skipBytes(4); + value = 0.0f; + } + analogs.add(value); + } + sensor.setAnalogValues(analogs); + // 鏅鸿兘浜曠洊鐗瑰畾閫氶亾澶勭悊 + if (String.valueOf(data.getStationId()).charAt(1) == '1') { + switch (channel) { + case 1: // A1淇″彿寮哄害 + sensor.setDescription("A1淇″彿寮哄害"); + break; + case 2: // A2鍩虹珯搴忓彿 + sensor.setDescription("A2鍩虹珯搴忓彿"); + break; + case 3: // A3浜曠洊瑙掑害 + sensor.setDescription("A3浜曠洊瑙掑害"); + break; + case 4: // A4鐢甸樆鍊1 + sensor.setDescription("A4鐢甸樆鍊1"); + break; + case 5: // A5鐢甸樆鍊2 + sensor.setDescription("A5鐢甸樆鍊2"); + break; + } + } + break; + case 0x05: // Q閫氶亾鏁版嵁锛堟暟瀛楅噺杈撳嚭锛 + int qValue = frame.readUnsignedShort(); + // 鏍¢獙 qValue 鑼冨洿锛0x0000 ~ 0xFFFF锛 + if (qValue < 0 || qValue > 0xFFFF) { + throw new IllegalArgumentException("Invalid Q channel value: " + qValue); + } + + // 瑙f瀽鍚勬姤璀︿綅鐘舵 + Map alarmStatus = new EnumMap<>(AlarmType.class); + for (AlarmType alarm : AlarmType.values()) { + alarmStatus.put(alarm, alarm.isTriggered(qValue)); + } + + // 鏋勫缓鎶ヨ鎻忚堪 + StringBuilder alarmDesc = new StringBuilder("Q閫氶亾鐘舵: "); + for (AlarmType alarm : AlarmType.values()) { + alarmDesc.append(alarm.getDescription()) + .append(alarmStatus.get(alarm) ? "瑙﹀彂" : "姝e父") + .append(", "); + } + sensor.setDescription(alarmDesc.toString().replaceAll(", $", "")); + + // 瀛樺偍鍘熷鎶ヨ鍊硷紙鍙夛級 + sensor.setqValue(qValue); + sensor.setAlarmStatus(alarmStatus); + + // 璁板綍鎶ヨ鏃ュ織 + if (alarmStatus.get(AlarmType.COVER_ALARM)) { + LoggerFactory.getLogger(UDPServer.class) + .warn("浜曠洊寮鐩栨姤璀﹁Е鍙戯紒绔欏彿: {}, Q鍊: {}", data.getStationId(), qValue); + } + break; + default: + int bytesToSkip2 = data.getDataCount() * 4; + if (frame.readableBytes() >= bytesToSkip2) { + frame.skipBytes(bytesToSkip2); + } else { +// System.err.printf("Not enough readable bytes to skip %d bytes. Current readable bytes: %d%n", +// bytesToSkip2, frame.readableBytes()); + // 鍙夋嫨鎶涘嚭寮傚父銆佽褰曟棩蹇楁垨鑰呭仛鍏朵粬澶勭悊 + } + continue; + } + sensorDataList.add(sensor); + } catch (Exception e) { + System.err.println("Error parsing sensor"); + e.printStackTrace(); + break; + } + // 妫鏌ユ槸鍚﹀埌杈剧粨鏉熺 + if (frame.readableBytes() >= 2 && frame.getByte(frame.readerIndex()) == 0x0D && frame.getByte(frame.readerIndex() + 1) == 0x0A) { + // 璺宠繃缁撴潫绗 + frame.skipBytes(2); + break; + } + } + data.setSensorDataList(sensorDataList); + return data; + } + + private String parseBcdTime(byte[] bytes) { + // bytes: 19 05 29 10 47 + int year = 2000 + ((bytes[0] >> 4) & 0xF) * 10 + (bytes[0] & 0xF); + int month = ((bytes[1] >> 4) & 0xF) * 10 + (bytes[1] & 0xF); + int day = ((bytes[2] >> 4) & 0xF) * 10 + (bytes[2] & 0xF); + int hour = ((bytes[3] >> 4) & 0xF) * 10 + (bytes[3] & 0xF); + int minute = ((bytes[4] >> 4) & 0xF) * 10 + (bytes[4] & 0xF); + + return String.format("%04d-%02d-%02d %02d:%02d", year, month, day, hour, minute); + } + + private static String bytesToHex(byte[] bytes) { + StringBuilder sb = new StringBuilder(); + for (byte b : bytes) { + sb.append(String.format("%02X ", b)); + } + return sb.toString(); + } + + + /** + * 閫氱敤浼犳劅鍣ㄦ暟鎹鐞嗘柟娉 + * + * @param stationId 绔欑偣id 鐢ㄤ簬redis缁勫悎key + * @param jsonArray 浼犳劅鍣ㄦ暟鎹暟缁 + * @param type 瑕佸鐞嗙殑鏁版嵁绫诲瀷 + * @param channelMappings 閫氶亾鏄犲皠 + * @param valueFieldName 鍊煎瓧娈靛悕 + * @param timePoints 鏃堕棿鐐瑰垪琛 + */ + private void processSensorData(String stationId, JSONArray jsonArray, int type, + Map channelMappings, + String valueFieldName, + List timePoints) { + try { + for (Object obj : jsonArray) { + JSONObject sensorData = (JSONObject) obj; + if (sensorData.getIntValue("type") == type) { + int channel = sensorData.getIntValue("channel"); + if (channelMappings.containsKey(channel)) { + String channelName = stationId + "_" + channelMappings.get(channel); + JSONArray values = sensorData.getJSONArray(valueFieldName); + + if (values != null && !values.isEmpty()) { + //鑾峰彇mpcode (浼樺厛浠庣紦瀛樻嬁) + String mpcode = getMpcodeFromCacheOrDB(stationId, channelName, channelMappings.get(channel)); + if (!mpcode.equals("鏈厤缃")) { + JSONObject dataCache = new JSONObject(); + + JSONArray jsonArray_mqtt = new JSONArray(); + for (int i = 0; i < values.size(); i++) { + String timePoint = timePoints.get(i); + timePoint = timePoint.length() == 16 ? timePoint + ":00" : timePoint; + Object value = values.get(i); + dataCache.put(timePoint, value); + //鎺ㄩ佽嚦kafka + mPointService.sendKafka4UDP("",mpcode, value, timePoint, i, values.size()); + + //娣诲姞鍒癿qtt鏁扮粍 + JSONObject jsonObject_mqtt = new JSONObject(); + jsonObject_mqtt.put("mpcode", mpcode); + jsonObject_mqtt.put("value", value); + jsonObject_mqtt.put("time", timePoint); + jsonArray_mqtt.add(jsonObject_mqtt); + } + + //鎵归噺鎺ㄩ乵qtt + mqttConfigService.doSendView(jsonArray_mqtt, CommString.Mqtt_Topic_DATA); + } else { + System.out.println("绔欑偣锛" + stationId + " 鏍囪瘑锛" + channelMappings.get(channel) + " 鏈厤缃"); + } + } + } + } + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + + // 浠庣紦瀛樻垨鏁版嵁搴撹幏鍙杕pcode + private String getMpcodeFromCacheOrDB(String stationId, String channelName, String tag) { + // 鍏堟煡缂撳瓨 + String mpcode = dataCache.get(channelName); + if (mpcode != null) { + return mpcode; + } + + // 缂撳瓨娌℃湁鍒欐煡璇㈡暟鎹簱 + List equipmentList = pipelineEquipmentService.selectListByWhere( + "where station_code = '" + stationId + "'"); + if (equipmentList != null && !equipmentList.isEmpty()) { + List mpointList = pipelineEquipmentMpointService.selectListByWhere( + "where pid = '" + equipmentList.get(0).getId() + "' and tag = '" + tag + "'"); + if (mpointList != null && !mpointList.isEmpty()) { + mpcode = mpointList.get(0).getMpcode(); + // 瀛樺叆缂撳瓨 + dataCache.put(channelName, mpcode); + return mpcode; + } + } + return "鏈厤缃"; // 鎴栨牴鎹笟鍔¢渶姹傝繑鍥為粯璁ゅ + } + + //鏃堕棿鐢熸垚鏂规硶 + private List generateTimePoints(String startTimeStr, int count, int intervalMinutes) { + List timePoints = new ArrayList<>(); + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + Date date = sdf.parse(startTimeStr); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + for (int i = 0; i < count; i++) { + timePoints.add(sdf.format(calendar.getTime())); + calendar.add(Calendar.MINUTE, intervalMinutes); + } + } catch (ParseException e) { + e.printStackTrace(); + // 濡傛灉瑙f瀽澶辫触锛屼娇鐢ㄧ畝鍗曠殑鏃堕棿鏍煎紡 + for (int i = 0; i < count; i++) { + timePoints.add(startTimeStr + " +" + (i * intervalMinutes) + "鍒嗛挓"); + } + } + return timePoints; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/controller/check/CheckServerController.java b/src/main/java/com/sipai/controller/check/CheckServerController.java new file mode 100644 index 0000000..7fedd69 --- /dev/null +++ b/src/main/java/com/sipai/controller/check/CheckServerController.java @@ -0,0 +1,75 @@ +package com.sipai.controller.check; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; + +/** + * 鏅綏绫充慨鏂 鐩戝惉鎺ュ彛 + */ +@RestController +@RequestMapping("/check") +public class CheckServerController { + + @RequestMapping("/server.do") + public String server() { + return "suc"; + } + + @RequestMapping("/testSendUdp.do") + public String testSendUdp() { + //淇敼鎴愭湇鍔$鐨処P +// String serverHost = "132.120.132.77"; +// String serverHost = "116.236.176.248"; + String serverHost = "192.168.10.18"; + int serverPort = 5006; + + //鏅鸿兘浜曠洊 +// String hexString = "ABCD004D00002505121109013C016800001F484B33352D49493B56312E313B56312E302E303600000000000000000401C25000000402000000000403429E293C040447C35000040547C3500005010004A70D0A"; + //娴侀噺浠 + String hexString = "AB CD 01 C7 00 7B 25 05 19 16 18 0A 01 02 E2 00 00 00 48 38 36 45 3B 31 2E 33 3B 31 2E 30 2E 33 35 20 20 20 20 20 00 00 00 00 00 00 00 00 01 01 00 00 00 00 00 00 00 00 01 00 00 00 03 00 00 00 05 00 00 00 07 00 00 00 09 00 00 00 0B 00 00 00 0D 00 00 00 0E 00 00 00 10 00 00 00 01 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 03 00 00 00 00 00 00 00 00 01 00 00 00 03 00 00 00 05 00 00 00 07 00 00 00 09 00 00 00 0B 00 00 00 0D 00 00 00 0E 00 00 00 10 00 00 00 04 01 40 EC 62 C6 40 EC 62 C6 40 EC 62 C6 40 EC 62 C6 40 EC 62 C6 40 EC D0 CD 40 48 F5 C3 40 48 F5 C3 40 48 F5 C3 40 48 F5 C3 04 02 40 EB 86 B8 40 EB 86 B8 40 EB 86 B8 40 EB 86 B8 40 EB 86 B8 40 EB F4 BF 3D FB E7 6D 3D FB E7 6D 3D FB E7 6D 3D FB E7 6D 04 03 41 F0 00 00 41 B0 00 00 41 F8 00 00 41 B8 00 00 41 B8 00 00 41 F8 00 00 41 F8 00 00 41 F8 00 00 41 F8 00 00 41 F8 00 00 04 04 41 BB 99 9A 41 BB 99 9A 41 BB 99 9A 41 BB 99 9A 41 BB 99 9A 41 BB 99 9A 41 BB 99 9A 41 BB 99 9A 41 BB 99 9A 41 BB 99 9A 04 07 42 ED 99 9A 42 ED 99 9A 42 ED 99 9A 42 ED 99 9A 42 ED 99 9A 42 ED 99 9A 42 B4 00 00 42 B4 00 00 42 B4 00 00 42 B4 00 00 04 08 3E 40 83 12 3E 40 83 12 3E 40 83 12 3E 40 83 12 3E 40 83 12 3E 40 83 12 3E 40 83 12 3E 40 83 12 3E 40 83 12 3E 40 83 12 05 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 6B 0D 0A"; + //鍘傚浼犵殑寮傚父鏁版嵁 +// String hexString = "AA AA B7 56 0E 25 06 03 10 15 08 31 02 E1 30 11 00 00 0B 47 00 00 0F 50 00 03 00 03 00 04 00 04 00 03 00 04 00 03 12 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 00 13 00 00 0B 47 00 00 0F 4C 00 03 00 03 00 04 00 04 00 03 00 04 00 03 31 00 02 00 02 00 02 00 02 00 02 00 02 00 02 00 02 32 00 08 00 08 00 08 00 08 00 08 00 08 00 08 00 08 33 04 B0 04 B0 04 B0 04 B0 04 B0 04 B0 04 B0 04 B0 34 07 9E 07 9E 07 9C 07 9D 07 99 07 99 07 9A 07 98 37 00 12 00 0A 00 0E 00 0E 00 0E 00 0E 00 0E 00 0E 38 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0D 0A"; + + hexString = hexString.replaceAll("\\s+", ""); // Remove all whitespace + byte[] data = hexStringToByteArray(hexString); + + try (DatagramSocket socket = new DatagramSocket()) { + InetAddress serverAddress = InetAddress.getByName(serverHost); + + // 鍙戦佹暟鎹寘 + DatagramPacket packet = new DatagramPacket( + data, data.length, serverAddress, serverPort); + socket.send(packet); + System.out.println("宸插彂閫佹暟鎹寘鍒版湇鍔″櫒"); + + // 鎺ユ敹鍝嶅簲 + byte[] buffer = new byte[1024]; + DatagramPacket response = new DatagramPacket(buffer, buffer.length); + socket.receive(response); + + String responseStr = new String( + response.getData(), 0, response.getLength()); + System.out.println("鏈嶅姟鍣ㄥ搷搴: " + responseStr); + + } catch (IOException e) { + e.printStackTrace(); + } + return "suc"; + } + + // 鍗佸叚杩涘埗瀛楃涓茶浆瀛楄妭鏁扮粍鐨勬柟娉 + private static byte[] hexStringToByteArray(String s) { + int len = s.length(); + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + + Character.digit(s.charAt(i + 1), 16)); + } + return data; + } +} diff --git a/src/main/java/com/sipai/controller/data/PipeTopicMPointController.java b/src/main/java/com/sipai/controller/data/PipeTopicMPointController.java new file mode 100644 index 0000000..c22090b --- /dev/null +++ b/src/main/java/com/sipai/controller/data/PipeTopicMPointController.java @@ -0,0 +1,170 @@ +package com.sipai.controller.data; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.sipai.entity.base.Result; +import com.sipai.entity.common.PageData; +import com.sipai.entity.data.PipeTopicMpoint; +import com.sipai.entity.data.PipelineEquipmentMpoint; +import com.sipai.entity.scada.MPoint; +import com.sipai.service.data.PipeTopicMpointService; +import com.sipai.service.scada.MPointService; +import com.sipai.tools.CommUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 绠$綉涓撻椤电偣浣嶆帶鍒跺櫒 + */ +@RestController +@RequestMapping("/pipeTopicMPoint") +public class PipeTopicMPointController { + + @Autowired + private PipeTopicMpointService pipeTopicMpointService; + @Autowired + private MPointService mPointService; + + /** + * 鏍规嵁涓婚敭鏌ヨ鐐逛綅淇℃伅 + */ + @GetMapping("/selectById.do") + public Result selectByPrimaryKey(@RequestParam Integer id) { + PipeTopicMpoint mpoint = pipeTopicMpointService.selectByPrimaryKey(id); + if (mpoint != null) { + return Result.success(mpoint); + } else { + return Result.failed("鐐逛綅涓嶅瓨鍦"); + } + } + + /** + * 鏂板鐐逛綅淇℃伅 + */ + @PostMapping("/save.do") + public String save(@ModelAttribute PipeTopicMpoint mpoint) { + int res = pipeTopicMpointService.insert(mpoint); + if (res > 0) { + return CommUtil.toJson(Result.success(mpoint.getId())); + } else { + return CommUtil.toJson(Result.failed("鏂板澶辫触")); + } + } + + /** + * 鏇存柊鐐逛綅淇℃伅 + */ + @PostMapping("/update.do") + public String update(@ModelAttribute PipeTopicMpoint mpoint) { + boolean res = pipeTopicMpointService.update(mpoint); + return CommUtil.toJson(res ? Result.success(1) : Result.failed("鏇存柊澶辫触")); + } + + /** + * 鏍规嵁涓婚敭鍒犻櫎鐐逛綅 + */ + @PostMapping("/deleteById.do") + public String deleteById(@RequestParam Integer id) { + boolean res = pipeTopicMpointService.delete(id); + return CommUtil.toJson(res ? Result.success(1) : Result.failed("鍒犻櫎澶辫触")); + } + + /** + * 鎵归噺鍒犻櫎鐐逛綅 + */ + @PostMapping("/deleteBatch.do") + public String deleteBatch(@RequestBody List idList) { + boolean res = pipeTopicMpointService.deleteBatch(idList); + return CommUtil.toJson(res ? Result.success(1) : Result.failed("鎵归噺鍒犻櫎澶辫触")); + } + + /** + * 鍒嗛〉鏌ヨ鐐逛綅鍒楄〃 + */ + @GetMapping("/list.do") + public PageData selectList( + @RequestParam(defaultValue = "1") Integer pageNum, + @RequestParam(defaultValue = "10") Integer pageSize, + @RequestParam(required = false) String type) { + + PageHelper.startPage(pageNum, pageSize); + String where = "where 1=1"; + if (type != null && !type.isEmpty()) { + where += " AND type = '" + type + "'"; + } + + List list = pipeTopicMpointService.selectListByWhere(where); + PageInfo pageInfo = new PageInfo<>(list); + return new PageData<>(pageInfo); + } + + /** + * 鑾峰彇 鈥滅缃戜笓棰橀〉鈥 鏁版嵁 + * + * @param type + * @return + */ + @GetMapping("/getData.do") + public Result getData(@RequestParam(required = false) String type) { + String where = "where 1=1"; + if (type != null && !type.isEmpty()) { + where += " AND type = '" + type + "'"; + } + + // 瀹氫箟 type 鍚箟鐨勬槧灏勫叧绯 + Map typeMap = new HashMap<>(); + typeMap.put("0", "姹℃按鍘"); + typeMap.put("1", "鏂板煄鍗楀ぇ閬撴薄姘存车绔"); + typeMap.put("2", "绁炲啘瑗垮ぇ閬撻洦姘存车绔"); + typeMap.put("3", "鏂扮ズ鍛ㄥぇ閬撻洦姘存车绔"); + + JSONArray jsonArray = new JSONArray(); + try { + List list = pipeTopicMpointService.selectListByWhere(where); + if (list != null && list.size() > 0) { + for (int i = 0; i < list.size(); i++) { + PipeTopicMpoint item = list.get(i); + JSONObject jsonObject = new JSONObject(); + + // 娣诲姞 type 淇℃伅锛堝鏋 type 瀛樺湪锛 + if (type != null && !type.isEmpty()) { + jsonObject.put("type", type); + jsonObject.put("typeName", typeMap.getOrDefault(type, "鏈煡绫诲瀷")); + } + + if (item.getIsConstant() == 1) { // 甯搁噺 + if (item.getPointName().equals("璋冨害妯″紡")) { + jsonObject.put("parmvalue", "杈撻佹ā寮-甯歌杈撻"); + } else { + jsonObject.put("parmvalue", item.getConstantValue()); + } + jsonObject.put("mpcode", item.getPointCode()); + jsonObject.put("mpname", item.getPointName()); + jsonObject.put("measuredt", CommUtil.nowDate()); + jsonObject.put("unit", ""); + } else { // 璇荤偣浣 + MPoint mPoint = mPointService.selectById("",item.getPointCode()); + if (mPoint != null) { + jsonObject.put("mpcode", mPoint.getMpointcode()); + jsonObject.put("mpname", mPoint.getParmname()); + jsonObject.put("parmvalue", mPoint.getParmvalue() != null ? mPoint.getParmvalue() : 0); + jsonObject.put("measuredt", mPoint.getMeasuredt()); + jsonObject.put("unit", mPoint.getUnit() != null ? mPoint.getUnit() : ""); + } + } + jsonArray.add(jsonObject); + } + } + return Result.success(jsonArray); + } catch (Exception e) { + return Result.failed("鏃犳暟鎹"); + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/controller/data/PipelineEquipmentController.java b/src/main/java/com/sipai/controller/data/PipelineEquipmentController.java new file mode 100644 index 0000000..2f058c8 --- /dev/null +++ b/src/main/java/com/sipai/controller/data/PipelineEquipmentController.java @@ -0,0 +1,271 @@ +package com.sipai.controller.data; + +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.sipai.entity.base.Result; +import com.sipai.entity.common.PageData; +import com.sipai.entity.data.PipelineEquipment; +import com.sipai.entity.data.PipelineEquipmentMpoint; +import com.sipai.entity.enums.DeviceTypeEnum; +import com.sipai.service.data.PipelineEquipmentMpointService; +import com.sipai.service.data.PipelineEquipmentService; +import com.sipai.tools.CommUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 绠$綉璁惧鍒楄〃 + */ +@RestController +@RequestMapping("/pipeline-equipment") +public class PipelineEquipmentController { + + @Autowired + private PipelineEquipmentService pipelineEquipmentService; + @Autowired + private PipelineEquipmentMpointService pipelineEquipmentMpointService; + + // 鏍规嵁涓婚敭鏌ヨ绠¢亾璁惧淇℃伅 + @GetMapping("/selectById.do") + public Result selectByPrimaryKey(@RequestParam(value = "id") Integer id) { + PipelineEquipment pipelineEquipment = pipelineEquipmentService.selectByPrimaryKey(id); + if(pipelineEquipment!=null){ + return Result.success(pipelineEquipment); + }else{ + return Result.failed("璁惧涓嶅瓨鍦"); + } + } + + // 鍒犻櫎鎸囧畾涓婚敭鐨勭閬撹澶囦俊鎭 + @PostMapping("/deleteById.do") + public String deleteByPrimaryKey(@RequestParam(value = "id") Integer id) { + boolean res = pipelineEquipmentService.delete(id); + if(res){ + Result result = Result.success(1); + return CommUtil.toJson(result); + }else{ + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + // 鍒犻櫎鎸囧畾涓婚敭鐨勭閬撹澶囦俊鎭 + @PostMapping("/deleteByIds.do") + public String deleteByIds(@RequestParam(value = "id") Integer id) { + boolean res = pipelineEquipmentService.delete(id); + if(res){ + Result result = Result.success(1); + return CommUtil.toJson(result); + }else{ + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + //鏂板 + @PostMapping("/save.do") + public String save(@ModelAttribute PipelineEquipment pipelineEquipment) { + int res = pipelineEquipmentService.insert(pipelineEquipment); + if (res > 0) { + int generatedId = pipelineEquipment.getId(); + Result result = Result.success(generatedId); + return CommUtil.toJson(result); + }else{ + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + //淇敼 + @PostMapping("/update.do") + public String update(@ModelAttribute PipelineEquipment pipelineEquipment) { + boolean res = pipelineEquipmentService.update(pipelineEquipment); + if(res){ + Result result = Result.success(1); + return CommUtil.toJson(result); + }else{ + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + /** + * 鍒嗛〉鏌ヨ绠¢亾璁惧鍒楄〃 + * @param pageNum + * @param pageSize + * @param equipmentTypeId 绫诲瀷id + * @param stationCode 绔欏彿 + * @param status 1鍦ㄧ嚎 0绂荤嚎 null涓烘湭妫娴 + * @return + */ + @GetMapping("/list.do") + public PageData selectListByWhere( + @RequestParam(defaultValue = "1") Integer pageNum, + @RequestParam(defaultValue = "10") Integer pageSize, + @RequestParam(required = false) String equipmentTypeId, + @RequestParam(required = false) String stationCode, + @RequestParam(required = false) String status) { + + // 璁剧疆鍒嗛〉鍙傛暟 + PageHelper.startPage(pageNum, pageSize); + + // 鏋勫缓鏌ヨ鏉′欢 + String where = "where 1=1"; + //绫诲瀷绛涢 + if (equipmentTypeId != null && !equipmentTypeId.isEmpty()) { + where += " AND equipment_type = '" + equipmentTypeId + "'"; + } + //绔欏彿绛涢 + if (stationCode != null && !stationCode.isEmpty()) { + where += " AND station_code = '" + stationCode + "'"; + } + //鐘舵佺瓫閫 + if (status != null && !status.isEmpty()) { + where += " AND status = '" + status + "'"; + } + + // 鎵ц鏌ヨ + List list = pipelineEquipmentService.selectListByWhere(where); + + // 灏佽鍒嗛〉淇℃伅 + PageInfo pageInfo = new PageInfo<>(list); + + // 杩斿洖鍒嗛〉鏁版嵁 + return new PageData<>(pageInfo); + } + + /** + * 鑾峰彇绠$綉璁惧绫诲瀷 + * @return + */ + @GetMapping("/device-types") + public List> getDeviceTypes() { + List> deviceTypes = new ArrayList<>(); + for (DeviceTypeEnum deviceType : DeviceTypeEnum.values()) { + Map deviceTypeMap = new HashMap<>(); + deviceTypeMap.put("typeName", deviceType.getTypeName()); + deviceTypeMap.put("typeCode", deviceType.getTypeCode()); + deviceTypes.add(deviceTypeMap); + } + return deviceTypes; + } + + /** + * 鎵嬪姩鍒濆鍖栧叧鑱 璁惧-鐐逛綅 鍏崇郴 + * + * @return + */ + @GetMapping("/hand-save.do") + public String handSave() { + + //浜曠洊 + List list = pipelineEquipmentService.selectListByWhere("where equipment_type = '1'"); + for (int i = 0; i < list.size(); i++) { + //鏍煎紡锛欿CGW_21001_A1 + String[] codes = new String[]{"A1", "A2", "A3", "A4", "A5", "Q10", "Q11", "Q12", "V1"}; + String[] names = new String[]{"淇″彿寮哄害", "鍩虹珯搴忓彿", "浜曠洊瑙掑害", "鐢甸樆鍊1", "鐢甸樆鍊2", "鐢靛帇鎶ヨ", "姘存蹈鎶ヨ", "寮鐩栨姤璀", "鐢垫睜鐢靛帇"}; + for (int j = 0; j < codes.length; j++) { + String mpcode = "KCGW_" + list.get(i).getStationCode() + "_" + codes[j]; + PipelineEquipmentMpoint pipelineEquipmentMpoint = new PipelineEquipmentMpoint(); + pipelineEquipmentMpoint.setPid(list.get(i).getId()); + pipelineEquipmentMpoint.setMpcode(mpcode); + pipelineEquipmentMpoint.setMpname(names[j]); + pipelineEquipmentMpoint.setTag(codes[j]); + pipelineEquipmentMpointService.insert(pipelineEquipmentMpoint); + } + } + + //娴侀噺璁 + List list2 = pipelineEquipmentService.selectListByWhere("where equipment_type = '2'"); + for (int i = 0; i < list2.size(); i++) { + //鏍煎紡锛欿CGW_21001_A1 + String[] codes = new String[]{"A1", "A2", "A4", "A7", "A8", "P1", "P2", "P3"}; + String[] names = new String[]{"杩囨按闈㈢Н","娑蹭綅","娓╁害","鐬椂娴侀噺","娴侀","姝e悜绱","鍙嶅悜绱","瀹為檯绱"}; + for (int j = 0; j < codes.length; j++) { + String mpcode = "KCGW_" + list2.get(i).getStationCode() + "_" + codes[j]; + PipelineEquipmentMpoint pipelineEquipmentMpoint = new PipelineEquipmentMpoint(); + pipelineEquipmentMpoint.setPid(list2.get(i).getId()); + pipelineEquipmentMpoint.setMpcode(mpcode); + pipelineEquipmentMpoint.setMpname(names[j]); + pipelineEquipmentMpoint.setTag(codes[j]); + pipelineEquipmentMpointService.insert(pipelineEquipmentMpoint); + } + } + + //娑蹭綅璁 + List list3 = pipelineEquipmentService.selectListByWhere("where equipment_type = '3'"); + for (int i = 0; i < list3.size(); i++) { + //鏍煎紡锛欿CGW_21001_A1 + String[] codes = new String[]{"A1", "A2", "A3", "A4", "A5", "A6", "A8", "A10"}; + String[] names = new String[]{"淇″彿鎺ユ敹鍔熺巼","淇″櫔姣","灏忓尯ID","鍊炬枩瑙掑害","鐢垫睜鐢靛帇","鎶曞叆寮忔恫浣","闆疯揪姘翠綅","缁煎悎娑蹭綅"}; + for (int j = 0; j < codes.length; j++) { + String mpcode = "KCGW_" + list3.get(i).getStationCode() + "_" + codes[j]; + PipelineEquipmentMpoint pipelineEquipmentMpoint = new PipelineEquipmentMpoint(); + pipelineEquipmentMpoint.setPid(list3.get(i).getId()); + pipelineEquipmentMpoint.setMpcode(mpcode); + pipelineEquipmentMpoint.setMpname(names[j]); + pipelineEquipmentMpoint.setTag(codes[j]); + pipelineEquipmentMpointService.insert(pipelineEquipmentMpoint); + } + } + + //鐢靛鐜 + List list4 = pipelineEquipmentService.selectListByWhere("where equipment_type = '4'"); + for (int i = 0; i < list4.size(); i++) { + //鏍煎紡锛欿CGW_21001_A1 + String[] codes = new String[]{"A7", "A8", "V"}; + String[] names = new String[]{"鐢靛鐜","娓╁害","鐢垫睜鐢靛帇"}; + for (int j = 0; j < codes.length; j++) { + String mpcode = "KCGW_" + list4.get(i).getStationCode() + "_" + codes[j]; + PipelineEquipmentMpoint pipelineEquipmentMpoint = new PipelineEquipmentMpoint(); + pipelineEquipmentMpoint.setPid(list4.get(i).getId()); + pipelineEquipmentMpoint.setMpcode(mpcode); + pipelineEquipmentMpoint.setMpname(names[j]); + pipelineEquipmentMpoint.setTag(codes[j]); + pipelineEquipmentMpointService.insert(pipelineEquipmentMpoint); + } + } + + //闆ㄩ噺璁 + List list5 = pipelineEquipmentService.selectListByWhere("where equipment_type = '5'"); + for (int i = 0; i < list5.size(); i++) { + //鏍煎紡锛欿CGW_21001_A1 + String[] codes = new String[]{"A1"}; + String[] names = new String[]{"闆ㄩ噺鍊"}; + for (int j = 0; j < codes.length; j++) { + String mpcode = "KCGW_" + list5.get(i).getStationCode() + "_" + codes[j]; + PipelineEquipmentMpoint pipelineEquipmentMpoint = new PipelineEquipmentMpoint(); + pipelineEquipmentMpoint.setPid(list5.get(i).getId()); + pipelineEquipmentMpoint.setMpcode(mpcode); + pipelineEquipmentMpoint.setMpname(names[j]); + pipelineEquipmentMpoint.setTag(codes[j]); + pipelineEquipmentMpointService.insert(pipelineEquipmentMpoint); + } + } + + //鍐呮稘鐩戞祴 + List list6 = pipelineEquipmentService.selectListByWhere("where equipment_type = '6'"); + for (int i = 0; i < list6.size(); i++) { + //鏍煎紡锛欿CGW_21001_A1 + String[] codes = new String[]{"A13", "P14"}; + String[] names = new String[]{"姘翠綅", "鐘舵侊紙鏈夋按/鏃犳按锛"}; + for (int j = 0; j < codes.length; j++) { + String mpcode = "KCGW_" + list6.get(i).getStationCode() + "_" + codes[j]; + PipelineEquipmentMpoint pipelineEquipmentMpoint = new PipelineEquipmentMpoint(); + pipelineEquipmentMpoint.setPid(list6.get(i).getId()); + pipelineEquipmentMpoint.setMpcode(mpcode); + pipelineEquipmentMpoint.setMpname(names[j]); + pipelineEquipmentMpoint.setTag(codes[j]); + pipelineEquipmentMpointService.insert(pipelineEquipmentMpoint); + } + } + + return "suc"; + } + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/controller/data/PipelineEquipmentMpointController.java b/src/main/java/com/sipai/controller/data/PipelineEquipmentMpointController.java new file mode 100644 index 0000000..7cf0fb9 --- /dev/null +++ b/src/main/java/com/sipai/controller/data/PipelineEquipmentMpointController.java @@ -0,0 +1,136 @@ +package com.sipai.controller.data; + +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.sipai.entity.base.Result; +import com.sipai.entity.common.PageData; +import com.sipai.entity.data.PipelineEquipmentMpoint; +import com.sipai.entity.data.PipelineMpointLibrary; +import com.sipai.service.data.PipelineEquipmentMpointService; +import com.sipai.service.data.PipelineMpointLibraryService; +import com.sipai.tools.CommUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 绠$綉璁惧闄勫睘鐐逛綅鍒楄〃 + */ +@RestController +@RequestMapping("/pipeline-equipment-mpoint") +public class PipelineEquipmentMpointController { + + @Autowired + private PipelineEquipmentMpointService pipelineEquipmentMpointService; + @Autowired + private PipelineMpointLibraryService pipelineMpointLibraryService; + + // 鏍规嵁涓婚敭鏌ヨ绠¢亾璁惧涓庢祴鐐瑰叧鑱斾俊鎭 + @GetMapping("/selectById.do") + public Result selectByPrimaryKey(@RequestParam(value = "id") Integer id) { + PipelineEquipmentMpoint mpoint = pipelineEquipmentMpointService.selectByPrimaryKey(id); + if (mpoint != null) { + return Result.success(mpoint); + } else { + return Result.failed("鍏宠仈淇℃伅涓嶅瓨鍦"); + } + } + + // 鍒犻櫎鎸囧畾涓婚敭鐨勭閬撹澶囦笌娴嬬偣鍏宠仈淇℃伅 + @PostMapping("/deleteById.do") + public String deleteByPrimaryKey(@RequestParam(value = "id") Integer id) { + boolean res = pipelineEquipmentMpointService.delete(id); + if (res) { + Result result = Result.success(1); + return CommUtil.toJson(result); + } else { + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + // 鏂板绠¢亾璁惧涓庢祴鐐瑰叧鑱斾俊鎭 + @PostMapping("/save.do") + public String save(@ModelAttribute PipelineEquipmentMpoint mpoint) { + boolean res = pipelineEquipmentMpointService.insert(mpoint); + if (res) { + Result result = Result.success(1); + return CommUtil.toJson(result); + } else { + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + // 淇敼绠¢亾璁惧涓庢祴鐐瑰叧鑱斾俊鎭 + @PostMapping("/update.do") + public String update(@ModelAttribute PipelineEquipmentMpoint mpoint) { + boolean res = pipelineEquipmentMpointService.update(mpoint); + if (res) { + Result result = Result.success(1); + return CommUtil.toJson(result); + } else { + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + // 鍒嗛〉鏌ヨ绠¢亾璁惧涓庢祴鐐瑰叧鑱斾俊鎭垪琛 + @GetMapping("/list.do") + public PageData selectListByWhere( + @RequestParam(defaultValue = "1") Integer pageNum, + @RequestParam(defaultValue = "10") Integer pageSize, + @RequestParam(required = false) String pid) { + + // 璁剧疆鍒嗛〉鍙傛暟 + PageHelper.startPage(pageNum, pageSize); + + // 鏋勫缓鏌ヨ鏉′欢 + String where = "where 1=1"; + if (pid != null && !pid.isEmpty()) { + where += " AND pid = '" + pid + "'"; + } + + // 鎵ц鏌ヨ + List list = pipelineEquipmentMpointService.selectListByWhere(where); + + // 灏佽鍒嗛〉淇℃伅 + PageInfo pageInfo = new PageInfo<>(list); + + // 杩斿洖鍒嗛〉鏁版嵁 + return new PageData<>(pageInfo); + } + + /** + * 鏍规嵁绫诲瀷涓閿鍏 + * + * @param equipmentTypeId + * @return + */ + @PostMapping("/import4Type.do") + public String import4Type(@RequestParam(required = true) Integer pid, + @RequestParam(required = true) String equipmentTypeId) { + try{ + // 鏋勫缓鏌ヨ鏉′欢 + String where = "where 1=1 AND equipment_type = '" + equipmentTypeId + "'"; + // 鎵ц鏌ヨ + List list = pipelineMpointLibraryService.selectListByWhere(where); + if (list != null && list.size() > 0) { + for (int i = 0; i < list.size(); i++) { + PipelineEquipmentMpoint pipelineEquipmentMpoint = new PipelineEquipmentMpoint(); + pipelineEquipmentMpoint.setPid(pid); + pipelineEquipmentMpoint.setTag(list.get(i).getCode()); + pipelineEquipmentMpoint.setMpname(list.get(i).getName()); + pipelineEquipmentMpointService.insert(pipelineEquipmentMpoint); + } + } + Result result = Result.success(1); + return CommUtil.toJson(result); + }catch (Exception e){ + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/controller/data/PipelineMpointLibraryController.java b/src/main/java/com/sipai/controller/data/PipelineMpointLibraryController.java new file mode 100644 index 0000000..e81b060 --- /dev/null +++ b/src/main/java/com/sipai/controller/data/PipelineMpointLibraryController.java @@ -0,0 +1,106 @@ +package com.sipai.controller.data; + +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.sipai.entity.base.Result; +import com.sipai.entity.common.PageData; +import com.sipai.entity.data.PipelineMpointLibrary; +import com.sipai.service.data.PipelineMpointLibraryService; +import com.sipai.tools.CommUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/pipeline-mpoint-library") +public class PipelineMpointLibraryController { + + @Autowired + private PipelineMpointLibraryService pipelineMpointLibraryService; + + // 鏍规嵁涓婚敭鏌ヨ璁板綍 + @GetMapping("/selectById.do") + public PipelineMpointLibrary selectByPrimaryKey(@RequestParam(value = "id") String id) { + return pipelineMpointLibraryService.selectByPrimaryKey(id); + } + + // 鍒犻櫎鎸囧畾涓婚敭鐨勮褰 + @PostMapping("/deleteById.do") + public String deleteByPrimaryKey(@RequestParam(value = "id") String id) { + boolean res = pipelineMpointLibraryService.delete(id); + if (res) { + Result result = Result.success(1); + return CommUtil.toJson(result); + } else { + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + // 澶氬垹鎸囧畾涓婚敭鐨勮褰 + @PostMapping("/deleteByIds.do") + public String deleteByIds(@RequestParam(value = "ids") List idList) { + int count = pipelineMpointLibraryService.deleteBatch(idList); + if (count > 0) { + Result result = Result.success(count); + return CommUtil.toJson(result); + } else { + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + // 鎻掑叆璁板綍 + @PostMapping("/save.do") + public String save(@ModelAttribute PipelineMpointLibrary pipelineMpointLibrary) { + pipelineMpointLibrary.setId(CommUtil.getUUID()); + boolean res = pipelineMpointLibraryService.insert(pipelineMpointLibrary); + if (res) { + Result result = Result.success(1); + return CommUtil.toJson(result); + } else { + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + // 鏍规嵁涓婚敭閫夋嫨鎬ф洿鏂拌褰 + @PostMapping("/update.do") + public String update(@ModelAttribute PipelineMpointLibrary pipelineMpointLibrary) { + boolean res = pipelineMpointLibraryService.update(pipelineMpointLibrary); + if (res) { + Result result = Result.success(1); + return CommUtil.toJson(result); + } else { + Result result = Result.failed("0"); + return CommUtil.toJson(result); + } + } + + // 鍒嗛〉鏌ヨ鍒楄〃 + @GetMapping("/list.do") + public PageData selectListByWhere( + @RequestParam(defaultValue = "1") Integer pageNum, + @RequestParam(defaultValue = "10") Integer pageSize, + @RequestParam(required = false) String equipmentTypeId) { + + // 璁剧疆鍒嗛〉鍙傛暟 + PageHelper.startPage(pageNum, pageSize); + + // 鏋勫缓鏌ヨ鏉′欢 + String where = "where 1=1"; + if (equipmentTypeId != null && !equipmentTypeId.isEmpty()) { + where += " AND equipment_type = '" + equipmentTypeId + "'"; + } + + // 鎵ц鏌ヨ + List list = pipelineMpointLibraryService.selectListByWhere(where); + + // 灏佽鍒嗛〉淇℃伅 + PageInfo pageInfo = new PageInfo<>(list); + + // 杩斿洖鍒嗛〉鏁版嵁 + return new PageData<>(pageInfo); + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/controller/kafka/KafkaController.java b/src/main/java/com/sipai/controller/kafka/KafkaController.java new file mode 100644 index 0000000..ecc39b9 --- /dev/null +++ b/src/main/java/com/sipai/controller/kafka/KafkaController.java @@ -0,0 +1,26 @@ +package com.sipai.controller.kafka; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/kafka") +public class KafkaController { + + @Autowired + private KafkaTemplate kafkaTemplate; + + @GetMapping("/testSendMessage") + public String readValue() { + String topic = "my-topic"; // 鏇挎崲涓轰綘鐨勪富棰樺悕 + String message = "Hello, Kafka!"; + // 鍙戦佹秷鎭 + kafkaTemplate.send(topic, message); + System.out.println("娑堟伅宸插彂閫: " + message); + return "suc"; + } +} diff --git a/src/main/java/com/sipai/controller/mqtt/MqttConfigController.java b/src/main/java/com/sipai/controller/mqtt/MqttConfigController.java new file mode 100644 index 0000000..8ea4a2a --- /dev/null +++ b/src/main/java/com/sipai/controller/mqtt/MqttConfigController.java @@ -0,0 +1,145 @@ +package com.sipai.controller.mqtt; + +import com.sipai.entity.mqtt.MqttConfig; +import com.sipai.service.mqtt.MqttConfigService; +import com.sipai.tools.Result; +import org.apache.commons.codec.binary.Base64; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttPersistenceException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.stereotype.Repository; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/04/22/14:30 + * @Description: mqtt閰嶇疆涓昏〃 + */ +@Controller +@RequestMapping("/mqttConfig") +public class MqttConfigController { + @Autowired + private MqttConfigService mqttConfigService; + + @GetMapping("/getById") + public String getById() { + MqttConfig mqttConfig = mqttConfigService.selectByPrimaryKey("2"); + if (mqttConfig != null) { + System.out.println(mqttConfig.getClientName()); + } else { + System.out.println("鏃犳暟鎹"); + } + return "index"; + } + + //杩炴帴浠g悊 + @RequestMapping("/connectStart.do") + @ResponseBody + public Result connectStart(HttpServletRequest request, Model model) { + String id = request.getParameter("id"); + mqttConfigService.connect(id); + Result res = Result.success(1); + return res; + } + + /** + * 杩炴帴 mqtt + * + * @param request + * @param model + */ + /*@GetMapping("/connect.do") + public void connect(HttpServletRequest request, Model model) { + String ids = request.getParameter("ids"); + if (ids != null && !ids.equals("")) { + String[] idstr = ids.split(","); + for (int i = 0; i < idstr.length; i++) { + MqttConfig mqttConfig = mqttConfigService.selectByPrimaryKey(idstr[i]); + if (mqttConfig != null) { + String str = "http://" + request.getServerName() + ":" + mqttConfig.getTomcatPort() + "/mqttConfig/connectStart.do?id=" + idstr[i]; + this.doPost(str); + } + } + } + }*/ + @GetMapping("/connect.do") + @ResponseBody + public Result connect(HttpServletRequest request, Model model) { + String ids = request.getParameter("ids"); + if (ids != null && !ids.equals("")) { + String[] idstr = ids.split(","); + for (int i = 0; i < idstr.length; i++) { + MqttConfig mqttConfig = mqttConfigService.selectByPrimaryKey(idstr[i]); + if (mqttConfig != null) { + //String str = "http://" + request.getServerName() + ":" + mqttConfig.getTomcatPort() + "/mqttConfig/connectStart.do?id=" + idstr[i]; + String str = "http://" + mqttConfig.getTomcatPort() + "/mqttConfig/connectStart.do?id=" + idstr[i]; + this.doPost(str); + } + } + } + Result res = Result.success(1); + return res; + } + + public String doPost(String URL) { + OutputStreamWriter out = null; + BufferedReader in = null; + StringBuilder result = new StringBuilder(); + HttpURLConnection conn = null; + try { + java.net.URL url = new URL(URL); + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("POST"); + //鍙戦丳OST璇锋眰蹇呴』璁剧疆涓簍rue + conn.setDoOutput(true); + conn.setDoInput(true); + //璁剧疆杩炴帴瓒呮椂鏃堕棿鍜岃鍙栬秴鏃舵椂闂 + conn.setConnectTimeout(30000); + conn.setReadTimeout(10000); + conn.setRequestProperty("Content-Type", "application/json"); + conn.setRequestProperty("Accept", "application/json"); + //鑾峰彇杈撳嚭娴 + out = new OutputStreamWriter(conn.getOutputStream()); + String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}"; + out.write(jsonStr); + out.flush(); + out.close(); + //鍙栧緱杈撳叆娴侊紝骞朵娇鐢≧eader璇诲彇 + if (200 == conn.getResponseCode()) { + in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); + String line; + while ((line = in.readLine()) != null) { + result.append(line); + System.out.println(line); + } + } else { + System.out.println("ResponseCode is an error code:" + conn.getResponseCode()); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (out != null) { + out.close(); + } + if (in != null) { + in.close(); + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } + return result.toString(); + } +} diff --git a/src/main/java/com/sipai/controller/mqtt/MqttConfigTopicController.java b/src/main/java/com/sipai/controller/mqtt/MqttConfigTopicController.java new file mode 100644 index 0000000..720c34d --- /dev/null +++ b/src/main/java/com/sipai/controller/mqtt/MqttConfigTopicController.java @@ -0,0 +1,41 @@ +package com.sipai.controller.mqtt; + +import com.sipai.entity.mqtt.MqttConfigTopic; +import com.sipai.service.mqtt.MqttConfigTopicService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/04/22/14:42 + * @Description: mqtt閰嶇疆涓昏〃 + */ +@Controller +@RequestMapping("/mqttConfigTopic") +public class MqttConfigTopicController { + @Autowired + private MqttConfigTopicService mqttConfigTopicService; + + @RequestMapping("/save.do") + @ResponseBody + public Integer save(HttpServletRequest request, Model model, + @ModelAttribute("mqttConfigTopic") MqttConfigTopic mqttConfigTopic) { + return mqttConfigTopicService.insert(mqttConfigTopic); + } + + @RequestMapping("/delete.do") + @ResponseBody + public int delete(HttpServletRequest request, Model model, + @ModelAttribute("id") String id) { + return mqttConfigTopicService.deleteByPrimaryKey(id); + } + +} diff --git a/src/main/java/com/sipai/controller/mqtt/MqttController.java b/src/main/java/com/sipai/controller/mqtt/MqttController.java new file mode 100644 index 0000000..3c62ffc --- /dev/null +++ b/src/main/java/com/sipai/controller/mqtt/MqttController.java @@ -0,0 +1,408 @@ +package com.sipai.controller.mqtt; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.sipai.entity.mqtt.MqttConfig; +import com.sipai.entity.mqtt.MqttConfigTopic; +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointES; +import com.sipai.entity.user.Company; +import com.sipai.service.mqtt.MqttConfigService; +import com.sipai.service.mqtt.MqttConfigTopicService; +import com.sipai.service.mqtt.MqttService; +import com.sipai.service.scada.MPointService; +import com.sipai.service.user.CompanyService; +import com.sipai.tools.CommUtil; +import com.sipai.tools.Result; +import org.apache.commons.codec.binary.Base64; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttPersistenceException; +import org.elasticsearch.index.query.BoolQueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; +import org.elasticsearch.search.sort.SortBuilders; +import org.elasticsearch.search.sort.SortOrder; +import org.redisson.api.RMap; +import org.redisson.api.RedissonClient; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; +import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; +import springfox.documentation.spring.web.json.Json; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.math.BigDecimal; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.List; +import java.util.Random; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@Controller +@RequestMapping("/mqtt") +public class MqttController { + @Autowired + private MqttService mqttService; + @Autowired + private CompanyService companyService; + @Autowired + private MPointService mPointService; + @Autowired + private MqttConfigService mqttConfigService; + @Autowired + private MqttConfigTopicService mqttConfigTopicService; + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; + @Autowired + private RedissonClient redissonClient; + + /** + * 鐢ㄤ簬鎻愪緵浜戝钩鍙 鏌ヨ鎸囧畾缃戝叧鏄惁鍦ㄧ嚎 (鍗曚釜缃戝叧) + * sj 2021-05-25 + */ + @RequestMapping("/getClientStatus.do") + @ResponseBody + public String getClientStatus(HttpServletRequest request, Model model) { + String unitId = request.getParameter("unitId");//鍘俰d + String line = null; + try { + URL url = new URL("http://172.16.242.16:28083/api/v4/clients/" + unitId + "_01"); + Base64 b = new Base64(); + String encoding = b.encodeAsString(new String("admin:public").getBytes()); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("Authorization", "Basic " + encoding); + InputStream content = (InputStream) connection.getInputStream(); + BufferedReader in = new BufferedReader(new InputStreamReader(content)); + while ((line = in.readLine()) != null) { + return line; + } + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } + + /** + * 鐢ㄤ簬鎻愪緵浜戝钩鍙 杩斿洖鎵鏈夊湪绾跨殑缃戝叧 (鎵鏈夌綉鍏) + * sj 2021-05-25 + */ + @RequestMapping("/getClientListStatus.do") + @ResponseBody + public String getClientListStatus() { + String line = null; + try { + URL url = new URL("http://172.16.242.16:28083/api/v4/clients/"); + Base64 b = new Base64(); + String encoding = b.encodeAsString(new String("admin:public").getBytes()); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("Authorization", "Basic " + encoding); + InputStream content = (InputStream) connection.getInputStream(); + BufferedReader in = new BufferedReader(new InputStreamReader(content)); + while ((line = in.readLine()) != null) { + return line; + } + } catch (Exception e) { + e.printStackTrace(); + } + System.out.println(line); + return ""; + } + + /** + * 鏍规嵁鍘俰d锛岃繑鍥炶鍘傛墍鏈夌殑缃戝叧鍦ㄧ嚎鐘舵 锛堝繀椤婚厤缃簡_COM鐐癸級 + * sj 2021-08-12 + */ + @RequestMapping("/getClientListStatus4UnitId.do") + @ResponseBody + public String getClientListStatus4UnitId(HttpServletRequest request, Model model, + @ModelAttribute("unitId") String unitId) { + + NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder(); + BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); + BoolQueryBuilder childBoolQueryBuilder = QueryBuilders.boolQuery(); + childBoolQueryBuilder.must(QueryBuilders.matchQuery("bizid", unitId)); + childBoolQueryBuilder.must(QueryBuilders.matchQuery("signaltag", "COMMU")); + boolQueryBuilder.should(childBoolQueryBuilder); + nativeSearchQueryBuilder.withQuery(boolQueryBuilder); + nativeSearchQueryBuilder.withPageable(PageRequest.of(0, 300)); + //鍏堟牴鎹甧s鎵惧埌鏀瑰巶鎵鏈夌殑閫氳鐐癸紝鐒跺悗鑾峰彇mpointId鍘荤綉鍏充腑鏌ヨ鍦ㄧ嚎鐘舵 + List runMPoint = this.mPointService.selectListByWhere4Es(nativeSearchQueryBuilder); + String str = ""; + String line = null; + JSONArray jsonArray = new JSONArray(); + if (runMPoint.size() > 0) { + //寰幆鎵鏈夌綉鍏 + for (int i = 0; i < runMPoint.size(); i++) { + String mpointid = runMPoint.get(i).getMpointid(); + String parmname = runMPoint.get(i).getParmname(); + //缃戝叧id + mpointid = mpointid.replace("_COM", ""); + + try { + URL url = new URL("http://172.16.242.16:28083/api/v4/clients/" + mpointid); + Base64 b = new Base64(); + String encoding = b.encodeAsString(new String("admin:public").getBytes()); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("Authorization", "Basic " + encoding); + InputStream content = (InputStream) connection.getInputStream(); + BufferedReader in = new BufferedReader(new InputStreamReader(content)); + + JSONObject jsonObject = JSONObject.parseObject(in.readLine()); + String data = jsonObject.get("data").toString(); + JSONArray jsonArrayStr = JSONArray.parseArray(data); + if (jsonArrayStr.size() > 0) { + //鑾峰彇绗竴涓綉鍏冲璞 + JSONObject jsonObjectStr = (JSONObject) jsonArrayStr.get(0); + + JSONObject jsonData = new JSONObject(); + jsonData.put("clientid", jsonObjectStr.get("clientid")); + jsonData.put("parmname", parmname); + jsonData.put("connected", true);//鍦ㄧ嚎 + jsonArray.add(jsonData); + } else { + JSONObject jsonData = new JSONObject(); + jsonData.put("clientid", mpointid); + jsonData.put("parmname", parmname); + jsonData.put("connected", false);//涓嶅湪绾 + jsonArray.add(jsonData); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + } + return jsonArray.toString(); + } + + /** + * 鐢ㄤ簬鎻愪緵浜戝钩鍙 缁檖lc鍙戝竷鎸囦护鎺ュ彛 + * sj 2021-05-25 + */ + @RequestMapping("/doPublish4Vue.do") + @ResponseBody + public String doPublish4Vue(HttpServletRequest request, Model model) { + String mpid = request.getParameter("mpid");//娴嬮噺鐐笽d + String bizType = request.getParameter("bizType");//缃戝叧缂栧彿 + String value = request.getParameter("value");//鎸囦护涓嬪彂鐨勫 + String userId = request.getParameter("userId");//鎿嶄綔浜哄憳id + String rate = request.getParameter("rate");//鍊嶇巼 + String directtype = request.getParameter("directtype");//鍙栧弽绫诲瀷 1涓哄彇鍙 鍏朵綑涓烘甯 + + String topic = bizType + "_DOWN"; + JSONObject jsonObject = new JSONObject(); + + String bizId = bizType.substring(0, 7); + Company company = companyService.selectByPrimaryKey(bizId); + if (company != null) { + bizId = company.getPid(); + } + + /* + 鍙栧弽鎿嶄綔 + */ + if (directtype != null && directtype.equals("1")) { + //鍙栧弽 + if (value.equals("0")) { + value = "1"; + } else if (value.equals("1")) { + value = "0"; + } else { + //姝e父 + } + } else { + //姝e父 + } + + BigDecimal val = null; + if (rate != null && !rate.equals("0")) { + BigDecimal num1 = new BigDecimal(value); + BigDecimal num2 = new BigDecimal(rate); + +// MPoint mPoint = mPointService.selectById(bizId, mpid); + MPoint mPoint = mPointService.selectById(bizId,mpid); + //AO鏍规嵁鍐欏叆鐨勫皬鏁颁綅璧嬪 + if (mPoint != null && mPoint.getSignaltype().equals("AO")) { + BigDecimal bd = new BigDecimal(String.valueOf(value)); + // bd.scale() 涓哄皬鏁颁綅 + val = num1.divide(num2, bd.scale(), BigDecimal.ROUND_HALF_UP); + } + //DO鎴彇0浣 + if (mPoint != null && mPoint.getSignaltype().equals("DO")) { + val = num1.divide(num2, 0, BigDecimal.ROUND_HALF_UP); + } + jsonObject.put("TagValue", val); + } else { + String str = String.valueOf(value);//娴偣鍙橀噺a杞崲涓哄瓧绗︿覆str + int idx = str.lastIndexOf(".");//鏌ユ壘灏忔暟鐐圭殑浣嶇疆 + if (idx == -1) { + jsonObject.put("TagValue", value); + } else { + String strNum = str.substring(0, idx);//鎴彇浠庡瓧绗︿覆寮濮嬪埌灏忔暟鐐逛綅缃殑瀛楃涓诧紝灏辨槸鏁存暟閮ㄥ垎 + int num = Integer.valueOf(strNum);//鎶婃暣鏁伴儴鍒嗛氳繃Integer.valueof鏂规硶杞崲涓烘暟瀛 + jsonObject.put("TagValue", num); + } + } + + jsonObject.put("method", "setValue"); + jsonObject.put("TagName", mpid); + + int res = this.mqttService.doPublish(jsonObject, topic, userId, bizId); + String json = null; + if (res == 0) { + Result result = Result.success(res); + json = CommUtil.toJson(result); + } else { + Result result = Result.failed("鎸囦护涓嬪彂澶辫触"); + json = CommUtil.toJson(result); + } + return json; + } + + /** + * 缃戝叧鏁版嵁鍏ㄩ儴鍙洖(Recall) 浼燽izid鍙洖璇ュ巶璇ョ綉鍏崇殑鎵鏈夋暟鎹 + * sj 2021-06-25 + * + * @param request + * @param model + * @return + */ + @RequestMapping("/doRecall.do") + @ResponseBody + public String doRecall(HttpServletRequest request, Model model) { + String unitId = request.getParameter("unitId");//鍘俰d + JSONObject jsonObject = new JSONObject(); + jsonObject.put("command", "Upload immediately"); + mqttService.doRecall(unitId, jsonObject); + Result result = Result.success(""); + String json = null; + json = CommUtil.toJson(result); + return json; + } + + /** + * 鍓嶇浼犱富棰橈紝鏍规嵁閰嶇疆锛屾煡璇㈠睘浜庡摢涓唬鐞 + * sj 2021-09-15 + * + * @param request + * @param model + * @return + */ + @RequestMapping("/getEmqx4Topic.do") + @ResponseBody + public String getEmqx4Topic(HttpServletRequest request, Model model) { + String topic = request.getParameter("topic");//鍘俰d + + if (topic != null && topic.contains("_VUE")) { + topic = topic.replace("_VUE", ""); + } + + JSONObject jsonObject = mqttConfigService.getEmqxHost4WS(topic); + + Result result = null; + if (jsonObject != null && jsonObject.size() > 0) { + result = Result.success(jsonObject); + } else { + result = Result.failed("鏃犳硶鏌ヨ璇ヤ唬鐞嗗湴鍧"); + } + String json = null; + json = CommUtil.toJson(result); + return json; + } + + /** + * 婕旂ず鎺ㄩ佸紑濮 + * + * @param request + * @param model + * @return + */ + @RequestMapping("/startSend.do") + @ResponseBody + public String startSend(HttpServletRequest request, Model model) { + String mp1 = "SPF_XFJZ1_FV2"; //15-50 1绉掑姞1 + String mp2 = "SPF_XFJZ1_FV2_test1"; //15-50 1绉掑姞1 + String mp3 = "SPF_XFJZ1_FV2_test2"; //15-50 1绉掑姞1 + String mp4 = "SPF_XFJZ1_FL2"; //3000-8000 闅忔満 + String mp5 = "SPF_XFJZ1_FL2_test1"; //3000-8000 闅忔満 + String mp6 = "SPF_XFJZ1_FL2_test2"; //3000-8000 闅忔満 + String mp7 = "SPF_XFJZ1_RUN1_test"; + + RMap map_list = redissonClient.getMap("test_mpoint"); + map_list.fastPutAsync(mp1, 15); + map_list.fastPutAsync(mp2, 15); + map_list.fastPutAsync(mp3, 15); + map_list.fastPutAsync(mp4, 3000); + map_list.fastPutAsync(mp5, 3000); + map_list.fastPutAsync(mp6, 3000); + map_list.fastPutAsync(mp7, 1); + + //灏嗘帹閫佺姸鎬佽缃负no + RMap map_status = redissonClient.getMap("test_mpoint_status"); + map_status.fastPutAsync("status", "yes"); + + return "寮濮嬫帹閫" + CommUtil.nowDate(); + } + + /** + * 婕旂ず鎺ㄩ佸紑濮 + * + * @param request + * @param model + * @return + */ + @RequestMapping("/stopSend.do") + @ResponseBody + public String stopSend(HttpServletRequest request, Model model) { + + String mp1 = "SPF_XFJZ1_FV2"; //15-50 1绉掑姞1 + String mp2 = "SPF_XFJZ1_FV2_test1"; //15-50 1绉掑姞1 + String mp3 = "SPF_XFJZ1_FV2_test2"; //15-50 1绉掑姞1 + String mp4 = "SPF_XFJZ1_FL2"; //3000-8000 闅忔満 + String mp5 = "SPF_XFJZ1_FL2_test1"; //3000-8000 闅忔満 + String mp6 = "SPF_XFJZ1_FL2_test2"; //3000-8000 闅忔満 + String mp7 = "SPF_XFJZ1_RUN1_test"; + + //鏁版嵁缃0 + RMap map_list = redissonClient.getMap("test_mpoint"); + map_list.fastPutAsync(mp1, 0); + map_list.fastPutAsync(mp2, 0); + map_list.fastPutAsync(mp3, 0); + map_list.fastPutAsync(mp4, 0); + map_list.fastPutAsync(mp5, 0); + map_list.fastPutAsync(mp6, 0); + map_list.fastPutAsync(mp7, 0); + + //鎺ㄩ佹暟鎹 +// mPointService.sendDataTest(map_list); + + //灏嗘帹閫佺姸鎬佽缃负no + RMap map_status = redissonClient.getMap("test_mpoint_status"); + map_status.fastPutAsync("status", "no"); + + return "鍏抽棴鎺ㄩ" + CommUtil.nowDate(); + } + +} diff --git a/src/main/java/com/sipai/controller/mqtt/WebHookController.java b/src/main/java/com/sipai/controller/mqtt/WebHookController.java new file mode 100644 index 0000000..4dafbfa --- /dev/null +++ b/src/main/java/com/sipai/controller/mqtt/WebHookController.java @@ -0,0 +1,108 @@ +package com.sipai.controller.mqtt; + +import com.alibaba.druid.util.StringUtils; +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointHistory; +import com.sipai.entity.user.Company; +import com.sipai.service.mqtt.MqttService; +import com.sipai.service.scada.MPointHistoryService; +import com.sipai.service.scada.MPointService; +import com.sipai.service.user.CompanyService; +import com.sipai.tools.CommUtil; +import com.sipai.tools.ConstantString; +import com.sipai.tools.SpringContextUtil; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.beans.factory.annotation.Autowired; +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.RestController; + +import java.math.BigDecimal; +import java.util.Map; + +/** + * 閫氳繃emqx webHook 鑾峰彇鎵鏈夎澶囩殑涓婁笅绾挎秷鎭 骞跺瓨鐢熶骇搴 _COM鐐 濡傛按鍙o細MZ_SK11_C_01_COM + * sj 2021-05-24 + */ +@Slf4j +@AllArgsConstructor +@RestController +@RequestMapping("/webHook") +public class WebHookController { + @Autowired + private MqttService mqttService; + + @PostMapping("/onJkWebHook") + public void onWebHook(@RequestBody Map param) { + MPointService mPointService = (MPointService) SpringContextUtil.getBean("mPointService"); + MPointHistoryService mPointHistoryService = (MPointHistoryService) SpringContextUtil.getBean("mPointHistoryService"); + CompanyService companyService = (CompanyService) SpringContextUtil.getBean("companyService"); + + String action = MapUtils.getString(param, "action", ""); + try { + String dt = "";//鏃堕棿鎴筹紙绉掞級 + String cid = "";//cid鎴彇9浣 涓哄巶id + String dtime = "";//鏃堕棿 (yyyy-MM-dd HH:mm:ss) + int st = 0; + //杩炴帴 + if ("client_connected".equals(action)) { + cid = MapUtils.getString(param, "client_id", ""); + if (StringUtils.isEmpty(cid)) { + cid = MapUtils.getString(param, "clientid", ""); + } + dt = MapUtils.getString(param, "connected_at", ""); + st = 1; + dtime = CommUtil.stampToDate(dt); + + System.out.println("杩炴帴锛歝id=" + cid); + } + //鏂紑杩炴帴 + if ("client_disconnected".equals(action)) { + cid = MapUtils.getString(param, "client_id", ""); + if (StringUtils.isEmpty(cid)) { + cid = MapUtils.getString(param, "clientid", ""); + } + dt = MapUtils.getString(param, "disconnected_at", ""); + st = 0; + dtime = CommUtil.stampToDate(dt); + + System.out.println("鏂紑锛歝id=" + cid); + } + String mpId = cid + "_COM";//娴嬮噺鐐筰d + String bizId = cid.substring(0, 9);//鍘俰d + Company company = companyService.selectByPrimaryKey(bizId); + if (company != null) { + bizId = company.getPid(); +// MPoint mPoint = mPointService.selectById(bizId, mpId); + MPoint mPoint = mPointService.selectById(bizId,mpId); + if (mPoint != null) { + MPointHistory mPointHistory = new MPointHistory(); + //淇敼涓昏〃 + mPoint.setId(mPoint.getId()); + mPoint.setMeasuredt(dtime); + mPoint.setParmvalue(new BigDecimal(st)); + mPointService.update(mPoint); + //鎻掑叆瀛愯〃 + mPointHistory.setMeasuredt(dtime); + mPointHistory.setParmvalue(new BigDecimal(st)); + mPointHistory.setTbName("[tb_mp_" + mpId + "]"); + mPointHistoryService.save(bizId, mPointHistory); + //System.out.println(mpId + "鎵ц鏃堕棿鎴筹細" + CommUtil.stampToDate(dt)); + + //缃戝叧鎺夌嚎鍙戦佽嚦鎶ヨ鏈嶅姟 + System.out.println("璁惧鎺夌嚎宸叉帹缁欐姤璀︽湇鍔(" + mpId + ")" + "----" + st); + mqttService.sentRabbitmq(ConstantString.MQ_ALARM_MQTT, mpId, st + "", dtime); + } else { + System.out.println("鐐逛笉瀛樺湪"); + } + } else { + System.out.println("鍘備笉瀛樺湪"); + } + } catch (Exception e) { + System.out.println("閫氳鎺ュ彛鎵ц澶辫触:" + e); + } + } +} diff --git a/src/main/java/com/sipai/controller/opc/OpcUaController.java b/src/main/java/com/sipai/controller/opc/OpcUaController.java new file mode 100644 index 0000000..0df21a6 --- /dev/null +++ b/src/main/java/com/sipai/controller/opc/OpcUaController.java @@ -0,0 +1,96 @@ +package com.sipai.controller.opc; + +import com.sipai.service.opc.InitOpcUaService; +import com.sipai.service.opc.OpcUaService; +import org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/api/opcua") +public class OpcUaController { + + private final OpcUaService opcUaService; + + @Autowired + private InitOpcUaService initOpcUaService; + + public OpcUaController(@Autowired(required = false) OpcUaService opcUaService) { + this.opcUaService = opcUaService; + } + + /** + * 璇诲彇鍗曚釜OPC UA鑺傜偣鐨勫 + * + * @param nodeId 鑺傜偣ID锛屾牸寮忎负锛歯s=2;s=閫氶亾 1.璁惧 1.鏍囪3 + * @return 鑺傜偣鍊兼垨閿欒淇℃伅 + */ + @GetMapping("/read") + public Object readValue(@RequestParam String nodeId) { + if (opcUaService == null) { + return "OPC UA 鏈惎鍔紝璇锋鏌ml閰嶇疆鏂囦欢閽燂細opc: enabled: true"; + } + try { + return opcUaService.readNodeValue(nodeId); + } catch (Exception e) { + return "璇诲彇鍊奸敊璇: " + e.getMessage(); + } + } + + /** + * 鍐欏叆鍗曚釜OPC UA鑺傜偣鐨勫 + * + * @param nodeId 鑺傜偣ID锛屾牸寮忎负锛歯s=2;s=閫氶亾 1.璁惧 1.鏍囪3 + * @param value 瑕佸啓鍏ョ殑鍊 + * @return 鍐欏叆鏄惁鎴愬姛鎴栭敊璇俊鎭 + */ + @PostMapping("/write") + public String writeValue(@RequestParam String nodeId, @RequestParam Object value) { + if (opcUaService == null) { + return "OPC UA 鏈惎鍔紝璇锋鏌ml閰嶇疆鏂囦欢閽燂細opc: enabled: true"; + } + try { + boolean success = opcUaService.writeNodeValue(nodeId, value); + return success ? "鍐欏叆鎴愬姛" : "鍐欏叆澶辫触"; + } catch (Exception e) { + return "鍐欏叆閿欒: " + e.getMessage(); + } + } + + /** + * 鍙栨秷璁㈤槄 + * + * @param nodeId + * @return + */ + @PostMapping("/unsubscribeFromNode") + public String unsubscribeFromNode(@RequestParam String nodeId) { + if (opcUaService == null) { + return "OPC UA 鏈惎鍔紝璇锋鏌ml閰嶇疆鏂囦欢閽燂細opc: enabled: true"; + } + try { + boolean success = opcUaService.unsubscribeFromNode(nodeId); + return success ? "鍙栨秷鎴愬姛" : "鍙栨秷澶辫触"; + } catch (Exception e) { + return "鍙栨秷閿欒: " + e.getMessage(); + } + } + + /** + * 鍚屾opcua璁㈤槄鐐逛綅锛堟煡璇s涓璷pcua鐨勯噰闆嗙偣浣嶏紝灏嗕笉闇瑕佺殑鐐逛綅鍙栨秷璁㈤槄锛-涓鑸粯璁1灏忔椂浼氳繘琛屼竴娆″悓姝ワ紝鏈変簺鐐逛綅淇敼鎬昏〃鎴杄s鍚庡彲鎵嬪姩璋冪敤涓娆$珛鍗冲悓姝 + * + * @return + */ + @PostMapping("/sysSub") + public String sysSub() { + if (opcUaService == null) { + return "OPC UA 鏈惎鍔紝璇锋鏌ml閰嶇疆鏂囦欢閽燂細opc: enabled: true"; + } + initOpcUaService.manualSyncSubscriptions(); + return "suc"; + } + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/controller/rabbitmq/MQController.java b/src/main/java/com/sipai/controller/rabbitmq/MQController.java new file mode 100644 index 0000000..986997b --- /dev/null +++ b/src/main/java/com/sipai/controller/rabbitmq/MQController.java @@ -0,0 +1,29 @@ +package com.sipai.controller.rabbitmq; + +import com.sipai.service.rabbitmq.MQService; +import com.sipai.tools.ConstantString; +import io.swagger.annotations.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/mq") +@Api(value = "/mq", tags = "鍙戦丷abbitMQ娑堟伅") +public class MQController { + @Autowired + private MQService mQService; + + @RequestMapping("sendMQ") + @ApiOperation(value = "鍙戦佹秷鎭", notes = "鍙戦佹秷鎭", httpMethod = "POST") + @ApiResponses({@ApiResponse(code = 400, message = "璇锋眰鍙傛暟娌″~濂")}) + @ApiImplicitParams({ + @ApiImplicitParam(name = "msg", value = "msg", dataType = "String", paramType = "query", example = "YES! PPG", required = true), + }) + public String sendMQ(@RequestParam(value = "msg", required = false, defaultValue = "YES! PPG") String msg) { + this.mQService.sendMQ(ConstantString.MQ_ALARM_MQTT, msg); + return "success"; + } + +} diff --git a/src/main/java/com/sipai/controller/scada/MPointController.java b/src/main/java/com/sipai/controller/scada/MPointController.java new file mode 100644 index 0000000..69cfb70 --- /dev/null +++ b/src/main/java/com/sipai/controller/scada/MPointController.java @@ -0,0 +1,114 @@ +package com.sipai.controller.scada; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.sipai.config.AppConfig; +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.user.Company; +import com.sipai.entity.user.User; +import com.sipai.service.scada.MPointService; +import com.sipai.tools.CommString; +import com.sipai.tools.Result; +import org.redisson.api.RMapCache; +import org.redisson.api.RedissonClient; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: 浣犵殑鍚嶅瓧 + * @Date: 2021/04/25/21:42 + * @Description: + */ +@Controller +@RequestMapping("/mPoint") +public class MPointController { + @Autowired + private MPointService mPointService; + @Autowired + private RedissonClient redissonClient; + @Autowired + private AppConfig appConfig; + + @RequestMapping("/update.do") + @ResponseBody + public Integer update(HttpServletRequest request, Model model, + @ModelAttribute("mPoint") MPoint mPoint, + @ModelAttribute("bizid") String bizid) { + return mPointService.update(mPoint); + } + + @RequestMapping("/selectById.do") + @ResponseBody + public MPoint selectById(HttpServletRequest request, Model model, + @ModelAttribute(value = "id") String id) { + MPoint mPoint = mPointService.selectById4Es(id); + return mPoint; + } + + /** + * 绠$綉骞冲彴鑾峰彇瀹炴椂鏁版嵁鎺ュ彛 + * @param request + * @param model + * @param mpcode + * @return + */ + @RequestMapping("/getDataByMpCode.do") + @ResponseBody + public Result getDataByMpCode(HttpServletRequest request, Model model, + @ModelAttribute(value = "mpcode") String mpcode) { + JSONArray jsonArray = new JSONArray(); + + String[] mpcodes = mpcode.split(","); + if (mpcodes != null && mpcodes.length > 0) { + if (mpcodes.length > appConfig.getMaxPoints()) { + Result res = Result.failed("涓娆℃渶澶氬鐞" + appConfig.getMaxPoints() + "涓偣浣"); + return res; + } else { + System.out.println("鏀跺埌鐐逛綅锛" + mpcodes.length + "涓級锛"); + } + + String ids = ""; + for (int i = 0; i < mpcodes.length; i++) { + ids += "'" + mpcodes[i] + "',"; + } + ids = ids.substring(0, ids.length() - 1); + + Map map = new HashMap<>(); + List list = mPointService.selectListByWhere("where 1=1 and id in (" + ids + ")"); + for (MPoint mPoint : list) { + if (mPoint.getParmvalue() != null && mPoint.getMeasuredt() != null) { + map.put(mPoint.getId(), mPoint.getParmvalue() + ";" + mPoint.getMeasuredt()); + } + } + + for (int i = 0; i < mpcodes.length; i++) { + if (map.get(mpcodes[i]) != null) { + String[] val = map.get(mpcodes[i]).split(";"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("mpcode", mpcodes[i]); + jsonObject.put("parmvalue", val[0]); + jsonObject.put("measuredt", val[1].length() > 19 ? val[1].substring(0, 19) : val[1]); + jsonArray.add(jsonObject); + } else { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("mpcode", mpcodes[i]); + jsonObject.put("parmvalue", ""); + jsonObject.put("measuredt", ""); + jsonArray.add(jsonObject); + } + } + + } + Result res = Result.success(jsonArray); + return res; + } +} diff --git a/src/main/java/com/sipai/controller/user/CompanyController.java b/src/main/java/com/sipai/controller/user/CompanyController.java new file mode 100644 index 0000000..e2b9739 --- /dev/null +++ b/src/main/java/com/sipai/controller/user/CompanyController.java @@ -0,0 +1,40 @@ +package com.sipai.controller.user; + +import com.sipai.entity.user.Company; +import com.sipai.service.user.CompanyService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: 浣犵殑鍚嶅瓧 + * @Date: 2021/04/25/21:15 + * @Description: + */ +@Controller +@RequestMapping("/company") +public class CompanyController { + @Autowired + private CompanyService companyService; + + @RequestMapping("/save.do") + @ResponseBody + public Integer save(HttpServletRequest request, Model model, + @ModelAttribute("company") Company company) { + return companyService.insert(company); + } + + @RequestMapping("/delete.do") + @ResponseBody + public int delete(HttpServletRequest request, Model model, + @ModelAttribute("id") String id) { + return companyService.deleteByPrimaryKey(id); + } +} diff --git a/src/main/java/com/sipai/controller/user/UserController.java b/src/main/java/com/sipai/controller/user/UserController.java new file mode 100644 index 0000000..d6b8ef8 --- /dev/null +++ b/src/main/java/com/sipai/controller/user/UserController.java @@ -0,0 +1,35 @@ +package com.sipai.controller.user; + +import com.sipai.entity.user.User; +import com.sipai.service.user.UserService; +import com.sipai.tools.Result; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +@Controller +@RequestMapping("/user") +public class UserController { + @Autowired + private UserService userService; + + @RequestMapping(value = "/test1") + @ResponseBody + public Result index(HttpServletRequest request) { + Result result = Result.success(1); + return result; + } + + @RequestMapping(value = "/test2") + @ResponseBody + public Result index2(HttpServletRequest request) { + Result result = Result.failed(""); + return result; + } + +} diff --git a/src/main/java/com/sipai/dao/Listener/ListenerHisDao.java b/src/main/java/com/sipai/dao/Listener/ListenerHisDao.java new file mode 100644 index 0000000..6adf421 --- /dev/null +++ b/src/main/java/com/sipai/dao/Listener/ListenerHisDao.java @@ -0,0 +1,24 @@ +package com.sipai.dao.Listener; + +import com.sipai.dao.base.CommDaoImpl; +import com.sipai.entity.Listener.ListenerHis; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public class ListenerHisDao extends CommDaoImpl { + + public ListenerHisDao() { + super(); + this.setMappernamespace("Listener.ListenerHisMapper"); + } + + public List selectTopByWhere(String where) { + ListenerHis listenerHis = new ListenerHis(); + listenerHis.setWhere(where); + List list = this.getSqlSession().selectList("Listener.ListenerHisMapper.selectTopByWhere", listenerHis); + return list; + } + +} diff --git a/src/main/java/com/sipai/dao/Listener/ListenerInterfaceDao.java b/src/main/java/com/sipai/dao/Listener/ListenerInterfaceDao.java new file mode 100644 index 0000000..c0e866e --- /dev/null +++ b/src/main/java/com/sipai/dao/Listener/ListenerInterfaceDao.java @@ -0,0 +1,15 @@ +package com.sipai.dao.Listener; + +import com.sipai.dao.base.CommDaoImpl; +import com.sipai.entity.Listener.ListenerInterface; +import org.springframework.stereotype.Repository; + +@Repository +public class ListenerInterfaceDao extends CommDaoImpl { + + public ListenerInterfaceDao() { + super(); + this.setMappernamespace("Listener.ListenerInterfaceMapper"); + } + +} diff --git a/src/main/java/com/sipai/dao/Listener/ListenerMessageDao.java b/src/main/java/com/sipai/dao/Listener/ListenerMessageDao.java new file mode 100644 index 0000000..b57e891 --- /dev/null +++ b/src/main/java/com/sipai/dao/Listener/ListenerMessageDao.java @@ -0,0 +1,15 @@ +package com.sipai.dao.Listener; + +import com.sipai.dao.base.CommDaoImpl; +import com.sipai.entity.Listener.ListenerMessage; +import org.springframework.stereotype.Repository; + +@Repository +public class ListenerMessageDao extends CommDaoImpl { + + public ListenerMessageDao() { + super(); + this.setMappernamespace("Listener.ListenerMessageMapper"); + } + +} diff --git a/src/main/java/com/sipai/dao/Listener/ListenerPointDao.java b/src/main/java/com/sipai/dao/Listener/ListenerPointDao.java new file mode 100644 index 0000000..4ad8d53 --- /dev/null +++ b/src/main/java/com/sipai/dao/Listener/ListenerPointDao.java @@ -0,0 +1,15 @@ +package com.sipai.dao.Listener; + +import com.sipai.dao.base.CommDaoImpl; +import com.sipai.entity.Listener.ListenerPoint; +import org.springframework.stereotype.Repository; + +@Repository +public class ListenerPointDao extends CommDaoImpl { + + public ListenerPointDao() { + super(); + this.setMappernamespace("Listener.ListenerPointMapper"); + } + +} diff --git a/src/main/java/com/sipai/dao/base/CommDao.java b/src/main/java/com/sipai/dao/base/CommDao.java new file mode 100644 index 0000000..27f71d1 --- /dev/null +++ b/src/main/java/com/sipai/dao/base/CommDao.java @@ -0,0 +1,125 @@ +package com.sipai.dao.base; + +import java.util.List; + + +public interface CommDao{ + /**====鍩虹鐨凜URD鎿嶄綔====**/ + /** + * 鏍规嵁id鏌ユ壘鍞竴瀵硅薄 + * @param + * @param t + * @return + */ + public T selectByPrimaryKey(String t); + /** + * 鏍规嵁id鍒犻櫎鍞竴瀵硅薄 + * @param + * @param t + * @return + */ + public int deleteByPrimaryKey(String t); + /** + * 鏍规嵁瀵硅薄淇℃伅鎻掑叆鏁版嵁 + * @param + * @param t + * @return + */ + public int insert(T t); + /** + * 鏍规嵁瀵硅薄淇℃伅鎻掑叆鏁版嵁锛屽彧鎻掑叆涓嶄负null鐨勫瓧娈,涓嶄細褰卞搷鏈夐粯璁ゅ肩殑瀛楁 + * @param + * @param t + * @return + */ +// public int insertSelective(T t); + /** + * 鏍规嵁瀵硅薄淇℃伅鏇存柊鏁版嵁锛屽彧璺熸柊涓嶄负null鐨勫瓧娈 + * @param + * @param t + * @return + */ + public int updateByPrimaryKeySelective(T t); + /** + * 鏍规嵁瀵硅薄id淇℃伅鏇存柊鏁版嵁锛屽彧璺熸柊涓嶄负null鐨勫瓧娈 + * @param + * @param t + * @return + */ +// public int updateByPrimaryKey(T t); + + /**=====鎵╁睍鐨勬煡璇=====**/ + /** + * 鏍规嵁where鏉′欢鏌ユ壘鍞竴瀵硅薄 + * @param + * @param t + * @return + */ + public T selectByWhere(T t); + + /** + * 鏍规嵁where鏉′欢鏌ユ壘瀵硅薄鍒楄〃 + * @param + * @param t + * @return + */ + public List selectList(T t); + /** + * 鏌ユ壘鍜宼鏌愪簺鍊肩浉绛夌殑瀵硅薄鍒楄〃 + * @param + * @param t + * @return + */ + + /** + * 鏍规嵁where鏉′欢鏌ユ壘瀵硅薄鍒楄〃 + * @param + * @param t + * @return + */ + public List selectListByWhere(T t); + /** + * 鏌ユ壘鍜宼鏌愪簺鍊肩浉绛夌殑瀵硅薄鍒楄〃 + * @param + * @param t + * @return + */ + public List selectListByObj(T t); + /** + * 鏍规嵁sql璇彞鏌ユ壘瀵硅薄鍒楄〃 + * @param + * @param t + * @return + */ + public List selectListBySql(T t); + /** + * 鏍规嵁sql璇彞鏌ヨ鍞竴瀛楁鍊 + * @param + * @param t + * @return + */ + public Object selectValueBySql(T t); + /** + * 鏍规嵁where鏉′欢鍒犻櫎 + * @param + * @param t + */ + public int deleteByWhere(T t); + /** + * 鏍规嵁where鏉′欢鏇存柊 + * @param + * @param t + */ + public int updateByWhere(T t); + /** + * 鎵цsql璇彞 锛氬锛屽垹锛屾敼 + * @param + * @param t + */ + public int executeSql(T t); + public void commit(); + public void close(); + + +} + diff --git a/src/main/java/com/sipai/dao/base/CommDaoImpl.java b/src/main/java/com/sipai/dao/base/CommDaoImpl.java new file mode 100644 index 0000000..4b5bb11 --- /dev/null +++ b/src/main/java/com/sipai/dao/base/CommDaoImpl.java @@ -0,0 +1,151 @@ +package com.sipai.dao.base; + +import java.math.BigDecimal; +import java.util.List; + +import javax.annotation.Resource; + +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.springframework.stereotype.Repository; + +@Repository +public class CommDaoImpl implements CommDao { + @Resource + private SqlSessionFactory sqlSessionFactory; + @Resource + private SqlSession sqlSession; + private String mappernamespace; // 闇瑕佹搷浣滅殑mappernamespace鍚(涔熸槸鏁版嵁搴撹〃鍚) + private boolean isAuto = true;// 榛樿鑷姩鎻愪氦 + + public CommDaoImpl() { + super(); + } + + public SqlSessionFactory getSqlSessionFactory() { + return sqlSessionFactory; + } + + public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { + this.sqlSessionFactory = sqlSessionFactory; + } + + public boolean isAuto() { + return isAuto; + } + + public void setAuto(boolean isAuto) { + this.isAuto = isAuto; + } + + public String getMappernamespace() { + return mappernamespace; + } + + public void setMappernamespace(String mappernamespace) { + this.mappernamespace = mappernamespace; + } + + public T selectByPrimaryKey(String t){ + T o = getSqlSession().selectOne(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + return o; + } + /** + * wxp涓篴ctiviti娴嬭瘯淇敼 + * @param t + * @return + */ + public T selectByID(BigDecimal t){ + T o = getSqlSession().selectOne(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + return o; + } + public int deleteByPrimaryKey(String t) { + return getSqlSession().delete(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + + public int insert(T t){ + return getSqlSession().insert(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + + public int insertSelective(T t){ + return getSqlSession().insert(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + + public int updateByPrimaryKeySelective(T t){ + return getSqlSession().update(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + +// public int updateByPrimaryKey(T t){ +// return getSqlSession().update(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); +// } + + public T selectByWhere( T t) { + List list = getSqlSession().selectList(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + if (list != null && list.size() > 0) { + return list.get(0); + } else { + return null; + } + } + + public List selectList(T t) { + List list = getSqlSession().selectList(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + return list; + } + + public List selectListByWhere( T t) { + List list = getSqlSession().selectList(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + return list; + } + + public List selectListByObj(T t) { + List list = getSqlSession().selectList(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + return list; + } + public List selectListByt( T t) { + List list = getSqlSession().selectList(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + return list; + } + + public List selectListBySql( T t) { + List list = getSqlSession().selectList(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + return list; + } + + public T selectValueBySql( T t) { + List list = getSqlSession().selectList(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + if (list != null && list.size() > 0) { + return list.get(0); + } else { + return null; + } + } + + public int deleteByWhere( T t) { + return this.getSqlSession().delete(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + + public int updateByWhere( T t) { + return this.getSqlSession().update(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + + public int executeSql( T t) { + return this.getSqlSession().update(mappernamespace+"."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + + public void commit() { + if (sqlSession != null) + sqlSession.commit(); + } + + public SqlSession getSqlSession() { + sqlSession = sqlSession == null ? sqlSessionFactory.openSession(isAuto) : sqlSession; + return sqlSession; + } + + public void close() { + if (sqlSession != null) + sqlSession.close(); + } + +} diff --git a/src/main/java/com/sipai/dao/data/PipeTopicMpointDao.java b/src/main/java/com/sipai/dao/data/PipeTopicMpointDao.java new file mode 100644 index 0000000..9fb8d0a --- /dev/null +++ b/src/main/java/com/sipai/dao/data/PipeTopicMpointDao.java @@ -0,0 +1,43 @@ +package com.sipai.dao.data; + +import com.sipai.entity.data.PipeTopicMpoint; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +@Repository +public interface PipeTopicMpointDao { + + /** + * 娣诲姞绠$綉涓撻椤电偣浣嶄俊鎭 + */ + int insert(PipeTopicMpoint pipeTopicMpoint); + + /** + * 鏍规嵁涓婚敭鍒犻櫎鐐逛綅淇℃伅 + */ + boolean deleteByPrimaryKey(Integer id); + + /** + * 鎵归噺鍒犻櫎鐐逛綅淇℃伅 + */ + int deleteBatchByIds(@Param("list") List idList); + + /** + * 鏇存柊鐐逛綅淇℃伅 + */ + boolean updateByPrimaryKeySelective(PipeTopicMpoint pipeTopicMpoint); + + /** + * 鏍规嵁涓婚敭鑾峰彇鐐逛綅璇︽儏 + */ + PipeTopicMpoint selectByPrimaryKey(Integer id); + + /** + * 鏍规嵁鏉′欢鏌ヨ鐐逛綅鍒楄〃 + */ + List selectListByWhere(PipeTopicMpoint pipeTopicMpoint); +} \ No newline at end of file diff --git a/src/main/java/com/sipai/dao/data/PipelineEquipmentDao.java b/src/main/java/com/sipai/dao/data/PipelineEquipmentDao.java new file mode 100644 index 0000000..5b69da8 --- /dev/null +++ b/src/main/java/com/sipai/dao/data/PipelineEquipmentDao.java @@ -0,0 +1,47 @@ +package com.sipai.dao.data; + +import com.sipai.dao.base.CommDaoImpl; +import com.sipai.entity.data.PipelineEquipment; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +@Repository +public interface PipelineEquipmentDao{ + + /** + * 娣诲姞璁惧 + */ + int insert(PipelineEquipment pipelineEquipment); + + /** + * 鍒犻櫎璁惧 + */ + boolean deleteByPrimaryKey(Integer id); + + /** + * 澶氬垹璁惧 + * @param idList + * @return + */ + int deleteBatchByIds(@Param("list") List idList); + + /** + * 鏇存柊璁惧淇℃伅 + */ + boolean updateByPrimaryKeySelective(PipelineEquipment equipment); + + /** + * 鑾峰彇璁惧璇︽儏 + */ + PipelineEquipment selectByPrimaryKey(Integer id); + + /** + * 鑾峰彇鎵鏈夎澶囧垪琛 + */ + List selectListByWhere(PipelineEquipment equipment); + +} diff --git a/src/main/java/com/sipai/dao/data/PipelineEquipmentMpointDao.java b/src/main/java/com/sipai/dao/data/PipelineEquipmentMpointDao.java new file mode 100644 index 0000000..596ff3c --- /dev/null +++ b/src/main/java/com/sipai/dao/data/PipelineEquipmentMpointDao.java @@ -0,0 +1,37 @@ +package com.sipai.dao.data; + +import com.sipai.entity.data.PipelineEquipmentMpoint; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +@Repository +public interface PipelineEquipmentMpointDao { + + /** + * 娣诲姞鍏宠仈淇℃伅 + */ + boolean insert(PipelineEquipmentMpoint mpoint); + + /** + * 鍒犻櫎鍏宠仈淇℃伅 + */ + boolean deleteByPrimaryKey(Integer id); + + /** + * 鏇存柊鍏宠仈淇℃伅 + */ + boolean updateByPrimaryKeySelective(PipelineEquipmentMpoint mpoint); + + /** + * 鑾峰彇鍏宠仈淇℃伅璇︽儏 + */ + PipelineEquipmentMpoint selectByPrimaryKey(Integer id); + + /** + * 鑾峰彇鎵鏈夊叧鑱斾俊鎭垪琛 + */ + List selectListByWhere(PipelineEquipmentMpoint mpoint); +} \ No newline at end of file diff --git a/src/main/java/com/sipai/dao/data/PipelineMpointLibraryDao.java b/src/main/java/com/sipai/dao/data/PipelineMpointLibraryDao.java new file mode 100644 index 0000000..020f526 --- /dev/null +++ b/src/main/java/com/sipai/dao/data/PipelineMpointLibraryDao.java @@ -0,0 +1,45 @@ +package com.sipai.dao.data; + +import com.sipai.entity.data.PipelineMpointLibrary; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +@Repository +public interface PipelineMpointLibraryDao { + + /** + * 娣诲姞娴嬬偣搴撲俊鎭 + */ + boolean insert(PipelineMpointLibrary mpointLibrary); + + /** + * 鍒犻櫎娴嬬偣搴撲俊鎭 + */ + boolean deleteByPrimaryKey(String id); + + /** + * 澶氬垹娴嬬偣搴撲俊鎭 + * @param idList + * @return + */ + int deleteBatchByIds(@Param("list") List idList); + + /** + * 鏇存柊娴嬬偣搴撲俊鎭 + */ + boolean updateByPrimaryKeySelective(PipelineMpointLibrary mpointLibrary); + + /** + * 鑾峰彇娴嬬偣搴撹鎯 + */ + PipelineMpointLibrary selectByPrimaryKey(String id); + + /** + * 鑾峰彇鎵鏈夋祴鐐瑰簱鍒楄〃 + */ + List selectListByWhere(PipelineMpointLibrary mpointLibrary); +} \ No newline at end of file diff --git a/src/main/java/com/sipai/dao/mqtt/MqttConfigDao.java b/src/main/java/com/sipai/dao/mqtt/MqttConfigDao.java new file mode 100644 index 0000000..2b22928 --- /dev/null +++ b/src/main/java/com/sipai/dao/mqtt/MqttConfigDao.java @@ -0,0 +1,32 @@ +package com.sipai.dao.mqtt; + +import com.sipai.entity.mqtt.MqttConfig; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: 浣犵殑鍚嶅瓧 + * @Date: 2021/03/24/17:14 + * @Description: + */ +@Mapper +@Repository +public interface MqttConfigDao { + + public abstract MqttConfig selectByPrimaryKey(String id); + + public abstract Integer deleteByPrimaryKey(String id); + + public abstract Integer insert(MqttConfig entity); + + public abstract Integer updateByPrimaryKeySelective(MqttConfig entity); + + public abstract List selectListByWhere(MqttConfig entity); + + public abstract Integer deleteByWhere(String where); + +} diff --git a/src/main/java/com/sipai/dao/mqtt/MqttConfigTopicDao.java b/src/main/java/com/sipai/dao/mqtt/MqttConfigTopicDao.java new file mode 100644 index 0000000..a628ac1 --- /dev/null +++ b/src/main/java/com/sipai/dao/mqtt/MqttConfigTopicDao.java @@ -0,0 +1,34 @@ +package com.sipai.dao.mqtt; + +import com.sipai.entity.mqtt.MqttConfigTopic; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: 浣犵殑鍚嶅瓧 + * @Date: 2021/03/24/17:55 + * @Description: + */ +@Mapper +@Repository +public interface MqttConfigTopicDao { + + public abstract MqttConfigTopic selectByPrimaryKey(String id); + + public abstract Integer deleteByPrimaryKey(String id); + + public abstract Integer insert(MqttConfigTopic entity); + + public abstract Integer updateByPrimaryKeySelective(MqttConfigTopic entity); + + public abstract List selectListByWhere(MqttConfigTopic entity); + + public abstract Integer deleteByWhere(String wherestr); + + public abstract List selectListByPid(String pid); + +} diff --git a/src/main/java/com/sipai/dao/scada/MPointBzwDao.java b/src/main/java/com/sipai/dao/scada/MPointBzwDao.java new file mode 100644 index 0000000..ba52a48 --- /dev/null +++ b/src/main/java/com/sipai/dao/scada/MPointBzwDao.java @@ -0,0 +1,25 @@ +package com.sipai.dao.scada; + +import com.sipai.entity.scada.MPointBzw; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +@Repository +public interface MPointBzwDao { + + public abstract MPointBzw selectByPrimaryKey(String id); + + public abstract int deleteByPrimaryKey(String id); + + public abstract int insert(MPointBzw entity); + + public abstract int updateByPrimaryKeySelective(MPointBzw entity); + + public abstract List selectListByWhere(MPointBzw entity); + + public abstract int deleteByWhere(String where); + +} diff --git a/src/main/java/com/sipai/dao/scada/MPointDao.java b/src/main/java/com/sipai/dao/scada/MPointDao.java new file mode 100644 index 0000000..480dd69 --- /dev/null +++ b/src/main/java/com/sipai/dao/scada/MPointDao.java @@ -0,0 +1,19 @@ +package com.sipai.dao.scada; + + +import com.sipai.dao.base.CommDaoImpl; +import com.sipai.entity.scada.MPoint; +import org.springframework.stereotype.Repository; + + +@Repository +public class MPointDao extends CommDaoImpl { + public MPointDao() { + super(); + this.setMappernamespace("scada.MPointMapper"); + } + + public int updateValueByKey(MPoint t) { + return getSqlSession().update("scada.MPointMapper."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/dao/scada/MPointHistoryDao.java b/src/main/java/com/sipai/dao/scada/MPointHistoryDao.java new file mode 100644 index 0000000..ee11507 --- /dev/null +++ b/src/main/java/com/sipai/dao/scada/MPointHistoryDao.java @@ -0,0 +1,64 @@ +package com.sipai.dao.scada; + +import com.sipai.dao.base.CommDaoImpl; +import com.sipai.entity.scada.MPointHistory; +import org.springframework.stereotype.Repository; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Repository +public class MPointHistoryDao extends CommDaoImpl { + public MPointHistoryDao() { + super(); + this.setMappernamespace("scada.MPointHistoryMapper"); + } + + public List selectListByTableAWhere(String tablename, String wherestr) { + Map paramMap=new HashMap<>(); + paramMap.put("table",tablename); + paramMap.put("where",wherestr); + List list = getSqlSession().selectList("scada.MPointHistoryMapper."+Thread.currentThread().getStackTrace()[1].getMethodName(), paramMap); + return list; + } + + public int deleteByTableAWhere(String tablename, String wherestr) { + Map paramMap=new HashMap<>(); + paramMap.put("table",tablename); + paramMap.put("where",wherestr); + return this.getSqlSession().delete("scada.MPointHistoryMapper."+Thread.currentThread().getStackTrace()[1].getMethodName(), paramMap); + } + + public int createTable(String tablename){ + Map paramMap=new HashMap<>(1); + paramMap.put("table",tablename); + return getSqlSession().update("scada.MPointHistoryMapper."+Thread.currentThread().getStackTrace()[1].getMethodName(), paramMap); + } + + public Integer checkTableExist(String tablename){ + Map paramMap = new HashMap<>(1); + paramMap.put("table",tablename); + return getSqlSession().selectOne("scada.MPointHistoryMapper.checkTableExist", paramMap); + } + + public Integer selectCount(MPointHistory t){ + return getSqlSession().selectOne("scada.MPointHistoryMapper."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + + public int updateByMeasureDt(MPointHistory t) { + return getSqlSession().update("scada.MPointHistoryMapper."+Thread.currentThread().getStackTrace()[1].getMethodName(), t); + } + + public List selectIndustrialLibrary(String IP,String MPointID, String intv, String sdt,String edt) { + Map paramMap=new HashMap<>(); + paramMap.put("IP",IP); + paramMap.put("MPointID",MPointID); + paramMap.put("intv",intv); + paramMap.put("sdt",sdt); + paramMap.put("edt",edt); + List list = getSqlSession().selectList("scada.MPointHistoryMapper."+Thread.currentThread().getStackTrace()[1].getMethodName(), paramMap); + return list; + } + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/dao/scada/MPointRepo.java b/src/main/java/com/sipai/dao/scada/MPointRepo.java new file mode 100644 index 0000000..a09486b --- /dev/null +++ b/src/main/java/com/sipai/dao/scada/MPointRepo.java @@ -0,0 +1,8 @@ +package com.sipai.dao.scada; + +import com.sipai.entity.scada.MPoint; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +public interface MPointRepo extends ElasticsearchRepository, MPointRepository { + +} diff --git a/src/main/java/com/sipai/dao/scada/MPointRepository.java b/src/main/java/com/sipai/dao/scada/MPointRepository.java new file mode 100644 index 0000000..ba5a784 --- /dev/null +++ b/src/main/java/com/sipai/dao/scada/MPointRepository.java @@ -0,0 +1,13 @@ +package com.sipai.dao.scada; + +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointES; + +import java.util.List; + +public interface MPointRepository { +// int updateSelective(MPoint mpoint); +// int updateValue(MPoint mpoint); + void batchInsert(List mPointES); + void batchUpdate(List mPointES); +} diff --git a/src/main/java/com/sipai/dao/scada/MPointRepositoryImpl.java b/src/main/java/com/sipai/dao/scada/MPointRepositoryImpl.java new file mode 100644 index 0000000..6b950f4 --- /dev/null +++ b/src/main/java/com/sipai/dao/scada/MPointRepositoryImpl.java @@ -0,0 +1,105 @@ +package com.sipai.dao.scada; + +import com.google.gson.Gson; +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointES; +import com.sipai.tools.CommUtil; +import org.elasticsearch.action.index.IndexRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.core.query.IndexQuery; +import org.springframework.data.elasticsearch.core.query.UpdateQuery; +import org.springframework.data.elasticsearch.core.query.UpdateQueryBuilder; + +import java.beans.PropertyDescriptor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +public class MPointRepositoryImpl implements MPointRepository { + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; + + public void batchInsert(List mPointES){ + + int counter = 0; + + //鍒ゆ柇index 鏄惁瀛樺湪 + if (!elasticsearchTemplate.indexExists("es_measurepoint")) { + elasticsearchTemplate.createIndex("es_measurepoint"); + } + + Gson gson = new Gson(); + List queries = new ArrayList(); + if(mPointES != null && mPointES.size()>0){ + for (MPointES item : mPointES) { + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(item.getId().toString()); + indexQuery.setSource(gson.toJson(item)); + indexQuery.setIndexName("es_measurepoint"); + indexQuery.setType("esmeasurepoint"); + queries.add(indexQuery); + //鍒嗘壒鎻愪氦绱㈠紩 + if (counter % 500 == 0) { + elasticsearchTemplate.bulkIndex(queries); + queries.clear(); + //System.out.println("bulkIndex counter : " + counter); + } + counter++; + } + + } + //涓嶈冻鎵圭殑绱㈠紩鏈鍚庝笉瑕佸繕璁版彁浜 + if (queries.size() > 0) { + elasticsearchTemplate.bulkIndex(queries); + } +// elasticsearchTemplate.refresh("es_measurepoint"); + } + + @Override + public void batchUpdate(List mPointES) { + + int counter = 0; + + //鍒ゆ柇index 鏄惁瀛樺湪 + if (!elasticsearchTemplate.indexExists("es_measurepoint")) { + elasticsearchTemplate.createIndex("es_measurepoint"); + } + + Gson gson = new Gson(); + + List queries = new ArrayList<>(); + if (mPointES != null && mPointES.size() > 0) { + for (MPointES item : mPointES) { + if (item.getMeasuredt() != null) { + IndexRequest indexRequest = new IndexRequest(); + indexRequest.source("measuredt", item.getMeasuredt()); + UpdateQuery updateQuery = new UpdateQueryBuilder().withId(item.getId()).withClass(MPoint.class).withIndexRequest(indexRequest).build(); + queries.add(updateQuery); + } + if (item.getParmvalue() != null) { + IndexRequest indexRequest = new IndexRequest(); + indexRequest.source("parmvalue", item.getParmvalue()); + UpdateQuery updateQuery = new UpdateQueryBuilder().withId(item.getId()).withClass(MPoint.class).withIndexRequest(indexRequest).build(); + queries.add(updateQuery); + } + //鍒嗘壒鎻愪氦绱㈠紩 + if (counter % 500 == 0) { + elasticsearchTemplate.bulkUpdate(queries); + queries.clear(); + } + counter++; + } + } + + //涓嶈冻鎵圭殑绱㈠紩鏈鍚庝笉瑕佸繕璁版彁浜 + if (queries.size() > 0) { + elasticsearchTemplate.bulkUpdate(queries); + } +// elasticsearchTemplate.refresh("es_measurepoint"); + } +} diff --git a/src/main/java/com/sipai/dao/user/CompanyDao.java b/src/main/java/com/sipai/dao/user/CompanyDao.java new file mode 100644 index 0000000..9437b85 --- /dev/null +++ b/src/main/java/com/sipai/dao/user/CompanyDao.java @@ -0,0 +1,25 @@ +package com.sipai.dao.user; + +import com.sipai.entity.user.Company; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +@Repository +public interface CompanyDao { + + public abstract Company selectByPrimaryKey(String id); + + public abstract Integer deleteByPrimaryKey(String id); + + public abstract Integer insert(Company entity); + + public abstract Integer updateByPrimaryKeySelective(Company entity); + + public abstract List selectListByWhere(Company entity); + + public abstract Integer deleteByWhere(String where); + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/dao/user/UserDao.java b/src/main/java/com/sipai/dao/user/UserDao.java new file mode 100644 index 0000000..a5e3f60 --- /dev/null +++ b/src/main/java/com/sipai/dao/user/UserDao.java @@ -0,0 +1,13 @@ +package com.sipai.dao.user; + +import com.sipai.entity.user.User; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +@Repository +public interface UserDao { + public abstract List listuser2(); +} diff --git a/src/main/java/com/sipai/entity/Listener/ListenerHis.java b/src/main/java/com/sipai/entity/Listener/ListenerHis.java new file mode 100644 index 0000000..e51877b --- /dev/null +++ b/src/main/java/com/sipai/entity/Listener/ListenerHis.java @@ -0,0 +1,56 @@ +package com.sipai.entity.Listener; + +import com.sipai.entity.base.SQLAdapter; + +public class ListenerHis extends SQLAdapter { + + private String id; + + private String pointid; + + private String value; + + private String type; + + private String insdt; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getPointid() { + return pointid; + } + + public void setPointid(String pointid) { + this.pointid = pointid; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getInsdt() { + return insdt; + } + + public void setInsdt(String insdt) { + this.insdt = insdt; + } +} diff --git a/src/main/java/com/sipai/entity/Listener/ListenerInterface.java b/src/main/java/com/sipai/entity/Listener/ListenerInterface.java new file mode 100644 index 0000000..7d8d80c --- /dev/null +++ b/src/main/java/com/sipai/entity/Listener/ListenerInterface.java @@ -0,0 +1,56 @@ +package com.sipai.entity.Listener; + +import com.sipai.entity.base.SQLAdapter; + +public class ListenerInterface extends SQLAdapter { + + private String id; + + private String name; + + private String type; + + private String url; + + private String port; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getPort() { + return port; + } + + public void setPort(String port) { + this.port = port; + } +} diff --git a/src/main/java/com/sipai/entity/Listener/ListenerMessage.java b/src/main/java/com/sipai/entity/Listener/ListenerMessage.java new file mode 100644 index 0000000..04ebbe9 --- /dev/null +++ b/src/main/java/com/sipai/entity/Listener/ListenerMessage.java @@ -0,0 +1,86 @@ +package com.sipai.entity.Listener; + +import com.sipai.entity.base.SQLAdapter; +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.user.Company; + +public class ListenerMessage extends SQLAdapter { + + private String id; + + private String Cmdtype; + + private String Objid; + + private String Action; + + private String insdt; + + private MPoint mPoint; +// private ProcessSection processSection; + private Company company; + + public MPoint getmPoint() { + return mPoint; + } + + public void setmPoint(MPoint mPoint) { + this.mPoint = mPoint; + } + +// public ProcessSection getProcessSection() { +// return processSection; +// } +// +// public void setProcessSection(ProcessSection processSection) { +// this.processSection = processSection; +// } + + public Company getCompany() { + return company; + } + + public void setCompany(Company company) { + this.company = company; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getCmdtype() { + return Cmdtype; + } + + public void setCmdtype(String cmdtype) { + Cmdtype = cmdtype; + } + + public String getObjid() { + return Objid; + } + + public void setObjid(String objid) { + Objid = objid; + } + + public String getAction() { + return Action; + } + + public void setAction(String action) { + Action = action; + } + + public String getInsdt() { + return insdt; + } + + public void setInsdt(String insdt) { + this.insdt = insdt; + } +} diff --git a/src/main/java/com/sipai/entity/Listener/ListenerPoint.java b/src/main/java/com/sipai/entity/Listener/ListenerPoint.java new file mode 100644 index 0000000..ef83dec --- /dev/null +++ b/src/main/java/com/sipai/entity/Listener/ListenerPoint.java @@ -0,0 +1,123 @@ +package com.sipai.entity.Listener; + +import com.sipai.entity.base.SQLAdapter; + +public class ListenerPoint extends SQLAdapter { + + private String id; + + private String intid; + + private String name; + + private String address; + + private String type; + + private String mpcode; + + private String datatype; + + private String unitid; + + //閫昏緫鏉′欢 + //= 绛変簬 + //> 澶т簬 + //< 灏忎簬 + //change 鍙樺寲 + private String logi; + + //閫昏緫鏉′欢瀵瑰簲鐨勫 + private String logiVal; + + //鍔ㄤ綔 濡傜瓑浜巖eset 涓虹疆0 + private String action; + + public String getLogiVal() { + return logiVal; + } + + public void setLogiVal(String logiVal) { + this.logiVal = logiVal; + } + + public String getLogi() { + return logi; + } + + public void setLogi(String logi) { + this.logi = logi; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getIntid() { + return intid; + } + + public void setIntid(String intid) { + this.intid = intid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMpcode() { + return mpcode; + } + + public void setMpcode(String mpcode) { + this.mpcode = mpcode; + } + + public String getDatatype() { + return datatype; + } + + public void setDatatype(String datatype) { + this.datatype = datatype; + } + + public String getUnitid() { + return unitid; + } + + public void setUnitid(String unitid) { + this.unitid = unitid; + } +} diff --git a/src/main/java/com/sipai/entity/base/Result.java b/src/main/java/com/sipai/entity/base/Result.java new file mode 100644 index 0000000..cb4cbd7 --- /dev/null +++ b/src/main/java/com/sipai/entity/base/Result.java @@ -0,0 +1,65 @@ +package com.sipai.entity.base; + +import com.alibaba.fastjson.JSON; + +/** + * + * @author WXP + * + */ +public class Result { + public static final int SUCCESS = 1; + public static final int FAILED = 0; + public static final int REPEATED = 2;//閲嶅娣诲姞 + + public Result(){ + + } + public Result(int code, String message, Object result) { + this.code = code; + this.msg = message; + if (result instanceof String) { + this.result = JSON.parse(result.toString()); + }else{ + this.result =result; + } + + } + public static Result success(Object result,String msg) { + return new Result(SUCCESS, msg, result); + } + public static Result success(Object result) { + return new Result(SUCCESS, "", result); + } + public static Result success() { + return new Result(SUCCESS, "", null); + } + public static Result failed(String msg) { + return new Result(FAILED, msg, null); + } + public int code; + public String msg; + public Object result; + + public int getCode() { + return code; + } + public void setCode(int code) { + this.code = code; + } + public String getMsg() { + return msg; + } + public void setMsg(String msg) { + this.msg = msg; + } + public Object getResult() { + return result; + } + public void setResult(Object result) { + this.result = result; + } + + + +} diff --git a/src/main/java/com/sipai/entity/base/SQLAdapter.java b/src/main/java/com/sipai/entity/base/SQLAdapter.java new file mode 100644 index 0000000..a3cee4a --- /dev/null +++ b/src/main/java/com/sipai/entity/base/SQLAdapter.java @@ -0,0 +1,22 @@ +package com.sipai.entity.base; + +public class SQLAdapter { + private String sql; + private String where; + + public String getSql() { + return sql; + } + public void setSql(String sql) { + this.sql = sql; + } + + public String getWhere() { + return where; + } + + public void setWhere(String where) { + this.where = where; + } + +} diff --git a/src/main/java/com/sipai/entity/common/PageData.java b/src/main/java/com/sipai/entity/common/PageData.java new file mode 100644 index 0000000..4f3c0d1 --- /dev/null +++ b/src/main/java/com/sipai/entity/common/PageData.java @@ -0,0 +1,37 @@ +package com.sipai.entity.common; + +import com.github.pagehelper.PageInfo; +import java.util.List; + +/** + * 鍒嗛〉鏁版嵁灏佽绫 + */ +public class PageData { + private long total; // 鎬昏褰曟暟 + private int pageSize; // 姣忛〉澶у皬 + private int pageNum; // 褰撳墠椤电爜 + private int pages; // 鎬婚〉鏁 + private List list; // 鏁版嵁鍒楄〃 + + public PageData() {} + + public PageData(PageInfo pageInfo) { + this.total = pageInfo.getTotal(); + this.pageSize = pageInfo.getPageSize(); + this.pageNum = pageInfo.getPageNum(); + this.pages = pageInfo.getPages(); + this.list = pageInfo.getList(); + } + + // getters and setters + public long getTotal() { return total; } + public void setTotal(long total) { this.total = total; } + public int getPageSize() { return pageSize; } + public void setPageSize(int pageSize) { this.pageSize = pageSize; } + public int getPageNum() { return pageNum; } + public void setPageNum(int pageNum) { this.pageNum = pageNum; } + public int getPages() { return pages; } + public void setPages(int pages) { this.pages = pages; } + public List getList() { return list; } + public void setList(List list) { this.list = list; } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/data/ChannelData.java b/src/main/java/com/sipai/entity/data/ChannelData.java new file mode 100644 index 0000000..62b71c4 --- /dev/null +++ b/src/main/java/com/sipai/entity/data/ChannelData.java @@ -0,0 +1,82 @@ +package com.sipai.entity.data; + +import java.util.List; + +/** + * 鎶ユ枃瀹炰綋绫 + * 棰戦亾鏁版嵁 + */ +public class ChannelData { + private int type; // 绫诲瀷 1-6 + private int channelNumber; // 閫氶亾鍙 + private String channelName; // 閫氶亾鍚嶇О P1, P2绛 + private int yesterdayFlow; // 鏄ㄦ棩娴侀噺 + private List cumulativeFlows; // 绱娴侀噺鍒楄〃 + private List analogValues; // 妯℃嫙閲忔暟鎹(绫诲瀷4) + private Integer qChannelData; // Q閫氶亾鏁版嵁(绫诲瀷5) + private Integer mChannelData; // M閫氶亾鏁版嵁(绫诲瀷6) + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + public int getChannelNumber() { + return channelNumber; + } + + public void setChannelNumber(int channelNumber) { + this.channelNumber = channelNumber; + } + + public String getChannelName() { + return channelName; + } + + public void setChannelName(String channelName) { + this.channelName = channelName; + } + + public int getYesterdayFlow() { + return yesterdayFlow; + } + + public void setYesterdayFlow(int yesterdayFlow) { + this.yesterdayFlow = yesterdayFlow; + } + + public List getCumulativeFlows() { + return cumulativeFlows; + } + + public void setCumulativeFlows(List cumulativeFlows) { + this.cumulativeFlows = cumulativeFlows; + } + + public List getAnalogValues() { + return analogValues; + } + + public void setAnalogValues(List analogValues) { + this.analogValues = analogValues; + } + + public Integer getqChannelData() { + return qChannelData; + } + + public void setqChannelData(Integer qChannelData) { + this.qChannelData = qChannelData; + } + + public Integer getmChannelData() { + return mChannelData; + } + + public void setmChannelData(Integer mChannelData) { + this.mChannelData = mChannelData; + } +} diff --git a/src/main/java/com/sipai/entity/data/DeviceData.java b/src/main/java/com/sipai/entity/data/DeviceData.java new file mode 100644 index 0000000..e0de66f --- /dev/null +++ b/src/main/java/com/sipai/entity/data/DeviceData.java @@ -0,0 +1,88 @@ +package com.sipai.entity.data; + +import java.util.List; + +public class DeviceData { + private int stationId; + private String startTime; + private int dataCount; + private int length; + private int intervalMinutes; + private float batteryVoltage; + private String deviceInfo; + + private int uploadCount; + private List sensorDataList; + + public int getUploadCount() { + return uploadCount; + } + + public void setUploadCount(int uploadCount) { + this.uploadCount = uploadCount; + } + + public int getLength() { + return length; + } + + public void setLength(int length) { + this.length = length; + } + + public int getStationId() { + return stationId; + } + + public void setStationId(int stationId) { + this.stationId = stationId; + } + + public String getStartTime() { + return startTime; + } + + public void setStartTime(String startTime) { + this.startTime = startTime; + } + + public int getDataCount() { + return dataCount; + } + + public void setDataCount(int dataCount) { + this.dataCount = dataCount; + } + + public int getIntervalMinutes() { + return intervalMinutes; + } + + public void setIntervalMinutes(int intervalMinutes) { + this.intervalMinutes = intervalMinutes; + } + + public float getBatteryVoltage() { + return batteryVoltage; + } + + public void setBatteryVoltage(float batteryVoltage) { + this.batteryVoltage = batteryVoltage; + } + + public String getDeviceInfo() { + return deviceInfo; + } + + public void setDeviceInfo(String deviceInfo) { + this.deviceInfo = deviceInfo; + } + + public List getSensorDataList() { + return sensorDataList; + } + + public void setSensorDataList(List sensorDataList) { + this.sensorDataList = sensorDataList; + } +} diff --git a/src/main/java/com/sipai/entity/data/DeviceDataPacket.java b/src/main/java/com/sipai/entity/data/DeviceDataPacket.java new file mode 100644 index 0000000..f04a42d --- /dev/null +++ b/src/main/java/com/sipai/entity/data/DeviceDataPacket.java @@ -0,0 +1,131 @@ +package com.sipai.entity.data; + +import java.time.LocalDateTime; +import java.util.Date; +import java.util.List; + +/** + * 鎶ユ枃瀹炰綋绫 + * 璁惧鏁版嵁鍒嗙粍 + */ +public class DeviceDataPacket { + private String startCode; // 璧峰绗 AB CD + private int length; // 闀垮害 0x007D + private int stationId; // 绔欏彿 0x0066 + private LocalDateTime timestamp; // 骞存湀鏃ユ椂鍒 11 05 24 16 15 + private int dataCount; // 鏁版嵁涓暟 0x03 + private int interval; // 鏁版嵁闂撮殧(鍒嗛挓) 0x15 + private float batteryVoltage; // 鐢垫睜鐢靛帇 7.18V + private int uploadCount; // 涓婂彂娆℃暟 5 + private int signalStrength; // 淇″彿寮哄害 0x1E + private String deviceInfo; // 璁惧淇℃伅 "D115 1.4 1.0.11" + private List channelDataList; // 閫氶亾鏁版嵁鍒楄〃 + private int checksum; // 鏍¢獙鍜 + private String endCode; // 缁撴潫绗 0D 0A + + public String getStartCode() { + return startCode; + } + + public void setStartCode(String startCode) { + this.startCode = startCode; + } + + public int getLength() { + return length; + } + + public void setLength(int length) { + this.length = length; + } + + public int getStationId() { + return stationId; + } + + public void setStationId(int stationId) { + this.stationId = stationId; + } + + public LocalDateTime getTimestamp() { + return timestamp; + } + + public void setTimestamp(LocalDateTime timestamp) { + this.timestamp = timestamp; + } + + public int getDataCount() { + return dataCount; + } + + public void setDataCount(int dataCount) { + this.dataCount = dataCount; + } + + public int getInterval() { + return interval; + } + + public void setInterval(int interval) { + this.interval = interval; + } + + public float getBatteryVoltage() { + return batteryVoltage; + } + + public void setBatteryVoltage(float batteryVoltage) { + this.batteryVoltage = batteryVoltage; + } + + public int getUploadCount() { + return uploadCount; + } + + public void setUploadCount(int uploadCount) { + this.uploadCount = uploadCount; + } + + public int getSignalStrength() { + return signalStrength; + } + + public void setSignalStrength(int signalStrength) { + this.signalStrength = signalStrength; + } + + public String getDeviceInfo() { + return deviceInfo; + } + + public void setDeviceInfo(String deviceInfo) { + this.deviceInfo = deviceInfo; + } + + public List getChannelDataList() { + return channelDataList; + } + + public void setChannelDataList(List channelDataList) { + this.channelDataList = channelDataList; + } + + public int getChecksum() { + return checksum; + } + + public void setChecksum(int checksum) { + this.checksum = checksum; + } + + public String getEndCode() { + return endCode; + } + + public void setEndCode(String endCode) { + this.endCode = endCode; + } +} + + diff --git a/src/main/java/com/sipai/entity/data/PipeTopicMpoint.java b/src/main/java/com/sipai/entity/data/PipeTopicMpoint.java new file mode 100644 index 0000000..d85b168 --- /dev/null +++ b/src/main/java/com/sipai/entity/data/PipeTopicMpoint.java @@ -0,0 +1,28 @@ +package com.sipai.entity.data; + +import com.sipai.entity.base.SQLAdapter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** + * 绠$綉涓撻椤电偣浣嶄俊鎭疄浣撶被 + */ +@Data +public class PipeTopicMpoint extends SQLAdapter implements Serializable { + private Integer id; // 鑷涓婚敭 + private String pointName; // 鐐逛綅鍚嶇О + private String pointCode; // 鐐逛綅缂栧彿 + private String type; // 鎵灞炵被鍨 + private Integer isConstant; // 鏄惁甯搁噺锛0-鍚︼紝1-鏄級 + private String constantValue; // 甯搁噺鍊 + private Integer sortOrder; // 鎺掑簭搴忓彿 + + @JsonIgnore + private String sql; + + @JsonIgnore + private String where; +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/data/PipelineEquipment.java b/src/main/java/com/sipai/entity/data/PipelineEquipment.java new file mode 100644 index 0000000..27a0401 --- /dev/null +++ b/src/main/java/com/sipai/entity/data/PipelineEquipment.java @@ -0,0 +1,32 @@ +package com.sipai.entity.data; + +import com.sipai.entity.base.SQLAdapter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * 绠¢亾璁惧瀹炰綋绫 + */ +@Data +public class PipelineEquipment extends SQLAdapter implements Serializable { + private Integer id; + private String stationCode;//绔欑偣缂栧彿 + private String equipmentType;//璁惧绫诲瀷锛氫簳鐩栥佹祦閲忚銆佹恫浣嶈銆佺數瀵肩巼銆侀洦閲忚銆佸唴娑濈洃娴 + private String productModel;//浜у搧鍨嬪彿 + private Integer uploadCycle;//涓婁紶鍛ㄦ湡 + private String uploadCycleUnit;//涓婁紶鍛ㄦ湡 鍗曚綅 + private String lastUploadTime;//鏈杩戜竴娆′笂浼犳暟鎹椂闂 + private String status; //1鍦ㄧ嚎 0绂荤嚎 null涓烘湭妫娴 + + //鐢ㄤ簬鏌ヨ瀵瑰簲鐨刵ame + private String equipmentTypeName;//璁惧绫诲瀷锛氫簳鐩栥佹祦閲忚銆佹恫浣嶈銆佺數瀵肩巼銆侀洦閲忚銆佸唴娑濈洃娴 + + @JsonIgnore + private String sql; + + @JsonIgnore + private String where; +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/data/PipelineEquipmentMpoint.java b/src/main/java/com/sipai/entity/data/PipelineEquipmentMpoint.java new file mode 100644 index 0000000..f6ec426 --- /dev/null +++ b/src/main/java/com/sipai/entity/data/PipelineEquipmentMpoint.java @@ -0,0 +1,25 @@ +package com.sipai.entity.data; + +import com.sipai.entity.base.SQLAdapter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; + +import java.io.Serializable; + +/** + * 绠¢亾璁惧涓庢祴鐐瑰叧鑱斿疄浣撶被 + */ +@Data +public class PipelineEquipmentMpoint extends SQLAdapter implements Serializable { + private Integer id; + private Integer pid; // 鍏宠仈 PipelineEquipment 鐨 id + private String mpcode; // 娴嬬偣 + private String mpname; // 鍚嶇О + private String tag; // 缂栫爜 + + @JsonIgnore + private String sql; + + @JsonIgnore + private String where; +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/data/PipelineMpointLibrary.java b/src/main/java/com/sipai/entity/data/PipelineMpointLibrary.java new file mode 100644 index 0000000..cf997e4 --- /dev/null +++ b/src/main/java/com/sipai/entity/data/PipelineMpointLibrary.java @@ -0,0 +1,27 @@ +package com.sipai.entity.data; + +import com.sipai.entity.base.SQLAdapter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; + +import java.io.Serializable; + +/** + * 绠¢亾娴嬬偣 搴擄紙杩欒竟缁存姢濂斤紝璁惧閭h竟鍙互鐩存帴瀵煎叆锛 + * sj 2025-06-18 + */ +@Data +public class PipelineMpointLibrary extends SQLAdapter implements Serializable { + private String id; + private String equipmentType; + private String code; + private String name; + private Integer morder; + + // 鐢ㄤ簬鏌ヨ瀵瑰簲鐨刵ame + @JsonIgnore + private String sql; + + @JsonIgnore + private String where; +} diff --git a/src/main/java/com/sipai/entity/data/SensorData.java b/src/main/java/com/sipai/entity/data/SensorData.java new file mode 100644 index 0000000..13a80ca --- /dev/null +++ b/src/main/java/com/sipai/entity/data/SensorData.java @@ -0,0 +1,120 @@ +package com.sipai.entity.data; + +import com.sipai.tools.AlarmType; + +import java.util.List; +import java.util.Map; + +public class SensorData { + private int type; // 1-鑴夊啿閲, 2-寮鍏抽噺, 3-鎶ヨ閲, 4-妯℃嫙閲, 5-Q閫氶亾, 6-M閫氶亾 + private int channel; + + // 鑴夊啿閲忕壒鏈 + private long yesterdayFlow; + private List accumulatedFlows; + + private int qValue; // 鍘熷Q閫氶亾鍊 + private Map alarmStatus; // 鎶ヨ鐘舵佹槧灏 + + // 寮鍏抽噺/鎶ヨ閲 + private List statusList; + + // 妯℃嫙閲 + private List analogValues; + + // Q閫氶亾 + private List qValues; + + // M閫氶亾 + private List mValues; + + private String description; + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + public int getChannel() { + return channel; + } + + public void setChannel(int channel) { + this.channel = channel; + } + + public long getYesterdayFlow() { + return yesterdayFlow; + } + + public void setYesterdayFlow(long yesterdayFlow) { + this.yesterdayFlow = yesterdayFlow; + } + + public List getAccumulatedFlows() { + return accumulatedFlows; + } + + public void setAccumulatedFlows(List accumulatedFlows) { + this.accumulatedFlows = accumulatedFlows; + } + + public List getStatusList() { + return statusList; + } + + public void setStatusList(List statusList) { + this.statusList = statusList; + } + + public List getAnalogValues() { + return analogValues; + } + + public void setAnalogValues(List analogValues) { + this.analogValues = analogValues; + } + + public List getqValues() { + return qValues; + } + + public void setqValues(List qValues) { + this.qValues = qValues; + } + + public List getmValues() { + return mValues; + } + + public void setmValues(List mValues) { + this.mValues = mValues; + } + + public int getqValue() { + return qValue; + } + + public void setqValue(int qValue) { + this.qValue = qValue; + } + + public Map getAlarmStatus() { + return alarmStatus; + } + + public void setAlarmStatus(Map alarmStatus) { + this.alarmStatus = alarmStatus; + } +} diff --git a/src/main/java/com/sipai/entity/enums/DeviceTypeEnum.java b/src/main/java/com/sipai/entity/enums/DeviceTypeEnum.java new file mode 100644 index 0000000..dc058ed --- /dev/null +++ b/src/main/java/com/sipai/entity/enums/DeviceTypeEnum.java @@ -0,0 +1,71 @@ +package com.sipai.entity.enums; + +public enum DeviceTypeEnum { + // 鏋氫妇甯搁噺锛屽搴斾笅鎷夋涓殑绫诲瀷 + MANHOLE_COVER("浜曠洊", "1"), + FLOW_METER("娴侀噺璁", "2"), + LIQUID_LEVEL_METER("娑蹭綅璁", "3"), + CONDUCTIVITY("鐢靛鐜", "4"), + RAIN_GAUGE("闆ㄩ噺璁", "5"), + WATERLOGGING_DETECTION("鍐呮稘妫娴", "6"); + + // 绫诲瀷鍚嶇О + private final String typeName; + // 绫诲瀷缂栫爜 + private final String typeCode; + + /** + * 鏋勯犳柟娉 + * @param typeName 绫诲瀷鍚嶇О + * @param typeCode 绫诲瀷缂栫爜 + */ + DeviceTypeEnum(String typeName, String typeCode) { + this.typeName = typeName; + this.typeCode = typeCode; + } + + /** + * 鑾峰彇绫诲瀷鍚嶇О + * @return 绫诲瀷鍚嶇О + */ + public String getTypeName() { + return typeName; + } + + /** + * 鑾峰彇绫诲瀷缂栫爜 + * @return 绫诲瀷缂栫爜 + */ + public String getTypeCode() { + return typeCode; + } + + // 涔熷彲鏍规嵁闇姹傛坊鍔犳牴鎹悕绉版垨缂栫爜鑾峰彇鏋氫妇甯搁噺鐨勬柟娉曪紝绀轰緥濡備笅锛 + /** + * 鏍规嵁绫诲瀷鍚嶇О鑾峰彇鏋氫妇甯搁噺 + * @param typeName 绫诲瀷鍚嶇О + * @return 瀵瑰簲鐨勬灇涓惧父閲忥紝鑻ユ湭鎵惧埌杩斿洖 null + */ + public static DeviceTypeEnum getByTypeName(String typeName) { + for (DeviceTypeEnum enumConstant : DeviceTypeEnum.values()) { + if (enumConstant.getTypeName().equals(typeName)) { + return enumConstant; + } + } + return null; + } + + /** + * 鏍规嵁绫诲瀷缂栫爜鑾峰彇鏋氫妇甯搁噺 + * @param typeCode 绫诲瀷缂栫爜 + * @return 瀵瑰簲鐨勬灇涓惧父閲忥紝鑻ユ湭鎵惧埌杩斿洖 null + */ + public static DeviceTypeEnum getByTypeCode(String typeCode) { + for (DeviceTypeEnum enumConstant : DeviceTypeEnum.values()) { + if (enumConstant.getTypeCode().equals(typeCode)) { + return enumConstant; + } + } + return null; + } +} diff --git a/src/main/java/com/sipai/entity/mqtt/Mqtt.java b/src/main/java/com/sipai/entity/mqtt/Mqtt.java new file mode 100644 index 0000000..4548a1a --- /dev/null +++ b/src/main/java/com/sipai/entity/mqtt/Mqtt.java @@ -0,0 +1,16 @@ +package com.sipai.entity.mqtt; + +import org.springframework.beans.factory.annotation.Autowired; + +/** + * 鐢ㄤ簬閰嶇疆emqx鐨勫父閲 鍜 鎻愪緵浜戝钩鍙扮殑涓浜涙帴鍙 濡傛寚浠や笅鍙戯紝鑾峰彇缃戝叧鍦ㄧ嚎鐘舵佺瓑 + * sj 2021-05-27 + */ +public class Mqtt { + + /*public static String BrokerAddress = "tcp://192.168.10.17:1883"; + public static String Dashboard_01 = "http://192.168.10.17:18083"; + + public static String Username = "admin"; + public static String Password = "sipai@64368180";*/ +} diff --git a/src/main/java/com/sipai/entity/mqtt/MqttConfig.java b/src/main/java/com/sipai/entity/mqtt/MqttConfig.java new file mode 100644 index 0000000..9996283 --- /dev/null +++ b/src/main/java/com/sipai/entity/mqtt/MqttConfig.java @@ -0,0 +1,102 @@ +package com.sipai.entity.mqtt; + +import com.sipai.entity.base.SQLAdapter; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/03/24/16:26 + * @Description: mqtt閰嶇疆涓昏〃 + */ +public class MqttConfig extends SQLAdapter { + private String id; + + private String insdt; + + private String clientId; + + private String clientName; + + private String brokerIp; + + private String tomcatPort; + + private String username; + + private String password; + + private Integer morder; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getInsdt() { + return insdt; + } + + public void setInsdt(String insdt) { + this.insdt = insdt; + } + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getClientName() { + return clientName; + } + + public void setClientName(String clientName) { + this.clientName = clientName; + } + + public String getBrokerIp() { + return brokerIp; + } + + public void setBrokerIp(String brokerIp) { + this.brokerIp = brokerIp; + } + + public String getTomcatPort() { + return tomcatPort; + } + + public void setTomcatPort(String tomcatPort) { + this.tomcatPort = tomcatPort; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Integer getMorder() { + return morder; + } + + public void setMorder(Integer morder) { + this.morder = morder; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/mqtt/MqttConfigTopic.java b/src/main/java/com/sipai/entity/mqtt/MqttConfigTopic.java new file mode 100644 index 0000000..881515a --- /dev/null +++ b/src/main/java/com/sipai/entity/mqtt/MqttConfigTopic.java @@ -0,0 +1,72 @@ +package com.sipai.entity.mqtt; + +import com.sipai.entity.base.SQLAdapter; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/03/24/16:26 + * @Description: mqtt閰嶇疆鍓〃 + */ +public class MqttConfigTopic extends SQLAdapter { + private String id; + + private String name; + + private String topic; + + private String status; + + private String pid; + + private Integer morder; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id == null ? null : id.trim(); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name == null ? null : name.trim(); + } + + public String getTopic() { + return topic; + } + + public void setTopic(String topic) { + this.topic = topic == null ? null : topic.trim(); + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status == null ? null : status.trim(); + } + + public String getPid() { + return pid; + } + + public void setPid(String pid) { + this.pid = pid == null ? null : pid.trim(); + } + + public Integer getMorder() { + return morder; + } + + public void setMorder(Integer morder) { + this.morder = morder; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/mqtt/MqttProperties.java b/src/main/java/com/sipai/entity/mqtt/MqttProperties.java new file mode 100644 index 0000000..022ad46 --- /dev/null +++ b/src/main/java/com/sipai/entity/mqtt/MqttProperties.java @@ -0,0 +1,45 @@ +package com.sipai.entity.mqtt; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix = "mqtt") +public class MqttProperties { + private String brokerAddress; // 瀵瑰簲鍘 BrokerAddress + private String dashboard01; // 瀵瑰簲鍘 Dashboard_01 + private String username; // 瀵瑰簲鍘 Username + private String password; // 瀵瑰簲鍘 Password + + public String getBrokerAddress() { + return brokerAddress; + } + + public void setBrokerAddress(String brokerAddress) { + this.brokerAddress = brokerAddress; + } + + public String getDashboard01() { + return dashboard01; + } + + public void setDashboard01(String dashboard01) { + this.dashboard01 = dashboard01; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/src/main/java/com/sipai/entity/scada/MPoint.java b/src/main/java/com/sipai/entity/scada/MPoint.java new file mode 100644 index 0000000..609bdce --- /dev/null +++ b/src/main/java/com/sipai/entity/scada/MPoint.java @@ -0,0 +1,608 @@ +package com.sipai.entity.scada; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.sipai.entity.base.SQLAdapter; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Mapping; +import org.springframework.data.elasticsearch.annotations.Setting; +import org.springframework.stereotype.Component; + +import java.io.Serializable; +import java.math.BigDecimal; + + +@Mapping(mappingPath = "mpoint_search_mapping.json") +@Setting(settingPath = "mpoint_search_setting.json") +@Document(indexName = "es_measurepoint", type = "esmeasurepoint") +@Component +public class MPoint extends SQLAdapter implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -7579438089469008076L; + public static String Flag_Enable = "1"; + public static String Flag_Disable = "0"; + + public static String Flag_Sql = "sql"; + public static String Flag_Modbus = "modbus"; + public static String Flag_LinkData = "link"; + + public static String Flag_Type_CAL = "CAL";//鍗曞厓鏍艰绠楁祴閲忕偣 + public static String Flag_Type_KPI = "KPI";//KPI娴嬮噺锟? + public static String Flag_Type_Data = "data"; + public static String Flag_Type_Hand = "hand";//鎵嬪姩娴嬮噺锟? + public static String Flag_Type_Auto = "auto";//鑷姩杞彂娴嬮噺锟? + + public static String Flag_BizType_Hand = "Manual"; + public static String Flag_BizType_Auto = "auto";//鑷姩杞彂 + + private String chineseValue;//娴嬮噺鐐癸拷? valuemeaning瀵瑰簲鐨勪腑鏂囷拷? + + @Id + private String id; + private String mpointid; + private String mpointcode; + private String parmname; + private String unit; + private BigDecimal alarmmax; + private BigDecimal alarmmin; + private BigDecimal parmvalue; + //@Field(type = FieldType.Date) + private String measuredt; + private BigDecimal rate; + private Integer freq; + private String frequnit; + private String signaltype; + @JsonProperty("signaltag") + private String signaltag; + private String ledtype; + private String ledcolor; + private String directtype; + private String bizid; + private String biztype; + private String numtail; + private String prochour; + private String procday; + private String procmonth; + private String showname; + private String exp; + private BigDecimal forcemin; + private BigDecimal forcemax; + private BigDecimal avgmax; + private BigDecimal avgmin; + private String remoteup; + private Integer morder; + private String triggeralarm; + private String confirmalarm; + private BigDecimal flowset; + private String triggercycle; + private BigDecimal cyclemax; + private BigDecimal cyclemin; + private String triggermutation; + private BigDecimal mutationset; + private BigDecimal causeset; + private BigDecimal operateset; + private BigDecimal resultset; + private String triggerequoff; + private String mathop; + private String valuetype; + private String valuemeaning; + private String active; + private String soundalarm; + private String scdtype; + private BigDecimal spanrange; + private String modbusfigid; + private String register; + private String processsectioncode; + private String equipmentid; + @JsonProperty("source_type") + private String sourceType; + @JsonProperty("patrol_type") + private String patrolType; + private String remark; + private Integer alarmLevel; + + private String bizname; + private String disname; + + private int subscriptionStatus; + + public String getChineseValue() { + return chineseValue; + } + + public void setChineseValue(String chineseValue) { + this.chineseValue = chineseValue; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getMpointid() { + return mpointid; + } + + public void setMpointid(String mpointid) { + this.mpointid = mpointid; + } + + public String getMpointcode() { + return mpointcode; + } + + public void setMpointcode(String mpointcode) { + this.mpointcode = mpointcode; + } + + public String getParmname() { + return parmname; + } + + public void setParmname(String parmname) { + this.parmname = parmname; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + + public BigDecimal getAlarmmax() { + return alarmmax; + } + + public void setAlarmmax(BigDecimal alarmmax) { + this.alarmmax = alarmmax; + } + + public BigDecimal getAlarmmin() { + return alarmmin; + } + + public void setAlarmmin(BigDecimal alarmmin) { + this.alarmmin = alarmmin; + } + + public BigDecimal getParmvalue() { + return parmvalue; + } + + public void setParmvalue(BigDecimal parmvalue) { + this.parmvalue = parmvalue; + } + + public String getMeasuredt() { + return measuredt; + } + + public void setMeasuredt(String measuredt) { + this.measuredt = measuredt; + } + + public BigDecimal getRate() { + return rate; + } + + public void setRate(BigDecimal rate) { + this.rate = rate; + } + + public Integer getFreq() { + return freq; + } + + public void setFreq(Integer freq) { + this.freq = freq; + } + + public String getFrequnit() { + return frequnit; + } + + public void setFrequnit(String frequnit) { + this.frequnit = frequnit; + } + + public String getSignaltype() { + return signaltype; + } + + public void setSignaltype(String signaltype) { + this.signaltype = signaltype; + } + + public String getSignaltag() { + return signaltag; + } + + public void setSignaltag(String signaltag) { + this.signaltag = signaltag; + } + + public String getLedtype() { + return ledtype; + } + + public void setLedtype(String ledtype) { + this.ledtype = ledtype; + } + + public String getLedcolor() { + return ledcolor; + } + + public void setLedcolor(String ledcolor) { + this.ledcolor = ledcolor; + } + + public String getDirecttype() { + return directtype; + } + + public void setDirecttype(String directtype) { + this.directtype = directtype; + } + + public String getBizid() { + return bizid; + } + + public void setBizid(String bizid) { + this.bizid = bizid; + } + + public String getBiztype() { + return biztype; + } + + public void setBiztype(String biztype) { + this.biztype = biztype; + } + + public String getNumtail() { + return numtail; + } + + public void setNumtail(String numtail) { + this.numtail = numtail; + } + + public String getProchour() { + return prochour; + } + + public void setProchour(String prochour) { + this.prochour = prochour; + } + + public String getProcday() { + return procday; + } + + public void setProcday(String procday) { + this.procday = procday; + } + + public String getProcmonth() { + return procmonth; + } + + public void setProcmonth(String procmonth) { + this.procmonth = procmonth; + } + + public String getShowname() { + return showname; + } + + public void setShowname(String showname) { + this.showname = showname; + } + + public String getExp() { + return exp; + } + + public void setExp(String exp) { + this.exp = exp; + } + + public BigDecimal getForcemin() { + return forcemin; + } + + public void setForcemin(BigDecimal forcemin) { + this.forcemin = forcemin; + } + + public BigDecimal getForcemax() { + return forcemax; + } + + public void setForcemax(BigDecimal forcemax) { + this.forcemax = forcemax; + } + + public BigDecimal getAvgmax() { + return avgmax; + } + + public void setAvgmax(BigDecimal avgmax) { + this.avgmax = avgmax; + } + + public BigDecimal getAvgmin() { + return avgmin; + } + + public void setAvgmin(BigDecimal avgmin) { + this.avgmin = avgmin; + } + + public String getRemoteup() { + return remoteup; + } + + public void setRemoteup(String remoteup) { + this.remoteup = remoteup; + } + + public Integer getMorder() { + return morder; + } + + public void setMorder(Integer morder) { + this.morder = morder; + } + + public String getTriggeralarm() { + return triggeralarm; + } + + public void setTriggeralarm(String triggeralarm) { + this.triggeralarm = triggeralarm; + } + + public String getConfirmalarm() { + return confirmalarm; + } + + public void setConfirmalarm(String confirmalarm) { + this.confirmalarm = confirmalarm; + } + + public BigDecimal getFlowset() { + return flowset; + } + + public void setFlowset(BigDecimal flowset) { + this.flowset = flowset; + } + + public String getTriggercycle() { + return triggercycle; + } + + public void setTriggercycle(String triggercycle) { + this.triggercycle = triggercycle; + } + + public BigDecimal getCyclemax() { + return cyclemax; + } + + public void setCyclemax(BigDecimal cyclemax) { + this.cyclemax = cyclemax; + } + + public BigDecimal getCyclemin() { + return cyclemin; + } + + public void setCyclemin(BigDecimal cyclemin) { + this.cyclemin = cyclemin; + } + + public String getTriggermutation() { + return triggermutation; + } + + public void setTriggermutation(String triggermutation) { + this.triggermutation = triggermutation; + } + + public BigDecimal getMutationset() { + return mutationset; + } + + public void setMutationset(BigDecimal mutationset) { + this.mutationset = mutationset; + } + + public BigDecimal getCauseset() { + return causeset; + } + + public void setCauseset(BigDecimal causeset) { + this.causeset = causeset; + } + + public BigDecimal getOperateset() { + return operateset; + } + + public void setOperateset(BigDecimal operateset) { + this.operateset = operateset; + } + + public BigDecimal getResultset() { + return resultset; + } + + public void setResultset(BigDecimal resultset) { + this.resultset = resultset; + } + + public String getTriggerequoff() { + return triggerequoff; + } + + public void setTriggerequoff(String triggerequoff) { + this.triggerequoff = triggerequoff; + } + + public String getMathop() { + return mathop; + } + + public void setMathop(String mathop) { + this.mathop = mathop; + } + + public String getValuetype() { + return valuetype; + } + + public void setValuetype(String valuetype) { + this.valuetype = valuetype; + } + + public String getValuemeaning() { + return valuemeaning; + } + + public void setValuemeaning(String valuemeaning) { + this.valuemeaning = valuemeaning; + } + + public String getActive() { + return active; + } + + public void setActive(String active) { + this.active = active; + } + + public String getSoundalarm() { + return soundalarm; + } + + public void setSoundalarm(String soundalarm) { + this.soundalarm = soundalarm; + } + + public String getScdtype() { + return scdtype; + } + + public void setScdtype(String scdtype) { + this.scdtype = scdtype; + } + + public BigDecimal getSpanrange() { + return spanrange; + } + + public void setSpanrange(BigDecimal spanrange) { + this.spanrange = spanrange; + } + + public String getModbusfigid() { + return modbusfigid; + } + + public void setModbusfigid(String modbusfigid) { + this.modbusfigid = modbusfigid; + } + + public String getRegister() { + return register; + } + + public void setRegister(String register) { + this.register = register; + } + + public String getProcesssectioncode() { + return processsectioncode; + } + + public void setProcesssectioncode(String processsectioncode) { + this.processsectioncode = processsectioncode; + } + + public String getEquipmentid() { + return equipmentid; + } + + public void setEquipmentid(String equipmentid) { + this.equipmentid = equipmentid; + } + + public String getSourceType() { + return sourceType; + } + + public void setSourceType(String sourceType) { + this.sourceType = sourceType; + } + + public String getPatrolType() { + return patrolType; + } + + public void setPatrolType(String patrolType) { + this.patrolType = patrolType; + } + + public String getRemark() { + return remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } + + public Integer getAlarmLevel() { + return alarmLevel; + } + + public void setAlarmLevel(Integer alarmLevel) { + this.alarmLevel = alarmLevel; + } + + public String getBizname() { + return bizname; + } + + public void setBizname(String bizname) { + this.bizname = bizname; + } + + public String getDisname() { + return disname; + } + + public void setDisname(String disname) { + this.disname = disname; + } + + public int getSubscriptionStatus() { + return subscriptionStatus; + } + + public void setSubscriptionStatus(int subscriptionStatus) { + this.subscriptionStatus = subscriptionStatus; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/scada/MPointBzw.java b/src/main/java/com/sipai/entity/scada/MPointBzw.java new file mode 100644 index 0000000..b21cacf --- /dev/null +++ b/src/main/java/com/sipai/entity/scada/MPointBzw.java @@ -0,0 +1,57 @@ +package com.sipai.entity.scada; + +import com.sipai.entity.base.SQLAdapter; + +import java.io.Serializable; + +/** + * 娴嬬偣鏍囪瘑瀵圭収琛ㄥ疄浣撶被 + */ +public class MPointBzw extends SQLAdapter implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 娴嬬偣ID + */ + private String mpointId; + + /** + * 娴嬬偣鏍囪瘑ID + */ + private String mpointbzwId; + + // 鏃犲弬鏋勯犲櫒 + public MPointBzw() { + } + + // 鍏ㄥ弬鏋勯犲櫒 + public MPointBzw(String mpointId, String mpointbzwId) { + this.mpointId = mpointId; + this.mpointbzwId = mpointbzwId; + } + + // Getters and Setters + public String getMpointId() { + return mpointId; + } + + public void setMpointId(String mpointId) { + this.mpointId = mpointId; + } + + public String getMpointbzwId() { + return mpointbzwId; + } + + public void setMpointbzwId(String mpointbzwId) { + this.mpointbzwId = mpointbzwId; + } + + @Override + public String toString() { + return "MPointBzw{" + + "mpointId='" + mpointId + '\'' + + ", mpointbzwId='" + mpointbzwId + '\'' + + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/scada/MPointES.java b/src/main/java/com/sipai/entity/scada/MPointES.java new file mode 100644 index 0000000..97497b7 --- /dev/null +++ b/src/main/java/com/sipai/entity/scada/MPointES.java @@ -0,0 +1,42 @@ +package com.sipai.entity.scada; + + +import com.alibaba.fastjson.JSON; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + + +public class MPointES extends MPoint { + + private static final long serialVersionUID = -4222932639259909065L; + private String source_type; + + public String getSource_type() { + return source_type; + } + + public void setSource_type(String source_type) { + this.source_type = source_type; + } + + + public static MPointES format(MPoint mPoint) { + String str = JSON.toJSONString(mPoint); + MPointES mPointES = JSON.parseObject(str, MPointES.class); + mPointES.setSource_type(mPoint.getSourceType()); + //鏃堕棿鏍煎紡澶勭悊 + DateTimeFormatter dfES = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"); + DateTimeFormatter dfSQL = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + if (mPoint.getMeasuredt() != null) { + try { + LocalDateTime confirmTime = LocalDateTime.parse(mPoint.getMeasuredt().substring(0, 19), dfSQL); + String confirmTimeStr = dfES.format(confirmTime); + mPointES.setMeasuredt(confirmTimeStr); + } catch (Exception e) { + + } + } + return mPointES; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/scada/MPointHistory.java b/src/main/java/com/sipai/entity/scada/MPointHistory.java new file mode 100644 index 0000000..567c043 --- /dev/null +++ b/src/main/java/com/sipai/entity/scada/MPointHistory.java @@ -0,0 +1,154 @@ +package com.sipai.entity.scada; + +import com.sipai.entity.base.SQLAdapter; +import java.io.Serializable; +import java.math.BigDecimal; + +public class MPointHistory extends SQLAdapter implements Serializable{ + /** + * + */ + private static final long serialVersionUID = 4552977217414444717L; + + private Long itemid; + + private BigDecimal parmvalue; + + private String measuredt; + + private String memotype; + + private String memo; + + private String userid; + + private String insdt; + + private String tbName; + + private short tag;//鏍囧織浣嶅 + + //涓烘姤琛ㄥ睍绀轰娇鐢 CPELM + private String year; + private String month; + private String day; + private String hour; + private String min; + + public short getTag() { + return tag; + } + + public void setTag(short tag) { + this.tag = tag; + } + + public Long getItemid() { + return itemid; + } + + public void setItemid(Long itemid) { + this.itemid = itemid; + } + + public BigDecimal getParmvalue() { + return parmvalue; + } + + public void setParmvalue(BigDecimal parmvalue) { + this.parmvalue = parmvalue; + } + + public String getMeasuredt() { + return measuredt; + } + + public void setMeasuredt(String measuredt) { + this.measuredt = measuredt; + } + + public String getMemotype() { + return memotype; + } + + public void setMemotype(String memotype) { + this.memotype = memotype; + } + + public String getMemo() { + return memo; + } + + public void setMemo(String memo) { + this.memo = memo; + } + + public String getUserid() { + return userid; + } + + public void setUserid(String userid) { + this.userid = userid; + } + + public String getInsdt() { + return insdt; + } + + public void setInsdt(String insdt) { + this.insdt = insdt; + } + + public String getTbName() { + return tbName; + } + + public void setTbName(String tbName) { + this.tbName = tbName; + } + + public String getYear() { + return year; + } + + public void setYear(String year) { + this.year = year; + } + + public String getMonth() { + return month; + } + + public void setMonth(String month) { + this.month = month; + } + + public String getDay() { + return day; + } + + public void setDay(String day) { + this.day = day; + } + + public String getHour() { + return hour; + } + + public void setHour(String hour) { + this.hour = hour; + } + + public String getMin() { + return min; + } + + public void setMin(String min) { + this.min = min; + } + + public static long getSerialversionuid() { + return serialVersionUID; + } + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/user/Company.java b/src/main/java/com/sipai/entity/user/Company.java new file mode 100644 index 0000000..47caaac --- /dev/null +++ b/src/main/java/com/sipai/entity/user/Company.java @@ -0,0 +1,201 @@ +package com.sipai.entity.user; + +import com.sipai.entity.base.SQLAdapter; + +import java.math.BigDecimal; + +/** + * 鍏徃琛 + */ +public class Company extends SQLAdapter { + + private String id; + + private String name; + + private String pid; + + private String address; + + private String tel; + + private String website; + + private String taskid; + + private String post; + + private String insdt; + + private String insuser; + + private Integer version; + + private Integer morder; + + private String sname; + + private String active; + + private String type; + + private String ename; + + private BigDecimal longitude; + + private BigDecimal latitude; + + private String isCount; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getPid() { + return pid; + } + + public void setPid(String pid) { + this.pid = pid; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getTel() { + return tel; + } + + public void setTel(String tel) { + this.tel = tel; + } + + public String getWebsite() { + return website; + } + + public void setWebsite(String website) { + this.website = website; + } + + public String getTaskid() { + return taskid; + } + + public void setTaskid(String taskid) { + this.taskid = taskid; + } + + public String getPost() { + return post; + } + + public void setPost(String post) { + this.post = post; + } + + public String getInsdt() { + return insdt; + } + + public void setInsdt(String insdt) { + this.insdt = insdt; + } + + public String getInsuser() { + return insuser; + } + + public void setInsuser(String insuser) { + this.insuser = insuser; + } + + public Integer getVersion() { + return version; + } + + public void setVersion(Integer version) { + this.version = version; + } + + public Integer getMorder() { + return morder; + } + + public void setMorder(Integer morder) { + this.morder = morder; + } + + public String getSname() { + return sname; + } + + public void setSname(String sname) { + this.sname = sname; + } + + public String getActive() { + return active; + } + + public void setActive(String active) { + this.active = active; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getEname() { + return ename; + } + + public void setEname(String ename) { + this.ename = ename; + } + + public BigDecimal getLongitude() { + return longitude; + } + + public void setLongitude(BigDecimal longitude) { + this.longitude = longitude; + } + + public BigDecimal getLatitude() { + return latitude; + } + + public void setLatitude(BigDecimal latitude) { + this.latitude = latitude; + } + + public String getIsCount() { + return isCount; + } + + public void setIsCount(String isCount) { + this.isCount = isCount; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/entity/user/User.java b/src/main/java/com/sipai/entity/user/User.java new file mode 100644 index 0000000..1195bde --- /dev/null +++ b/src/main/java/com/sipai/entity/user/User.java @@ -0,0 +1,36 @@ +package com.sipai.entity.user; + +import com.sipai.entity.base.SQLAdapter; + +/** + * 浜哄憳琛 + */ +public class User extends SQLAdapter { + private String id; + private String userName; + private String passWord; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getPassWord() { + return passWord; + } + + public void setPassWord(String passWord) { + this.passWord = passWord; + } +} diff --git a/src/main/java/com/sipai/schedule/DataSynJob.java b/src/main/java/com/sipai/schedule/DataSynJob.java new file mode 100644 index 0000000..881b788 --- /dev/null +++ b/src/main/java/com/sipai/schedule/DataSynJob.java @@ -0,0 +1,73 @@ +package com.sipai.schedule; + +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointHistory; +import com.sipai.service.mqtt.MqttConfigService; +import com.sipai.service.opc.InitOpcUaService; +import com.sipai.service.scada.MPointHistoryService; +import com.sipai.service.scada.MPointService; +import com.sipai.tools.CommUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import java.util.*; + +/** + * 瀹氭椂灏嗘昏〃鏁版嵁鎻掑叆鍒板瓙琛 + */ +@Service +public class DataSynJob { + @Autowired + private MPointService mPointService; + @Autowired + private MPointHistoryService mPointHistoryService; + @Autowired + private MqttConfigService mqttConfigService; + @Autowired + private InitOpcUaService initOpcUaService; + + //瀹氭椂鍣▂ml閰嶇疆鏄惁鍚姩 + @Value("${scheduled.enabled:true}") + private boolean scheduledEnabled; + + // @Scheduled(fixedRate = 3600000) // 鍚屾涓娆pcua鐨勮闃 + public void syncSubscriptions() { + initOpcUaService.manualSyncSubscriptions(); + } + + @Async + @Scheduled(initialDelay = 10000, fixedRate = 600000)//鑷姩璁㈤槄mqtt + public void job1() { + if (!scheduledEnabled) return; // 鎵嬪姩鎷︽埅 + System.out.println("鑷姩璁㈤槄========" + CommUtil.nowDate()); + mqttConfigService.connect("1"); + } + + @Async +// @Scheduled(cron = "0 0/3 * * * ?")//鏁版嵁杞彂 + public void job2() { + if (!scheduledEnabled) return; // 鎵嬪姩鎷︽埅 + String addstr = "zhuanfa"; + System.out.println("寮濮嬪畾鏃跺櫒-----------------" + CommUtil.nowDate() + "-----------------" + addstr); + List list2 = this.mPointService.selectListByWhere("where bizid = '0791CNWS' and SignalType='AI' and MeasureDT>DATE_SUB(NOW(), INTERVAL 5 MINUTE) and source_type='auto' "); + if (list2 != null && list2.size() > 0) { + for (int j = 0; j < list2.size(); ++j) { + MPointHistory mPointHistory = new MPointHistory(); + mPointHistory.setParmvalue(list2.get(j).getParmvalue()); + mPointHistory.setMeasuredt(list2.get(j).getMeasuredt()); + mPointHistory.setTbName(list2.get(j).getMpointcode()); + mPointHistory.setUserid("data_job"); + mPointHistory.setInsdt(CommUtil.nowDate()); + mPointHistoryService.saveByCreate(list2.get(j).getBizid(), mPointHistory); + } + System.out.println("瀹屾垚涓娆★紙鏈夋暟鎹級杞彂锛屾墽琛屼簡" + list2.size() + "娆$偣"); + } else { + System.out.println("瀹屾垚涓娆★紙鏃犳暟鎹級杞彂锛屾墽琛屼簡" + 0 + "娆$偣"); + } + System.out.println("缁撴潫瀹氭椂鍣-----------------" + CommUtil.nowDate()); + } + +} diff --git a/src/main/java/com/sipai/service/Listener/ListenerHisService.java b/src/main/java/com/sipai/service/Listener/ListenerHisService.java new file mode 100644 index 0000000..c863d5e --- /dev/null +++ b/src/main/java/com/sipai/service/Listener/ListenerHisService.java @@ -0,0 +1,23 @@ +package com.sipai.service.Listener; + +import com.sipai.entity.Listener.ListenerHis; + +import java.util.List; + +public interface ListenerHisService { + + public abstract ListenerHis selectById(String id); + + public abstract int deleteById(String id); + + public abstract int save(ListenerHis entity); + + public abstract int update(ListenerHis entity); + + public abstract List selectListByWhere(String wherestr); + + public abstract int deleteByWhere(String wherestr); + + public abstract List selectTopByWhere(String wherestr); + +} diff --git a/src/main/java/com/sipai/service/Listener/ListenerInterfaceService.java b/src/main/java/com/sipai/service/Listener/ListenerInterfaceService.java new file mode 100644 index 0000000..cdc2c9a --- /dev/null +++ b/src/main/java/com/sipai/service/Listener/ListenerInterfaceService.java @@ -0,0 +1,22 @@ +package com.sipai.service.Listener; + + +import com.sipai.entity.Listener.ListenerInterface; + +import java.util.List; + +public interface ListenerInterfaceService { + + public abstract ListenerInterface selectById(String id); + + public abstract int deleteById(String id); + + public abstract int save(ListenerInterface entity); + + public abstract int update(ListenerInterface entity); + + public abstract List selectListByWhere(String wherestr); + + public abstract int deleteByWhere(String wherestr); + +} diff --git a/src/main/java/com/sipai/service/Listener/ListenerMessageService.java b/src/main/java/com/sipai/service/Listener/ListenerMessageService.java new file mode 100644 index 0000000..2e731fb --- /dev/null +++ b/src/main/java/com/sipai/service/Listener/ListenerMessageService.java @@ -0,0 +1,24 @@ +package com.sipai.service.Listener; + +import com.sipai.entity.Listener.ListenerMessage; + +import java.util.List; + +public interface ListenerMessageService { + + public abstract ListenerMessage selectById(String id); + + public abstract int deleteById(String id); + + public abstract int save(ListenerMessage entity); + + public abstract int update(ListenerMessage entity); + + public abstract List selectListByWhere(String wherestr); + + //甯﹀叆璁惧缂栧彿鏌ヨ + public abstract List selectListByWhere4Equ(String wherestr, String equipmentId); + + public abstract int deleteByWhere(String wherestr); + +} diff --git a/src/main/java/com/sipai/service/Listener/ListenerPointService.java b/src/main/java/com/sipai/service/Listener/ListenerPointService.java new file mode 100644 index 0000000..209c446 --- /dev/null +++ b/src/main/java/com/sipai/service/Listener/ListenerPointService.java @@ -0,0 +1,22 @@ +package com.sipai.service.Listener; + + +import com.sipai.entity.Listener.ListenerPoint; + +import java.util.List; + +public interface ListenerPointService { + + public abstract ListenerPoint selectById(String id); + + public abstract int deleteById(String id); + + public abstract int save(ListenerPoint entity); + + public abstract int update(ListenerPoint entity); + + public abstract List selectListByWhere(String wherestr); + + public abstract int deleteByWhere(String wherestr); + +} diff --git a/src/main/java/com/sipai/service/Listener/impl/ListenerHisServiceImpl.java b/src/main/java/com/sipai/service/Listener/impl/ListenerHisServiceImpl.java new file mode 100644 index 0000000..ba34280 --- /dev/null +++ b/src/main/java/com/sipai/service/Listener/impl/ListenerHisServiceImpl.java @@ -0,0 +1,62 @@ +package com.sipai.service.Listener.impl; + +import com.sipai.dao.Listener.ListenerHisDao; +import com.sipai.entity.Listener.ListenerHis; +import com.sipai.service.Listener.ListenerHisService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +@Service("listenerHisService") +public class ListenerHisServiceImpl implements ListenerHisService { + + @Resource + public ListenerHisDao listenerHisDao; + + @Override + public ListenerHis selectById(String id) { + ListenerHis listenerHis = listenerHisDao.selectByPrimaryKey(id); + return listenerHis; + } + + @Override + public int deleteById(String id) { + int i = listenerHisDao.deleteByPrimaryKey(id); + return i; + } + + @Override + public int save(ListenerHis entity) { + int insert = listenerHisDao.insert(entity); + return insert; + } + + @Override + public int update(ListenerHis entity) { + int i = listenerHisDao.updateByPrimaryKeySelective(entity); + return i; + } + + @Override + public List selectListByWhere(String wherestr) { + ListenerHis listenerHis = new ListenerHis(); + listenerHis.setWhere(wherestr); + List listenerHiss = listenerHisDao.selectListByWhere(listenerHis); + return listenerHiss; + } + + @Override + public int deleteByWhere(String wherestr) { + ListenerHis listenerHis = new ListenerHis(); + listenerHis.setWhere(wherestr); + int i = listenerHisDao.deleteByWhere(listenerHis); + return i; + } + + @Override + public List selectTopByWhere(String wherestr) { + List listenerHis = listenerHisDao.selectTopByWhere(wherestr); + return listenerHis; + } +} diff --git a/src/main/java/com/sipai/service/Listener/impl/ListenerInterfaceServiceImpl.java b/src/main/java/com/sipai/service/Listener/impl/ListenerInterfaceServiceImpl.java new file mode 100644 index 0000000..92b823a --- /dev/null +++ b/src/main/java/com/sipai/service/Listener/impl/ListenerInterfaceServiceImpl.java @@ -0,0 +1,56 @@ +package com.sipai.service.Listener.impl; + +import com.sipai.dao.Listener.ListenerInterfaceDao; +import com.sipai.entity.Listener.ListenerInterface; +import com.sipai.service.Listener.ListenerInterfaceService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +@Service("listenerInterfaceService") +public class ListenerInterfaceServiceImpl implements ListenerInterfaceService { + + @Resource + public ListenerInterfaceDao listenerInterfaceDao; + + @Override + public ListenerInterface selectById(String id) { + ListenerInterface listenerInterface = listenerInterfaceDao.selectByPrimaryKey(id); + return listenerInterface; + } + + @Override + public int deleteById(String id) { + int i = listenerInterfaceDao.deleteByPrimaryKey(id); + return i; + } + + @Override + public int save(ListenerInterface entity) { + int insert = listenerInterfaceDao.insert(entity); + return insert; + } + + @Override + public int update(ListenerInterface entity) { + int i = listenerInterfaceDao.updateByPrimaryKeySelective(entity); + return i; + } + + @Override + public List selectListByWhere(String wherestr) { + ListenerInterface listenerInterface = new ListenerInterface(); + listenerInterface.setWhere(wherestr); + List listenerInterfaces = listenerInterfaceDao.selectListByWhere(listenerInterface); + return listenerInterfaces; + } + + @Override + public int deleteByWhere(String wherestr) { + ListenerInterface listenerInterface = new ListenerInterface(); + listenerInterface.setWhere(wherestr); + int i = listenerInterfaceDao.deleteByWhere(listenerInterface); + return i; + } +} diff --git a/src/main/java/com/sipai/service/Listener/impl/ListenerMessageServiceImpl.java b/src/main/java/com/sipai/service/Listener/impl/ListenerMessageServiceImpl.java new file mode 100644 index 0000000..7fdc257 --- /dev/null +++ b/src/main/java/com/sipai/service/Listener/impl/ListenerMessageServiceImpl.java @@ -0,0 +1,96 @@ +package com.sipai.service.Listener.impl; + +import com.sipai.dao.Listener.ListenerMessageDao; +import com.sipai.entity.Listener.ListenerMessage; +import com.sipai.service.Listener.ListenerMessageService; +import com.sipai.service.scada.MPointService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.List; + +@Service("listenerMessageService") +public class ListenerMessageServiceImpl implements ListenerMessageService { + + @Resource + ListenerMessageDao listenerMessageDao; +// @Resource +// private CompanyService companyService; +// @Resource +// private ProcessSectionService processSectionService; + @Resource + private MPointService mPointService; + + @Override + public ListenerMessage selectById(String id) { + ListenerMessage listenerMessage = listenerMessageDao.selectByPrimaryKey(id); + return listenerMessage; + } + + @Override + public int deleteById(String id) { + int i = listenerMessageDao.deleteByPrimaryKey(id); + return i; + } + + @Override + public int save(ListenerMessage entity) { + int insert = listenerMessageDao.insert(entity); + return insert; + } + + @Override + public int update(ListenerMessage entity) { + int i = listenerMessageDao.updateByPrimaryKeySelective(entity); + return i; + } + + @Override + public List selectListByWhere(String wherestr) { + ListenerMessage listenerMessage = new ListenerMessage(); + listenerMessage.setWhere(wherestr); + List listenerMessages = listenerMessageDao.selectListByWhere(listenerMessage); + for (ListenerMessage entity : listenerMessages) { + +// MPoint mPoint = mPointService.selectById(entity.getObjid()); +// if (mPoint != null) { +// entity.setmPoint(mPoint); +// Company company = companyService.selectByPrimaryKey(mPoint.getBizid()); +// entity.setCompany(company); +// } + } + return listenerMessages; + } + + @Override + public List selectListByWhere4Equ(String wherestr, String equipmentId) { + ListenerMessage listenerMessage = new ListenerMessage(); + listenerMessage.setWhere(wherestr); + List listenerMessages = listenerMessageDao.selectListByWhere(listenerMessage); + List listenerMessages2 = new ArrayList<>(); + for (int i = 0; i < listenerMessages.size(); i++) { +// MPoint mPoint = mPointService.selectById(listenerMessages.get(i).getObjid()); +// if (mPoint != null && mPoint.getEquipmentid().equals(equipmentId)) { +// listenerMessages2.add(listenerMessages.get(i)); +// } + } + for (ListenerMessage entity : listenerMessages2) { +// MPoint mPoint = mPointService.selectById(entity.getObjid()); +// if (mPoint != null) { +// entity.setmPoint(mPoint); +// Company company = companyService.selectByPrimaryKey(mPoint.getBizid()); +// entity.setCompany(company); +// } + } + return listenerMessages2; + } + + @Override + public int deleteByWhere(String wherestr) { + ListenerMessage listenerMessage = new ListenerMessage(); + listenerMessage.setWhere(wherestr); + int i = listenerMessageDao.deleteByWhere(listenerMessage); + return i; + } +} diff --git a/src/main/java/com/sipai/service/Listener/impl/ListenerPointServiceImpl.java b/src/main/java/com/sipai/service/Listener/impl/ListenerPointServiceImpl.java new file mode 100644 index 0000000..ca1d275 --- /dev/null +++ b/src/main/java/com/sipai/service/Listener/impl/ListenerPointServiceImpl.java @@ -0,0 +1,57 @@ +package com.sipai.service.Listener.impl; + +import com.sipai.dao.Listener.ListenerPointDao; +import com.sipai.entity.Listener.ListenerPoint; +import com.sipai.service.Listener.ListenerPointService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +@Service("listenerPointService") +public class ListenerPointServiceImpl implements ListenerPointService { + + @Resource + ListenerPointDao listenerPointDao; + + @Override + public ListenerPoint selectById(String id) { + ListenerPoint listenerPoint = listenerPointDao.selectByPrimaryKey(id); + return listenerPoint; + } + + @Override + public int deleteById(String id) { + int i = listenerPointDao.deleteByPrimaryKey(id); + return i; + } + + @Override + public int save(ListenerPoint entity) { + int insert = listenerPointDao.insert(entity); + return insert; + } + + @Override + public int update(ListenerPoint entity) { + int i = listenerPointDao.updateByPrimaryKeySelective(entity); + return i; + } + + @Override + public List selectListByWhere(String wherestr) { + ListenerPoint listenerPoint = new ListenerPoint(); + listenerPoint.setWhere(wherestr); + List listenerPoints = listenerPointDao.selectListByWhere(listenerPoint); + return listenerPoints; + } + + @Override + public int deleteByWhere(String wherestr) { + ListenerPoint listenerPoint = new ListenerPoint(); + listenerPoint.setWhere(wherestr); + int i = listenerPointDao.deleteByWhere(listenerPoint); + return i; + } + +} diff --git a/src/main/java/com/sipai/service/data/DeviceDataParser.java b/src/main/java/com/sipai/service/data/DeviceDataParser.java new file mode 100644 index 0000000..3dfaf72 --- /dev/null +++ b/src/main/java/com/sipai/service/data/DeviceDataParser.java @@ -0,0 +1,126 @@ +package com.sipai.service.data; + +import com.sipai.entity.data.ChannelData; +import com.sipai.entity.data.DeviceDataPacket; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +public class DeviceDataParser { + + public static DeviceDataPacket parse(byte[] data) { + ByteBuffer buffer = ByteBuffer.wrap(data); + buffer.order(ByteOrder.LITTLE_ENDIAN); // 璁剧疆涓轰綆浣嶅湪鍓 + + // 1. 楠岃瘉璧峰绗 + if (buffer.get() != (byte) 0xAB || buffer.get() != (byte) 0xCD) { + throw new IllegalArgumentException("Invalid start code (expected AB CD)"); + } + + DeviceDataPacket packet = new DeviceDataPacket(); + packet.setStartCode("ABCD"); + + // 2. 瑙f瀽鍥哄畾瀛楁 + packet.setLength(buffer.getShort() & 0xFFFF); // 闀垮害 + packet.setStationId(buffer.getShort() & 0xFFFF); // 绔欏彿 + + // 3. 瑙f瀽鏃堕棿鎴筹紙BCD鐮侊細骞(1)鏈(1)鏃(1)鏃(1)鍒(1)锛 + byte[] timeBytes = new byte[5]; + buffer.get(timeBytes); + packet.setTimestamp(LocalDateTime.of( + 2000 + bcdToInt(timeBytes[0]), // 骞 + bcdToInt(timeBytes[1]), // 鏈 + bcdToInt(timeBytes[2]), // 鏃 + bcdToInt(timeBytes[3]), // 鏃 + bcdToInt(timeBytes[4]) // 鍒 + )); + + // 4. 瑙f瀽鍏朵粬瀛楁 + packet.setDataCount(buffer.get() & 0xFF); // 鏁版嵁涓暟 + packet.setInterval(buffer.get() & 0xFF); // 闂撮殧锛堝垎閽燂級 + packet.setBatteryVoltage((buffer.getShort() & 0xFFFF) / 100.0f); // 鐢垫睜鐢靛帇 + packet.setUploadCount(buffer.getShort() & 0xFFFF); // 涓婂彂娆℃暟 + packet.setSignalStrength(buffer.get() & 0xFF); // 淇″彿寮哄害 + + // 5. 瑙f瀽璁惧淇℃伅锛20瀛楄妭ASCII锛 + byte[] deviceInfoBytes = new byte[20]; + buffer.get(deviceInfoBytes); + packet.setDeviceInfo(new String(deviceInfoBytes).trim()); + + // 璺宠繃淇濈暀瀛楁锛8瀛楄妭锛 + buffer.position(buffer.position() + 8); + + // 6. 瑙f瀽閫氶亾鏁版嵁 + List channelDataList = new ArrayList<>(); + while (buffer.remaining() > 3) { // 鑷冲皯闇瑕3瀛楄妭锛堟牎楠屽拰+缁撴潫绗︼級 + ChannelData channelData = parseChannelData(buffer, packet.getDataCount()); + channelDataList.add(channelData); + } + + packet.setChannelDataList(channelDataList); + + // 7. 鏍¢獙鍜屼笌缁撴潫绗 + if (buffer.remaining() >= 1) { + packet.setChecksum(buffer.get() & 0xFF); + } + if (buffer.remaining() >= 2) { + packet.setEndCode(String.format("%02X%02X", buffer.get(), buffer.get())); + } + + return packet; + } + + private static ChannelData parseChannelData(ByteBuffer buffer, int dataCount) { + ChannelData channelData = new ChannelData(); + channelData.setType(buffer.get() & 0xFF); // 绫诲瀷 + channelData.setChannelNumber(buffer.get() & 0xFF); // 閫氶亾鍙 + + // 淇channelName涔辩爜锛氱洿鎺ヨ浆涓篐EX瀛楃涓 + byte[] nameBytes = new byte[]{buffer.get(), buffer.get()}; + channelData.setChannelName(String.format("%02X%02X", nameBytes[0], nameBytes[1])); + + // 鏍规嵁绫诲瀷瑙f瀽鏁版嵁 + switch (channelData.getType()) { + case 1: // 鑴夊啿閲 + case 2: // 寮鍏抽噺 + case 3: // 鎶ヨ閲 + channelData.setYesterdayFlow(buffer.getInt()); + channelData.setCumulativeFlows(parseIntList(buffer, dataCount)); + break; + case 4: // 妯℃嫙閲 + channelData.setYesterdayFlow(buffer.getInt()); + channelData.setAnalogValues(parseFloatList(buffer, dataCount)); + break; + case 5: // 铏氭嫙Q閫氶亾 + channelData.setqChannelData(buffer.getShort() & 0xFFFF); + break; + case 6: // 铏氭嫙M閫氶亾 + channelData.setmChannelData(buffer.getInt()); + break; + } + return channelData; + } + + private static List parseIntList(ByteBuffer buffer, int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count && buffer.remaining() >= 4; i++) { + list.add(buffer.getInt()); + } + return list; + } + + private static List parseFloatList(ByteBuffer buffer, int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count && buffer.remaining() >= 4; i++) { + list.add(buffer.getFloat()); + } + return list; + } + + private static int bcdToInt(byte b) { + return ((b >> 4) & 0xF) * 10 + (b & 0xF); + } +} diff --git a/src/main/java/com/sipai/service/data/PipeTopicMpointService.java b/src/main/java/com/sipai/service/data/PipeTopicMpointService.java new file mode 100644 index 0000000..86fc878 --- /dev/null +++ b/src/main/java/com/sipai/service/data/PipeTopicMpointService.java @@ -0,0 +1,41 @@ +package com.sipai.service.data; + +import com.sipai.entity.data.PipeTopicMpoint; + +import java.util.List; + +/** + * 绠$綉涓撻椤电偣浣嶆湇鍔℃帴鍙 + */ +public interface PipeTopicMpointService { + + /** + * 娣诲姞鐐逛綅淇℃伅 + */ + int insert(PipeTopicMpoint pipeTopicMpoint); + + /** + * 鏍规嵁涓婚敭鍒犻櫎鐐逛綅 + */ + boolean delete(Integer id); + + /** + * 鎵归噺鍒犻櫎鐐逛綅 + */ + boolean deleteBatch(List idList); + + /** + * 鏇存柊鐐逛綅淇℃伅 + */ + boolean update(PipeTopicMpoint pipeTopicMpoint); + + /** + * 鏍规嵁涓婚敭鑾峰彇鐐逛綅璇︽儏 + */ + PipeTopicMpoint selectByPrimaryKey(Integer id); + + /** + * 鏍规嵁鏉′欢鏌ヨ鐐逛綅鍒楄〃 + */ + List selectListByWhere(String where); +} \ No newline at end of file diff --git a/src/main/java/com/sipai/service/data/PipelineEquipmentMpointService.java b/src/main/java/com/sipai/service/data/PipelineEquipmentMpointService.java new file mode 100644 index 0000000..acb0fa0 --- /dev/null +++ b/src/main/java/com/sipai/service/data/PipelineEquipmentMpointService.java @@ -0,0 +1,35 @@ +package com.sipai.service.data; + +import com.sipai.entity.data.PipelineEquipmentMpoint; + +import java.util.List; + +/** + * 绠¢亾璁惧涓庢祴鐐瑰叧鑱旀湇鍔℃帴鍙 + */ +public interface PipelineEquipmentMpointService { + /** + * 娣诲姞鍏宠仈淇℃伅 + */ + boolean insert(PipelineEquipmentMpoint mpoint); + + /** + * 鍒犻櫎鍏宠仈淇℃伅 + */ + boolean delete(Integer id); + + /** + * 鏇存柊鍏宠仈淇℃伅 + */ + boolean update(PipelineEquipmentMpoint mpoint); + + /** + * 鑾峰彇鍏宠仈淇℃伅璇︽儏 + */ + PipelineEquipmentMpoint selectByPrimaryKey(Integer id); + + /** + * 鑾峰彇鎵鏈夊叧鑱斾俊鎭垪琛 + */ + List selectListByWhere(String where); +} \ No newline at end of file diff --git a/src/main/java/com/sipai/service/data/PipelineEquipmentService.java b/src/main/java/com/sipai/service/data/PipelineEquipmentService.java new file mode 100644 index 0000000..05c7596 --- /dev/null +++ b/src/main/java/com/sipai/service/data/PipelineEquipmentService.java @@ -0,0 +1,60 @@ +package com.sipai.service.data; + +import com.sipai.entity.data.PipelineEquipment; + +import java.util.List; + +/** + * 绠¢亾璁惧鏈嶅姟鎺ュ彛 + */ +public interface PipelineEquipmentService { + /** + * 娣诲姞璁惧 + */ + int insert(PipelineEquipment pipelineEquipment); + + /** + * 鍒犻櫎璁惧 + */ + boolean delete(Integer id); + + /** + * 鏇存柊璁惧淇℃伅 + */ + boolean update(PipelineEquipment equipment); + + /** + * 鑾峰彇璁惧璇︽儏 + */ + PipelineEquipment selectByPrimaryKey(Integer id); + + /** + * 鑾峰彇鎵鏈夎澶囧垪琛 + */ + List selectListByWhere(String where); + + /** + * 鏍规嵁绔欑偣缂栧彿鏌ヨ璁惧 + */ + /*List getEquipmentByStation(String stationCode); + + *//** + * 鏍规嵁璁惧绫诲瀷鏌ヨ璁惧 + *//* + List getEquipmentByType(String equipmentType); + + *//** + * 鏍规嵁鐘舵佹煡璇㈣澶 + *//* + List getEquipmentByStatus(String status);*/ + + /** + * 鏇存柊璁惧鐘舵 + */ +// boolean updateEquipmentStatus(String id, String status); + + /** + * 鏇存柊璁惧鏈鍚庝笂浼犳椂闂 + */ +// boolean updateLastUploadTime(String id); +} diff --git a/src/main/java/com/sipai/service/data/PipelineMpointLibraryService.java b/src/main/java/com/sipai/service/data/PipelineMpointLibraryService.java new file mode 100644 index 0000000..a60a408 --- /dev/null +++ b/src/main/java/com/sipai/service/data/PipelineMpointLibraryService.java @@ -0,0 +1,42 @@ +package com.sipai.service.data; + +import com.sipai.entity.data.PipelineMpointLibrary; + +import java.util.List; + +/** + * 绠¢亾娴嬬偣搴撴湇鍔℃帴鍙 + */ +public interface PipelineMpointLibraryService { + /** + * 娣诲姞娴嬬偣搴撲俊鎭 + */ + boolean insert(PipelineMpointLibrary mpointLibrary); + + /** + * 鍒犻櫎娴嬬偣搴撲俊鎭 + */ + boolean delete(String id); + + /** + * 澶氬垹娴嬬偣搴撲俊鎭 + * @param idList + * @return + */ + int deleteBatch(List idList); + + /** + * 鏇存柊娴嬬偣搴撲俊鎭 + */ + boolean update(PipelineMpointLibrary mpointLibrary); + + /** + * 鑾峰彇娴嬬偣搴撹鎯 + */ + PipelineMpointLibrary selectByPrimaryKey(String id); + + /** + * 鑾峰彇鎵鏈夋祴鐐瑰簱鍒楄〃 + */ + List selectListByWhere(String where); +} \ No newline at end of file diff --git a/src/main/java/com/sipai/service/data/impl/PipeTopicMpointServiceImpl.java b/src/main/java/com/sipai/service/data/impl/PipeTopicMpointServiceImpl.java new file mode 100644 index 0000000..41af8d1 --- /dev/null +++ b/src/main/java/com/sipai/service/data/impl/PipeTopicMpointServiceImpl.java @@ -0,0 +1,59 @@ +package com.sipai.service.data.impl; + +import com.sipai.dao.data.PipeTopicMpointDao; +import com.sipai.entity.data.PipeTopicMpoint; +import com.sipai.service.data.PipeTopicMpointService; +import org.apache.commons.collections4.CollectionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class PipeTopicMpointServiceImpl implements PipeTopicMpointService { + + @Autowired + private PipeTopicMpointDao pipeTopicMpointDao; + + public PipeTopicMpointServiceImpl(PipeTopicMpointDao pipeTopicMpointDao) { + this.pipeTopicMpointDao = pipeTopicMpointDao; + } + + @Override + public int insert(PipeTopicMpoint pipeTopicMpoint) { + return pipeTopicMpointDao.insert(pipeTopicMpoint); + } + + @Override + public boolean delete(Integer id) { + return pipeTopicMpointDao.deleteByPrimaryKey(id); + } + + @Override + public boolean deleteBatch(List idList) { + if (CollectionUtils.isEmpty(idList)) { + return false; + } + int count = pipeTopicMpointDao.deleteBatchByIds(idList); + return count > 0; + } + + @Override + public boolean update(PipeTopicMpoint pipeTopicMpoint) { + return pipeTopicMpointDao.updateByPrimaryKeySelective(pipeTopicMpoint); + } + + @Override + public PipeTopicMpoint selectByPrimaryKey(Integer id) { + return pipeTopicMpointDao.selectByPrimaryKey(id); + } + + @Override + public List selectListByWhere(String where) { + PipeTopicMpoint pipeTopicMpoint = new PipeTopicMpoint(); + pipeTopicMpoint.setWhere(where); + return pipeTopicMpointDao.selectListByWhere(pipeTopicMpoint); + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/service/data/impl/PipelineEquipmentMpointServiceImpl.java b/src/main/java/com/sipai/service/data/impl/PipelineEquipmentMpointServiceImpl.java new file mode 100644 index 0000000..626f544 --- /dev/null +++ b/src/main/java/com/sipai/service/data/impl/PipelineEquipmentMpointServiceImpl.java @@ -0,0 +1,48 @@ +package com.sipai.service.data.impl; + +import com.sipai.dao.data.PipelineEquipmentMpointDao; +import com.sipai.entity.data.PipelineEquipmentMpoint; +import com.sipai.service.data.PipelineEquipmentMpointService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class PipelineEquipmentMpointServiceImpl implements PipelineEquipmentMpointService { + @Autowired + private PipelineEquipmentMpointDao pipelineEquipmentMpointDao; + + public PipelineEquipmentMpointServiceImpl(PipelineEquipmentMpointDao mpointDao) { + this.pipelineEquipmentMpointDao = mpointDao; + } + + @Override + public boolean insert(PipelineEquipmentMpoint mpoint) { + return pipelineEquipmentMpointDao.insert(mpoint); + } + + @Override + public boolean delete(Integer id) { + return pipelineEquipmentMpointDao.deleteByPrimaryKey(id); + } + + @Override + public boolean update(PipelineEquipmentMpoint mpoint) { + return pipelineEquipmentMpointDao.updateByPrimaryKeySelective(mpoint); + } + + @Override + public PipelineEquipmentMpoint selectByPrimaryKey(Integer id) { + return pipelineEquipmentMpointDao.selectByPrimaryKey(id); + } + + @Override + public List selectListByWhere(String where) { + PipelineEquipmentMpoint mpoint = new PipelineEquipmentMpoint(); + mpoint.setWhere(where); + return pipelineEquipmentMpointDao.selectListByWhere(mpoint); + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/service/data/impl/PipelineEquipmentServiceImpl.java b/src/main/java/com/sipai/service/data/impl/PipelineEquipmentServiceImpl.java new file mode 100644 index 0000000..f35b671 --- /dev/null +++ b/src/main/java/com/sipai/service/data/impl/PipelineEquipmentServiceImpl.java @@ -0,0 +1,126 @@ +package com.sipai.service.data.impl; + +import com.sipai.dao.data.PipelineEquipmentDao; +import com.sipai.dao.scada.MPointDao; +import com.sipai.entity.data.PipelineEquipment; +import com.sipai.entity.enums.DeviceTypeEnum; +import com.sipai.service.data.PipelineEquipmentService; +import org.apache.commons.collections4.CollectionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class PipelineEquipmentServiceImpl implements PipelineEquipmentService { + @Autowired + private PipelineEquipmentDao pipelineEquipmentDao; + + public PipelineEquipmentServiceImpl(PipelineEquipmentDao equipmentDao) { + this.pipelineEquipmentDao = equipmentDao; + } + + @Override + public int insert(PipelineEquipment equipment) { + int result = pipelineEquipmentDao.insert(equipment); + if (result > 0) { + // 鎻掑叆鎴愬姛锛岃幏鍙栬嚜澧炵殑ID + int generatedId = equipment.getId(); + } + return result; + } + + @Override + public boolean delete(Integer id) { + return pipelineEquipmentDao.deleteByPrimaryKey(id); + } + + /*@Override + public boolean deleteBatch(List idList) { + // 鍙傛暟鏍¢獙 + if (CollectionUtils.isEmpty(idList)) { + return false; + } + + // 鎵ц鎵归噺鍒犻櫎 + int count = pipelineEquipmentDao.deleteBatchByIds(idList); + + return count > 0; + }*/ + + @Override + public boolean update(PipelineEquipment equipment) { + return pipelineEquipmentDao.updateByPrimaryKeySelective(equipment); + } + + @Override + public PipelineEquipment selectByPrimaryKey(Integer id) { + PipelineEquipment pipelineEquipment = pipelineEquipmentDao.selectByPrimaryKey(id); + if (pipelineEquipment != null) { + + //鏌ヨ瀵瑰簲鐨勮澶囧悕绉 + String typeCode = pipelineEquipment.getEquipmentType(); + DeviceTypeEnum deviceType = DeviceTypeEnum.getByTypeCode(typeCode); + if (deviceType != null) { + pipelineEquipment.setEquipmentTypeName(deviceType.getTypeName()); + } + + return pipelineEquipment; + } else { + return null; + } + } + + @Override + public List selectListByWhere(String where) { + PipelineEquipment pipelineEquipment = new PipelineEquipment(); + pipelineEquipment.setWhere(where); + + List list = pipelineEquipmentDao.selectListByWhere(pipelineEquipment); + for (PipelineEquipment equipment : list) { + String typeCode = equipment.getEquipmentType(); + DeviceTypeEnum deviceType = DeviceTypeEnum.getByTypeCode(typeCode); + if (deviceType != null) { + equipment.setEquipmentTypeName(deviceType.getTypeName()); + } + } + return list; + } + + /*@Override + public List getEquipmentByStation(String stationCode) { + return equipmentDao.selectByStationCode(stationCode); + } + + @Override + public List getEquipmentByType(String equipmentType) { + return equipmentDao.selectByEquipmentType(equipmentType); + } + + @Override + public List getEquipmentByStatus(String status) { + return equipmentDao.selectByStatus(status); + }*/ + + /*@Override + public boolean updateEquipmentStatus(String id, String status) { + PipelineEquipment equipment = pipelineEquipmentDao.selectByPrimaryKey(id); + if (equipment == null) { + return false; + } + equipment.setStatus(status); + return pipelineEquipmentDao.updateByPrimaryKeySelective(equipment) > 0; + } + + @Override + public boolean updateLastUploadTime(String id) { + PipelineEquipment equipment = pipelineEquipmentDao.selectByPrimaryKey(id); + if (equipment == null) { + return false; + } + equipment.setLastUploadTime(new Date()); + return pipelineEquipmentDao.updateByPrimaryKeySelective(equipment) > 0; + }*/ +} diff --git a/src/main/java/com/sipai/service/data/impl/PipelineMpointLibraryServiceImpl.java b/src/main/java/com/sipai/service/data/impl/PipelineMpointLibraryServiceImpl.java new file mode 100644 index 0000000..bf3c950 --- /dev/null +++ b/src/main/java/com/sipai/service/data/impl/PipelineMpointLibraryServiceImpl.java @@ -0,0 +1,54 @@ +package com.sipai.service.data.impl; + +import com.sipai.dao.data.PipelineMpointLibraryDao; +import com.sipai.entity.data.PipelineMpointLibrary; +import com.sipai.service.data.PipelineMpointLibraryService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class PipelineMpointLibraryServiceImpl implements PipelineMpointLibraryService { + @Autowired + private PipelineMpointLibraryDao pipelineMpointLibraryDao; + + public PipelineMpointLibraryServiceImpl(PipelineMpointLibraryDao mpointLibraryDao) { + this.pipelineMpointLibraryDao = mpointLibraryDao; + } + + @Override + public boolean insert(PipelineMpointLibrary mpointLibrary) { + return pipelineMpointLibraryDao.insert(mpointLibrary); + } + + @Override + public boolean delete(String id) { + return pipelineMpointLibraryDao.deleteByPrimaryKey(id); + } + + @Override + public int deleteBatch(List idList) { + return pipelineMpointLibraryDao.deleteBatchByIds(idList); + } + + @Override + public boolean update(PipelineMpointLibrary mpointLibrary) { + return pipelineMpointLibraryDao.updateByPrimaryKeySelective(mpointLibrary); + } + + @Override + public PipelineMpointLibrary selectByPrimaryKey(String id) { + return pipelineMpointLibraryDao.selectByPrimaryKey(id); + } + + @Override + public List selectListByWhere(String where) { + PipelineMpointLibrary pipelineMpointLibrary = new PipelineMpointLibrary(); + pipelineMpointLibrary.setWhere(where); + + return pipelineMpointLibraryDao.selectListByWhere(pipelineMpointLibrary); + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/service/kafka/KafkaConsumerService.java b/src/main/java/com/sipai/service/kafka/KafkaConsumerService.java new file mode 100644 index 0000000..ae2c4b7 --- /dev/null +++ b/src/main/java/com/sipai/service/kafka/KafkaConsumerService.java @@ -0,0 +1,24 @@ +package com.sipai.service.kafka; + +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.kafka.support.Acknowledgment; +import org.springframework.stereotype.Service; + +/** + * 娑堣垂鑰呮湇鍔 + */ +/*@Service +public class KafkaConsumerService { + + @KafkaListener(topics = "topic_data", groupId = "my-group-2.2.0") + public void listen(String message, Acknowledgment ack) { + try { +// System.out.println("topic_data鏀跺埌鏁版嵁: " + message); + // 鎵嬪姩鎻愪氦offset + ack.acknowledge(); + } catch (Exception e) { + // 澶勭悊寮傚父 + System.err.println("Error processing message: " + e.getMessage()); + } + } +}*/ diff --git a/src/main/java/com/sipai/service/kafka/KafkaProducerService.java b/src/main/java/com/sipai/service/kafka/KafkaProducerService.java new file mode 100644 index 0000000..414ef41 --- /dev/null +++ b/src/main/java/com/sipai/service/kafka/KafkaProducerService.java @@ -0,0 +1,38 @@ +package com.sipai.service.kafka; + +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.support.SendResult; +import org.springframework.util.concurrent.ListenableFuture; +import org.springframework.util.concurrent.ListenableFutureCallback; +import org.springframework.stereotype.Service; + +/** + * 鐢熶骇鑰呮湇鍔 + */ +/*@Service +public class KafkaProducerService { + + private final KafkaTemplate kafkaTemplate; + + public KafkaProducerService(KafkaTemplate kafkaTemplate) { + this.kafkaTemplate = kafkaTemplate; + } + + public void sendMessage(String topic, String message) { + ListenableFuture> future = kafkaTemplate.send(topic, message); + + future.addCallback(new ListenableFutureCallback>() { + @Override + public void onSuccess(SendResult result) { + System.out.println("Sent message=[" + message + + "] with offset=[" + result.getRecordMetadata().offset() + "]"); + } + + @Override + public void onFailure(Throwable ex) { + System.err.println("Unable to send message=[" + + message + "] due to : " + ex.getMessage()); + } + }); + } +}*/ diff --git a/src/main/java/com/sipai/service/mqtt/MqttConfigService.java b/src/main/java/com/sipai/service/mqtt/MqttConfigService.java new file mode 100644 index 0000000..acf5824 --- /dev/null +++ b/src/main/java/com/sipai/service/mqtt/MqttConfigService.java @@ -0,0 +1,62 @@ +package com.sipai.service.mqtt; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.sipai.entity.mqtt.MqttConfig; +import com.sipai.entity.scada.MPoint; + +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/03/24/16:44 + * @Description: + */ +public interface MqttConfigService { + + public abstract MqttConfig selectByPrimaryKey(String id); + + public abstract Integer deleteByPrimaryKey(String id); + + public abstract Integer insert(MqttConfig entity); + + public abstract Integer updateByPrimaryKeySelective(MqttConfig entity); + + public abstract List selectListByWhere(String wherestr); + + public abstract Integer deleteByWhere(String wherestr); + + public String connect(String id); + + /** + * 鏍规嵁涓婚杩斿洖emqx浠g悊鍦板潃 websocket鏂瑰紡 + * sj 2021-09-15 + * @param topic + * @return + */ + public JSONObject getEmqxHost4WS(String topic); + + /** + * 鏍规嵁涓婚杩斿洖emqx浠g悊鍦板潃 tcp鏂瑰紡 + * sj 2021-09-15 + * @param topic + * @return + */ + public String getEmqxHost4TCP(String topic); + + public void doSendMqttVue(List list, String topic); + + /** + * @param jsonArray 闇瑕佹帹閫佺殑鏁版嵁 + * @param topic 鎺ㄩ佺殑涓婚 + */ + public void doSendView(JSONArray jsonArray, String topic); + + /** + * @param jsonObject 闇瑕佹帹閫佺殑鏁版嵁 + * @param topic 鎺ㄩ佺殑涓婚 + */ + public void doSendJson(JSONObject jsonObject, String topic); +} diff --git a/src/main/java/com/sipai/service/mqtt/MqttConfigTopicService.java b/src/main/java/com/sipai/service/mqtt/MqttConfigTopicService.java new file mode 100644 index 0000000..ba8d314 --- /dev/null +++ b/src/main/java/com/sipai/service/mqtt/MqttConfigTopicService.java @@ -0,0 +1,28 @@ +package com.sipai.service.mqtt; + +import com.sipai.entity.mqtt.MqttConfigTopic; + +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/03/24/17:56 + * @Description: + */ +public interface MqttConfigTopicService { + public abstract MqttConfigTopic selectByPrimaryKey(String id); + + public abstract Integer deleteByPrimaryKey(String id); + + public abstract Integer insert(MqttConfigTopic entity); + + public abstract Integer updateByPrimaryKeySelective(MqttConfigTopic entity); + + public abstract List selectListByWhere(String wherestr); + + public abstract Integer deleteByWhere(String wherestr); + + public abstract List selectListByPid(String pid); +} diff --git a/src/main/java/com/sipai/service/mqtt/MqttService.java b/src/main/java/com/sipai/service/mqtt/MqttService.java new file mode 100644 index 0000000..fc9c722 --- /dev/null +++ b/src/main/java/com/sipai/service/mqtt/MqttService.java @@ -0,0 +1,57 @@ +package com.sipai.service.mqtt; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import org.springframework.scheduling.annotation.Scheduled; + +public interface MqttService { + /** + * 鐢ㄤ簬鎻愪緵浜戝钩鍙 缁檖lc鍙戝竷鎸囦护鎺ュ彛 + * @param json + * @param topic + * @param userId + * @param bizId + * @return + */ + public abstract int doPublish(JSONObject json, String topic, String userId, String bizId); + + /** + * 澶勭悊mqtt璁㈤槄鍒扮殑鏁版嵁 + * @param bizId + * @param topic + * @param ip4 + * @param port + * @param jsonArray + */ + public abstract void doHandle(String bizId, String topic, String ip4, String port, JSONArray jsonArray); + + /** + * 澶勭悊mqtt璁㈤槄鍒扮殑鏁版嵁 -- 锛堣ˉ鍙戠殑鏁版嵁 1.涓嶆姤璀 2.涓嶆洿鏂颁富琛 3.AI鐐3鍒嗛挓瀛樹竴娆 DI鐐规瘡娆¢兘瀛橈級 + * @param bizId + * @param topic + * @param ip4 + * @param port + * @param jsonArray + */ + public abstract void doHandleHis(String bizId, String topic, String ip4, String port, JSONArray jsonArray); + + /** + * 缃戝叧鏁版嵁鍏ㄩ儴鍙洖 + * @param bizId + * @return + */ + public abstract void doRecall(String bizId,JSONObject jsonObject); + + /** + * 鍙戦 rabbitmq + * + * @return + */ + public abstract void sentRabbitmq(String exchange, String key, String value_BigDecimal, String date); + + /** + * 娓呯悊娴嬮噺鐐瑰璞$紦瀛 + */ + @Scheduled(fixedRate = 3600000) // 姣忓皬鏃舵竻鐞嗕竴娆 + void cleanCache(); +} diff --git a/src/main/java/com/sipai/service/mqtt/PushCallback.java b/src/main/java/com/sipai/service/mqtt/PushCallback.java new file mode 100644 index 0000000..d5c07ab --- /dev/null +++ b/src/main/java/com/sipai/service/mqtt/PushCallback.java @@ -0,0 +1,229 @@ +package com.sipai.service.mqtt; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.sipai.entity.user.Company; +import com.sipai.service.rabbitmq.MQService; +import com.sipai.service.user.CompanyService; +import com.sipai.tools.CommUtil; +import com.sipai.tools.SpringContextUtil; +import org.eclipse.paho.client.mqttv3.*; + +import javax.management.MBeanServer; +import javax.management.MalformedObjectNameException; +import javax.management.ObjectName; +import javax.management.Query; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.lang.management.ManagementFactory; +import java.math.BigDecimal; +import java.net.*; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Set; + +/** + * 鍙戝竷娑堟伅鐨勫洖璋冪被 + *

+ * 蹇呴』瀹炵幇MqttCallback鐨勬帴鍙e苟瀹炵幇瀵瑰簲鐨勭浉鍏虫帴鍙f柟娉旵allBack 绫诲皢瀹炵幇 MqttCallBack銆 + * 姣忎釜瀹㈡埛鏈烘爣璇嗛兘闇瑕佷竴涓洖璋冨疄渚嬨傚湪姝ょず渚嬩腑锛屾瀯閫犲嚱鏁颁紶閫掑鎴锋満鏍囪瘑浠ュ彟瀛樹负瀹炰緥鏁版嵁銆 + * 鍦ㄥ洖璋冧腑锛屽皢瀹冪敤鏉ユ爣璇嗗凡缁忓惎鍔ㄤ簡璇ュ洖璋冪殑鍝釜瀹炰緥銆 + * 蹇呴』鍦ㄥ洖璋冪被涓疄鐜颁笁涓柟娉曪細 + *

+ * public void messageArrived(MqttTopic topic, MqttMessage message)鎺ユ敹宸茬粡棰勮鐨勫彂甯冦 + *

+ * public void connectionLost(Throwable cause)鍦ㄦ柇寮杩炴帴鏃惰皟鐢ㄣ + *

+ * public void deliveryComplete(MqttDeliveryToken token)) + * 鎺ユ敹鍒板凡缁忓彂甯冪殑 QoS 1 鎴 QoS 2 娑堟伅鐨勪紶閫掍护鐗屾椂璋冪敤銆 + * 鐢 MqttClient.connect 婵娲绘鍥炶皟銆 + */ + +public class PushCallback implements MqttCallbackExtended { + + InetAddress ip4;//ip + + { + try { + ip4 = Inet4Address.getLocalHost(); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + } + + MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer(); + Set objectNames; + String port = "";//绔彛 + + { + try { + objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"), + Query.match(Query.attr("protocol"), Query.value("HTTP/1.1"))); +// port = objectNames.iterator().next().getKeyProperty("port"); + port = "8080"; + } catch (MalformedObjectNameException e) { + e.printStackTrace(); + } + } + + private MqttClient client; + private MqttConnectOptions options; + private String[] topic; + private int[] qos; + + public PushCallback(MqttClient client, MqttConnectOptions options, String[] topic, int[] qos) { + this.client = client; + this.options = options; + this.topic = topic; + this.qos = qos; + } + + /** + * 杩炴帴鏂紑鍥炶皟鏂规硶 + */ + public void connectionLost(Throwable cause) { + System.out.println("===杩炴帴鏂紑鍥炶皟鏂规硶"); + try { + if (null != client && !client.isConnected()) { + System.out.println("灏濊瘯閲嶆柊杩炴帴"); + client.connect(options); + } else { + System.out.println("灏濊瘯寤虹珛鏂拌繛鎺"); + client.connect(options); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 杩炴帴鎴愬姛鍥炶皟鏂规硶 + */ + @Override + public void connectComplete(boolean reconnect, String serverURI) { + System.out.println("===杩炴帴鎴愬姛鍥炶皟鏂规硶"); + try { + if (null != topic && null != qos) { + if (client.isConnected()) { + client.subscribe(topic, qos); + System.out.println("mqtt杩炴帴鎴愬姛"); + } else { + System.out.println("mqtt杩炴帴澶辫触"); + } + } + } catch (Exception e) { + System.out.println("mqtt璁㈤槄涓婚寮傚父:" + e); + } + } + + public void deliveryComplete(IMqttDeliveryToken token) { +// System.out.println("deliveryComplete---------" + token.isComplete()); + } + + public void messageArrived(String topic, MqttMessage message) { + try { + JSONArray jsonArray = JSONArray.parseArray(message.toString()); +// System.out.println(topic + "===寮濮===" + CommUtil.nowDate() + "===" + jsonArray.size()); + String unitId = topic.substring(0, 4);//鎴彇topic鐨勫墠闈㈤儴鍒嗕綔涓哄巶id + MqttService mqttService = (MqttService) SpringContextUtil.getBean("mqttService"); + //姝e父鐨勪富棰 -- 鏁版嵁澶勭悊 + mqttService.doHandle(unitId, topic, ip4.toString(), port, jsonArray); + } catch (Exception e) { + System.out.println(topic + "鎵ц澶辫触" + e); + } + } + + + /** + * 鏃ユ湡鏍煎紡瀛楃涓茶浆鎹㈡垚鏃堕棿鎴 + * + * @param date_str 瀛楃涓叉棩鏈 + * @param format 濡傦細yyyy-MM-dd HH:mm:ss + * @return + */ + public static String date2TimeStamp(String date_str, String format) { + try { + SimpleDateFormat sdf = new SimpleDateFormat(format); + return String.valueOf(sdf.parse(date_str).getTime() / 1000); + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } + + /** + * 鍙戦 rabbitmq + * + * @param key + * @param value_BigDecimal + * @param date + */ + public static void sentRabbitmq(String exchange, String key, String value_BigDecimal, String date) { + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("id", key); + jsonObject1.put("value", value_BigDecimal); + jsonObject1.put("time", date); + MQService mqService = (MQService) SpringContextUtil.getBean("mQService"); + mqService.sendMQ(exchange, jsonObject1.toString()); + } + + public static void sentRabbitMqMpoint(String exchange, String json) { + MQService mqService = (MQService) SpringContextUtil.getBean("mQService"); + mqService.sendMQ(exchange, json); + } + + public String doPost(String URL) { + OutputStreamWriter out = null; + BufferedReader in = null; + StringBuilder result = new StringBuilder(); + HttpURLConnection conn = null; + try { + java.net.URL url = new URL(URL); + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("POST"); + //鍙戦丳OST璇锋眰蹇呴』璁剧疆涓簍rue + conn.setDoOutput(true); + conn.setDoInput(true); + //璁剧疆杩炴帴瓒呮椂鏃堕棿鍜岃鍙栬秴鏃舵椂闂 + conn.setConnectTimeout(30000); + conn.setReadTimeout(10000); + conn.setRequestProperty("Content-Type", "application/json"); + conn.setRequestProperty("Accept", "application/json"); + //鑾峰彇杈撳嚭娴 + out = new OutputStreamWriter(conn.getOutputStream()); + String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}"; + out.write(jsonStr); + out.flush(); + out.close(); + //鍙栧緱杈撳叆娴侊紝骞朵娇鐢≧eader璇诲彇 + if (200 == conn.getResponseCode()) { + in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); + String line; + while ((line = in.readLine()) != null) { + result.append(line); + } + } else { + System.out.println("ResponseCode is an error code:" + conn.getResponseCode()); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (out != null) { + out.close(); + } + if (in != null) { + in.close(); + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } + return result.toString(); + } + +} diff --git a/src/main/java/com/sipai/service/mqtt/impl/MqttConfigServiceImpl.java b/src/main/java/com/sipai/service/mqtt/impl/MqttConfigServiceImpl.java new file mode 100644 index 0000000..57016ea --- /dev/null +++ b/src/main/java/com/sipai/service/mqtt/impl/MqttConfigServiceImpl.java @@ -0,0 +1,348 @@ +package com.sipai.service.mqtt.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.sipai.entity.mqtt.Mqtt; +import com.sipai.entity.mqtt.MqttProperties; +import com.sipai.entity.scada.MPoint; +import com.sipai.service.mqtt.PushCallback; +import com.sipai.dao.mqtt.MqttConfigDao; +import com.sipai.entity.mqtt.MqttConfig; +import com.sipai.entity.mqtt.MqttConfigTopic; +import com.sipai.service.mqtt.MqttConfigService; +import com.sipai.service.mqtt.MqttConfigTopicService; +import com.sipai.tools.CommUtil; +import org.apache.commons.codec.binary.Base64; +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/03/24/16:45 + * @Description: + */ +@Service +public class MqttConfigServiceImpl implements MqttConfigService { + private final MqttProperties mqttProperties; + @Autowired + private MqttConfigDao mqttConfigDao; + @Autowired + private MqttConfigTopicService mqttConfigTopicService; + + private static MqttClient mqttClient1; + + // 鏋勯犲櫒娉ㄥ叆 + @Autowired + public MqttConfigServiceImpl(MqttProperties mqttProperties) { + this.mqttProperties = mqttProperties; + } + + private static MqttClient connect(String brokeraddress, String clientId, String userName, String password) throws MqttException { + MemoryPersistence persistence = new MemoryPersistence(); + MqttConnectOptions connOpts = new MqttConnectOptions(); + connOpts.setCleanSession(true); + connOpts.setUserName(userName); + connOpts.setPassword(password.toCharArray()); + connOpts.setConnectionTimeout(1000); + connOpts.setKeepAliveInterval(1000); + mqttClient1 = new MqttClient(brokeraddress, clientId, persistence); + mqttClient1.connect(connOpts); + return mqttClient1; + } + + @Override + public MqttConfig selectByPrimaryKey(String id) { + return mqttConfigDao.selectByPrimaryKey(id); + } + + @Override + public Integer deleteByPrimaryKey(String id) { + return mqttConfigDao.deleteByPrimaryKey(id); + } + + @Override + public Integer insert(MqttConfig entity) { + return mqttConfigDao.insert(entity); + } + + @Override + public Integer updateByPrimaryKeySelective(MqttConfig entity) { + return mqttConfigDao.insert(entity); + } + + @Override + public List selectListByWhere(String whereStr) { + MqttConfig entity = new MqttConfig(); + entity.setWhere(whereStr); + return mqttConfigDao.selectListByWhere(entity); + } + + @Override + public Integer deleteByWhere(String whereStr) { + return mqttConfigDao.deleteByWhere(whereStr); + } + + @Override + public String connect(String id) { + String clientId = ""; + MqttConfig mqttConfig = mqttConfigDao.selectByPrimaryKey(id); + if (mqttConfig != null) { + clientId = mqttConfig.getTomcatPort() + "-" + CommUtil.getUUID(); + System.out.println(clientId); + String sql = "where id = '" + mqttConfig.getId() + "'"; + mqttConfig.setWhere(sql); + List list_config = mqttConfigDao.selectListByWhere(mqttConfig); + List topic_str = new ArrayList<>(); + + //姣忎釜瀹㈡埛绔牴鎹厤缃殑tomcat绔彛鍙疯繘琛屽垎鍖鸿繛鎺 + if (list_config != null && list_config.size() > 0) { + //寰幆閰嶇疆涓昏〃 + for (int i = 0; i < list_config.size(); i++) { + String sql_detail = "where pid = '" + list_config.get(i).getId() + "'"; + List list_topic = mqttConfigTopicService.selectListByWhere(sql_detail); + if (list_topic != null && list_topic.size() > 0) { + //寰幆閰嶇疆闄勮〃锛堣幏鍙栨墍鏈塼opic锛 + for (int j = 0; j < list_topic.size(); j++) { + //閰嶇疆鐨刜UP涓婚 +// topic_str.add("$queue/" + list_topic.get(j).getTopic()); + topic_str.add(list_topic.get(j).getTopic()); + } + } + } + } + + //閰嶇疆鐨勬潯鏁板嵆涓烘暟缁勭殑闀垮害 + String[] topic = new String[topic_str.size()]; + System.out.println("璁㈤槄涓婚锛" + topic_str); + int[] qos = new int[topic_str.size()]; + for (int j = 0; j < topic_str.size(); j++) { + topic[j] = topic_str.get(j); + qos[j] = 0; + } + try { + MqttConnectOptions connOpts = new MqttConnectOptions(); + connOpts.setCleanSession(true); + connOpts.setConnectionTimeout(1000); + //姣忛殧1.5*10绉掔殑鏃堕棿鍚戝鎴风鍙戦佷釜娑堟伅鍒ゆ柇瀹㈡埛绔槸鍚﹀湪绾 + connOpts.setKeepAliveInterval(1000); + //鑷姩閲嶈繛 + connOpts.setAutomaticReconnect(true); + connOpts.setUserName(mqttProperties.getUsername()); + connOpts.setPassword(mqttProperties.getPassword().toCharArray()); + + if (mqttClient1 != null) { + System.out.println("宸茶繛鎺"); + //鍥炶皟 + mqttClient1.setCallback(new PushCallback(mqttClient1, connOpts, topic, qos)); + //璁㈤槄 + mqttClient1.subscribe(topic, qos); + } else { + System.out.println("閲嶆柊杩炴帴"); + //杩炴帴 + mqttClient1 = connect(mqttConfig.getBrokerIp(), clientId, mqttProperties.getUsername(), mqttProperties.getPassword()); + //鍥炶皟 + mqttClient1.setCallback(new PushCallback(mqttClient1, connOpts, topic, qos)); + //璁㈤槄 + mqttClient1.subscribe(topic, qos); + } + + } catch (MqttException me) { + me.printStackTrace(); + } + } + return clientId; + } + + public Boolean clientStatus(String clientId) { + boolean status = true; + try { + System.out.println(mqttProperties.getDashboard01() + "/api/v4/clients/" + clientId); + URL url = new URL(mqttProperties.getDashboard01() + "/api/v4/clients/" + clientId); + Base64 b = new Base64(); + String encoding = b.encodeAsString(new String("admin:sipai@64368180").getBytes()); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("Authorization", "Basic " + encoding); + InputStream content = connection.getInputStream(); + BufferedReader in = new BufferedReader(new InputStreamReader(content)); + + JSONObject jsonObject = JSONObject.parseObject(in.readLine()); + String data = jsonObject.get("data").toString(); + JSONArray jsonArrayStr = JSONArray.parseArray(data); + if (jsonArrayStr.size() > 0) { + JSONObject jsonObject1 = jsonArrayStr.getJSONObject(0); + if (jsonObject1.get("connected").equals(true)) { + status = true; + } else { + status = false; + } + } else { + status = false; + } + } catch (Exception e) { + e.printStackTrace(); + } + return status; + } + + @Override + public JSONObject getEmqxHost4WS(String topic) { + JSONObject jsonObject = new JSONObject(); + List list = mqttConfigTopicService.selectListByWhere("where topic = '" + topic + "'"); + if (list != null && list.size() > 0) { + MqttConfig mqttConfig = new MqttConfig(); + //澧炲姞涓惊鐜煡鍑烘墍鏈夌殑 鏈変簺鏃ф暟鎹 璺宠繃 鍙煡鏈変富琛ㄦ暟鎹殑 + for (int i = 0; i < list.size(); i++) { + mqttConfig.setWhere("where id = '" + list.get(i).getPid() + "'"); + List list2 = mqttConfigDao.selectListByWhere(mqttConfig); + if (list2 != null && list2.size() > 0) { + if (list2.get(0).getBrokerIp() != null && !list2.get(0).getBrokerIp().trim().equals("")) { + String ip = list2.get(0).getBrokerIp(); + ip = ip.replace("tcp://", ""); + String host = ip.substring(0, ip.indexOf(":")); + //涓鏈 + if (host != null && host.equals("172.16.242.16")) { + jsonObject.put("host", "58.254.140.62"); + jsonObject.put("port", "8088"); + } + //浜屾湡 + if (host != null && host.equals("172.16.242.24")) { + jsonObject.put("host", "58.254.140.121"); + jsonObject.put("port", "8083"); + } + } + break; + } + } + } + return jsonObject; + } + + @Override + public String getEmqxHost4TCP(String topic) { + String host = mqttProperties.getBrokerAddress();//榛樿涓鏈 + List list = mqttConfigTopicService.selectListByWhere("where topic = '" + topic + "'"); + if (list != null && list.size() > 0) { + MqttConfig mqttConfig = new MqttConfig(); + //澧炲姞涓惊鐜煡鍑烘墍鏈夌殑 鏈変簺鏃ф暟鎹 璺宠繃 鍙煡鏈変富琛ㄦ暟鎹殑 + for (int i = 0; i < list.size(); i++) { + + mqttConfig.setWhere("where id = '" + list.get(i).getPid() + "'"); + List list2 = mqttConfigDao.selectListByWhere(mqttConfig); + if (list2 != null && list2.size() > 0) { + if (list2.get(0).getBrokerIp() != null && !list2.get(0).getBrokerIp().trim().equals("")) { + host = list2.get(0).getBrokerIp(); + } + break; + } + } + } + return host; + } + + @Async + public void doSendMqttVue(List list, String topic) { + JSONArray jsonVue = (JSONArray) JSONArray.toJSON(list); + MqttMessage message = new MqttMessage(jsonVue.toString().getBytes()); + message.setQos(0); + message.setRetained(false); + try { + String host = this.getEmqxHost4TCP(topic); + if (host != null && !host.equals("")) { + String[] str = host.split(";"); + String ip = str[0];//杩炴帴鐨刬p + String topic_vue = topic; + if (topic != null && topic.contains("_IM")) { + topic_vue = topic.replace("_IM", ""); + } +// topic_vue = topic_vue + "_VIEW"; + topic_vue = topic_vue.substring(0, 4) + "_01_UP_VIEW"; + int size = list != null ? list.size() : 0; + StringBuilder ids = new StringBuilder(); + if (list != null) { + int max = Math.min(5, list.size()); + for (int i = 0; i < max; i++) { + ids.append(list.get(i).getId()); + if (i < max - 1) ids.append(","); + } + } + System.out.println("鎺ㄩ乂IEW: topic=" + topic_vue + " size=" + size); + if (mqttClient1 != null && mqttClient1.isConnected()) { + //鍙戝竷 +// System.out.println("鎺ㄩ佸墠绔細" + topic_vue); + mqttClient1.publish(topic_vue, message); + } else { + System.out.println("===閲嶆柊杩炴帴===" + "鎺╒UE===涓婚锛" + topic_vue + "===" + ip + "===" + CommUtil.nowDate() + "==="); + //杩炴帴 + String clientId = "send_vue_" + str[2]; + mqttClient1 = connect(ip, clientId, mqttProperties.getUsername(), mqttProperties.getPassword()); + //鍙戝竷 + mqttClient1.publish(topic_vue, message); + } + } + } catch (MqttException e) { + e.printStackTrace(); + } + } + + @Async + public void doSendView(JSONArray jsonArray, String topic) { + MqttMessage message = new MqttMessage(jsonArray.toString().getBytes()); + message.setQos(0); + message.setRetained(false); + try { + if (mqttClient1 != null && mqttClient1.isConnected()) { + //鍙戝竷 + mqttClient1.publish(topic, message); + } else { + mqttClient1 = connect(mqttProperties.getBrokerAddress(), "send_vue_" + CommUtil.getUUID(), mqttProperties.getUsername(), mqttProperties.getPassword()); + //鍙戝竷 + mqttClient1.publish(topic, message); + } + } catch (MqttException e) { + e.printStackTrace(); + } + } + + /** + * @param jsonObject 闇瑕佹帹閫佺殑鏁版嵁 + * @param topic 鎺ㄩ佺殑涓婚 + */ + @Async + public void doSendJson(JSONObject jsonObject, String topic) { + MqttMessage message = new MqttMessage(jsonObject.toString().getBytes()); + message.setQos(0); + message.setRetained(false); + try { + if (mqttClient1 != null && mqttClient1.isConnected()) { + //鍙戝竷 + mqttClient1.publish(topic, message); + } else { + mqttClient1 = connect(mqttProperties.getBrokerAddress(), "send_vue_" + CommUtil.getUUID(), mqttProperties.getUsername(), mqttProperties.getPassword()); + //鍙戝竷 + mqttClient1.publish(topic, message); + } + } catch (MqttException e) { + e.printStackTrace(); + } + } + +} diff --git a/src/main/java/com/sipai/service/mqtt/impl/MqttConfigTopicServiceImpl.java b/src/main/java/com/sipai/service/mqtt/impl/MqttConfigTopicServiceImpl.java new file mode 100644 index 0000000..4c3120e --- /dev/null +++ b/src/main/java/com/sipai/service/mqtt/impl/MqttConfigTopicServiceImpl.java @@ -0,0 +1,61 @@ +package com.sipai.service.mqtt.impl; + +import com.sipai.dao.mqtt.MqttConfigTopicDao; +import com.sipai.entity.mqtt.MqttConfigTopic; +import com.sipai.service.mqtt.MqttConfigTopicService; +import com.sipai.tools.DataSourceEnum; +import com.sipai.tools.DataSourceTypeAnno; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/03/24/17:56 + * @Description: + */ +@Service +public class MqttConfigTopicServiceImpl implements MqttConfigTopicService { + @Autowired + private MqttConfigTopicDao mqttConfigTopicDao; + + @Override + public MqttConfigTopic selectByPrimaryKey(String id) { + return mqttConfigTopicDao.selectByPrimaryKey(id); + } + + @Override + public Integer deleteByPrimaryKey(String id) { + return mqttConfigTopicDao.deleteByPrimaryKey(id); + } + + @Override + public Integer insert(MqttConfigTopic entity) { + return mqttConfigTopicDao.insert(entity); + } + + @Override + public Integer updateByPrimaryKeySelective(MqttConfigTopic entity) { + return mqttConfigTopicDao.updateByPrimaryKeySelective(entity); + } + + @Override + public List selectListByWhere(String wherestr) { + MqttConfigTopic entity = new MqttConfigTopic(); + entity.setWhere(wherestr); + return mqttConfigTopicDao.selectListByWhere(entity); + } + + @Override + public Integer deleteByWhere(String wherestr) { + return mqttConfigTopicDao.deleteByWhere(wherestr); + } + + @Override + public List selectListByPid(String pid) { + return mqttConfigTopicDao.selectListByPid(pid); + } +} diff --git a/src/main/java/com/sipai/service/mqtt/impl/MqttServiceImpl.java b/src/main/java/com/sipai/service/mqtt/impl/MqttServiceImpl.java new file mode 100644 index 0000000..a1e4480 --- /dev/null +++ b/src/main/java/com/sipai/service/mqtt/impl/MqttServiceImpl.java @@ -0,0 +1,553 @@ +package com.sipai.service.mqtt.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.sipai.entity.mqtt.Mqtt; +import com.sipai.entity.mqtt.MqttProperties; +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointES; +import com.sipai.entity.scada.MPointHistory; +import com.sipai.service.Listener.ListenerPointService; +import com.sipai.service.mqtt.MqttConfigService; +import com.sipai.service.mqtt.MqttConfigTopicService; +import com.sipai.service.mqtt.MqttService; +import com.sipai.service.rabbitmq.MQService; +import com.sipai.service.scada.MPointHistoryService; +import com.sipai.service.scada.MPointService; +import com.sipai.tools.*; +import jodd.util.ClassUtil; +import org.eclipse.paho.client.mqttv3.*; +import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; +import org.redisson.api.RBatch; +import org.redisson.api.RedissonClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; + +@Service("mqttService") +public class MqttServiceImpl implements MqttService { + private final MqttProperties mqttProperties; + @Autowired + private MPointService mPointService; + @Autowired + private MqttConfigService mqttConfigService; + @Autowired + private MqttConfigTopicService mqttConfigTopicService; + @Autowired + private ListenerPointService listenerPointService; + @Autowired + private RedissonClient redissonClient; + + private static MqttClient mqttClient; + private static String ipStr = ""; + private static final Logger loggger = LoggerFactory.getLogger(ClassUtil.class); + + //娴嬮噺鐐瑰璞$紦瀛 + private final Map mPointCache = new ConcurrentHashMap<>(); + private final Set notFoundKeys = ConcurrentHashMap.newKeySet(); + + @Override + @Scheduled(fixedRate = 3600000)//姣忓皬鏃舵竻鐞嗕竴娆 + public void cleanCache() { + loggger.info("娓呯悊缂撳瓨(" + mPointCache.size() + " 鏉):" + CommUtil.nowDate()); + mPointCache.clear(); + notFoundKeys.clear(); + } + + public MqttServiceImpl(MqttProperties mqttProperties) { + this.mqttProperties = mqttProperties; + } + + private static MqttClient connect(String brokeraddress, String clientId, String userName, String password) throws MqttException { + + ipStr = brokeraddress; + + MemoryPersistence persistence = new MemoryPersistence(); + MqttConnectOptions connOpts = new MqttConnectOptions(); + connOpts.setCleanSession(true); + connOpts.setUserName(userName); + connOpts.setPassword(password.toCharArray()); + connOpts.setConnectionTimeout(10); + connOpts.setKeepAliveInterval(20); +// String[] uris = {"tcp://10.100.124.206:1883","tcp://10.100.124.207:1883"}; +// connOpts.setServerURIs(uris); //璧峰埌璐熻浇鍧囪 鍜岄珮鍙敤鐨勪綔鐢 +// MqttClient mqttClient = new MqttClient(brokeraddress, clientId, persistence); + mqttClient = new MqttClient(brokeraddress, clientId, persistence); + //mqttClient.setCallback(new PushCallback("test")); + mqttClient.connect(connOpts); + return mqttClient; + } + + @Async("getAsyncMqttHandle") + @Override + public void doHandle(String bizId, String topic, String ip4, String port, JSONArray jsonArray) { +// System.out.println("MQTT鎺ユ敹: biz=" + bizId + " topic=" + topic + " msgCount=" + jsonArray.size()); + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + // 瑙f瀽鏃堕棿鎴 + String timestamp = jsonObject.getString("timestamp"); + String[] times = timestamp.split("\\."); + String date = CommUtil.timeStamp2Date(times[0], "yyyy-MM-dd HH:mm:ss"); + + // 瑙f瀽鏁版嵁瀵硅薄 + JSONObject data = jsonObject.getJSONObject("Data"); + if (data == null || data.isEmpty()) { + loggger.warn("Data涓虹┖锛岃烦杩: @{}", date); + continue; + } + + List redisList = new ArrayList<>(); + List vueList = new ArrayList<>(); + + // 閬嶅巻鏁版嵁鏉$洰 + for (String key : data.keySet()) { + String valueStr = data.getString(key); + // 杩囨护鏃犳晥鍊 + if (!isValidValue(valueStr)) { + loggger.warn("鍊兼棤鏁堬紝璺宠繃: key={} raw={} @{}", key, valueStr, date); + continue; + } + // 鑾峰彇鐐逛綅淇℃伅 + MPoint mPoint = getMPointCacheOrES(bizId, key); + if (mPoint == null) { + boolean inNotFound = notFoundKeys.contains(key); + loggger.warn("鐐逛綅涓嶅瓨鍦紝璺宠繃: key={} notFoundCache={} @{}", key, inNotFound, date); + continue; + } + // 澶勭悊鏁板艰浆鎹€佸嶇巼璁$畻銆佸彇鍙嶆搷浣溿佹帹鎶ヨ淇℃伅銆佸彂閫並afka娑堟伅 + BigDecimal value = handleValueConversion(bizId, valueStr, key, date, vueList); + if (value == null) { + loggger.warn("鏁板艰浆鎹㈠け璐ワ紝璺宠繃: key={} raw={} @{}", key, valueStr, date); + continue; + } + // 澶勭悊ES鏁版嵁 + MPointES esPoint = buildEsPoint(mPoint, value, date); + redisList.add(esPoint); + } + // 鎺ㄩ佸墠绔暟鎹 +// loggger.info("鍑嗗鎺ㄩ佸墠绔: topic={} size={} @{}", topic, vueList.size(), date); + mqttConfigService.doSendMqttVue(vueList, topic); + + // 鎵归噺鍐欏叆Redis + saveToRedisBatch(redisList); +// loggger.info("鎵归噺鍐欏叆Redis瀹屾垚: size={} @{}", redisList.size(), date); + } + } + + /** + * 鏍¢獙鍊兼槸鍚︽湁鏁堬紙闈炵┖涓旈暱搴﹀悎娉曪級 + */ + private boolean isValidValue(String value) { + if (value == null || value.isEmpty()) { + loggger.warn("鏃犳晥鍊: 绌哄瓧绗︿覆"); + return false; + } + BigDecimal bd = new BigDecimal(value); + String plainValue = bd.toPlainString(); + String[] parts = plainValue.split("\\."); + boolean ok = parts[0].length() <= 15; + if (!ok) { + loggger.warn("鏃犳晥鍊: 鏁存暟浣嶈繃闀 len={} raw={}", parts[0].length(), value); + } + return ok; + } + + /** + * 澶勭悊鏁板艰浆鎹€佸嶇巼璁$畻銆佸彇鍙嶆搷浣溿佹帹鎶ヨ淇℃伅銆佸彂閫並afka娑堟伅 + */ + private BigDecimal handleValueConversion(String unitId, String valueStr, String key, String date, List vueList) { + try { + double valDou = Double.parseDouble(valueStr); + MPoint mPoint = getMPointCacheOrES(unitId, key); + if (mPoint == null) { + return null; + } + + // 鍊嶇巼璁$畻 + BigDecimal rate = mPoint.getRate() != null ? mPoint.getRate() : BigDecimal.ONE; + BigDecimal value = (valDou == 0 || rate.compareTo(BigDecimal.ZERO) == 0) + ? BigDecimal.ZERO + : rate.multiply(new BigDecimal(valueStr)).divide(BigDecimal.ONE, 10, RoundingMode.HALF_UP); + + // 鍙栧弽鎿嶄綔 + if ("1".equals(mPoint.getDirecttype())) { + value = "0".equals(valueStr) ? BigDecimal.ONE : ("1".equals(valueStr) ? BigDecimal.ZERO : value); + } + + // 鎺ㄩ佹姤璀︿俊鎭 + if (mPoint.getTriggeralarm() != null && !"0".equals(mPoint.getTriggeralarm().trim())) { +// loggger.info("鎺ㄩ佹姤璀: {}={} @{}", key, value, date); +// mPointService.sendKafka4MQTT_Alarm(key, value, date, 0, 1); + } + + // 鍙戦並afka娑堟伅 +// mPointService.sendKafka4MQTT(unitId,key, value, date, 0, 1, mPoint.getSignaltype()); + + // 鏋勫缓鍓嶇鏁版嵁 + buildVuePoint(mPoint, value, date, vueList); + + return value; + } catch (NumberFormatException e) { + loggger.error("鏁板艰浆鎹㈠け璐: {}", valueStr, e); + return null; + } + } + + /** + * 鏋勫缓鍓嶇灞曠ず鐢ㄧ偣浣嶅璞 + */ + private void buildVuePoint(MPoint mPoint, BigDecimal value, String date, List vueList) { + MPoint vuePoint = new MPoint(); + vuePoint.setId(mPoint.getId()); + vuePoint.setMeasuredt(date); + int numtail = doNumtail(mPoint.getNumtail()); + vuePoint.setParmvalue(value.setScale(numtail, RoundingMode.HALF_UP)); + vueList.add(vuePoint); + } + + /** + * 鏋勫缓ES瀛樺偍鐢ㄧ偣浣嶅璞 + */ + private MPointES buildEsPoint(MPoint mPoint, BigDecimal value, String date) { + MPoint esPoint = new MPoint(); + esPoint.setId(mPoint.getId()); + esPoint.setMeasuredt(date); + esPoint.setParmvalue(value); + esPoint.setNumtail(mPoint.getNumtail()); + return MPointES.format(esPoint); + } + + /** + * 鎵归噺淇濆瓨鏁版嵁鍒癛edis + */ + private void saveToRedisBatch(List esList) { + if (esList.isEmpty()) { + return; + } + + int batchSize = 200; + int total = esList.size(); + int batches = (total + batchSize - 1) / batchSize; + + try { + for (int i = 0; i < batches; i++) { + int start = i * batchSize; + int end = Math.min((i + 1) * batchSize, total); + RBatch batch = redissonClient.createBatch(); + + for (MPoint mPoint : esList.subList(start, end)) { + int num = mPoint.getId().hashCode() % 25; + String dt = mPoint.getMeasuredt().replace("T", " ").replace("Z", ""); + int numtail = doNumtail(mPoint.getNumtail()); + String val = mPoint.getParmvalue().setScale(numtail, RoundingMode.HALF_UP) + + ";" + mPoint.getParmvalue() + ";" + dt; + + batch.getMapCache(CommString.RedisMpointFlag + num) + .fastPutAsync(mPoint.getId(), val, 1, TimeUnit.DAYS); + } + batch.execute(); + } + } catch (Exception e) { + loggger.error("Redis鎵归噺淇濆瓨澶辫触", e); + } + } + + @Async("getAsyncMqttHandle") + @Override + public void doHandleHis(String bizId, String topic, String ip4, String port, JSONArray jsonArray) { + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + String timestamp = jsonObject.get("timestamp").toString();//鏃堕棿鎴 + String[] times = timestamp.split("\\."); + String date = CommUtil.timeStamp2Date(times[0], "yyyy-MM-dd HH:mm:ss"); + //鏁版嵁 + JSONObject data = jsonObject.getJSONObject("Data"); + + MPointService mPointService = (MPointService) SpringContextUtil.getBean("mPointService"); + MPointHistoryService mPointHistoryService = (MPointHistoryService) SpringContextUtil.getBean("mPointHistoryService"); + MPointHistory mPointHistory = new MPointHistory(); + + for (String str : data.keySet()) { + String key = str;//娴嬮噺鐐筰d + String value = data.get(str) + ""; + + //杩囨护鎺夐暱搴﹁秴杩15浣嶇殑鏁板 money鏃犳硶瀛 + if (value != null && !value.equals("")) { + BigDecimal bd = new BigDecimal(value); + value = bd.toPlainString(); + if (value.contains(".")) { + String[] vals = value.split("\\."); + if (vals[0].length() > 15) { + //瓒呭嚭 + continue; + } else { + //鏈秴鍑 + } + } else { + if (value.length() > 15) { + //瓒呭嚭 + continue; + } else { + //鏈秴鍑 + } + } + } else { + //涓虹┖ 杩囨护鎺 涓嶅瓨鏃ュ織 + continue; + } + + BigDecimal value_BigDecimal = null; + double valDou = 0;//鍒ゆ柇鏄惁涓0 鎴栬0.00 鎴 0.000绛 + + //灏唈son涓负""鐨勮繃婊ゆ帀 + if (value != null && !value.equals("")) { + valDou = Double.parseDouble(value);//鍒ゆ柇鏄惁涓0 鎴栬0.00 鎴 0.000绛 +// MPoint mPoint = mPointService.selectById(bizId, key); + MPoint mPoint = mPointService.selectById(bizId, key.toString()); + if (mPoint != null) { + BigDecimal numDecimal = mPoint.getRate(); + if (valDou == 0 || mPoint.getRate().equals(0)) { + value_BigDecimal = new BigDecimal(0); + } else { + value_BigDecimal = numDecimal.multiply(new BigDecimal(value)); + //鎴彇闀垮害闃叉 杩囬暱 闄1鍐嶆埅鍙10浣 + value_BigDecimal = value_BigDecimal.divide(new BigDecimal(1), 10, BigDecimal.ROUND_HALF_UP); + } + + //鍙栧弽鎿嶄綔 + if (mPoint.getDirecttype() != null && mPoint.getDirecttype().equals("1")) { + //鍙栧弽 + if (value.equals("0")) { + value_BigDecimal = new BigDecimal(1); + } else if (value.equals("1")) { + value_BigDecimal = new BigDecimal(0); + } else { + //姝e父 + } + } else { + //姝e父 + } + + try { + //DI鐐圭洿鎺ュ瓨 + if (mPoint.getSignaltype() != null && mPoint.getSignaltype().equals("DI")) { + mPointHistory.setMeasuredt(date); + mPointHistory.setParmvalue(value_BigDecimal); + mPointHistory.setTbName("[tb_mp_" + key + "]"); + mPointHistory.setUserid(ip4 + ":" + port); + mPointHistoryService.save(bizId, mPointHistory); + } + //AI鐐3鍒嗛挓瀛樹竴娆 + if (mPoint.getSignaltype() != null && mPoint.getSignaltype().equals("DI")) { + String sqlStr = "where MeasureDT>dateadd(mi,-3,'" + date + "') order by MeasureDT desc"; + /*List mPointHistoryList = mPointHistoryService.selectTopNumListByTableAWhere(mPoint.getBizid(),"[tb_mp_" + key + "]", sqlStr, "1"); + if (mPointHistoryList != null && mPointHistoryList.size() > 0) { + //3鍒嗛挓鍐呭瓨鍦 鍒欎笉瀛 + } else { + mPointHistory.setMeasuredt(date); + mPointHistory.setParmvalue(value_BigDecimal); + mPointHistory.setTbName("[tb_mp_" + key + "]"); + mPointHistory.setUserid(ip4 + ":" + port); + mPointHistoryService.save(bizId, mPointHistory); + }*/ + } + } catch (Exception e) { + System.out.println("鏂板瀛愯〃--鎵ц缁撴灉锛" + e); + } + } + } + } + } + } + + /** + * 鍙戦 rabbitmq + * + * @param key + * @param value_BigDecimal + * @param date + */ + @Override + public void sentRabbitmq(String exchange, String key, String value_BigDecimal, String date) { + JSONObject jsonObject1 = new JSONObject(); + jsonObject1.put("id", key); + jsonObject1.put("value", value_BigDecimal); + jsonObject1.put("time", date); + MQService mqService = (MQService) SpringContextUtil.getBean("mQService"); + mqService.sendMQ(exchange, jsonObject1.toString()); + } + + /** + * 鎸囦护涓嬪彂 + * + * @param json + * @param topic + * @param userId + * @param bizId + * @return + */ + @Override + public int doPublish(JSONObject json, String topic, String userId, String bizId) { + try { + MqttMessage message = new MqttMessage(json.toString().getBytes()); + message.setQos(2); + message.setRetained(false); + + //鏌ヨ涓婚灞炰簬鍝釜浠g悊 + String topic_up = ""; + if (topic != null && !topic.equals("")) { + topic_up = topic.replace("_DOWN", "_UP"); + } + String host = mqttConfigService.getEmqxHost4TCP(topic_up); + + System.out.println("鎸囦护涓嬪彂锛" + host); + + //杩炴帴 + mqttClient = connect(host, "gy_publish_8080", mqttProperties.getUsername(), mqttProperties.getPassword()); + //鍙戝竷 + mqttClient.publish(topic, message); + //鏂紑杩炴帴 + mqttClient.disconnect(); + } catch (MqttPersistenceException e) { + e.printStackTrace(); + } catch (MqttException e) { + e.printStackTrace(); + } + return 0; + } + + /** + * 鍙洖缃戝叧鍏ㄩ儴鏁版嵁 + * + * @param bizId + * @param jsonObject + */ + @Override + public void doRecall(String bizId, JSONObject jsonObject) { + try { + MqttMessage message = new MqttMessage(jsonObject.toString().getBytes()); + message.setQos(2); + message.setRetained(false); + + //鏌ヨ涓婚灞炰簬鍝釜浠g悊 + String topic_up = bizId + "_01_UP"; + + String host = mqttConfigService.getEmqxHost4TCP(topic_up); + + System.out.println(CommUtil.nowDate() + "鏁版嵁鍙洖-鎵цRecall锛" + bizId + "_01_RECALL" + "------" + host); + + //杩炴帴 + mqttClient = connect(host, "gy_recall_8080", mqttProperties.getUsername(), mqttProperties.getPassword()); + //鍙戝竷涓婚 + mqttClient.publish(bizId + "_01_RECALL", message); + //鏂紑杩炴帴 + mqttClient.disconnect(); + } catch (MqttException e) { + e.printStackTrace(); + } + } + + /** + * 灏嗗鐞嗗悗鐨刴qtt娑堟伅浼犲埌vue鍓嶇 + */ + @Async + public void doSendMqttVue(List list, String topic) { + JSONArray jsonVue = (JSONArray) JSONArray.toJSON(list); + MqttMessage message = new MqttMessage(jsonVue.toString().getBytes()); + message.setQos(0); + message.setRetained(false); + try { + if (mqttClient == null) { + System.out.println("鎺夌嚎_sendMqttVue"); + mqttClient = connect(mqttProperties.getBrokerAddress(), "gy_sendMqttVue" + CommUtil.getUUID(), mqttProperties.getUsername(), mqttProperties.getPassword()); + } else { +// System.out.println("姝e父_sendMqttVue"); + } + String topic_vue = topic; + if (topic != null && topic.contains("_IM")) { + topic_vue = topic.replace("_IM", ""); + } + topic_vue = topic_vue + "_VUE"; + mqttClient.publish(topic_vue, message); + } catch (MqttException e) { + e.printStackTrace(); + } + } + + /** + * 杩斿洖绮惧害 + * + * @param num + * @return + */ + public int doNumtail(String num) { + int numtail = 0; + if (num != null && !num.trim().equals("")) { + //0.00杩欑鍚庨潰涓嶇敤 鏆傛椂鍐欐 浠ュ悗鏍囧噯鍏ㄩ儴鐢ㄦ暟瀛 + if (num.contains(".")) { + if (num.equals("0.0")) { + numtail = 1; + } + if (num.equals("0.00")) { + numtail = 2; + } + if (num.equals("0.000")) { + numtail = 3; + } + if (num.equals("0.0000")) { + numtail = 4; + } + } else { + numtail = Integer.parseInt(num); + } + } else { + numtail = 0; + } + return numtail; + } + + /** + * 浼樺厛浠庣紦瀛樻煡璇Point瀵硅薄锛屼笉瀛樺湪鍒欏幓es涓煡璇 + * + * @param key + * @return + */ + private MPoint getMPointCacheOrES(String unitId, String key) { + // 鏌ヨ缂撳瓨鏄惁瀛樺湪 + if (mPointCache.containsKey(key)) { + MPoint mp = mPointCache.get(key); +// loggger.debug("缂撳瓨鍛戒腑: key={} id={}", key, mp.getId()); + return mp; + } + // 鐐逛綅涓嶅瓨鍦 锛堟柊鍔犵殑鐐逛綅闇瑕佸畾鏃舵竻鐞嗙紦瀛樼殑鏃跺欐墠浼氳繘鍏ョ紦瀛橈紝涓嶇劧棰戠箒鍘绘煡璇s锛 + if (notFoundKeys.contains(key)) { +// loggger.debug("宸叉爣璁版湭鎵惧埌锛岃烦杩嘐S鏌ヨ: key={}", key); + return null; + } + // 浠嶦S鏌ヨ + MPoint mPoint = mPointService.selectById(unitId, key); + if (mPoint != null) { + //娣诲姞缂撳瓨 + mPointCache.put(key, mPoint); +// loggger.debug("ES鏌ヨ鎴愬姛骞剁紦瀛: key={} id={}", key, mPoint.getId()); + } else { + //娌℃湁璇ョ偣浣 + notFoundKeys.add(key); +// loggger.warn("ES鏈壘鍒扮偣浣嶏紝鍔犲叆鏈壘鍒伴泦鍚: key={}", key); + } + return mPoint; + } + +} diff --git a/src/main/java/com/sipai/service/opc/InitOpcUaService.java b/src/main/java/com/sipai/service/opc/InitOpcUaService.java new file mode 100644 index 0000000..9d24bf7 --- /dev/null +++ b/src/main/java/com/sipai/service/opc/InitOpcUaService.java @@ -0,0 +1,134 @@ +package com.sipai.service.opc; + +import com.sipai.entity.scada.MPoint; +import com.sipai.service.opc.OpcUaService; +import com.sipai.service.scada.MPointService; +import com.sipai.tools.CommString; +import com.sipai.tools.CommUtil; +import org.elasticsearch.index.query.BoolQueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.search.sort.SortBuilders; +import org.redisson.api.RBatch; +import org.redisson.api.RedissonClient; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; + +/** + * 鍒濆鍖栬闃呮暟鎹 + */ +@Service +public class InitOpcUaService { + @Autowired(required = false) + private OpcUaService opcUaService; + @Autowired + private MPointService mPointService; + + // 鏈湴缂撳瓨 + private final Cache mPointCache = Caffeine.newBuilder() + .maximumSize(10000) // 浠呰缃渶澶х紦瀛樻暟閲 +// .expireAfterWrite(1, TimeUnit.HOURS) // 1灏忔椂鍚庤繃鏈 + .build(); + + // 宸茶闃呯殑鐐逛綅闆嗗悎 + private Set subscribedNodeIds = new HashSet<>(); + + @PostConstruct + public void init() { + if (opcUaService == null) { + System.out.println("OPC UA 鏈惎鍔紝璇锋鏌ml閰嶇疆鏂囦欢閽燂細opc: enabled: true"); + return; + } + try { + //鏌ヨ鎵鏈夌殑opcua閲囬泦鐐逛綅 + List nodeIdList = fetchNodeIdsFromEs(); + for (String nodeId : nodeIdList) { + MPoint mPoint = mPointCache.get(nodeId, key -> mPointService.selectById("",nodeId)); + System.out.println(mPoint); + Consumer callback = value -> { + if (mPoint != null) { + mPointService.sendKafka4OpcUa(mPoint.getId(), value, CommUtil.nowDate()); + } + }; + opcUaService.subscribeToNode(nodeId, callback); + subscribedNodeIds.add(nodeId); // 璁板綍宸茶闃呯殑鐐逛綅 + } + System.out.println("Subscribed to " + nodeIdList.size() + " nodes"); + } catch (Exception e) { + System.err.println("Failed to subscribe: " + e.getMessage()); + } + } + + /** + * 鍚屾涓娆pcua璁㈤槄鐐逛綅 + */ + public void manualSyncSubscriptions() { + try { + List currentNodeIds = fetchNodeIdsFromEs(); // 鑾峰彇褰撳墠 Elasticsearch 涓殑鐐逛綅淇℃伅 + Set newSubscribedNodeIds = new HashSet<>(); + + // 澶勭悊鏂板鐐逛綅 + for (String nodeId : currentNodeIds) { + if (!subscribedNodeIds.contains(nodeId)) { // 鏂板鐐逛綅 + MPoint mPoint = mPointCache.get(nodeId, key -> mPointService.selectById("",nodeId)); + System.out.println(mPoint); + Consumer callback = value -> { + if (mPoint != null) { + mPointService.sendKafka4OpcUa(mPoint.getId(), value, CommUtil.nowDate()); + } + }; + opcUaService.subscribeToNode(nodeId, callback); + newSubscribedNodeIds.add(nodeId); + } else { + newSubscribedNodeIds.add(nodeId); // 淇濈暀宸茶闃呯殑鐐逛綅 + } + } + + // 澶勭悊鍒犻櫎鐐逛綅 + for (String nodeId : subscribedNodeIds) { + if (!currentNodeIds.contains(nodeId)) { // 鍒犻櫎鐐逛綅 + opcUaService.unsubscribeFromNode(nodeId); + } + } + + // 鏇存柊宸茶闃呯偣浣嶉泦鍚 + subscribedNodeIds = newSubscribedNodeIds; + + System.out.println("杩涜涓娆pcua璁㈤槄鍚屾"); + } catch (Exception e) { + System.err.println("opcua璁㈤槄鍚屾澶辫触: " + e.getMessage()); + } + } + + /** + * 鏌ヨ鎵鏈夌殑opcua閲囬泦鐐逛綅 + * + * @return + */ + private List fetchNodeIdsFromEs() { + NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder(); + BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); + BoolQueryBuilder childBoolQueryBuilder = QueryBuilders.boolQuery(); + childBoolQueryBuilder.must(QueryBuilders.matchPhraseQuery("biztype", "opcua")); + boolQueryBuilder.should(childBoolQueryBuilder); + nativeSearchQueryBuilder.withQuery(boolQueryBuilder); + nativeSearchQueryBuilder.withPageable(PageRequest.of(0, 10000)); + List list_mps = this.mPointService.selectListByWhere4Es(nativeSearchQueryBuilder); + List nodeIdList = new ArrayList<>(); + for (MPoint mPoint : list_mps) { + nodeIdList.add(mPoint.getMpointid()); + } + return nodeIdList; + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/service/opc/OpcUaService.java b/src/main/java/com/sipai/service/opc/OpcUaService.java new file mode 100644 index 0000000..457b2f6 --- /dev/null +++ b/src/main/java/com/sipai/service/opc/OpcUaService.java @@ -0,0 +1,277 @@ +package com.sipai.service.opc; + +import com.sipai.config.OpcUaProperties; +import org.eclipse.milo.opcua.sdk.client.OpcUaClient; +import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription; +import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem; +import org.eclipse.milo.opcua.sdk.client.nodes.UaVariableNode; +import org.eclipse.milo.opcua.stack.core.AttributeId; +import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned; +import org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode; +import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn; +import org.eclipse.milo.opcua.stack.core.types.structured.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue; +import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId; +import org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode; +import org.eclipse.milo.opcua.stack.core.types.builtin.Variant; + +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + + +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +@Service +public class OpcUaService { + + @Autowired(required = false) + private final OpcUaClient opcUaClient; + private final OpcUaProperties opcUaProperties; + + @Autowired + public OpcUaService(@Autowired(required = false) OpcUaClient opcUaClient, OpcUaProperties opcUaProperties) { + this.opcUaClient = opcUaClient; + this.opcUaProperties = opcUaProperties; + } + + /*public void printConfig() { + System.out.println("OPC UA Server URL: " + opcUaProperties.getServerUrl()); + System.out.println("Security Policy: " + opcUaProperties.getSecurityPolicy()); + System.out.println("Security Mode: " + opcUaProperties.getSecurityMode()); + }*/ + + /** + * 璇诲彇鍗曚釜鐐逛綅鐨勫 + * + * @param nodeId + * @return + * @throws ExecutionException + * @throws InterruptedException + */ + public Object readNodeValue(String nodeId) throws ExecutionException, InterruptedException { + if (opcUaClient == null) { + throw new IllegalStateException("OPC UA 鏈惎鍔紝璇锋鏌ml閰嶇疆鏂囦欢閽燂細opc: enabled: true"); + } + NodeId node = NodeId.parse(nodeId); + DataValue dataValue = opcUaClient.readValue(0, TimestampsToReturn.Both, node).get(); + Variant variant = dataValue.getValue(); + return variant.getValue(); + } + + /** + * 鍐欏叆鍗曚釜鐐逛綅鐨勫 + * + * @param nodeId 鑺傜偣ID + * @param value 瑕佸啓鍏ョ殑鍊 + * @return 鍐欏叆鏄惁鎴愬姛 + * @throws ExecutionException + * @throws InterruptedException + */ + public boolean writeNodeValue(String nodeId, Object value) { + try { + NodeId node = NodeId.parse(nodeId); + + // 璇诲彇鑺傜偣鐨勬暟鎹被鍨嬶紙浣跨敤 UaVariableNode 鏇夸唬 VariableNode锛 + UaVariableNode variableNode = (UaVariableNode) opcUaClient.getAddressSpace().getVariableNode(node); + if (variableNode == null) { + throw new RuntimeException("鏃犳硶鎵惧埌鑺傜偣: " + nodeId); + } + + NodeId dataTypeId = variableNode.getDataType(); + System.out.println(dataTypeId); + + if (dataTypeId == null) { + throw new RuntimeException("鏃犳硶鑾峰彇鑺傜偣鐨勬暟鎹被鍨"); + } + + // 鏍规嵁鏁版嵁绫诲瀷鍒涘缓瀵瑰簲鐨 Variant + Variant variant = createVariantForDataType(value, dataTypeId); + + DataValue dataValue = DataValue.valueOnly(variant); + StatusCode statusCode = opcUaClient.writeValue(node, dataValue).get(); + System.out.println(statusCode); + return statusCode.isGood(); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * typeId璺熸爣鍑嗚鑼冧笉涓鑷达紝鐩墠鐢 KEPServerEX6鑷甫鐨凮PCUA鏈嶅姟 娴嬭瘯鐨勭粨鏋 + * + * @param value + * @param dataTypeId + * @return + */ + private Variant createVariantForDataType(Object value, NodeId dataTypeId) { + int typeId = ((Number) dataTypeId.getIdentifier()).intValue(); + // 鏍囧噯绫诲瀷澶勭悊 + switch (typeId) { + case 1: + return new Variant(convertToBoolean(value)); + case 4: // Int16 (鏈夌鍙穝hort) + short shortValue = (value instanceof Number) ? + ((Number) value).shortValue() : + Short.parseShort(value.toString()); + return new Variant(shortValue); + case 5: // UInt16/Word (鏃犵鍙穝hort) + int intValue = (value instanceof Number) ? + ((Number) value).intValue() : + Integer.parseInt(value.toString()); + if (intValue < 0 || intValue > 65535) { + throw new IllegalArgumentException("UInt16 鍊煎繀椤诲湪 0~65535 涔嬮棿"); + } + return new Variant(Unsigned.ushort(intValue)); + case 6: // Int32 + return new Variant(convertToInt(value)); + case 10: //Float + return new Variant(convertToFloat(value)); + case 11: // Double + return new Variant(convertToDouble(value)); + default: + return new Variant(value.toString()); + } + } + + // 绫诲瀷杞崲杈呭姪鏂规硶锛堜繚鎸佷笉鍙橈級 + private boolean convertToBoolean(Object value) { + if (value instanceof Boolean) return (Boolean) value; + String strVal = value.toString().trim().toLowerCase(); + return strVal.equals("true") || strVal.equals("1"); + } + + private float convertToFloat(Object value) { + if (value instanceof Number) return ((Number) value).floatValue(); + return Float.parseFloat(value.toString()); + } + + private double convertToDouble(Object value) { + if (value instanceof Number) return ((Number) value).doubleValue(); + return Double.parseDouble(value.toString()); + } + + private int convertToInt(Object value) { + if (value instanceof Number) return ((Number) value).intValue(); + return Integer.parseInt(value.toString()); + } + + private long convertToUInt(Object value) { + if (value instanceof Number) return ((Number) value).longValue(); + return Long.parseLong(value.toString()); + } + + // 璁㈤槄鐐逛綅 + public void subscribeToNode(String nodeId, Consumer callback) throws Exception { + if (opcUaClient == null) { + throw new IllegalStateException("OPC UA 鏈惎鍔紝璇锋鏌ml閰嶇疆鏂囦欢閽燂細opc: enabled: true"); + } + try { + NodeId node = NodeId.parse(nodeId); + + UaSubscription subscription = opcUaClient + .getSubscriptionManager() + .createSubscription(1000.0) + .get(); + + MonitoringParameters parameters = new MonitoringParameters( + Unsigned.uint(1), + 1000.0, + null, + Unsigned.uint(10), + true + ); + + MonitoredItemCreateRequest request = new MonitoredItemCreateRequest( + new ReadValueId( + node, + AttributeId.Value.uid(), + null, + null + ), + MonitoringMode.Reporting, + parameters + ); + + subscription.createMonitoredItems( + TimestampsToReturn.Both, + Collections.singletonList(request), + new UaSubscription.ItemCreationCallback() { + @Override + public void onItemCreated(UaMonitoredItem item, int i) { + // 璁剧疆鍊肩殑鍥炶皟澶勭悊鍣 + item.setValueConsumer(value -> { + Variant variant = value.getValue(); + Object rawValue = variant.getValue(); + + if (rawValue instanceof Number) { + callback.accept(((Number) rawValue).doubleValue()); // 杞负 Double + } else if (rawValue instanceof Boolean) { + callback.accept(((Boolean) rawValue) ? 1.0 : 0.0); // 甯冨皵杞0 1 + } else { + throw new ClassCastException("Expected Number or Boolean but received: " + + rawValue.getClass().getSimpleName()); + } + }); + } + } + ).get(); + + } catch (Exception e) { + throw new Exception("璁㈤槄澶辫触: " + e.getMessage(), e); + } + } + + // 鍙栨秷璁㈤槄鐐逛綅 + public boolean unsubscribeFromNode(String nodeId) { + if (opcUaClient == null) { + throw new IllegalStateException("OPC UA 鏈惎鍔紝璇锋鏌ml閰嶇疆鏂囦欢閽燂細opc: enabled: true"); + } + try { + NodeId node = NodeId.parse(nodeId); + + // 鑾峰彇鎵鏈夎闃 + List subscriptions = opcUaClient.getSubscriptionManager().getSubscriptions(); + + for (UaSubscription subscription : subscriptions) { + // 鑾峰彇鎵鏈夌洃鎺ч」 + List monitoredItems = subscription.getMonitoredItems(); + + for (UaMonitoredItem monitoredItem : monitoredItems) { + if (monitoredItem.getReadValueId().getNodeId().equals(node)) { + // 鍒犻櫎鐩戞帶椤 + CompletableFuture> deleteFuture = subscription.deleteMonitoredItems( + Collections.singletonList(monitoredItem) + ); + + // 绛夊緟鍒犻櫎鎿嶄綔瀹屾垚 + List statusCodes = deleteFuture.get(5, TimeUnit.SECONDS); + + // 妫鏌ュ垹闄ょ粨鏋 + for (StatusCode statusCode : statusCodes) { + if (!statusCode.isGood()) { + System.err.println("鍒犻櫎鐩戞帶椤瑰け璐: " + statusCode); + return false; + } + } + + System.out.println("鎴愬姛鍙栨秷璁㈤槄鑺傜偣: " + nodeId); + return true; + } + } + } + + System.out.println("鏈壘鍒拌妭鐐: " + nodeId); + return false; + } catch (Exception e) { + System.err.println("鍙栨秷璁㈤槄澶辫触: " + e.getMessage()); + return false; + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/service/rabbitmq/MQService.java b/src/main/java/com/sipai/service/rabbitmq/MQService.java new file mode 100644 index 0000000..650f742 --- /dev/null +++ b/src/main/java/com/sipai/service/rabbitmq/MQService.java @@ -0,0 +1,5 @@ +package com.sipai.service.rabbitmq; + +public interface MQService { + void sendMQ(String exchange, String msg); +} diff --git a/src/main/java/com/sipai/service/rabbitmq/impl/MQServiceImpl.java b/src/main/java/com/sipai/service/rabbitmq/impl/MQServiceImpl.java new file mode 100644 index 0000000..22327f4 --- /dev/null +++ b/src/main/java/com/sipai/service/rabbitmq/impl/MQServiceImpl.java @@ -0,0 +1,23 @@ +package com.sipai.service.rabbitmq.impl; + +import com.sipai.service.rabbitmq.MQService; +import com.sipai.tools.ConstantString; +import org.springframework.amqp.core.AmqpTemplate; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; + +@Service("mQService") +public class MQServiceImpl implements MQService { + @Resource + @Lazy + private AmqpTemplate amqpTemplate; + + @Override + public void sendMQ(String exchange,String msg) { +// String exchange = ConstantString.MQ_ALARM_MQTT; + String key = ConstantString.KEY_ALARM_MSG; + this.amqpTemplate.convertAndSend(exchange,key,msg); + } +} diff --git a/src/main/java/com/sipai/service/scada/MPointBzwService.java b/src/main/java/com/sipai/service/scada/MPointBzwService.java new file mode 100644 index 0000000..ad26385 --- /dev/null +++ b/src/main/java/com/sipai/service/scada/MPointBzwService.java @@ -0,0 +1,21 @@ +package com.sipai.service.scada; + +import com.sipai.entity.scada.MPointBzw; + +import java.util.List; + +public interface MPointBzwService { + + public abstract MPointBzw selectByPrimaryKey(String id); + + public abstract Integer deleteByPrimaryKey(String id); + + public abstract Integer insert(MPointBzw entity); + + public abstract Integer updateByPrimaryKeySelective(MPointBzw entity); + + public abstract List selectListByWhere(String wherestr); + + public abstract Integer deleteByWhere(String wherestr); + +} diff --git a/src/main/java/com/sipai/service/scada/MPointHistoryService.java b/src/main/java/com/sipai/service/scada/MPointHistoryService.java new file mode 100644 index 0000000..8cf94c1 --- /dev/null +++ b/src/main/java/com/sipai/service/scada/MPointHistoryService.java @@ -0,0 +1,17 @@ +package com.sipai.service.scada; + +import com.sipai.entity.scada.MPointHistory; + +import java.util.List; + +public interface MPointHistoryService { + int save(String bizId, MPointHistory mPointHistory); + + List selectListByTableAWhere(String bizId, String table, String wherestr); + + int deleteByTableAWhere(String bizId,String table ,String wherestr); + + int saveByCreate(String bizId, MPointHistory mPointHistory); + + List selectIndustrialLibrary(String bizId, String IP,String MPointID, String intv, String sdt, String edt); +} diff --git a/src/main/java/com/sipai/service/scada/MPointService.java b/src/main/java/com/sipai/service/scada/MPointService.java new file mode 100644 index 0000000..14c2341 --- /dev/null +++ b/src/main/java/com/sipai/service/scada/MPointService.java @@ -0,0 +1,87 @@ +package com.sipai.service.scada; + +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointES; +import com.sipai.entity.scada.MPointHistory; +import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; + +import java.util.List; +import java.util.Map; + +/** + *

+ * 鏈嶅姟绫 + *

+ * + * @author YYJ + * @since 2021-06-25 + */ +public interface MPointService { + MPoint selectById(String unitId,String id); + + MPoint selectById4Es(String id); + + List selectListByWhere(String wherestr); + + List selectListByES(Map map, Integer page, Integer rows); + + public abstract List selectListByWhere4Es(NativeSearchQueryBuilder nativeSearchQueryBuilder); + +// void publish(String msg); +// +// void receive(); + +// String testSchedulePublish(String bizId, String equipmentId); + + // int update(String bizId, MPoint entity); + int update(MPoint entity); + + int updateValueByKey(String bizId, MPoint entity); + + /** + * 鏍规嵁name鑾峰彇涓婚涓嬪搴旂殑key value + * sj 2021-08-08 + * + * @param topicName + * @return + */ +// String getData4Topic(String topicName); + +// String getData4Bim(String topicName); + + /** + * 鎺ㄩ佹暟鎹嚦kafka + * sj 2021-08-08 + * + * @param id + * @param uuid + * @return + */ +// String sentData4Kafka(String id, String uuid); + +// void publish4TopicName(String msg, String topicName); + + /** + * 鏈哄櫒浜鸿皟鐢ㄥ伐涓氬簱鏁版嵁 + * 鏈哄櫒浜轰紶浠栦滑鑷繁鐨刬d鍦╡xcel涓壘鍒板搴旂殑mpid + * + * @param + * @return + */ +// String getIndustrialLibrary4Id(String id); + +// public abstract int saveInfluxdb(String bizId, MPointHistory entity); + public abstract void saveAsync(List mPointES); + + //鎺ㄩ佹暟鎹埌kafka +// public void sendKafka4OpcUa(String nodeId, Double value); + public void sendKafka4OpcUa(String nodeId, Double value, String time); + + public void sendKafka4UDP(String unitId,String mpcode, Object value, String timePoint, int i, int length); + + public void sendKafka4MQTT(String unitId,String mpcode, Object value, String timePoint, int i, int length,String signaltype); + + public void sendKafka4MQTT_Alarm(String mpcode, Object value, String timePoint, int i, int length); + + public void saveRedis(String mpcode, Object value, String time); +} diff --git a/src/main/java/com/sipai/service/scada/impl/MPointBzwServiceImpl.java b/src/main/java/com/sipai/service/scada/impl/MPointBzwServiceImpl.java new file mode 100644 index 0000000..a3727a7 --- /dev/null +++ b/src/main/java/com/sipai/service/scada/impl/MPointBzwServiceImpl.java @@ -0,0 +1,63 @@ +package com.sipai.service.scada.impl; + +import com.sipai.dao.scada.MPointBzwDao; +import com.sipai.entity.scada.MPointBzw; +import com.sipai.service.scada.MPointBzwService; +import com.sipai.tools.DataSourceTypeAnno; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: 浣犵殑鍚嶅瓧 + * @Date: 2021/04/25/21:37 + * @Description: + */ +@Service("mPointBzwService") +public class MPointBzwServiceImpl implements MPointBzwService { + @Autowired + private MPointBzwDao mPointBzwDao; + + @Override + @DataSourceTypeAnno() + public MPointBzw selectByPrimaryKey(String id) { + return mPointBzwDao.selectByPrimaryKey(id); + } + + @Override + @DataSourceTypeAnno() + public Integer deleteByPrimaryKey(String id) { + return mPointBzwDao.deleteByPrimaryKey(id); + } + + @Override + @DataSourceTypeAnno() + public Integer insert(MPointBzw entity) { + return mPointBzwDao.insert(entity); + } + + @Async + @Override + @DataSourceTypeAnno() + public Integer updateByPrimaryKeySelective(MPointBzw entity) { + return mPointBzwDao.updateByPrimaryKeySelective(entity); + } + + @Override + @DataSourceTypeAnno() + public List selectListByWhere(String wherestr) { + MPointBzw mPoint = new MPointBzw(); + mPoint.setWhere(wherestr); + return mPointBzwDao.selectListByWhere(mPoint); + } + + @Override + @DataSourceTypeAnno() + public Integer deleteByWhere(String wherestr) { + return mPointBzwDao.deleteByWhere(wherestr); + } + +} diff --git a/src/main/java/com/sipai/service/scada/impl/MPointHistoryServiceImpl.java b/src/main/java/com/sipai/service/scada/impl/MPointHistoryServiceImpl.java new file mode 100644 index 0000000..5776c1e --- /dev/null +++ b/src/main/java/com/sipai/service/scada/impl/MPointHistoryServiceImpl.java @@ -0,0 +1,79 @@ +package com.sipai.service.scada.impl; + +import com.sipai.dao.scada.MPointHistoryDao; +import com.sipai.entity.scada.MPointHistory; +import com.sipai.service.scada.MPointHistoryService; +import com.sipai.tools.CommUtil; +import com.sipai.tools.DataSourceContextHolder; +import com.sipai.tools.DataSourceTypeAnno; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Slf4j(topic = "MPointHistoryServiceImpl") +@Service +public class MPointHistoryServiceImpl implements MPointHistoryService { + + @Autowired + MPointHistoryDao mPointHistoryDao; + + @DataSourceTypeAnno() + @Override + public int save(String bizId, MPointHistory mPointHistory) { + try { + int res = mPointHistoryDao.insert(mPointHistory); + return res; + } catch (Exception e) { + System.out.println(e); + throw new RuntimeException(); + } + } + + @DataSourceTypeAnno() + @Override + public List selectListByTableAWhere(String bizId, String table, String wherestr) { + return mPointHistoryDao.selectListByTableAWhere(table ,wherestr); + } + + @DataSourceTypeAnno() + @Override + public int deleteByTableAWhere(String bizId,String table ,String wherestr) { + return mPointHistoryDao.deleteByTableAWhere(table ,wherestr); + } + + @DataSourceTypeAnno() + @Override + public int saveByCreate(String bizId, MPointHistory mPointHistory) { + mPointHistory.setTbName(CommUtil.getMPointTableName(mPointHistory.getTbName())); + if(CommUtil.isBlank(bizId)){ + return 0; + } + try { + int i = this.mPointHistoryDao.checkTableExist(mPointHistory.getTbName()); + if(i == 0) { + log.info(String.format("[閲嶈]鍒涘缓浜嗚〃锛%s %s",mPointHistory.getTbName(), DataSourceContextHolder.getDataSourceType())); + mPointHistoryDao.createTable(mPointHistory.getTbName()); + } + + // 娣诲姞鏃堕棿鍒ゆ柇 todo 灏嗘潵浼樺寲 + mPointHistory.setWhere(" where MeasureDT = '" + mPointHistory.getMeasuredt() + "'"); + Integer count = this.mPointHistoryDao.selectCount(mPointHistory); + + int result = count == 0 ? mPointHistoryDao.insert(mPointHistory) : mPointHistoryDao.updateByMeasureDt(mPointHistory); + return result; + } catch (Exception e) { + System.out.println(DataSourceContextHolder.getDataSourceType() + " | " + e); + // 杩斿洖榛樿鍊 + return 0; + } + } + + @DataSourceTypeAnno() + @Override + public List selectIndustrialLibrary(String bizId, String IP, String MPointID, String intv, String sdt, String edt) { + return mPointHistoryDao.selectIndustrialLibrary(IP, MPointID, intv, sdt, edt); + } + +} diff --git a/src/main/java/com/sipai/service/scada/impl/MPointServiceImpl.java b/src/main/java/com/sipai/service/scada/impl/MPointServiceImpl.java new file mode 100644 index 0000000..05da6e9 --- /dev/null +++ b/src/main/java/com/sipai/service/scada/impl/MPointServiceImpl.java @@ -0,0 +1,498 @@ +package com.sipai.service.scada.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.sipai.dao.scada.MPointDao; +import com.sipai.dao.scada.MPointRepo; +import com.sipai.entity.scada.MPoint; +import com.sipai.entity.scada.MPointES; +import com.sipai.entity.scada.MPointHistory; +import com.sipai.service.mqtt.MqttConfigService; +import com.sipai.service.scada.MPointHistoryService; +import com.sipai.service.scada.MPointService; +import com.sipai.tools.CommString; +import com.sipai.tools.CommUtil; +import com.sipai.tools.DataSourceTypeAnno; +import lombok.extern.slf4j.Slf4j; +import org.elasticsearch.index.query.BoolQueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.redisson.api.RBatch; +import org.redisson.api.RMap; +import org.redisson.api.RTopic; +import org.redisson.api.RedissonClient; +import org.redisson.api.listener.MessageListener; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; +import org.springframework.data.elasticsearch.core.query.SearchQuery; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.support.SendResult; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import org.springframework.util.concurrent.ListenableFuture; +import org.springframework.util.concurrent.ListenableFutureCallback; + +import javax.annotation.Resource; +import java.io.File; +import java.io.IOException; +import java.math.BigDecimal; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.TimeUnit; + +/** + *

+ * 鏈嶅姟瀹炵幇绫 + *

+ * + * @author YYJ + * @since 2021-06-25 + */ +//@Slf4j(topic = "MPointServiceImpl") +@Service("mPointService") +@Slf4j +public class MPointServiceImpl implements MPointService { + @Resource + private MPointDao mPointDao; + @Autowired + private RedissonClient redissonClient; + @Autowired + private KafkaTemplate kafkaTemplate; + // @Autowired +// private InfluxDBConfig influxDBConfig; + @Autowired + private MPointRepo mPointRepo; + @Autowired + private MPointHistoryService mPointHistoryService; + @Autowired + private MPointService mPointService; + @Autowired + private MqttConfigService mqttConfigService; + +// @Value("${file.path}") +// private String path; + + /*@DataSourceTypeAnno() + public MPoint selectById(String unitId, String id) { + return mPointDao.selectByPrimaryKey(id); + }*/ + + @DataSourceTypeAnno() + public MPoint selectById(String unitId, String id) { + return mPointDao.selectByPrimaryKey(id); + } + + /** + * es鏌ヨ + * + * @param id + * @return + */ + @Override + public MPoint selectById4Es(String id) { + if (id == null || id.isEmpty()) { + return null; + } + /*try { + Optional m = mPointRepo.findById(id); + if (!m.isPresent()) { + log.error(id + "鏈壘鍒扮偣浣"); + return null; + } + MPoint mPoint = m.get(); + return mPoint; + } catch (Exception e) { + log.error(id + "鏈壘鍒扮偣浣"); + e.printStackTrace(); + return null; + }*/ + + NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder(); + SearchQuery searchQuery = nativeSearchQueryBuilder.withQuery(QueryBuilders.idsQuery().addIds(id)).build(); + List mPoints = mPointRepo.search(searchQuery).getContent(); + if (mPoints != null && mPoints.size() > 0) { + return mPoints.get(0); + } else { + return null; + } + + } + + // @DataSourceTypeAnno() + @Override + public List selectListByWhere(String wherestr) { + MPoint mpoint = new MPoint(); + mpoint.setWhere(wherestr); + List mPoints = mPointDao.selectListByWhere(mpoint); + for (MPoint mPoint : mPoints) { + if (mPoint.getNumtail() != null) { + BigDecimal value = CommUtil.formatMPointValue(mPoint.getParmvalue(), mPoint.getNumtail(), mPoint.getRate()); + if (value != null) { + try { + mPoint.setParmvalue(value); + } catch (Exception e) { +// log.info(e.toString()); + System.out.println(e.toString()); + } + } + } + } + return mPoints; + } + + @Override + public List selectListByES(Map map, Integer page, Integer rows) { + List mpoints = new ArrayList<>(); + try { + NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder(); + BoolQueryBuilder childBoolQueryBuilder = QueryBuilders.boolQuery(); + //TODO 鎴栦笌闈 + for (Map.Entry entry : map.entrySet()) { + if (entry.getKey() != null && !entry.getKey().isEmpty() && entry.getValue() != null) { + childBoolQueryBuilder.must(QueryBuilders.matchQuery(entry.getKey(), entry.getValue())); + } + } +// boolQueryBuilder.should(childBoolQueryBuilder); + nativeSearchQueryBuilder.withQuery(childBoolQueryBuilder); + if (page != null && rows != null && page > 0 && rows > 0) { + nativeSearchQueryBuilder.withPageable(PageRequest.of(page - 1, rows)); + } + SearchQuery searchQuery = nativeSearchQueryBuilder.build(); + Page mPage = mPointRepo.search(searchQuery); + for (MPoint mPoint : mPage) { + if (mPoint.getNumtail() != null) { + BigDecimal value = CommUtil.formatMPointValue(mPoint.getParmvalue(), mPoint.getNumtail(), mPoint.getRate()); + if (value != null) { + try { + mPoint.setParmvalue(value); + } catch (Exception e) { + log.error(e.toString()); + } + } + } + } + mpoints = mPage.getContent(); + nativeSearchQueryBuilder = null; +// boolQueryBuilder = null; + childBoolQueryBuilder = null; + searchQuery = null; + mPage = null; + } catch (Exception e) { + e.printStackTrace(); + } + return mpoints; + } + + // @DataSourceTypeAnno() + @Override + public int update(MPoint entity) { + try { + int res = mPointDao.updateByPrimaryKeySelective(entity); + return res; + } catch (Exception e) { + System.out.println(e); + throw new RuntimeException(); + } + } + + @DataSourceTypeAnno() + @Override + public int updateValueByKey(String bizId, MPoint entity) { + try { + int res = mPointDao.updateValueByKey(entity); + return res; + } catch (Exception e) { + System.out.println(e); + throw new RuntimeException(); + } + } + + /*@Override + public void publish(MPoint mPoint) { + RTopic topic = redissonClient.getTopic(CommString.MPOINT_TOPIC); + topic.publish(mPoint); + }*/ + + /*@Override + public String getData4Topic(String topicName) { + + RMap map2 = redissonClient.getMap(topicName); + JSONArray jsonArray = new JSONArray(); + for (String key : map2.keySet()) { + String value = map2.get(key).toString();// + JSONObject jsonObject = new JSONObject(); + jsonObject.put("id", key); + jsonObject.put("value", value); + jsonArray.add(jsonObject); + } + + return jsonArray.toString(); + }*/ + + /*public String str = ""; + + @Override + public void publish4TopicName(String msg, String topicName) { + RTopic topic = redissonClient.getTopic(topicName); + topic.publish(msg); + }*/ + + /** + * 淇濆瓨鍒 Influxdb + * + * @param bizId + * @param entity + * @return + */ + public int saveInfluxdb(String bizId, MPointHistory entity) { + Map fields = new HashMap<>(); + Map tags = new HashMap<>(); + if (entity.getMemo() != null) { + tags.put("memo", entity.getMemo()); + } + if (entity.getMemotype() != null) { + tags.put("memotype", entity.getMemotype()); + } + SimpleDateFormat longDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + long time = Calendar.getInstance().getTimeInMillis(); + try { + fields.put("parmvalue", Float.parseFloat(entity.getParmvalue().toString())); + time = longDateFormat.parse(entity.getMeasuredt()).getTime(); +// influxDBConfig.insert("tb_mp_" + entity.getTbName(), time, tags, fields); +// System.out.println("===鎻掑叆鏁版嵁鎴愬姛===" + entity.getTbName() + "===" + Float.parseFloat(entity.getParmvalue().toString())); + } catch (ParseException e) { + e.printStackTrace(); + } + return 1; + } + + /** + * 鎵归噺鏇存柊es + * + * @param mPointES + */ +// @Async + @Override + public void saveAsync(List mPointES) { + this.mPointRepo.batchUpdate(mPointES); + } + + /** + * es鏌ヨ + * + * @return + */ + public List selectListByWhere4Es(NativeSearchQueryBuilder nativeSearchQueryBuilder) { + SearchQuery searchQuery = nativeSearchQueryBuilder.build(); + Page mPage = mPointRepo.search(searchQuery); + List mPoints = mPage.getContent(); + for (MPoint mPoint : mPoints) { + if (mPoint.getNumtail() != null) { + BigDecimal value = CommUtil.formatMPointValue(mPoint.getParmvalue(), mPoint.getNumtail(), mPoint.getRate()); + if (value != null) { + try { + mPoint.setParmvalue(value); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + return mPoints; + } + + /** + * +8灏忔椂 + * + * @param time + * @return + * @throws Exception + */ + public static String formatTimeEight(String time) throws Exception { + Date d = null; + SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + d = sd.parse(time); + long rightTime = (long) (d.getTime() + 8 * 60 * 60 * 1000); //鎶婂綋鍓嶅緱鍒扮殑鏃堕棿鐢╠ate.getTime()鐨勬柟娉曞啓鎴愭椂闂存埑鐨勫舰寮忥紝鍐嶅姞涓8灏忔椂瀵瑰簲鐨勬绉掓暟 + String newtime = sd.format(rightTime); //鎶婂緱鍒扮殑鏂扮殑鏃堕棿鎴冲啀娆℃牸寮忓寲鎴愭椂闂寸殑鏍煎紡 + return newtime; + } + + public void sendKafka4OpcUa(String id, Double value, String time) { + JSONObject message = new JSONObject(); + message.put("id", id); + message.put("value", value); + message.put("value", value + ""); + message.put("time", time); + message.put("sourceType", "opcua"); + String messageStr = JSON.toJSONString(message); + //鍥炶皟 + ListenableFutureCallback> callback = + new ListenableFutureCallback>() { + @Override + public void onSuccess(SendResult result) { + //鎴愬姛 + } + + @Override + public void onFailure(Throwable ex) { + //澶辫触 + } + }; + //寮傛鍙戦佸埌涓変釜涓婚 + sendAsync(CommString.Kafka_Topic_Data, messageStr, callback);//瀹炴椂鏁版嵁 + sendAsync(CommString.Kafka_Topic_Alarm, messageStr, callback);//鎶ヨ鏁版嵁 (浠呮帹閫侀渶瑕佹姤璀︾殑鐐逛綅) + sendAsync(CommString.Kafka_Topic_Frontend, messageStr, callback);//鍓嶇鏁版嵁 + } + + /** + * 寮傛鍙戦佹柟娉 + * + * @param topic 涓婚鍚嶇О + * @param message 娑堟伅鍐呭 + * @param callback 鍥炶皟澶勭悊鍣 + */ + private void sendAsync(String topic, String message, + ListenableFutureCallback> callback) { + try { + ListenableFuture> future = kafkaTemplate.send(topic, message); + future.addCallback(callback); + } catch (Exception e) { +// log.error("Exception occurred while sending message to topic {}", topic, e); + } + } + + @Override + public void saveRedis(String mpcode, Object value, String time) { + RBatch batch = redissonClient.createBatch(); + int hashCode = mpcode.hashCode(); + int num = hashCode % 25; + String dt = time; + String val = value + ";" + value + ";" + dt; + batch.getMapCache(CommString.RedisMpointFlag + num).fastPutAsync(mpcode, val, 2, TimeUnit.DAYS); + batch.execute(); + } + + public void sendKafka4UDP(String unitId,String mpcode, Object value, String timePoint, int i, int length) { + + JSONObject message = new JSONObject(); + message.put("id", mpcode); + message.put("value", value); + message.put("time", timePoint); + message.put("sourceType", "udp"); + String messageStr = JSON.toJSONString(message); + //鍥炶皟 + ListenableFutureCallback> callback = + new ListenableFutureCallback>() { + @Override + public void onSuccess(SendResult result) { + //鎴愬姛 + } + + @Override + public void onFailure(Throwable ex) { + //澶辫触 + } + }; + //寮傛鍙戦佸埌涓変釜涓婚 + sendAsync(CommString.Kafka_Topic_Data, messageStr, callback);//瀹炴椂鏁版嵁 +// sendAsync(CommString.Kafka_Topic_Alarm, messageStr, callback);//鎶ヨ鏁版嵁 (浠呮帹閫侀渶瑕佹姤璀︾殑鐐逛綅) +// sendAsync(CommString.Kafka_Topic_Frontend, messageStr, callback);//鍓嶇鏁版嵁 + + //鎺ㄩ丮qtt鏁版嵁锛堢粰绠$綉骞冲彴鍘傚锛 +// mqttConfigService.doSendJson(message, CommString.Mqtt_Topic_DATA); + + try { + MPointHistory mPointHistory = new MPointHistory(); + mPointHistory.setParmvalue(CommUtil.toBigDecimal(value)); + mPointHistory.setMeasuredt(timePoint); + mPointHistory.setTbName(mpcode); + mPointHistory.setUserid("datacollector"); + mPointHistory.setInsdt(CommUtil.nowDate()); + //鍐欏瓙琛 + mPointHistoryService.saveByCreate(CommString.BIZID_KCGW, mPointHistory); + } catch (Exception e) { + e.printStackTrace(); + } + + //鏇存柊鏈鍚庝竴鏉℃暟鎹埌鎬昏〃 + if (i == length - 1) { + try { + MPoint mPoint = mPointService.selectById(unitId,mpcode); + if (mPoint != null) { + mPoint.setParmvalue(CommUtil.toBigDecimal(value)); + mPoint.setMeasuredt(timePoint); + mPointService.update(mPoint); + } + //鏇存柊redis + mPointService.saveRedis(mpcode, value, timePoint); + } catch (Exception e) { + e.printStackTrace(); + } + } + + } + + // @Async + @Override + public void sendKafka4MQTT(String unitId,String mpcode, Object value, String timePoint, int i, int length, String signaltype) { + //鍐欏瓙琛 + if (signaltype != null && signaltype.equals("DI")) { + try { + MPointHistory mPointHistory = new MPointHistory(); + mPointHistory.setParmvalue(CommUtil.toBigDecimal(value)); + mPointHistory.setMeasuredt(timePoint); + mPointHistory.setTbName(mpcode); + mPointHistory.setUserid("datacollector"); + mPointHistory.setInsdt(CommUtil.nowDate()); + mPointHistoryService.saveByCreate(CommString.BIZID_KCGW, mPointHistory); + } catch (Exception e) { + e.printStackTrace(); + } + } + + //鏇存柊鏈鍚庝竴鏉℃暟鎹埌鎬昏〃 + if (i == length - 1) { + try { + MPoint mPoint = mPointService.selectById(unitId,mpcode); + if (mPoint != null) { + mPoint.setParmvalue(CommUtil.toBigDecimal(value)); + mPoint.setMeasuredt(timePoint); + mPointService.update(mPoint); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + // @Async + @Override + public void sendKafka4MQTT_Alarm(String mpcode, Object value, String timePoint, int i, int length) { + JSONObject message = new JSONObject(); + message.put("id", mpcode); + message.put("value", value); + message.put("time", timePoint); + message.put("sourceType", "mqtt"); + String messageStr = JSON.toJSONString(message); + //鍥炶皟 + ListenableFutureCallback> callback = + new ListenableFutureCallback>() { + @Override + public void onSuccess(SendResult result) { + //鎴愬姛 + } + + @Override + public void onFailure(Throwable ex) { + //澶辫触 + } + }; + //寮傛鍙戦佸埌涓変釜涓婚 + sendAsync(CommString.Kafka_Topic_Alarm, messageStr, callback);//鎶ヨ鏁版嵁 (浠呮帹閫侀渶瑕佹姤璀︾殑鐐逛綅) + } + +} diff --git a/src/main/java/com/sipai/service/user/CompanyService.java b/src/main/java/com/sipai/service/user/CompanyService.java new file mode 100644 index 0000000..8d3fb73 --- /dev/null +++ b/src/main/java/com/sipai/service/user/CompanyService.java @@ -0,0 +1,27 @@ +package com.sipai.service.user; + +import com.sipai.entity.user.Company; + +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/04/25/21:09 + * @Description: + */ +public interface CompanyService { + public abstract Company selectByPrimaryKey(String id); + + public abstract Integer deleteByPrimaryKey(String id); + + public abstract Integer insert(Company entity); + + public abstract Integer updateByPrimaryKeySelective(Company entity); + + public abstract List selectListByWhere(String wherestr); + + public abstract Integer deleteByWhere(String wherestr); + +} diff --git a/src/main/java/com/sipai/service/user/UserService.java b/src/main/java/com/sipai/service/user/UserService.java new file mode 100644 index 0000000..217452e --- /dev/null +++ b/src/main/java/com/sipai/service/user/UserService.java @@ -0,0 +1,9 @@ +package com.sipai.service.user; + +import com.sipai.entity.user.User; + +import java.util.List; + +public interface UserService { + public abstract List listuser2(); +} diff --git a/src/main/java/com/sipai/service/user/impl/CompanyServiceImpl.java b/src/main/java/com/sipai/service/user/impl/CompanyServiceImpl.java new file mode 100644 index 0000000..ce134e1 --- /dev/null +++ b/src/main/java/com/sipai/service/user/impl/CompanyServiceImpl.java @@ -0,0 +1,57 @@ +package com.sipai.service.user.impl; + +import com.sipai.dao.user.CompanyDao; +import com.sipai.entity.user.Company; +import com.sipai.service.user.CompanyService; +import com.sipai.tools.DataSourceEnum; +import com.sipai.tools.DataSourceTypeAnno; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * Created with IntelliJ IDEA. + * + * @Auther: sj + * @Date: 2021/04/25/21:10 + * @Description: + */ +@Service("companyService") +public class CompanyServiceImpl implements CompanyService { + @Autowired + private CompanyDao companyDao; + + @Override + public Company selectByPrimaryKey(String id) { + return companyDao.selectByPrimaryKey(id); + } + + @Override + public Integer deleteByPrimaryKey(String id) { + return companyDao.deleteByPrimaryKey(id); + } + + @Override + public Integer insert(Company entity) { + return companyDao.insert(entity); + } + + @Override + public Integer updateByPrimaryKeySelective(Company entity) { + return companyDao.updateByPrimaryKeySelective(entity); + } + + @Override + public List selectListByWhere(String wherestr) { + Company company = new Company(); + company.setWhere(wherestr); + return companyDao.selectListByWhere(company); + } + + @Override + public Integer deleteByWhere(String wherestr) { + return companyDao.deleteByWhere(wherestr); + } + +} diff --git a/src/main/java/com/sipai/service/user/impl/UserServiceImpl.java b/src/main/java/com/sipai/service/user/impl/UserServiceImpl.java new file mode 100644 index 0000000..3c21608 --- /dev/null +++ b/src/main/java/com/sipai/service/user/impl/UserServiceImpl.java @@ -0,0 +1,21 @@ +package com.sipai.service.user.impl; + +import com.sipai.dao.user.UserDao; +import com.sipai.entity.user.User; +import com.sipai.service.user.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class UserServiceImpl implements UserService { + + @Autowired + private UserDao userDao; + + @Override + public List listuser2() { + return userDao.listuser2(); + } +} diff --git a/src/main/java/com/sipai/tools/AlarmType.java b/src/main/java/com/sipai/tools/AlarmType.java new file mode 100644 index 0000000..294eed4 --- /dev/null +++ b/src/main/java/com/sipai/tools/AlarmType.java @@ -0,0 +1,23 @@ +package com.sipai.tools; + +public enum AlarmType { + VOLTAGE_ALARM(0, "鐢靛帇鎶ヨ"), + WATER_ALARM(1, "姘存蹈鎶ヨ"), + COVER_ALARM(2, "寮鐩栨姤璀"); + + private final int bitPosition; + private final String description; + + AlarmType(int bitPosition, String description) { + this.bitPosition = bitPosition; + this.description = description; + } + + public boolean isTriggered(int qValue) { + return (qValue & (1 << bitPosition)) != 0; + } + + public String getDescription() { + return description; + } +} diff --git a/src/main/java/com/sipai/tools/CommString.java b/src/main/java/com/sipai/tools/CommString.java new file mode 100644 index 0000000..1777197 --- /dev/null +++ b/src/main/java/com/sipai/tools/CommString.java @@ -0,0 +1,244 @@ +package com.sipai.tools; + +public class CommString { +// public static final String DEFAULT_DATABASE = "021CTWS";//榛樿鐢熶骇搴 +// public static final String DEFAULT_UNITID = "021CTWS";//榛樿鐢熶骇搴 + + public static final String DEFAULT_DATABASE = "020GYHB";//榛樿鐢熶骇搴 + public static final String DEFAULT_UNITID = "020GYHB";//榛樿鐢熶骇搴 + + public static final String DUBBO_VERSION_BASE = "1"; + public static final String DUBBO_VERSION_EQUIPMENT = "1"; + public static final String DUBBO_VERSION_PATROL = "1"; + public static final String DUBBO_VERSION_VISUAL = "1"; + public static final String DUBBO_VERSION_OPERATION = "2"; + public static final String DUBBO_VERSION_EXPERT = "2"; + + public static final String REDISSON_ALARM_LIST = "AlarmUpdateList"; + + public static final String MQ_ALARM_MSG = "DM_ALARM_MSG"; + + public static final String KEY_ALARM_MSG = "mq.all.send"; + + public static final String MQ_ALARM_MQTT = "DM_ALARM"; + + public static final String FLAG_MON = "MON"; + + public static final String FLAG_DAY = "DAY"; + + public static final String FLAG_YEA = "YEA"; + + // KIO鐩戞祴鎺ュ彛锛氳幏鍙栬繍缁村钩鍙版墍鏈夎妭鐐圭殑淇℃伅锛屽锛氳妭鐐瑰悕绉般佸湴鍧銆佺鍙h妭鐐归厤缃俊鎭乧up銆佸唴瀛樸佽繍琛岀姸鎬 + public static final String KIO_MONITOR_GETNODEINFOSLIST = "/getNodeInfosList"; + // KIO鐩戞祴鎺ュ彛锛氳幏鍙栧凡鐩戞祴鑺傜偣涓嬬殑鎵鏈夊疄渚嬶紙KH銆並IO銆並S锛夌殑杩愯淇℃伅銆傚寘鎷細瀹炰緥鐨勫悕绉般佽繍琛岀姸鎬併乧pu浣跨敤鐜囷紝鍐呭瓨浣跨敤鐜囷紝杩炴帴鏁般佸瓨鍌ㄧ姸鎬併佹巿鏉冪被鍨嬬瓑 + public static final String KIO_MONITOR_GETALLNODEAPPINFOSLIST = "/getAllNodeAppInfosList"; + // KIO鐩戞祴鎺ュ彛锛氳幏鍙朓OServer鐨勮澶囩姸鎬佷俊鎭 + public static final String KIO_MONITOR_GETNODEKIODEVICEINFOS = "/getNodeKIODeviceInfos"; + // KIO鐩戞祴鎺ュ彛锛氭帶鍒舵寚瀹氳妭鐐瑰凡閮ㄧ讲浜у搧鐨勮繍琛岀姸鎬併傚锛氬惎鍔ㄣ佸仠姝€佸惎鍔ㄩ噰闆嗐佸仠姝㈤噰闆 + public static final String KIO_MONITOR_CONTRLAPPSTATE = "/contrlappstate"; + // KIO鐩戞祴CPU鎶ヨ涓婇檺 + public static final int KIO_CPU_ALARM = 90; + // KIO鐩戞祴鍐呭瓨鎶ヨ涓婇檺 + public static final int KIO_MEMORY_ALARM = 90; + // KIO鐩戞祴纭洏鎶ヨ涓嬮檺 + public static final int KIO_HARDDISK_ALARM = 2048; + + public static final String REDIS_LOCK_RTDB_ALARM = "RTDBALARM"; + + public static final String REDIS_LOCK_MPOINT_PUTIN = "MPOINT_PUTIN"; + + public static final String REDIS_LOCK_EQUIPMENT_FAULT = "EQUIPMENT_FAULT"; + + public static final String REDIS_LOCK_MPOINT_USE_FREQ = "MPOINT_USE_FREQ"; + public static final String REDIS_LOCK_MPOINT_CURRENT_VALUE = "MPOINT_CURENT_VALUE"; + + //绠$悊鍛業D + public static final String ID_Admin = "emp01";//绠$悊鍛 + + //鍚敤 绂佺敤 active + public static final String Flag_Active = "1";//鍚敤 + public static final String Flag_Unactive = "0";//绂佺敤 + + //璁惧鏍囪瘑 鏋勭瓚鐗╂爣璇 + public static final String Flag_Equipment = "E";//璁惧鏍囪瘑 + public static final String Flag_Structure = "S";//鏋勭瓚鐗╂爣璇 + + + //鏍戣妭鐐瑰瓧绗︿覆 + public static final String Tree_Root = "-1";//鏍硅妭鐐 + + //鏁版嵁鍚屾瀛楁 + public static final String Sync_Insert = "I";//鎻掑叆 + public static final String Sync_Edit = "E";//缂栬緫 + public static final String Sync_Delete = "D";//鍒犻櫎 + public static final String Sync_Finish = "F";//鍚屾瀹屾垚 + + //unit type + public static final String UNIT_TYPE_USER = "U";// 鐢ㄦ埛 + public static final String UNIT_TYPE_DEPT = "D";//閮ㄩ棬 + public static final String UNIT_TYPE_BIZ = "B";//姘村巶 + public static final String UNIT_TYPE_WORKSHOP = "W";//杞﹂棿 + public static final String UNIT_TYPE_COMPANY = "C";//鍏徃 + public static final String UNIT_TYPE_Maintainer = "M";//杩愮淮鍟 + public static final String UNIT_TYPE_JOB = "J";//鑱屼綅 + + //鍥炬爣 + public static final String UNIT_BIZ_ICON = "fa fa-fw fa-industry";//姘村巶 fa-cog fa-steam fa-gears + public static final String UNIT_COMPANY_ICON = "fa fa-fw fa-building";//鍏徃 + public static final String UNIT_DEPT_ICON = "fa fa-fw fa-group";//閮ㄩ棬 + public static final String UNIT_USER_ICON = "fa fa-fw fa-male";//鐢ㄦ埛 + public static final String UNIT_Maintainer_ICON = "fa fa-fw fa-wrench";//缁存姢鍟 + + public static final String Active_True = "1";// 鍚敤 + public static final String Active_False = "0";//绂佺敤 + + //浜哄憳绫诲瀷 + public static final String UserType_Biz = "0";// 姘村巶浜哄憳 + public static final String UserType_Maintainer = "1";//渚涘簲鍟 + public static final String UserType_Other = "2";//鍏跺畠 + + //miniMES鎺ユ敹宸ュ崟鐨勫懡鍚嶇┖闂 + public static final String Resp_Success = "pass"; + public static final String Resp_Failure = "resp_fail"; + //宸ヨ壓瀵煎叆浜у搧浠g爜鏍囪瘑瀛楃涓 + public static final String Flag_Technics_Name = "浜у搧鍨嬪彿"; + public static final String TaskType_Start = "startEvent"; + public static final String TaskType_UserTask = "task"; + public static final String TaskType_End = "endEvent"; + public static final String TaskType_Gateway = "gateway"; + + public static final String NO_CURRENT_PROCESS = "NO_CURRENT_PROCESS"; + public static final String NO_CURRENT_PROCEDURE = "NO_CURRENT_PROCEDURE"; + public static final String NO_CURRENT_WORKORDER = "NO_CURRENT_WORKORDER"; + public static final String NO_TASKDEMANDS = "NO_TASKDEMANDS"; + public static final String NO_TASKS = "NO_TASKS"; + + public static final String NO_WORKSTATION = "NO_WORKSTATION"; + + public static final String ACTI_Condition_PASS = "${pass}"; //activiti鍒ゆ柇鑺傜偣閫氳繃鏉′欢 + public static final String ACTI_Condition_FAIL = "${!pass}";//activiti鍒ゆ柇鑺傜偣涓嶉氳繃鏉′欢 + public static final String ACTI_KEK_Condition = "pass"; + public static final String ACTI_KEK_Assignee = "applicantId"; + public static final String ACTI_KEK_Candidate_Users = "userIds"; + + //娴嬮噺鐐瑰姛鑳藉垎绫 + public static final String[] MPointFunType = {"鍚仠", "寰呮満", "鏁呴殰", "鍚姩", "鍋滄"}; + //宸ュ簭鎺掑簭鍒嗙被 + + public static final String Resp_Success_RFID = "true"; + public static final String Resp_Failure_RFID = "false"; + + public static final String[] MaintenanceMethod = {"鐢佃剳杩滅▼", "涓婇棬鏈嶅姟"}; + + //杩斿洖缁撴灉瀛楁 + public static final int ONE_STRING = 1;//琛ㄧず鏁板瓧1 + public static final int TWO_STRING = 2;//琛ㄧず鏁板瓧2 + public static final int ZERO_STRING = 0;//琛ㄧず鏁板瓧0 + + public static final String Default_Theme = "skin-blue";//榛樿涓婚 + + public static final String MainPageType_Produce = "produce";//棣栭〉鍒嗙被-鐢熶骇 + public static final String MainPageType_Security = "security";//棣栭〉鍒嗙被-瀹夊叏 + public static final String MainPageType_Efficiency = "efficiency";//棣栭〉鍒嗙被-鏁堢巼 + + + public static final String ChartType_Base = "base";//鍥捐〃灞曠ず绫诲瀷-鍩虹 + public static final String ChartType_Gauge = "gauge";//鍥捐〃灞曠ず绫诲瀷-浠〃 + public static final String ChartType_Bar = "bar";//鍥捐〃灞曠ず绫诲瀷-鏌辩姸鍥 + public static final String ChartType_Line = "line";//鍥捐〃灞曠ず绫诲瀷-鎶樼嚎 + public static final String Chart_timeIntervalType = "date";//鍘嗗彶鏇茬嚎鏃堕棿闂撮殧澶 + + public static final String AnalysisChartType_Word = "word";//鏁版嵁鍒嗘瀽鍥捐〃灞曠ず绫诲瀷-鏂囧瓧 + public static final String AnalysisChartType_WaterLiquid = "waterLiquid";//鏁版嵁鍒嗘瀽鍥捐〃灞曠ず绫诲瀷-姘寸悆鍥 + public static final String AnalysisChartType_WaterRange = "waterRange";//鏁版嵁鍒嗘瀽鍥捐〃灞曠ず绫诲瀷-姘寸悆鍥鹃噺绋 + public static final String AnalysisChartType_Line = "line";//鏁版嵁鍒嗘瀽鍥捐〃灞曠ず绫诲瀷-绾垮浘 + + + //APP鎺ュ彛璋冨彇鏁版嵁鏄惁鎴愬姛鍙橀噺 + public static final String Status_Pass = "pass";//鑾峰彇鏁版嵁鎴愬姛 + public static final String Status_Fail = "fail";//鑾峰彇鏁版嵁澶辫触 + + //APP鎺ュ彛璋冪敤棣栭〉閰嶇疆淇℃伅鍒嗙被 + public static final String Type_Efficiency = "efficiency";//鏁堢巼 + public static final String Type_Produce = "produce";//鐢熶骇 + + //APP鎺ュ彛璋冪敤KPI grade瀛楁绾у埆绛涢 + public static final String KPI_Grade_Important = "1";//鏁堢巼 + + public static final String JWT_SESSION_HEADER = "jwt_session"; + public static final String TOKEN_HEADER = "token"; + public static final int ERROR_CODE_SERVER = 500; + + public static final String REDIS_LOCK_MPOINT_PROP_SOURCE_DAY = "MPOINT_PROP_SOURCE_DAY"; + public static final String REDIS_LOCK_MPOINT_PROP_SOURCE_HOUR = "MPOINT_PROP_SOURCE_HOUR"; + public static final String REDIS_LOCK_MPOINT_PROP_SOURCE_MINUTE = "MPOINT_PROP_SOURCE_MINUTE"; + public static final String REDIS_UNIT_LIST = "REDIS_UNIT_LIST"; + + + //宸茶闃 + public static final String SUBSCRIPTION_STATUS_NORMAL = "1"; + //鏈闃 + public static final String SUBSCRIPTION_STATUS_CANCEL = "0"; + + //绯荤粺鏇茬嚎鏂规 + public static final int CURVES_PLAN_SYSTERM = 1; + //鐢ㄦ埛鏇茬嚎鏂规 + public static final int CURVES_PLAN_USER = 2; + //鍙湁灞傜骇鍏崇郴 + public static final int CURVES_PLAN = 3; + + public static final String TABLE_NAME_TB_SCADA_ALARM = "tb_scada_alarm"; + public static final String TABLE_NAME_TB_SCADA_ALARM1 = "tb_scada_alarm"; + + /** + * minio namespace鍦板潃 + */ + public static final String MINIO_NAMESPACE_CONFIG_FILE = "mpointidfile"; + + public static final String ALARMANDPUSHMSG_REDIS_LOCK = "AlarmAndPushMsgRedis"; + + // KPI 璁$畻鐐规湀寮濮嬫棩鏈 + public static final int KPI_MPOINT_START_DAY = 21; + // KPI 璁$畻鐐规棩寮濮嬫椂闂 + public static final int KPI_MPOINT_START_HOUR = 8; + // KPI 璁$畻鐐瑰垎寮濮嬫椂闂 + public static final int KPI_MPOINT_START_MINUTE = 0; + + public static final String UseFreqHistoryFlag = "MPUHistoryFreq"; + public static final String UseFreqFlag = "MPUFreq"; + public static final String CollectFreqFlag = "MPCFreq"; + public static final String MPCurrentValueFlag = "MPAlarmValueFlag";//鎶ヨ + + public static final String MPFlag = "MPFlag";//娴嬮噺鐐癸紙鐢ㄤ簬鏌ヨ閲岄潰鐨勫睘鎬э級 + public static final String MPFlagTimeStamp = "MPFlagTimeStamp";//娴嬮噺鐐(鎺ㄩ侀槦鍒楃殑鏃堕棿鎴) + + /** + * Redis + */ + public static final String RedisMpointFlag = "mpoint:current:"; + public static final String RedisMpointUnitId = "mpoint:unitId:"; + public static final String RedisEmqxTopic = "EmqxTopic";//瀛樹富棰樺拰mqtt浠g悊涔嬮棿鐨勫叧绯 + public static final String RedisBizDatabase = "BizDatabase";//瀛樹富棰樺拰mqtt浠g悊涔嬮棿鐨勫叧绯 + public static final String RedisZhuanFaCheck = "ZhuanFaCheck";//鐢ㄤ簬妫鏌ヨ浆鍙戠殑鍋ュ悍鐘舵 y杞彂姝e父 n杞彂寮傚父 寮傚父鍚庡惎鐢ㄥ鐢ㄨ浆鍙戞湇鍔 + public static final String REDISMqttTopicMpoint = "mpoint:mqttTopicMpoint";//璁㈤槄鐨勪富棰樺拰鐐逛綅鐨勫叧绯 + public static final String RedisMPointBzw = "MPointBzw";//鏍囧織浣嶇紦瀛樿〃 + + /** + * Kafka + */ + public static final String Kafka_topic_MPOINTSTREAM = "MPOINTSTREAM";//kafka 瀹炴椂鏁版嵁涓婚 + public static final String Kafka_topic_Alarm = "ALARM_DATA";//kafka 鎶ヨ涓婚 + public static final String Kafka_topic_MSG = "ALARM_MSG";//kafka PLC涓婚 + + public static final String Kafka_Topic_Data = "topic_data";//kafka PLC涓婚 + public static final String Kafka_Topic_Alarm = "topic_alarm";//kafka PLC涓婚 + public static final String Kafka_Topic_Frontend = "topic_frontend";//kafka PLC涓婚 + + /** + * mqtt涓婚 + */ + public static final String Mqtt_Topic_DATA = "topic_data";//闀垮啘姘村巶涓婚 + + + public static final String BIZID_KCGW = "0791KCGW";//鍗楁槍绠$綉 +} diff --git a/src/main/java/com/sipai/tools/CommUtil.java b/src/main/java/com/sipai/tools/CommUtil.java new file mode 100644 index 0000000..4589980 --- /dev/null +++ b/src/main/java/com/sipai/tools/CommUtil.java @@ -0,0 +1,245 @@ +package com.sipai.tools; + + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.serializer.SerializerFeature; + +import java.math.BigDecimal; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.*; + +/** + * @author Administrator + */ +public class CommUtil { + + private static final SimpleDateFormat dateFormat = new SimpleDateFormat( + "yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE); + + private static final SimpleDateFormat timeFormat = new SimpleDateFormat( + "hh:mm:ss", Locale.SIMPLIFIED_CHINESE); + + private static final SimpleDateFormat longDateFormat = new SimpleDateFormat( + "yyyy-MM-dd HH:mm:ss", Locale.SIMPLIFIED_CHINESE); + + private static final CommUtil util = new CommUtil(); + + /*public static String HTTP_TYPE="http";//http璁块棶server + public static String WEBSERVICE_TYPE="webservice";//webservice璁块棶server +*/ + public CommUtil() { + } + + public static String getwherestr(String unitid) { + String wherestr = ""; + String[] str = null; + if (unitid == null || unitid.trim().equals("") || unitid.trim().equals(",")) { + wherestr = ""; + } else { + str = unitid.split(","); + for (int i = 0; i < str.length; i++) { + wherestr += "'" + str[i].trim() + "',"; + } + wherestr += "''"; + } + str = null; + return wherestr; + } + + + /** + * 銆* @description: 娴嬮噺鐐瑰兼牸寮忓寲,鑻ュ间笉瀛樺湪鍒欒繑鍥 BigDecimal(0.0) + * 銆* @param numTail 淇濈暀浣嶆暟 褰㈠锛2锛,rate 鍊嶇巼 + * 銆* @return + * 銆* @author WXP + * 銆* @date 2020/12/26 15:56 + */ + public static BigDecimal formatMPointValue(BigDecimal source, String numTail, BigDecimal rate) { + if (source == null) { + source = new BigDecimal(0.0); + } + // todo 骞夸笟鍘绘帀杩欎釜 +// if (rate!=null){ +// source = source.multiply(rate); +// } + int length = 0; + if (numTail != null && !numTail.isEmpty()) { + if (numTail.contains(".")) { + length = numTail.length() - numTail.indexOf(".0") - 1; + } else { + length = Integer.parseInt(numTail); + } + } + source = source.setScale(length, BigDecimal.ROUND_HALF_DOWN); + return source; + } + + /** + * jep 鍏紡鏍煎紡鍖 + * + * @param formula + * @return + */ + public static String formatJepFormula(String formula) { + if (formula == null) { + return ""; + } + formula = formula.replaceAll(" ", "").replace("#", ""); + formula = formula.replaceAll("锛", "(").replaceAll("锛", ")"); + return formula; + } + + public static String getLastYearMonth() { + java.time.format.DateTimeFormatter fmt = + java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"); + //鑾峰彇褰撳墠骞存湀鏃 + LocalDate date = LocalDate.now(); + date = date.minusMonths(1); + String dateStr = date.format(fmt); + return dateStr.substring(0, 7); + } + + public static String getTargetMonthLastSecond(String yearMonth) { + java.time.format.DateTimeFormatter fmt = + java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + String timeStr = yearMonth + "-01 00:00:00"; + LocalDateTime time = LocalDateTime.parse(timeStr, fmt); + time = time.plusMonths(1);//鍔犱竴涓湀 + time = time.minusSeconds(1);//鍑忎竴绉 + String res = time.format(fmt); + return res; + } + + /** + * 鏃堕棿鎴宠浆涓烘棩鏈熸牸寮 + * + * @param s + * @return + */ + public static String stampToDate(String s) { + String res; + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + long lt = new Long(s); + Date date = new Date(lt); + res = simpleDateFormat.format(date); + return res; + } + + /** + * 鑾峰彇褰撳墠鏃堕棿 + * + * @return + */ + public static String nowDate() { + return longDateFormat.format(new Date()); + } + + /** + * 寰楀埌鍞竴鍊 + * + * @return 杩斿洖java鐨剈til涓敮涓鍊煎嚱鏁扮殑鍊 + */ + public static String getUUID() { + String uuid = null; + uuid = java.util.UUID.randomUUID().toString().replace("-", ""); + return uuid; + } + + /** + * 鎺ュ彛杩斿洖缁撴灉json澶勭悊 + * + * @param result + * @return + * @throws Exception + */ + public static String toJson(Object result) { + + String json = JSON.toJSONString(result, + SerializerFeature.WriteMapNullValue, + SerializerFeature.WriteNullNumberAsZero, + SerializerFeature.WriteNullListAsEmpty, + SerializerFeature.WriteNullStringAsEmpty, + SerializerFeature.WriteNullBooleanAsFalse, + SerializerFeature.DisableCircularReferenceDetect); + return json; + } + + /** + * 鏃堕棿鎴宠浆鎹㈡垚鏃ユ湡鏍煎紡瀛楃涓 + * + * @param seconds 绮剧‘鍒扮鐨勫瓧绗︿覆 + * @param format + * @return + */ + public static String timeStamp2Date(String seconds, String format) { + if (seconds == null || seconds.isEmpty() || seconds.equals("null")) { + return ""; + } + if (format == null || format.isEmpty()) { + format = "yyyy-MM-dd HH:mm:ss"; + } + SimpleDateFormat sdf = new SimpleDateFormat(format); + return sdf.format(new Date(Long.valueOf(seconds + "000"))); + } + + /** + * 鑾峰彇娴嬮噺鐐箃able鍚嶇О + * + * @param mpointCode + * @return + */ + public static String getMPointTableName(String mpointCode) { + String tableName = "tb_mp_" + mpointCode.replace(".", "_").replace(" ", "_"); + + return tableName; + } + + public static boolean isBlank(String str) { + int strLen; + if (str != null && (strLen = str.length()) != 0) { + for (int i = 0; i < strLen; ++i) { + if (!Character.isWhitespace(str.charAt(i))) { + return false; + } + } + + return true; + } else { + return true; + } + } + + public static BigDecimal toBigDecimal(Object value) { + if (value == null) { + return null; + } + + if (value instanceof BigDecimal) { + return (BigDecimal) value; + } else if (value instanceof Integer) { + return BigDecimal.valueOf((Integer) value); + } else if (value instanceof Long) { + return BigDecimal.valueOf((Long) value); + } else if (value instanceof Double) { + // 娉ㄦ剰锛氱洿鎺ヤ娇鐢―ouble鏋勯燘igDecimal鍙兘瀵艰嚧绮惧害闂 + return new BigDecimal(value.toString()); + } else if (value instanceof Float) { + return new BigDecimal(value.toString()); + } else if (value instanceof String) { + try { + return new BigDecimal((String) value); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("Invalid numeric string: " + value, e); + } + } else { + throw new IllegalArgumentException("Unsupported numeric type: " + value.getClass().getName()); + } + } +} + + + + + diff --git a/src/main/java/com/sipai/tools/ConstantString.java b/src/main/java/com/sipai/tools/ConstantString.java new file mode 100644 index 0000000..f0c429e --- /dev/null +++ b/src/main/java/com/sipai/tools/ConstantString.java @@ -0,0 +1,18 @@ +package com.sipai.tools; + +public class ConstantString { + public static final String DUBBO_VERSION_BASE = "1"; + public static final String DUBBO_VERSION_EQUIPMENT = "1"; + public static final String DUBBO_VERSION_PATROL = "1"; + public static final String DUBBO_VERSION_VISUAL = "1"; + public static final String DUBBO_VERSION_OPERATION = "2"; + + public static final String MQ_ALARM_MSG = "DM_ALARM_MSG"; + + public static final String KEY_ALARM_MSG = "mq.all.send"; + + public static final String MQ_ALARM_MQTT = "DM_ALARM";//鐜板満鎶ヨ + public static final String MQ_MPOINT_MQTT = "DM_MPOINT";//鐜板満娴嬮噺鐐 + + public static final String REDISSON_ALARM_LIST = "AlarmUpdateList"; +} diff --git a/src/main/java/com/sipai/tools/DataSourceAspect.java b/src/main/java/com/sipai/tools/DataSourceAspect.java new file mode 100644 index 0000000..b525273 --- /dev/null +++ b/src/main/java/com/sipai/tools/DataSourceAspect.java @@ -0,0 +1,89 @@ +package com.sipai.tools; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.After; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Method; + +/** + * aop鎷︽埅 -- asp + */ +@Component +@Aspect +@Order(-100)//涓轰簡淇濊瘉鍙互鎷︽埅鍒 +public class DataSourceAspect { + @Pointcut("execution(* com.sipai.*.*..*(..)) " + //杩欓噷鎵弿鐨勫垏鐐瑰寘鏄富瑕佹槸service灞傦紝鏍规嵁service灞傛柟娉曠殑涓婅竟鎵璇寸殑鐨勮嚜瀹氫箟娉ㄨВ锛屽幓鍒ゆ柇鎵浣跨敤鐨勬暟鎹簮绫诲瀷锛屽苟鍔ㄦ佸垏鎹㈡暟鎹簮 + "&& @annotation(com.sipai.tools.DataSourceTypeAnno)") + public void dataSourcePointcut() { + } + + @Around("dataSourcePointcut()") + public Object doAround(ProceedingJoinPoint pjp) { + MethodSignature methodSignature = (MethodSignature) pjp.getSignature(); + Method method = methodSignature.getMethod(); + DataSourceTypeAnno typeAnno = method.getAnnotation(DataSourceTypeAnno.class); + DataSourceEnum sourceEnum = typeAnno.value(); + + Object[] argusObjects = pjp.getArgs(); + Object argus = argusObjects[0]; + +// if (argus == DataSourceEnum.master) { +// DataSourceContextHolder.setDataSourceType(DataSourceEnum.master); +// } else if (sourceEnum == DataSourceEnum.slaver) { +// DataSourceContextHolder.setDataSourceType(DataSourceEnum.slaver); +// } + + if (argus != null && !argus.equals("") && argusObjects.length >= 2) { + //DataSourceContextHolder.setDataSourceType(DataSourceEnum.valueOf("SCADA_" + argus.toString())); + DataSourceContextHolder.setDataSourceType(DataSourceEnum.valueOf("SCADA_" + argus.toString())); + } else { + DataSourceContextHolder.setDataSourceType(DataSourceEnum.master); + } + Object result = null; + try { + result = pjp.proceed(); + } catch (Throwable throwable) { + throwable.printStackTrace(); + } finally { + DataSourceContextHolder.resetDataSourceType(); + } + return result; + } + + /*@Around("dataSourcePointcut()") + public Object before(ProceedingJoinPoint jp) { + Object[] argusObjects = jp.getArgs(); + Object argus = argusObjects[0]; + //鑻ュ彧鏈変竴涓弬鏁帮紝鍒欓粯璁や娇鐢╡s + *//*if (argusObjects == null || argusObjects.length < 2 || !(argusObjects[0] instanceof String)) { + return; + }*//* + if (argus != null) { + DataSourceContextHolder.setDataSourceType(DataSourceEnum.master); + } else { + DataSourceContextHolder.setDataSourceType(DataSourceEnum.slaver); + } + Object result = null; + try { + result = jp.proceed(); + } catch (Throwable throwable) { + throwable.printStackTrace(); + } finally { + DataSourceContextHolder.resetDataSourceType(); + } + + return result; + } + + @After("dataSourcePointcut()") + public void after(ProceedingJoinPoint jp) { + DataSourceContextHolder.resetDataSourceType(); + }*/ +} diff --git a/src/main/java/com/sipai/tools/DataSourceContextHolder.java b/src/main/java/com/sipai/tools/DataSourceContextHolder.java new file mode 100644 index 0000000..ef1cb9d --- /dev/null +++ b/src/main/java/com/sipai/tools/DataSourceContextHolder.java @@ -0,0 +1,33 @@ +package com.sipai.tools; + +/** + * 鏋氫妇绫诲伐鍏 set + */ +public class DataSourceContextHolder { + private static final ThreadLocal CONTEXT_HOLDER = new ThreadLocal() { + @Override + protected DataSourceEnum initialValue() { + return DataSourceEnum.master; + } + }; + + /** + * 璁剧疆鏁版嵁婧 + * @param type + */ + public static void setDataSourceType(DataSourceEnum type) { + CONTEXT_HOLDER.set(type); + } + + /** + * 鍙栧緱褰撳墠鏁版嵁婧 + * @return + */ + public static DataSourceEnum getDataSourceType() { + return CONTEXT_HOLDER.get(); + } + + public static void resetDataSourceType() { + CONTEXT_HOLDER.set(DataSourceEnum.master); + } +} diff --git a/src/main/java/com/sipai/tools/DataSourceEnum.java b/src/main/java/com/sipai/tools/DataSourceEnum.java new file mode 100644 index 0000000..8a3fdc5 --- /dev/null +++ b/src/main/java/com/sipai/tools/DataSourceEnum.java @@ -0,0 +1,10 @@ +package com.sipai.tools; + +/** + * 鏁版嵁婧愭灇涓 + */ +public enum DataSourceEnum { + master + // + ,SCADA_JS1C,SCADA_JS2C,SCADA_JSBZ +} diff --git a/src/main/java/com/sipai/tools/DataSourceTypeAnno.java b/src/main/java/com/sipai/tools/DataSourceTypeAnno.java new file mode 100644 index 0000000..c9988bb --- /dev/null +++ b/src/main/java/com/sipai/tools/DataSourceTypeAnno.java @@ -0,0 +1,16 @@ +package com.sipai.tools; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 鑷畾涔夋敞瑙 + */ +@Retention(RetentionPolicy.RUNTIME) // 鍦ㄨ繍琛屾椂鍙 +@Target(ElementType.METHOD) // 娉ㄨВ鍙互鐢ㄥ湪鏂规硶涓 +public @interface DataSourceTypeAnno { + //浣跨敤鏂瑰紡鍦╯ervice灞傛柟娉曚笂娣诲姞@DataSourceTypeAnno(DataSourceEnum.鏁版嵁婧愭灇涓剧被鍨)鐢ㄤ簬鎸囧畾鎵浣跨敤鐨勬暟鎹簮 + DataSourceEnum value() default DataSourceEnum.master; +} diff --git a/src/main/java/com/sipai/tools/DynamicDataSource.java b/src/main/java/com/sipai/tools/DynamicDataSource.java new file mode 100644 index 0000000..e790667 --- /dev/null +++ b/src/main/java/com/sipai/tools/DynamicDataSource.java @@ -0,0 +1,12 @@ +package com.sipai.tools; + +import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; + +/** + * 缁ф壙 AbstractRoutingDataSource 绫伙紝瀹炵幇瀵瑰簲鏁版嵁婧恔ey鐨勫垏鎹 + */ +public class DynamicDataSource extends AbstractRoutingDataSource { + protected Object determineCurrentLookupKey() { + return DataSourceContextHolder.getDataSourceType(); + } +} diff --git a/src/main/java/com/sipai/tools/EncryptGISUtils.java b/src/main/java/com/sipai/tools/EncryptGISUtils.java new file mode 100644 index 0000000..47965cf --- /dev/null +++ b/src/main/java/com/sipai/tools/EncryptGISUtils.java @@ -0,0 +1,99 @@ +package com.sipai.tools; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +public class EncryptGISUtils { + + // 鍙傛暟鍒嗗埆浠h〃 绠楁硶鍚嶇О/鍔犲瘑妯″紡/鏁版嵁濉厖鏂瑰紡锛圕BC妯″紡蹇呴』鎸囧畾IV锛 + private static final String ALGORITHMSTR = "AES/CBC/NoPadding"; // 娉ㄦ剰锛歂oPadding 闇鎵嬪姩澶勭悊濉厖 + private static final String KEY = "jP0fD2cJ3tC9xT5k"; // 16瀛楄妭锛128浣嶏級瀵嗛挜锛岀鍚圓ES瑕佹眰 + private static final String IV = "rA3sN2rJ5uZ7dY4u"; // 鑷畾涔塈V锛屽繀椤讳负16瀛楄妭锛圕BC妯″紡鍧楀ぇ灏忎负16瀛楄妭锛 + + // 灏佽榛樿IV鐨勪究鎹锋柟娉 + public static String encrypt(String content) throws Exception { + return encrypt(content, KEY, IV); + } + + public static String decrypt(String encryptStr) throws Exception { + return decrypt(encryptStr, KEY, IV); + } + + /** + * 鍔犲瘑锛堝惈IV澶勭悊锛 + */ + public static String encrypt(String content, String encryptKey, String iv) throws Exception { + // 鏍¢獙IV闀垮害锛堝繀椤讳负16瀛楄妭锛 + if (iv.getBytes(StandardCharsets.UTF_8).length != 16) { + throw new IllegalArgumentException("IV蹇呴』涓16瀛楄妭锛128浣嶏級"); + } + + SecretKeySpec secretKey = new SecretKeySpec(encryptKey.getBytes(StandardCharsets.UTF_8), "AES"); + IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)); + Cipher cipher = Cipher.getInstance(ALGORITHMSTR); + cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec); + + // 澶勭悊NoPadding鐨勫~鍏咃紙鏄庢枃闇涓16瀛楄妭鏁存暟鍊嶏級 + byte[] plaintextBytes = content.getBytes(StandardCharsets.UTF_8); + int blockSize = cipher.getBlockSize(); + int paddingLength = blockSize - (plaintextBytes.length % blockSize); + if (paddingLength != 0 && paddingLength != blockSize) { // 闈炴暣鏁板嶆椂濉厖 + byte[] paddedBytes = new byte[plaintextBytes.length + paddingLength]; + System.arraycopy(plaintextBytes, 0, paddedBytes, 0, plaintextBytes.length); + plaintextBytes = paddedBytes; + } else if (paddingLength == 0 && blockSize != plaintextBytes.length) { // 鑻ユ濂芥暣闄や絾闈炲潡澶у皬锛屼笉濉厖锛堜粎閫傜敤浜庣壒娈婂満鏅級 + // 鑻ヤ笟鍔¤姹傚繀椤诲~鍏咃紝鍙己鍒舵坊鍔燽lockSize瀛楄妭濉厖 + } + + byte[] encryptedBytes = cipher.doFinal(plaintextBytes); + return Base64.getEncoder().encodeToString(encryptedBytes); + } + + /** + * 瑙e瘑锛堝惈IV澶勭悊锛 + */ + public static String decrypt(String encryptStr, String decryptKey, String iv) throws Exception { + // 鏍¢獙IV闀垮害 + if (iv.getBytes(StandardCharsets.UTF_8).length != 16) { + throw new IllegalArgumentException("IV蹇呴』涓16瀛楄妭锛128浣嶏級"); + } + + SecretKeySpec secretKey = new SecretKeySpec(decryptKey.getBytes(StandardCharsets.UTF_8), "AES"); + IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)); + Cipher cipher = Cipher.getInstance(ALGORITHMSTR); + cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec); + + byte[] encryptedBytes = Base64.getDecoder().decode(encryptStr); + byte[] decryptedBytes = cipher.doFinal(encryptedBytes); + + // 鍘婚櫎NoPadding鐨勫~鍏咃紙闇涓庡姞瀵嗛昏緫涓鑷达級 + int blockSize = cipher.getBlockSize(); + int dataLength = decryptedBytes.length; + if (dataLength % blockSize != 0) { + throw new IllegalArgumentException("瀵嗘枃闀垮害闈炲潡澶у皬鏁存暟鍊嶏紝瑙e瘑澶辫触"); + } + // 鑻ュ姞瀵嗘椂鏈~鍏咃紝鐩存帴杩斿洖鏄庢枃 + return new String(decryptedBytes, StandardCharsets.UTF_8); + } + + + + /*public static void main(String[] args) { + try { + String original = "admin"; + String encrypted = encrypt(original); + String decrypted = decrypt(encrypted); + System.out.println(encrypted); + System.out.println("-----------"); + System.out.println(decrypted); + } catch (Exception e) { + e.printStackTrace(); + } + }*/ + +} \ No newline at end of file diff --git a/src/main/java/com/sipai/tools/HttpUtil.java b/src/main/java/com/sipai/tools/HttpUtil.java new file mode 100644 index 0000000..bb3ce23 --- /dev/null +++ b/src/main/java/com/sipai/tools/HttpUtil.java @@ -0,0 +1,311 @@ +package com.sipai.tools; + +//import org.apache.axis2.addressing.EndpointReference; +//import org.apache.axis2.client.Options; +//import org.apache.axis2.rpc.client.RPCServiceClient; +import org.apache.http.Consts; +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.ParseException; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.protocol.HTTP; +import org.apache.http.util.EntityUtils; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + + +/** + * @author wxp + * + */ +public class HttpUtil { + + private static final CloseableHttpClient httpclient = HttpClients.createDefault(); + private static final String APPLICATION_JSON = "application/json"; + private static final String CONTENT_TYPE_TEXT_JSON = "application/json"; + + /** + * 鍙戦丠ttpGet璇锋眰 + * @param url + * @return + */ + public static String sendGet(String url) { + + HttpGet httpget = new HttpGet(url); + CloseableHttpResponse response = null; + try { + response = httpclient.execute(httpget); + } catch (IOException e1) { + e1.printStackTrace(); + } + String result = null; + if(response!=null){ + try { + HttpEntity entity = response.getEntity(); + if (entity != null) { + result = EntityUtils.toString(entity); + } + } catch (ParseException | IOException e) { + e.printStackTrace(); + } finally { + try { + + response.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return result; + } + + public static String sendGet(String url, Map params, Map headers) { + String result = null; + try { + // 鏋勫缓甯﹀弬鏁扮殑URL + URIBuilder uriBuilder = new URIBuilder(url); + + // 娣诲姞鏌ヨ鍙傛暟 + if (params != null && !params.isEmpty()) { + for (Map.Entry entry : params.entrySet()) { + uriBuilder.addParameter(entry.getKey(), entry.getValue()); + } + } + + // 鍒涘缓GET璇锋眰 + HttpGet httpGet = new HttpGet(uriBuilder.build()); + + // 璁剧疆璇锋眰澶 + if (headers != null && !headers.isEmpty()) { + for (Map.Entry entry : headers.entrySet()) { + httpGet.setHeader(entry.getKey(), entry.getValue()); + } + } + + // 鎵ц璇锋眰 + try (CloseableHttpResponse response = httpclient.execute(httpGet)) { + // 鑾峰彇鍝嶅簲缁撴灉 + if (response.getEntity() != null) { + result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + /** + * 鍙戦丠ttpPost璇锋眰锛屽弬鏁颁负map + * @param url + * @param map + * @return + */ + public static String sendPost(String url, Map map) { + List formparams = new ArrayList(); + for (Map.Entry entry : map.entrySet()) { + formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); + HttpPost httppost = new HttpPost(url); + httppost.setEntity(entity); + CloseableHttpResponse response = null; + try { + response = httpclient.execute(httppost); + } catch (IOException e) { + e.printStackTrace(); + } + HttpEntity entity1 = response.getEntity(); + String result = null; + try { + result = EntityUtils.toString(entity1); + } catch (ParseException | IOException e) { + e.printStackTrace(); + } + return result; + } + + /** + * 鍙戦佸甫璇锋眰澶寸殑POST璇锋眰 + * @param url 璇锋眰鍦板潃 + * @param map 璇锋眰鍙傛暟 + * @param headers 璇锋眰澶翠俊鎭紙鍙寘鍚玹oken锛 + * @return 鍝嶅簲缁撴灉 + */ + public static String sendPost(String url, Map map, Map headers) { + String result = null; + try { + HttpPost httppost = new HttpPost(url); + + // 璇诲彇 Content-Type 鍐冲畾 body 鏋勯犳柟寮 + String ct = null; + if (headers != null && !headers.isEmpty()) { + for (Map.Entry e : headers.entrySet()) { + if (!"Content-Type".equalsIgnoreCase(e.getKey())) { // Content-Type 鐢卞疄浣撹嚜鍔ㄨ缃 + httppost.setHeader(e.getKey(), e.getValue()); + } else { + ct = e.getValue(); + } + } + } + String ctLower = ct == null ? "" : ct.toLowerCase(); + + HttpEntity entity; + if (ctLower.contains("multipart/form-data")) { + // === form-data (multipart) === + MultipartEntityBuilder mb = MultipartEntityBuilder.create() + .setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + if (map != null) { + for (Map.Entry e : map.entrySet()) { + mb.addTextBody(e.getKey(), + e.getValue() == null ? "" : e.getValue(), + ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8)); + } + } + entity = mb.build(); // 浼氳嚜鍔ㄥ甫 boundary 鍜屾纭殑 Content-Type + } else if (ctLower.contains("application/x-www-form-urlencoded")) { + // === x-www-form-urlencoded === + List formparams = new ArrayList<>(); + if (map != null) { + for (Map.Entry e : map.entrySet()) { + formparams.add(new BasicNameValuePair(e.getKey(), + e.getValue() == null ? "" : e.getValue())); + } + } + entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); + } else { + // === 榛樿璧 JSON === + String jsonParams = mapToJson(map); // 浣犵被閲屽凡鏈 + StringEntity se = new StringEntity(jsonParams, StandardCharsets.UTF_8); + se.setContentType("application/json"); + entity = se; + } + + httppost.setEntity(entity); + + try (CloseableHttpResponse response = httpclient.execute(httppost)) { + if (response.getEntity() != null) { + result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + /** + * 鍙戦丠ttpPost璇锋眰锛屽弬鏁颁负json + * @param url + * @param json + * @return + */ + public static String sendPost(String url, String json) { + String result = null; + try { + StringEntity entity = new StringEntity(json); + entity.setContentType(CONTENT_TYPE_TEXT_JSON); + entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON)); + HttpPost httppost = new HttpPost(url); + httppost.setEntity(entity); + CloseableHttpResponse response = null; + response = httpclient.execute(httppost); + HttpEntity entity1 = response.getEntity(); + result = EntityUtils.toString(entity1); + } catch (ParseException | IOException e) { + e.printStackTrace(); + } + return result; + } + + /** + * 鍙戦佷笉甯﹀弬鏁扮殑HttpPost璇锋眰 + * @param url + * @return + */ + public static String sendPost(String url) { + HttpPost httppost = new HttpPost(url); + CloseableHttpResponse response = null; + try { + response = httpclient.execute(httppost); + } catch (IOException e) { + e.printStackTrace(); + } + HttpEntity entity = response.getEntity(); + String result = null; + try { + result = EntityUtils.toString(entity); + } catch (ParseException | IOException e) { + e.printStackTrace(); + } + return result; + } + /** + * 鍙戦亀ebservice璇锋眰 + * @param + * @return + *//* + public static String sendWebServie(String server,String method,String[] param ,String namespace,boolean flag) { + String result = null; + EndpointReference targetEPR = new EndpointReference(server); + RPCServiceClient sender; + try { + sender = new RPCServiceClient(); + Options options = sender.getOptions(); + options.setTimeOutInMilliSeconds(1000*5);//瓒呮椂鏃堕棿5s + options.setTo(targetEPR); + QName qname = new QName(namespace,method); + int length =param.length; + //String result="{\"res\":"+json+"}"; +// param = new Object[]{CommUtil.GZIPcompress(paramJson)}; + Class[] types = new Class[length]; + //杩欐槸閽堝杩斿肩被鍨嬬殑 + + for(int i=0;i map) { + if (map == null || map.isEmpty()) { + return "{}"; + } + // 浣跨敤fastjson绀轰緥 + return com.alibaba.fastjson.JSONObject.toJSONString(map); + } +} \ No newline at end of file diff --git a/src/main/java/com/sipai/tools/MyBatisConfig.java b/src/main/java/com/sipai/tools/MyBatisConfig.java new file mode 100644 index 0000000..2b70d78 --- /dev/null +++ b/src/main/java/com/sipai/tools/MyBatisConfig.java @@ -0,0 +1,110 @@ +package com.sipai.tools; + +import org.apache.ibatis.session.SqlSessionFactory; +import org.mybatis.spring.SqlSessionFactoryBean; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.jdbc.DataSourceBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; + +import javax.sql.DataSource; +import java.util.HashMap; +import java.util.Map; + +@Configuration +@MapperScan(basePackages = "com.sipai.dao")//鎵弿dao灞俶apper鎺ュ彛 +public class MyBatisConfig { + /** + * @return + * @throws Exception + * @Primary 蹇呴渶鎸囧畾涓涓笖鍙兘鏈変竴涓富鏁版嵁婧愶紝鍚﹀垯鎶ラ敊 + */ + @Primary + @Bean("masterDataSource") + @ConfigurationProperties(prefix = "spring.datasource.master")//鏍规嵁鏁版嵁婧愬墠缂鍒癮pplication.yml璇诲彇鏁版嵁婧愪俊鎭//姝ゅ鏀瑰彉鍓嶇紑鍙互鏀瑰彉榛樿鏁版嵁婧// + public DataSource masterDataSource() throws Exception { + return DataSourceBuilder.create().build(); + } + + /** + * 涓嬮潰涓虹缃 + */ + @Bean("SCADA_JS1C") + @ConfigurationProperties(prefix = "spring.datasource.js1") + //鏍规嵁鏁版嵁婧愬墠缂鍒癮pplication.yml璇诲彇鏁版嵁婧愪俊鎭//鍙互閰嶇疆鏇村鏁版嵁婧愶紝鍒板墠鎻愭槸application.yml涓瓨鍦紝鑰屼笖涔熼渶瑕佸湪鏋氫妇绫讳腑娣诲姞鏋氫妇绫诲瀷 + public DataSource fssk() throws Exception { + return DataSourceBuilder.create().build(); + } + + /** + * 涓嬮潰涓虹缃 + */ + @Bean("SCADA_JS2C") + @ConfigurationProperties(prefix = "spring.datasource.js2") + //鏍规嵁鏁版嵁婧愬墠缂鍒癮pplication.yml璇诲彇鏁版嵁婧愪俊鎭//鍙互閰嶇疆鏇村鏁版嵁婧愶紝鍒板墠鎻愭槸application.yml涓瓨鍦紝鑰屼笖涔熼渶瑕佸湪鏋氫妇绫讳腑娣诲姞鏋氫妇绫诲瀷 + public DataSource fssk2() throws Exception { + return DataSourceBuilder.create().build(); + } + + /** + * 涓嬮潰涓虹缃 + */ + @Bean("SCADA_JSBZ") + @ConfigurationProperties(prefix = "spring.datasource.js3") + //鏍规嵁鏁版嵁婧愬墠缂鍒癮pplication.yml璇诲彇鏁版嵁婧愪俊鎭//鍙互閰嶇疆鏇村鏁版嵁婧愶紝鍒板墠鎻愭槸application.yml涓瓨鍦紝鑰屼笖涔熼渶瑕佸湪鏋氫妇绫讳腑娣诲姞鏋氫妇绫诲瀷 + public DataSource fssk3() throws Exception { + return DataSourceBuilder.create().build(); + } + + /** + * @Qualifier 鏍规嵁鍚嶇О杩涜娉ㄥ叆锛岄氬父鏄湪鍏锋湁鐩稿悓鐨勫涓被鍨嬬殑瀹炰緥鐨勪竴涓敞鍏ワ紙渚嬪鏈夊涓狣ataSource绫诲瀷鐨勫疄渚嬶級 + * @DataSourceTypeAnno(DataSourceEnum.master)浜嬪姟鏂规硶闇瑕佹寚瀹氭暟鎹簮 + */ + @Bean("dynamicDataSource") + public DynamicDataSource dynamicDataSource(@Qualifier("masterDataSource") DataSource masterDataSource, + @Qualifier("SCADA_JS1C") DataSource SCADA_JS1C, + @Qualifier("SCADA_JS2C") DataSource SCADA_JS2C, + @Qualifier("SCADA_JSBZ") DataSource SCADA_JSBZ) { + Map targetDataSources = new HashMap(); + targetDataSources.put(DataSourceEnum.master, masterDataSource); + + targetDataSources.put(DataSourceEnum.SCADA_JS1C, SCADA_JS1C); + targetDataSources.put(DataSourceEnum.SCADA_JS2C, SCADA_JS2C); + targetDataSources.put(DataSourceEnum.SCADA_JSBZ, SCADA_JSBZ); + + DynamicDataSource dataSource = new DynamicDataSource(); + dataSource.setTargetDataSources(targetDataSources);// 璇ユ柟娉曟槸AbstractRoutingDataSource鐨勬柟娉 + dataSource.setDefaultTargetDataSource(masterDataSource);// 榛樿鐨刣atasource璁剧疆涓簃yTestDbDataSource + + return dataSource; + } + + /** + * 鏍规嵁鏁版嵁婧愬垱寤篠qlSessionFactory + */ + @Bean + public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DynamicDataSource dynamicDataSource, + @Value("mybatis.type-aliases-package") String typeAliasesPackage) throws Exception { + SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); + factoryBean.setDataSource(dynamicDataSource);// 鎸囧畾鏁版嵁婧(杩欎釜蹇呴』鏈夛紝鍚﹀垯鎶ラ敊) + // 涓嬭竟涓ゅ彞浠呬粎鐢ㄤ簬*.xml鏂囦欢锛屽鏋滄暣涓寔涔呭眰鎿嶄綔涓嶉渶瑕佷娇鐢ㄥ埌xml鏂囦欢鐨勮瘽锛堝彧鐢ㄦ敞瑙e氨鍙互鎼炲畾锛夛紝鍒欎笉鍔 D:\ideawork\emqx\src\main\resources\mybatis\mapper + factoryBean.setTypeAliasesPackage(typeAliasesPackage);// 鎸囧畾瀹炰綋绫绘墍鍦ㄧ殑鍖 + factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/**/*.xml"));//鎵弿mapper.xml鏂囦欢鍖 + return factoryBean.getObject(); + } + + /** + * 閰嶇疆浜嬪姟绠$悊鍣 + */ + @Bean + public DataSourceTransactionManager transactionManager(DynamicDataSource dataSource) throws Exception { + return new DataSourceTransactionManager(dataSource); + } + +} diff --git a/src/main/java/com/sipai/tools/Result.java b/src/main/java/com/sipai/tools/Result.java new file mode 100644 index 0000000..b5337f9 --- /dev/null +++ b/src/main/java/com/sipai/tools/Result.java @@ -0,0 +1,68 @@ +package com.sipai.tools; + +import com.alibaba.fastjson.JSON; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +//@Data +//@AllArgsConstructor +//@NoArgsConstructor +//@Builder +public class Result { + public static final int SUCCESS = 1; + public static final int FAILED = 0; + public static final int REPEATED = 2;//閲嶅娣诲姞 + + public Result() { + + } + + public Result(int code, String message, Object result) { + this.code = code; + this.msg = message; + if (result instanceof String) { + this.result = JSON.parse(result.toString()); + } else { + this.result = result; + } + + } + + public static Result success(Object result) { + return new Result(SUCCESS, "", result); + } + + public static Result failed(String msg) { + return new Result(FAILED, msg, null); + } + + public int code; + public String msg; + public Object result; + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public Object getResult() { + return result; + } + + public void setResult(Object result) { + this.result = result; + } +} diff --git a/src/main/java/com/sipai/tools/SpringContextUtil.java b/src/main/java/com/sipai/tools/SpringContextUtil.java new file mode 100644 index 0000000..7d0712b --- /dev/null +++ b/src/main/java/com/sipai/tools/SpringContextUtil.java @@ -0,0 +1,49 @@ +package com.sipai.tools; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +@Component +public class SpringContextUtil implements ApplicationContextAware { + + private static ApplicationContext applicationContext; // Spring搴旂敤涓婁笅鏂囩幆澧 + + // 涓嬮潰鐨勮繖涓柟娉曚笂鍔犱簡@Override娉ㄨВ锛屽師鍥犳槸缁ф壙ApplicationContextAware鎺ュ彛鏄繀椤诲疄鐜扮殑鏂规硶 + @Override + public void setApplicationContext(ApplicationContext applicationContext) + throws BeansException { + SpringContextUtil.applicationContext = applicationContext; + } + + public static ApplicationContext getApplicationContext() { + return applicationContext; + } + + public static Object getBean(String name) throws BeansException { + return applicationContext.getBean(name); + } + + public static Object getBean(String name, Class requiredType) + throws BeansException { + return applicationContext.getBean(name, requiredType); + } + + public static boolean containsBean(String name) { + return applicationContext.containsBean(name); + } + + public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException { + return applicationContext.isSingleton(name); + } + + public static Class getType(String name) throws NoSuchBeanDefinitionException { + return applicationContext.getType(name); + } + + public static String[] getAliases(String name) throws NoSuchBeanDefinitionException { + return applicationContext.getAliases(name); + } +} diff --git a/src/main/java/com/sipai/tools/Test.java b/src/main/java/com/sipai/tools/Test.java new file mode 100644 index 0000000..c7b6541 --- /dev/null +++ b/src/main/java/com/sipai/tools/Test.java @@ -0,0 +1,40 @@ +package com.sipai.tools; + +import java.util.LinkedHashMap; +import java.util.HashMap; +import java.util.Map; + +public class Test { + + // ==== 閰嶇疆 ==== + private static final String BASE_URL = "http://223.84.61.83:3033/SIPAIIS_DataCenter/work/mPointProp/saveHistory.do"; // TODO: 鎹㈡垚瀹為檯 IP + private static final String SDT = "2025-06-01 15:00:00"; + private static final String EDT = "2025-09-06 20:00:00"; + private static final String TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpbk5hbWUiOiJzaXBhaSIsImV4cCI6MTc1NzE4MjgyOSwidXNlcklkIjoiMzUxMDQ1MjA4NzQzNDgxMzQ0IiwiaWF0IjoxNzU3MTMyNDI5fQ.394bRjBQfty7VFxVUWOl97ktQoi-SR8wmMZSAVf3Xr8"; // <<< 甯搁噺 token + + public static void main(String[] args) { + // 澶达細鎼哄甫 token锛堜互鍙婂彲閫夌殑 Content-Type锛 + Map headers = new HashMap<>(); + headers.put("token", TOKEN); + headers.put("Content-Type", "multipart/form-data"); + + for (int i = 1; i <= 2; i++) { + String id = String.format("KCGW_220%02d_P1_HOUR", i); + + Map form = new LinkedHashMap<>(); + form.put("id", id); + form.put("sdt", SDT); + form.put("edt", EDT); + form.put("unitId", ""); + form.put("searchChildFlag", "false"); + + String resp = HttpUtil.sendPost(BASE_URL, form, headers); + System.out.println(id + " -> " + cut(resp, 200)); + + try { Thread.sleep(150); } catch (InterruptedException ignored) {} + } + } + + private static String cut(String s, int n) { return s == null ? "" : (s.length() > n ? s.substring(0, n) + "..." : s); } + +} diff --git a/src/main/java/com/sipai/tools/ThreadConfig.java b/src/main/java/com/sipai/tools/ThreadConfig.java new file mode 100644 index 0000000..e13a6cf --- /dev/null +++ b/src/main/java/com/sipai/tools/ThreadConfig.java @@ -0,0 +1,57 @@ +package com.sipai.tools; + +import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.AsyncConfigurer; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.Executor; + +/** + * @Auther: sj + * @Date: 2021/04/25/23:01 + * @Description: + */ +@Configuration +@EnableAsync +public class ThreadConfig implements AsyncConfigurer { + + @Override + public Executor getAsyncExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + // 閰嶇疆鏍稿績绾跨▼鏁 + executor.setCorePoolSize(10); + // 璁剧疆鏈澶х嚎绋嬫暟 + executor.setMaxPoolSize(100); + // 璁剧疆闃熷垪瀹归噺 + executor.setQueueCapacity(9999); + // 璁剧疆绾跨▼娲昏穬鏃堕棿锛堢锛 + executor.setKeepAliveSeconds(60); + executor.initialize(); + return executor; + } + + @Bean + public Executor getAsyncMqttHandle() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + // 閰嶇疆鏍稿績绾跨▼鏁 + executor.setCorePoolSize(10); + // 璁剧疆鏈澶х嚎绋嬫暟 + executor.setMaxPoolSize(1000); + // 璁剧疆闃熷垪瀹归噺 + executor.setQueueCapacity(9999); + // 璁剧疆绾跨▼娲昏穬鏃堕棿锛堢锛 + executor.setKeepAliveSeconds(60); + // 閰嶇疆绾跨▼姹犱腑鐨勭嚎绋嬬殑鍚嶇О鍓嶇紑 + executor.setThreadNamePrefix("mqttHandle"); + executor.initialize(); + return executor; + } + + @Override + public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { + return null; + } +} diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml new file mode 100644 index 0000000..b447ca1 --- /dev/null +++ b/src/main/resources/application-dev.yml @@ -0,0 +1,160 @@ +# 寮鍙戠幆澧冮厤缃 +server: + # 鏈嶅姟鍣ㄧ殑HTTP绔彛锛岄粯璁や负8080 + port: 8092 + servlet: + # 搴旂敤鐨勮闂矾寰 + context-path: /sipaiis_data + tomcat: + # tomcat鐨刄RI缂栫爜 + uri-encoding: UTF-8 + +# DataSource Config +spring: + redis: + mode: single #鍗曟湇鍔℃ā寮 + host: 132.120.136.19 + port: 6379 + database: 0 + cluster: + nodes: 172.16.242.44:6379,172.16.242.45:6379,172.16.242.46:6379,172.16.242.47:6379,172.16.242.48:6379,172.16.242.49:6379 + max-redirects: 3 + password: zaqwsx + timeout: 100000 + + data: + elasticsearch: + cluster-name: elasticsearch-sipaiis + cluster-nodes: 132.120.136.19:9200 + + datasource: + master: + username: sa + password: ZAQwsx@2016 + jdbc-url: jdbc:sqlserver://132.120.136.19:1433;DatabaseName=JSYW + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + type: com.alibaba.druid.pool.DruidDataSource + + #鐢熶骇搴 + js1: + username: sa + password: ZAQwsx@2016 + jdbc-url: jdbc:sqlserver://132.120.136.19:1433;DatabaseName=EIP_PRD_JS1C + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + type: com.alibaba.druid.pool.DruidDataSource + + #鐢熶骇搴 + js2: + username: sa + password: ZAQwsx@2016 + jdbc-url: jdbc:sqlserver://132.120.136.19:1433;DatabaseName=EIP_PRD_JS1C + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + type: com.alibaba.druid.pool.DruidDataSource + + #鐢熶骇搴 + js3: + username: sa + password: ZAQwsx@2016 + jdbc-url: jdbc:sqlserver://132.120.136.19:1433;DatabaseName=EIP_PRD_JS1C + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + type: com.alibaba.druid.pool.DruidDataSource + + kafka: + # Kafka 鏈嶅姟鍣ㄥ湴鍧 (KRaft妯″紡) + bootstrap-servers: 192.168.10.17:9092 + + # 鐢熶骇鑰呴厤缃 + producer: + key-serializer: org.apache.kafka.common.serialization.StringSerializer + value-serializer: org.apache.kafka.common.serialization.StringSerializer + acks: all + retries: 3 + + # 娑堣垂鑰呴厤缃 + consumer: + group-id: my-group-2.2.0 + auto-offset-reset: earliest + key-deserializer: org.apache.kafka.common.serialization.StringDeserializer + value-deserializer: org.apache.kafka.common.serialization.StringDeserializer + enable-auto-commit: false + properties: + missing.topics.fatal: false # 鍏抽敭淇鐐 + + listener: + ack-mode: manual # 璁剧疆涓烘墜鍔ㄦ彁浜 + + # Admin瀹㈡埛绔厤缃紙鐢ㄤ簬topic鑷姩鍒涘缓锛 + admin: + fail-fast: true + properties: + auto.create.topics.enable: true + + # 閫傞厤Kafka 3.x鐨勯澶栭厤缃 + properties: + security.protocol: PLAINTEXT + # interceptor.classes: org.apache.kafka.clients.interceptor.ProducerInterceptor + + # rabbitmq: + # host: 10.18.68.10:90 + # port: 5672 + # username: admin + # password: admin + # #铏氭嫙host 鍙互涓嶈缃,浣跨敤server榛樿host + # virtual-host: / + + main: + allow-bean-definition-overriding: true #褰撻亣鍒板悓鏍峰悕瀛楃殑鏃跺欙紝鏄惁鍏佽瑕嗙洊娉ㄥ唽 + +mybatis: + mapper-locations: classpath:mybatis/mapper/**/*.xml + type-aliases-package: com.sipai.entity + +#showSql +logging: + config: classpath:log4j2.xml +# level: +# com: +# example: +# mapper: debug + +thymeleaf: + mode: HTML + encoding: utf-8 + cache: false + enabled: false + prefix: classpath:/templates/ + +# PageHelper閰嶇疆锛坅pplication.yml锛 +pagehelper: + helper-dialect: mysql + reasonable: true + support-methods-arguments: true + params: count=countSql + +opcua: + enabled: false # 鏄惁鍚敤OPC UA鍔熻兘锛岄粯璁や负true + server-url: "opc.tcp://132.120.136.19:49320" # OPC UA鏈嶅姟鍣ㄥ湴鍧鍜岀鍙 + # security-policy: Basic256Sha256 + # security-mode: SignAndEncrypt + security-policy: None # 瀹夊叏绛栫暐璁句负None + security-mode: None # 瀹夊叏妯″紡璁句负None + username: "administrator" # 鐢ㄦ埛鍚(鍙) + password: "sipai@64368180" # 瀵嗙爜(鍙) + +app: + max-points: 200 #瀹炴椂鏁版嵁鎺ュ彛涓娆℃渶澶氱偣浣嶆暟 + +mqtt: + broker-address: "tcp://192.168.10.17:1883" + dashboard-01: "http://192.168.10.17:18083" + username: "admin" + password: "sipai@64368180" + +# udp鏈嶅姟 +udp: + server: + enabled: false # 鏄惁鍚敤UDP鏈嶅姟锛岄粯璁や负true + port: 5006 # UDP鏈嶅姟绔彛 + +scheduled: + enabled: true # 璁剧疆涓篺alse鍗冲彲涓存椂鍏抽棴瀹氭椂浠诲姟 \ No newline at end of file diff --git a/src/main/resources/application-pro.yml b/src/main/resources/application-pro.yml new file mode 100644 index 0000000..793ac01 --- /dev/null +++ b/src/main/resources/application-pro.yml @@ -0,0 +1,160 @@ +# 寮鍙戠幆澧冮厤缃 +server: + # 鏈嶅姟鍣ㄧ殑HTTP绔彛锛岄粯璁や负8080 + port: 8092 + servlet: + # 搴旂敤鐨勮闂矾寰 + context-path: /sipaiis_data + tomcat: + # tomcat鐨刄RI缂栫爜 + uri-encoding: UTF-8 + +# DataSource Config +spring: + redis: + mode: single #鍗曟湇鍔℃ā寮 + host: 172.30.24.104 + port: 6379 + database: 0 + cluster: + nodes: 172.16.242.44:6379,172.16.242.45:6379,172.16.242.46:6379,172.16.242.47:6379,172.16.242.48:6379,172.16.242.49:6379 + max-redirects: 3 + password: zaqwsx + timeout: 100000 + + data: + elasticsearch: + cluster-name: elasticsearch-sipaiis + cluster-nodes: 172.30.24.104:9200 + + datasource: + master: + username: sa + password: ZAQwsx@2016 + jdbc-url: jdbc:sqlserver://172.30.24.104:1433;DatabaseName=SIPAIIS_WMS + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + type: com.alibaba.druid.pool.DruidDataSource + + #鐢熶骇搴 + js1: + username: sa + password: ZAQwsx@2016 + jdbc-url: jdbc:sqlserver://172.30.24.110:1433;DatabaseName=EIP_PRD_JS1C + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + type: com.alibaba.druid.pool.DruidDataSource + + #鐢熶骇搴 + js2: + username: sa + password: ZAQwsx@2016 + jdbc-url: jdbc:sqlserver://172.30.24.110:1433;DatabaseName=EIP_PRD_JS2C + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + type: com.alibaba.druid.pool.DruidDataSource + + #鐢熶骇搴 + js3: + username: sa + password: ZAQwsx@2016 + jdbc-url: jdbc:sqlserver://172.30.24.110:1433;DatabaseName=EIP_PRD_JSBZ + driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver + type: com.alibaba.druid.pool.DruidDataSource + + kafka: + # Kafka 鏈嶅姟鍣ㄥ湴鍧 (KRaft妯″紡) + bootstrap-servers: 192.168.10.17:9092 + + # 鐢熶骇鑰呴厤缃 + producer: + key-serializer: org.apache.kafka.common.serialization.StringSerializer + value-serializer: org.apache.kafka.common.serialization.StringSerializer + acks: all + retries: 3 + + # 娑堣垂鑰呴厤缃 + consumer: + group-id: my-group-2.2.0 + auto-offset-reset: earliest + key-deserializer: org.apache.kafka.common.serialization.StringDeserializer + value-deserializer: org.apache.kafka.common.serialization.StringDeserializer + enable-auto-commit: false + properties: + missing.topics.fatal: false # 鍏抽敭淇鐐 + + listener: + ack-mode: manual # 璁剧疆涓烘墜鍔ㄦ彁浜 + + # Admin瀹㈡埛绔厤缃紙鐢ㄤ簬topic鑷姩鍒涘缓锛 + admin: + fail-fast: true + properties: + auto.create.topics.enable: true + + # 閫傞厤Kafka 3.x鐨勯澶栭厤缃 + properties: + security.protocol: PLAINTEXT + # interceptor.classes: org.apache.kafka.clients.interceptor.ProducerInterceptor + + # rabbitmq: + # host: 10.18.68.10:90 + # port: 5672 + # username: admin + # password: admin + # #铏氭嫙host 鍙互涓嶈缃,浣跨敤server榛樿host + # virtual-host: / + + main: + allow-bean-definition-overriding: true #褰撻亣鍒板悓鏍峰悕瀛楃殑鏃跺欙紝鏄惁鍏佽瑕嗙洊娉ㄥ唽 + +mybatis: + mapper-locations: classpath:mybatis/mapper/**/*.xml + type-aliases-package: com.sipai.entity + +#showSql +logging: + config: classpath:log4j2.xml +# level: +# com: +# example: +# mapper: debug + +thymeleaf: + mode: HTML + encoding: utf-8 + cache: false + enabled: false + prefix: classpath:/templates/ + +# PageHelper閰嶇疆锛坅pplication.yml锛 +pagehelper: + helper-dialect: mysql + reasonable: true + support-methods-arguments: true + params: count=countSql + +opcua: + enabled: false # 鏄惁鍚敤OPC UA鍔熻兘锛岄粯璁や负true + server-url: "opc.tcp://172.30.24.110:49320" # OPC UA鏈嶅姟鍣ㄥ湴鍧鍜岀鍙 + # security-policy: Basic256Sha256 + # security-mode: SignAndEncrypt + security-policy: None # 瀹夊叏绛栫暐璁句负None + security-mode: None # 瀹夊叏妯″紡璁句负None + username: "administrator" # 鐢ㄦ埛鍚(鍙) + password: "sipai@64368180" # 瀵嗙爜(鍙) + +app: + max-points: 200 #瀹炴椂鏁版嵁鎺ュ彛涓娆℃渶澶氱偣浣嶆暟 + +mqtt: + broker-address: "tcp://172.30.24.110:1883" + dashboard-01: "http://172.30.24.110:18083" + username: "admin" + password: "sipai@64368180" + +# udp鏈嶅姟 +udp: + server: + enabled: false # 鏄惁鍚敤UDP鏈嶅姟锛岄粯璁や负true + port: 5006 # UDP鏈嶅姟绔彛 + +scheduled: + enabled: true # 璁剧疆涓篺alse鍗冲彲涓存椂鍏抽棴瀹氭椂浠诲姟 \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..1728aa5 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,4 @@ +spring: + profiles: +# active: dev + active: pro diff --git a/src/main/resources/generatior-config.xml b/src/main/resources/generatior-config.xml new file mode 100644 index 0000000..5b672f1 --- /dev/null +++ b/src/main/resources/generatior-config.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
\ No newline at end of file diff --git a/src/main/resources/log4j2.xml b/src/main/resources/log4j2.xml new file mode 100644 index 0000000..414b860 --- /dev/null +++ b/src/main/resources/log4j2.xml @@ -0,0 +1,116 @@ + + + + + ${sys:server.port:-unknown} + + ./logs_emqx/${server.port} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mybatis-config.xml b/src/main/resources/mybatis-config.xml new file mode 100644 index 0000000..b2cfc83 --- /dev/null +++ b/src/main/resources/mybatis-config.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/Listener/ListenerHis.xml b/src/main/resources/mybatis/mapper/Listener/ListenerHis.xml new file mode 100644 index 0000000..a399850 --- /dev/null +++ b/src/main/resources/mybatis/mapper/Listener/ListenerHis.xml @@ -0,0 +1,114 @@ + + + + + + + + + + + + id, pointid, value, type, insdt + + + + delete + from Listener_His + where id = #{id,jdbcType=VARCHAR} + + + insert into Listener_His (id, pointid, value, type, insdt) + values (#{id,jdbcType=VARCHAR}, #{pointid,jdbcType=VARCHAR}, #{value,jdbcType=VARCHAR}, + #{type,jdbcType=VARCHAR}, #{insdt,jdbcType=VARCHAR}) + + + insert into Listener_His + + + id, + + + pointid, + + + value, + + + type, + + + insdt + + + + + #{id,jdbcType=VARCHAR}, + + + #{pointid,jdbcType=VARCHAR}, + + + #{value,jdbcType=VARCHAR}, + + + #{type,jdbcType=VARCHAR}, + + + #{insdt,jdbcType=VARCHAR} + + + + + update Listener_His + + + id = #{id,jdbcType=VARCHAR}, + + + pointid = #{pointid,jdbcType=VARCHAR}, + + + value = #{value,jdbcType=VARCHAR}, + + + type = #{type,jdbcType=VARCHAR}, + + + insdt = #{insdt,jdbcType=VARCHAR} + + + where id = #{id,jdbcType=VARCHAR} + + + update Listener_His + set id = #{id,jdbcType=VARCHAR}, + pointid = #{pointid,jdbcType=VARCHAR}, + value = #{value,jdbcType=VARCHAR}, + type = #{type,jdbcType=VARCHAR}, + insdt = #{insdt,jdbcType=VARCHAR} + where id = #{id,jdbcType=VARCHAR} + + + + delete + from Listener_His + ${where} + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/Listener/ListenerInterfaceMapper.xml b/src/main/resources/mybatis/mapper/Listener/ListenerInterfaceMapper.xml new file mode 100644 index 0000000..00b7a95 --- /dev/null +++ b/src/main/resources/mybatis/mapper/Listener/ListenerInterfaceMapper.xml @@ -0,0 +1,108 @@ + + + + + + + + + + + + id, name, type, url, port + + + + delete + from Listener_Interface + where id = #{id,jdbcType=VARCHAR} + + + insert into Listener_interface (id, name, type, url, port) + values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, + #{url,jdbcType=VARCHAR}, #{port,jdbcType=VARCHAR}) + + + insert into Listener_Interface + + + id, + + + name, + + + type, + + + url, + + + port + + + + + #{id,jdbcType=VARCHAR}, + + + #{name,jdbcType=VARCHAR}, + + + #{type,jdbcType=VARCHAR}, + + + #{url,jdbcType=VARCHAR}, + + + #{port,jdbcType=VARCHAR} + + + + + update Listener_Interface + + + id = #{id,jdbcType=VARCHAR}, + + + name = #{name,jdbcType=VARCHAR}, + + + type = #{type,jdbcType=VARCHAR}, + + + url = #{url,jdbcType=VARCHAR}, + + + port = #{port,jdbcType=VARCHAR} + + + where id = #{id,jdbcType=VARCHAR} + + + update Listener_Interface + set id = #{id,jdbcType=VARCHAR}, + name = #{name,jdbcType=VARCHAR}, + type = #{type,jdbcType=VARCHAR}, + url = #{url,jdbcType=VARCHAR}, + port = #{port,jdbcType=VARCHAR} + where id = #{id,jdbcType=VARCHAR} + + + + delete + from Listener_Interface + ${where} + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/Listener/ListenerMessageMapper.xml b/src/main/resources/mybatis/mapper/Listener/ListenerMessageMapper.xml new file mode 100644 index 0000000..738dcaa --- /dev/null +++ b/src/main/resources/mybatis/mapper/Listener/ListenerMessageMapper.xml @@ -0,0 +1,108 @@ + + + + + + + + + + + + id, Cmdtype, Objid, Action, insdt + + + + delete + from listener_message + where id = #{id, jdbcType=VARCHAR} + + + insert into listener_message (id, Cmdtype, Objid, Action, insdt) + values (#{id,jdbcType=VARCHAR}, #{Cmdtype,jdbcType=VARCHAR}, #{Objid,jdbcType=VARCHAR}, + #{Action,jdbcType=VARCHAR}, #{insdt,jdbcType=VARCHAR}) + + + insert into listener_message + + + id, + + + Cmdtype, + + + Objid, + + + Action, + + + insdt, + + + + + #{id,jdbcType=VARCHAR}, + + + #{Cmdtype,jdbcType=VARCHAR}, + + + #{Objid,jdbcType=VARCHAR}, + + + #{Action,jdbcType=VARCHAR}, + + + #{insdt,jdbcType=VARCHAR}, + + + + + update listener_message + + + id = #{id,jdbcType=VARCHAR}, + + + Cmdtype = #{Cmdtype,jdbcType=VARCHAR}, + + + Objid = #{Objid,jdbcType=VARCHAR}, + + + Action = #{Action,jdbcType=VARCHAR}, + + + insdt = #{insdt,jdbcType=VARCHAR}, + + + where id = #{id,jdbcType=VARCHAR} + + + update listener_message + set id = #{id,jdbcType=VARCHAR}, + Cmdtype = #{Cmdtype,jdbcType=VARCHAR}, + Objid = #{Objid,jdbcType=VARCHAR}, + Action = #{Action,jdbcType=VARCHAR}} + insdt = #{insdt,jdbcType=VARCHAR}} + where id = #{id,jdbcType=VARCHAR} + + + + delete + from listener_message + ${where} + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/Listener/ListenerPointMapper.xml b/src/main/resources/mybatis/mapper/Listener/ListenerPointMapper.xml new file mode 100644 index 0000000..3bfb8b9 --- /dev/null +++ b/src/main/resources/mybatis/mapper/Listener/ListenerPointMapper.xml @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + id + , intid, name, address, type, mpcode, datatype, unitid,logi,logi_val,action + + + + delete + from Listener_Point + where id = #{id,jdbcType=VARCHAR} + + + insert into Listener_Point (id, intid, name, address, type, mpcode, datatype, unitid) + values (#{id,jdbcType=VARCHAR}, #{intid,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, + #{address,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, #{mpcode,jdbcType=VARCHAR}, + #{datatype,jdbcType=VARCHAR}, #{unitid,jdbcType=VARCHAR}, #{logi,jdbcType=VARCHAR}, + #{action,jdbcType=VARCHAR}) + + + insert into Listener_Point + + + id, + + + intid, + + + name, + + + address, + + + type, + + + mpcode, + + + datatype + + + unitid + + + logi + + + action + + + + + #{id,jdbcType=VARCHAR}, + + + #{intid,jdbcType=VARCHAR}, + + + #{name,jdbcType=VARCHAR}, + + + #{address,jdbcType=VARCHAR}, + + + #{type,jdbcType=VARCHAR}, + + + #{mpcode,jdbcType=VARCHAR}, + + + #{datatype,jdbcType=VARCHAR} + + + #{unitid,jdbcType=VARCHAR} + + + #{logi,jdbcType=VARCHAR} + + + #{action,jdbcType=VARCHAR} + + + + + update Listener_Point + + + id = #{id,jdbcType=VARCHAR}, + + + intid = #{intid,jdbcType=VARCHAR}, + + + name = #{name,jdbcType=VARCHAR}, + + + address = #{address,jdbcType=VARCHAR}, + + + type = #{type,jdbcType=VARCHAR}, + + + mpcode = #{mpcode,jdbcType=VARCHAR}, + + + datatype = #{datatype,jdbcType=VARCHAR} + + + unitid = #{unitid,jdbcType=VARCHAR} + + + logi = #{logi,jdbcType=VARCHAR} + + + action = #{action,jdbcType=VARCHAR} + + + where id = #{id,jdbcType=VARCHAR} + + + update Listener_Point + set id = #{id,jdbcType=VARCHAR}, + intid = #{intid,jdbcType=VARCHAR}, + name = #{name,jdbcType=VARCHAR}, + address = #{address,jdbcType=VARCHAR}, + type = #{type,jdbcType=VARCHAR}, + mpcode = #{mpcode,jdbcType=VARCHAR}, + datatype = #{datatype,jdbcType=VARCHAR}, + unitid = #{unitid,jdbcType=VARCHAR}, + logi = #{logi,jdbcType=VARCHAR}, + action = #{action,jdbcType=VARCHAR} + where id = #{id,jdbcType=VARCHAR} + + + + delete + from Listener_Point ${where} + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/data/PipeTopicMpointMapper.xml b/src/main/resources/mybatis/mapper/data/PipeTopicMpointMapper.xml new file mode 100644 index 0000000..4a50596 --- /dev/null +++ b/src/main/resources/mybatis/mapper/data/PipeTopicMpointMapper.xml @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + id, point_name, point_code, type, is_constant, constant_value, sort_order + + + + + + delete from tb_pipe_topic_mpoint + where id = #{id,jdbcType=INTEGER} + + + + insert into tb_pipe_topic_mpoint (id, point_name, point_code, + type, is_constant, constant_value, + sort_order + ) + values (#{id,jdbcType=INTEGER}, #{pointName,jdbcType=VARCHAR}, #{pointCode,jdbcType=VARCHAR}, + #{type,jdbcType=VARCHAR}, #{isConstant,jdbcType=INTEGER}, #{constantValue,jdbcType=VARCHAR}, + #{sortOrder,jdbcType=INTEGER} + ) + + + + insert into tb_pipe_topic_mpoint + + + id, + + + point_name, + + + point_code, + + + type, + + + is_constant, + + + constant_value, + + + sort_order, + + + + + #{id,jdbcType=INTEGER}, + + + #{pointName,jdbcType=VARCHAR}, + + + #{pointCode,jdbcType=VARCHAR}, + + + #{type,jdbcType=VARCHAR}, + + + #{isConstant,jdbcType=INTEGER}, + + + #{constantValue,jdbcType=VARCHAR}, + + + #{sortOrder,jdbcType=INTEGER}, + + + + + + update tb_pipe_topic_mpoint + + + point_name = #{pointName,jdbcType=VARCHAR}, + + + point_code = #{pointCode,jdbcType=VARCHAR}, + + + type = #{type,jdbcType=VARCHAR}, + + + is_constant = #{isConstant,jdbcType=INTEGER}, + + + constant_value = #{constantValue,jdbcType=VARCHAR}, + + + sort_order = #{sortOrder,jdbcType=INTEGER}, + + + where id = #{id,jdbcType=INTEGER} + + + + update tb_pipe_topic_mpoint + set point_name = #{pointName,jdbcType=VARCHAR}, + point_code = #{pointCode,jdbcType=VARCHAR}, + type = #{type,jdbcType=VARCHAR}, + is_constant = #{isConstant,jdbcType=INTEGER}, + constant_value = #{constantValue,jdbcType=VARCHAR}, + sort_order = #{sortOrder,jdbcType=INTEGER} + where id = #{id,jdbcType=INTEGER} + + + + + + delete from + tb_pipe_topic_mpoint + ${where} + + + + delete from tb_pipe_topic_mpoint + where id in + + #{id} + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/data/PipelineEquipmentMapper.xml b/src/main/resources/mybatis/mapper/data/PipelineEquipmentMapper.xml new file mode 100644 index 0000000..eedf5b9 --- /dev/null +++ b/src/main/resources/mybatis/mapper/data/PipelineEquipmentMapper.xml @@ -0,0 +1,152 @@ + + + + + + + + + + + + + + + id, station_code, equipment_type, product_model, upload_cycle, upload_cycle_unit, last_upload_time, status + + + + delete from tb_pipeline_equipment + where id = #{id,jdbcType=INTEGER} + + + insert into tb_pipeline_equipment (id, station_code, equipment_type, + product_model, upload_cycle, upload_cycle_unit, + last_upload_time, status + ) + values (#{id,jdbcType=INTEGER}, #{stationCode,jdbcType=VARCHAR}, #{equipmentType,jdbcType=VARCHAR}, + #{productModel,jdbcType=VARCHAR}, #{uploadCycle,jdbcType=INTEGER}, #{uploadCycleUnit,jdbcType=VARCHAR}, + #{lastUploadTime,jdbcType=TIMESTAMP}, #{status,jdbcType=VARCHAR} + ) + + + insert into tb_pipeline_equipment + + + id, + + + station_code, + + + equipment_type, + + + product_model, + + + upload_cycle, + + + upload_cycle_unit, + + + last_upload_time, + + + status, + + + + + #{id,jdbcType=INTEGER}, + + + #{stationCode,jdbcType=VARCHAR}, + + + #{equipmentType,jdbcType=VARCHAR}, + + + #{productModel,jdbcType=VARCHAR}, + + + #{uploadCycle,jdbcType=INTEGER}, + + + #{uploadCycleUnit,jdbcType=VARCHAR}, + + + #{lastUploadTime,jdbcType=TIMESTAMP}, + + + #{status,jdbcType=VARCHAR}, + + + + + update tb_pipeline_equipment + + + station_code = #{stationCode,jdbcType=VARCHAR}, + + + equipment_type = #{equipmentType,jdbcType=VARCHAR}, + + + product_model = #{productModel,jdbcType=VARCHAR}, + + + upload_cycle = #{uploadCycle,jdbcType=INTEGER}, + + + upload_cycle_unit = #{uploadCycleUnit,jdbcType=VARCHAR}, + + + last_upload_time = #{lastUploadTime,jdbcType=TIMESTAMP}, + + + status = #{status,jdbcType=VARCHAR}, + + + where id = #{id,jdbcType=INTEGER} + + + update tb_pipeline_equipment + set station_code = #{stationCode,jdbcType=VARCHAR}, + equipment_type = #{equipmentType,jdbcType=VARCHAR}, + product_model = #{productModel,jdbcType=VARCHAR}, + upload_cycle = #{uploadCycle,jdbcType=INTEGER}, + upload_cycle_unit = #{uploadCycleUnit,jdbcType=VARCHAR}, + last_upload_time = #{lastUploadTime,jdbcType=TIMESTAMP}, + status = #{status,jdbcType=VARCHAR} + where id = #{id,jdbcType=INTEGER} + + + + + + delete from + tb_pipeline_equipment + ${where} + + + + delete from tb_pipeline_equipment + where id in + + #{id} + + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/data/PipelineEquipmentMpointMapper.xml b/src/main/resources/mybatis/mapper/data/PipelineEquipmentMpointMapper.xml new file mode 100644 index 0000000..98bb17a --- /dev/null +++ b/src/main/resources/mybatis/mapper/data/PipelineEquipmentMpointMapper.xml @@ -0,0 +1,102 @@ + + + + + + + + + + + + id, pid, mpcode, tag, mpname + + + + delete from tb_pipeline_equipment_mpoint + where id = #{id,jdbcType=INTEGER} + + + insert into tb_pipeline_equipment_mpoint (id, pid, mpcode, tag, mpname) + values (#{id,jdbcType=INTEGER}, #{pid,jdbcType=INTEGER}, #{mpcode,jdbcType=VARCHAR}, #{tag,jdbcType=VARCHAR}, #{mpname,jdbcType=VARCHAR}) + + + insert into tb_pipeline_equipment_mpoint + + + id, + + + pid, + + + mpcode, + + + tag, + + + mpname, + + + + + #{id,jdbcType=INTEGER}, + + + #{pid,jdbcType=INTEGER}, + + + #{mpcode,jdbcType=VARCHAR}, + + + #{tag,jdbcType=VARCHAR}, + + + #{mpname,jdbcType=VARCHAR}, + + + + + update tb_pipeline_equipment_mpoint + + + pid = #{pid,jdbcType=INTEGER}, + + + mpcode = #{mpcode,jdbcType=VARCHAR}, + + + tag = #{tag,jdbcType=VARCHAR}, + + + mpname = #{mpname,jdbcType=VARCHAR}, + + + where id = #{id,jdbcType=INTEGER} + + + update tb_pipeline_equipment_mpoint + set pid = #{pid,jdbcType=INTEGER}, + mpcode = #{mpcode,jdbcType=VARCHAR}, + tag = #{tag,jdbcType=VARCHAR}, + mpname = #{mpname,jdbcType=VARCHAR} + where id = #{id,jdbcType=INTEGER} + + + + delete from + tb_pipeline_equipment_mpoint + ${where} + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/data/PipelineMpointLibraryMapper.xml b/src/main/resources/mybatis/mapper/data/PipelineMpointLibraryMapper.xml new file mode 100644 index 0000000..dd66dd3 --- /dev/null +++ b/src/main/resources/mybatis/mapper/data/PipelineMpointLibraryMapper.xml @@ -0,0 +1,102 @@ + + + + + + + + + + + + id, equipment_type, code, name, morder + + + + delete from tb_pipeline_mpoint_library + where id = #{id,jdbcType=VARCHAR} + + + insert into tb_pipeline_mpoint_library (id, equipment_type, code, name, morder) + values (#{id,jdbcType=VARCHAR}, #{equipmentType,jdbcType=VARCHAR}, #{code,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{morder,jdbcType=INTEGER}) + + + insert into tb_pipeline_mpoint_library + + + id, + + + equipment_type, + + + code, + + + name, + + + morder, + + + + + #{id,jdbcType=VARCHAR}, + + + #{equipmentType,jdbcType=VARCHAR}, + + + #{code,jdbcType=VARCHAR}, + + + #{name,jdbcType=VARCHAR}, + + + #{morder,jdbcType=INTEGER}, + + + + + update tb_pipeline_mpoint_library + + + equipment_type = #{equipmentType,jdbcType=VARCHAR}, + + + code = #{code,jdbcType=VARCHAR}, + + + name = #{name,jdbcType=VARCHAR}, + + + morder = #{morder,jdbcType=INTEGER}, + + + where id = #{id,jdbcType=VARCHAR} + + + update tb_pipeline_mpoint_library + set equipment_type = #{equipmentType,jdbcType=VARCHAR}, + code = #{code,jdbcType=VARCHAR}, + name = #{name,jdbcType=VARCHAR}, + morder = #{morder,jdbcType=INTEGER} + where id = #{id,jdbcType=VARCHAR} + + + + delete from + tb_pipeline_mpoint_library + ${where} + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/mqtt/MqttConfigMapper.xml b/src/main/resources/mybatis/mapper/mqtt/MqttConfigMapper.xml new file mode 100644 index 0000000..f4247e4 --- /dev/null +++ b/src/main/resources/mybatis/mapper/mqtt/MqttConfigMapper.xml @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + id, insdt, client_id, client_name, broker_ip, tomcat_port, username, password, morder + + + + delete from tb_mqtt_config + where id = #{id,jdbcType=VARCHAR} + + + insert into tb_mqtt_config (id, insdt, client_id, + client_name, broker_ip, tomcat_port, + username, password, morder + ) + values (#{id,jdbcType=VARCHAR}, #{insdt,jdbcType=TIMESTAMP}, #{clientId,jdbcType=VARCHAR}, + #{clientName,jdbcType=VARCHAR}, #{brokerIp,jdbcType=VARCHAR}, #{tomcatPort,jdbcType=VARCHAR}, + #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{morder,jdbcType=INTEGER} + ) + + + insert into tb_mqtt_config + + + id, + + + insdt, + + + client_id, + + + client_name, + + + broker_ip, + + + tomcat_port, + + + username, + + + password, + + + morder, + + + + + #{id,jdbcType=VARCHAR}, + + + #{insdt,jdbcType=TIMESTAMP}, + + + #{clientId,jdbcType=VARCHAR}, + + + #{clientName,jdbcType=VARCHAR}, + + + #{brokerIp,jdbcType=VARCHAR}, + + + #{tomcatPort,jdbcType=VARCHAR}, + + + #{username,jdbcType=VARCHAR}, + + + #{password,jdbcType=VARCHAR}, + + + #{morder,jdbcType=INTEGER}, + + + + + update tb_mqtt_config + + + insdt = #{insdt,jdbcType=TIMESTAMP}, + + + client_id = #{clientId,jdbcType=VARCHAR}, + + + client_name = #{clientName,jdbcType=VARCHAR}, + + + broker_ip = #{brokerIp,jdbcType=VARCHAR}, + + + tomcat_port = #{tomcatPort,jdbcType=VARCHAR}, + + + username = #{username,jdbcType=VARCHAR}, + + + password = #{password,jdbcType=VARCHAR}, + + + morder = #{morder,jdbcType=INTEGER}, + + + where id = #{id,jdbcType=VARCHAR} + + + update tb_mqtt_config + set insdt = #{insdt,jdbcType=TIMESTAMP}, + client_id = #{clientId,jdbcType=VARCHAR}, + client_name = #{clientName,jdbcType=VARCHAR}, + broker_ip = #{brokerIp,jdbcType=VARCHAR}, + tomcat_port = #{tomcatPort,jdbcType=VARCHAR}, + username = #{username,jdbcType=VARCHAR}, + password = #{password,jdbcType=VARCHAR}, + morder = #{morder,jdbcType=INTEGER} + where id = #{id,jdbcType=VARCHAR} + + + + delete from + tb_mqtt_config + ${where} + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/mqtt/MqttConfigTopicMapper.xml b/src/main/resources/mybatis/mapper/mqtt/MqttConfigTopicMapper.xml new file mode 100644 index 0000000..ede96ec --- /dev/null +++ b/src/main/resources/mybatis/mapper/mqtt/MqttConfigTopicMapper.xml @@ -0,0 +1,123 @@ + + + + + + + + + + + + + id, name, topic, status, pid, morder + + + + delete from tb_mqtt_config_topic + where id = #{id,jdbcType=VARCHAR} + + + insert into tb_mqtt_config_topic (id, name, topic, + status, pid, morder + ) + values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{topic,jdbcType=VARCHAR}, + #{status,jdbcType=VARCHAR}, #{pid,jdbcType=VARCHAR}, #{morder,jdbcType=INTEGER} + ) + + + insert into tb_mqtt_config_topic + + + id, + + + name, + + + topic, + + + status, + + + pid, + + + morder, + + + + + #{id,jdbcType=VARCHAR}, + + + #{name,jdbcType=VARCHAR}, + + + #{topic,jdbcType=VARCHAR}, + + + #{status,jdbcType=VARCHAR}, + + + #{pid,jdbcType=VARCHAR}, + + + #{morder,jdbcType=INTEGER}, + + + + + update tb_mqtt_config_topic + + + name = #{name,jdbcType=VARCHAR}, + + + topic = #{topic,jdbcType=VARCHAR}, + + + status = #{status,jdbcType=VARCHAR}, + + + pid = #{pid,jdbcType=VARCHAR}, + + + morder = #{morder,jdbcType=INTEGER}, + + + where id = #{id,jdbcType=VARCHAR} + + + update tb_mqtt_config_topic + set name = #{name,jdbcType=VARCHAR}, + topic = #{topic,jdbcType=VARCHAR}, + status = #{status,jdbcType=VARCHAR}, + pid = #{pid,jdbcType=VARCHAR}, + morder = #{morder,jdbcType=INTEGER} + where id = #{id,jdbcType=VARCHAR} + + + + delete from + tb_mqtt_config_topic + ${where} + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/scada/MPointBzw.xml b/src/main/resources/mybatis/mapper/scada/MPointBzw.xml new file mode 100644 index 0000000..8c4ef70 --- /dev/null +++ b/src/main/resources/mybatis/mapper/scada/MPointBzw.xml @@ -0,0 +1,78 @@ + + + + + + + + + + mpoint_id, mpointbzw_Id + + + + + + delete from tb_measurepoint_bzw + where mpoint_id = #{mpointId,jdbcType=VARCHAR} + + + + insert into tb_measurepoint_bzw (mpoint_id, mpointbzw_Id) + values (#{mpointId,jdbcType=VARCHAR}, #{mpointbzwId,jdbcType=VARCHAR}) + + + + insert into tb_measurepoint_bzw + + + mpoint_id, + + + mpointbzw_Id, + + + + + #{mpointId,jdbcType=VARCHAR}, + + + #{mpointbzwId,jdbcType=VARCHAR}, + + + + + + update tb_measurepoint_bzw + + + mpointbzw_Id = #{mpointbzwId,jdbcType=VARCHAR}, + + + where mpoint_id = #{mpointId,jdbcType=VARCHAR} + + + + update tb_measurepoint_bzw + set mpointbzw_Id = #{mpointbzwId,jdbcType=VARCHAR} + where mpoint_id = #{mpointId,jdbcType=VARCHAR} + + + + + + delete from tb_measurepoint_bzw + ${where} + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/scada/MPointHistoryMapper.xml b/src/main/resources/mybatis/mapper/scada/MPointHistoryMapper.xml new file mode 100644 index 0000000..bc773ec --- /dev/null +++ b/src/main/resources/mybatis/mapper/scada/MPointHistoryMapper.xml @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + insert into `${tbName}` (ParmValue, MeasureDT, + memotype, memo, userid, + insdt) + values (#{parmvalue,jdbcType=DECIMAL}, #{measuredt,jdbcType=TIMESTAMP}, + #{memotype,jdbcType=VARCHAR}, #{memo,jdbcType=VARCHAR}, #{userid,jdbcType=VARCHAR}, + #{insdt,jdbcType=VARCHAR}) + + + + + + delete + from ${table} ${where} + + + + + + + + CREATE TABLE `${table}` + ( + `ItemID` bigint NOT NULL AUTO_INCREMENT, + `ParmValue` decimal(18, 4) NOT NULL, + `MeasureDT` datetime NOT NULL, + `memotype` varchar(100) NULL, + `memo` varchar(50) NULL, + `userid` varchar(50) NULL, + `insdt` datetime NULL ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`ItemID`), + INDEX `index_dt`(`MeasureDT`) + ); + + + + update `${tbName}` + set ParmValue = #{parmvalue,jdbcType=DECIMAL}, memotype = #{memotype,jdbcType=VARCHAR} + where MeasureDT = #{measuredt,jdbcType=TIMESTAMP} + + + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/scada/MPointMapper.xml b/src/main/resources/mybatis/mapper/scada/MPointMapper.xml new file mode 100644 index 0000000..6f390d1 --- /dev/null +++ b/src/main/resources/mybatis/mapper/scada/MPointMapper.xml @@ -0,0 +1,718 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ID, MPointID, MPointCode, ParmName, Unit, alarmmax, alarmmin, ParmValue, MeasureDT, + Rate, Freq, FreqUnit, SignalType, SignalTag, LEDType, LEDColor, DirectType, BizId, BizType, + NumTail, prochour, procday, procmonth, ShowName, exp, forcemin, forcemax, avgmax, + avgmin, remoteup, morder, TriggerAlarm, ConfirmAlarm, flowset, triggerCycle, cyclemax, + cyclemin, triggerMutation, mutationset, causeset, operateset, resultset, triggerEquOff, + mathop, valuetype, valueMeaning, active, SoundAlarm, scdtype, spanrange, modbusfigid, + register, processSectionCode, equipmentId, source_type, patrol_type, remark, alarm_level, disname + + + + delete from TB_MeasurePoint + where ID = #{id,jdbcType=VARCHAR} + + + insert into TB_MeasurePoint (ID, MPointID, MPointCode, + ParmName, Unit, alarmmax, + alarmmin, ParmValue, MeasureDT, + Rate, Freq, SignalType, + LEDType, LEDColor, DirectType, + BizId, BizType, NumTail, + prochour, procday, procmonth, + ShowName, exp, forcemin, + forcemax, avgmax, avgmin, + remoteup, morder, TriggerAlarm, + ConfirmAlarm, flowset, triggerCycle, + cyclemax, cyclemin, triggerMutation, + mutationset, causeset, operateset, + resultset, triggerEquOff, mathop, + valuetype, active, SoundAlarm, + scdtype, spanrange, modbusfigid, + register, processSectionCode, equipmentId, + pointfunctiondefinition, type + ) + values (#{id,jdbcType=VARCHAR}, #{mpointid,jdbcType=VARCHAR}, #{mpointcode,jdbcType=VARCHAR}, + #{parmname,jdbcType=VARCHAR}, #{unit,jdbcType=VARCHAR}, #{alarmmax,jdbcType=DECIMAL}, + #{alarmmin,jdbcType=DECIMAL}, #{parmvalue,jdbcType=DECIMAL}, #{measuredt,jdbcType=TIMESTAMP}, + #{rate,jdbcType=DECIMAL}, #{freq,jdbcType=INTEGER}, #{signaltype,jdbcType=VARCHAR}, + #{ledtype,jdbcType=CHAR}, #{ledcolor,jdbcType=CHAR}, #{directtype,jdbcType=CHAR}, + #{bizid,jdbcType=VARCHAR}, #{biztype,jdbcType=VARCHAR}, #{numtail,jdbcType=VARCHAR}, + #{prochour,jdbcType=VARCHAR}, #{procday,jdbcType=VARCHAR}, #{procmonth,jdbcType=VARCHAR}, + #{showname,jdbcType=CHAR}, #{exp,jdbcType=VARCHAR}, #{forcemin,jdbcType=DECIMAL}, + #{forcemax,jdbcType=DECIMAL}, #{avgmax,jdbcType=DECIMAL}, #{avgmin,jdbcType=DECIMAL}, + #{remoteup,jdbcType=CHAR}, #{morder,jdbcType=INTEGER}, #{triggeralarm,jdbcType=CHAR}, + #{confirmalarm,jdbcType=CHAR}, #{flowset,jdbcType=DECIMAL}, #{triggercycle,jdbcType=CHAR}, + #{cyclemax,jdbcType=DECIMAL}, #{cyclemin,jdbcType=DECIMAL}, #{triggermutation,jdbcType=CHAR}, + #{mutationset,jdbcType=DECIMAL}, #{causeset,jdbcType=DECIMAL}, #{operateset,jdbcType=DECIMAL}, + #{resultset,jdbcType=DECIMAL}, #{triggerequoff,jdbcType=CHAR}, #{mathop,jdbcType=CHAR}, + #{valuetype,jdbcType=VARCHAR}, #{active,jdbcType=VARCHAR}, #{soundalarm,jdbcType=CHAR}, + #{scdtype,jdbcType=VARCHAR}, #{spanrange,jdbcType=DECIMAL}, #{modbusfigid,jdbcType=VARCHAR}, + #{register,jdbcType=VARCHAR}, #{processsectioncode,jdbcType=VARCHAR}, #{equipmentid,jdbcType=VARCHAR}, + #{pointfunctiondefinition,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR} + ) + + + insert into TB_MeasurePoint + + + ID, + + + MPointID, + + + MPointCode, + + + ParmName, + + + Unit, + + + alarmmax, + + + alarmmin, + + + ParmValue, + + + MeasureDT, + + + Rate, + + + Freq, + + + SignalType, + + + LEDType, + + + LEDColor, + + + DirectType, + + + BizId, + + + BizType, + + + NumTail, + + + prochour, + + + procday, + + + procmonth, + + + ShowName, + + + exp, + + + forcemin, + + + forcemax, + + + avgmax, + + + avgmin, + + + remoteup, + + + morder, + + + TriggerAlarm, + + + ConfirmAlarm, + + + flowset, + + + triggerCycle, + + + cyclemax, + + + cyclemin, + + + triggerMutation, + + + mutationset, + + + causeset, + + + operateset, + + + resultset, + + + triggerEquOff, + + + mathop, + + + valuetype, + + + active, + + + SoundAlarm, + + + scdtype, + + + spanrange, + + + modbusfigid, + + + register, + + + processSectionCode, + + + equipmentId, + + + pointfunctiondefinition, + + + type, + + + + + #{id,jdbcType=VARCHAR}, + + + #{mpointid,jdbcType=VARCHAR}, + + + #{mpointcode,jdbcType=VARCHAR}, + + + #{parmname,jdbcType=VARCHAR}, + + + #{unit,jdbcType=VARCHAR}, + + + #{alarmmax,jdbcType=DECIMAL}, + + + #{alarmmin,jdbcType=DECIMAL}, + + + #{parmvalue,jdbcType=DECIMAL}, + + + #{measuredt,jdbcType=TIMESTAMP}, + + + #{rate,jdbcType=DECIMAL}, + + + #{freq,jdbcType=INTEGER}, + + + #{signaltype,jdbcType=VARCHAR}, + + + #{ledtype,jdbcType=CHAR}, + + + #{ledcolor,jdbcType=CHAR}, + + + #{directtype,jdbcType=CHAR}, + + + #{bizid,jdbcType=VARCHAR}, + + + #{biztype,jdbcType=VARCHAR}, + + + #{numtail,jdbcType=VARCHAR}, + + + #{prochour,jdbcType=VARCHAR}, + + + #{procday,jdbcType=VARCHAR}, + + + #{procmonth,jdbcType=VARCHAR}, + + + #{showname,jdbcType=CHAR}, + + + #{exp,jdbcType=VARCHAR}, + + + #{forcemin,jdbcType=DECIMAL}, + + + #{forcemax,jdbcType=DECIMAL}, + + + #{avgmax,jdbcType=DECIMAL}, + + + #{avgmin,jdbcType=DECIMAL}, + + + #{remoteup,jdbcType=CHAR}, + + + #{morder,jdbcType=INTEGER}, + + + #{triggeralarm,jdbcType=CHAR}, + + + #{confirmalarm,jdbcType=CHAR}, + + + #{flowset,jdbcType=DECIMAL}, + + + #{triggercycle,jdbcType=CHAR}, + + + #{cyclemax,jdbcType=DECIMAL}, + + + #{cyclemin,jdbcType=DECIMAL}, + + + #{triggermutation,jdbcType=CHAR}, + + + #{mutationset,jdbcType=DECIMAL}, + + + #{causeset,jdbcType=DECIMAL}, + + + #{operateset,jdbcType=DECIMAL}, + + + #{resultset,jdbcType=DECIMAL}, + + + #{triggerequoff,jdbcType=CHAR}, + + + #{mathop,jdbcType=CHAR}, + + + #{valuetype,jdbcType=VARCHAR}, + + + #{active,jdbcType=VARCHAR}, + + + #{soundalarm,jdbcType=CHAR}, + + + #{scdtype,jdbcType=VARCHAR}, + + + #{spanrange,jdbcType=DECIMAL}, + + + #{modbusfigid,jdbcType=VARCHAR}, + + + #{register,jdbcType=VARCHAR}, + + + #{processsectioncode,jdbcType=VARCHAR}, + + + #{equipmentid,jdbcType=VARCHAR}, + + + #{pointfunctiondefinition,jdbcType=VARCHAR}, + + + #{type,jdbcType=VARCHAR}, + + + + + update TB_MeasurePoint + + + MPointID = #{mpointid,jdbcType=VARCHAR}, + + + MPointCode = #{mpointcode,jdbcType=VARCHAR}, + + + ParmName = #{parmname,jdbcType=VARCHAR}, + + + Unit = #{unit,jdbcType=VARCHAR}, + + + alarmmax = #{alarmmax,jdbcType=DECIMAL}, + + + alarmmin = #{alarmmin,jdbcType=DECIMAL}, + + + ParmValue = #{parmvalue,jdbcType=DECIMAL}, + + + MeasureDT = #{measuredt,jdbcType=TIMESTAMP}, + + + Rate = #{rate,jdbcType=DECIMAL}, + + + Freq = #{freq,jdbcType=INTEGER}, + + + FreqUnit = #{frequnit,jdbcType=VARCHAR}, + + + SignalType = #{signaltype,jdbcType=VARCHAR}, + + + LEDType = #{ledtype,jdbcType=CHAR}, + + + LEDColor = #{ledcolor,jdbcType=CHAR}, + + + DirectType = #{directtype,jdbcType=CHAR}, + + + BizId = #{bizid,jdbcType=VARCHAR}, + + + BizType = #{biztype,jdbcType=VARCHAR}, + + + NumTail = #{numtail,jdbcType=VARCHAR}, + + + prochour = #{prochour,jdbcType=VARCHAR}, + + + procday = #{procday,jdbcType=VARCHAR}, + + + procmonth = #{procmonth,jdbcType=VARCHAR}, + + + ShowName = #{showname,jdbcType=CHAR}, + + + exp = #{exp,jdbcType=VARCHAR}, + + + forcemin = #{forcemin,jdbcType=DECIMAL}, + + + forcemax = #{forcemax,jdbcType=DECIMAL}, + + + avgmax = #{avgmax,jdbcType=DECIMAL}, + + + avgmin = #{avgmin,jdbcType=DECIMAL}, + + + remoteup = #{remoteup,jdbcType=CHAR}, + + + morder = #{morder,jdbcType=INTEGER}, + + + TriggerAlarm = #{triggeralarm,jdbcType=CHAR}, + + + ConfirmAlarm = #{confirmalarm,jdbcType=CHAR}, + + + flowset = #{flowset,jdbcType=DECIMAL}, + + + triggerCycle = #{triggercycle,jdbcType=CHAR}, + + + cyclemax = #{cyclemax,jdbcType=DECIMAL}, + + + cyclemin = #{cyclemin,jdbcType=DECIMAL}, + + + triggerMutation = #{triggermutation,jdbcType=CHAR}, + + + mutationset = #{mutationset,jdbcType=DECIMAL}, + + + causeset = #{causeset,jdbcType=DECIMAL}, + + + operateset = #{operateset,jdbcType=DECIMAL}, + + + resultset = #{resultset,jdbcType=DECIMAL}, + + + triggerEquOff = #{triggerequoff,jdbcType=CHAR}, + + + mathop = #{mathop,jdbcType=CHAR}, + + + valuetype = #{valuetype,jdbcType=VARCHAR}, + + + valueMeaning = #{valuemeaning,jdbcType=VARCHAR}, + + + active = #{active,jdbcType=VARCHAR}, + + + SoundAlarm = #{soundalarm,jdbcType=CHAR}, + + + scdtype = #{scdtype,jdbcType=VARCHAR}, + + + spanrange = #{spanrange,jdbcType=DECIMAL}, + + + modbusfigid = #{modbusfigid,jdbcType=VARCHAR}, + + + register = #{register,jdbcType=VARCHAR}, + + + processSectionCode = #{processsectioncode,jdbcType=VARCHAR}, + + + equipmentId = #{equipmentid,jdbcType=VARCHAR}, + + + source_type = #{sourceType,jdbcType=VARCHAR}, + + + patrol_type = #{patrolType,jdbcType=VARCHAR}, + + + remark = #{remark,jdbcType=VARCHAR}, + + + alarm_level = #{alarmLevel,jdbcType=INTEGER}, + + + disname = #{disname,jdbcType=VARCHAR}, + + + where ID = #{id,jdbcType=VARCHAR} + + + update TB_MeasurePoint + set MPointID = #{mpointid,jdbcType=VARCHAR}, + MPointCode = #{mpointcode,jdbcType=VARCHAR}, + ParmName = #{parmname,jdbcType=VARCHAR}, + Unit = #{unit,jdbcType=VARCHAR}, + alarmmax = #{alarmmax,jdbcType=DECIMAL}, + alarmmin = #{alarmmin,jdbcType=DECIMAL}, + ParmValue = #{parmvalue,jdbcType=DECIMAL}, + MeasureDT = #{measuredt,jdbcType=TIMESTAMP}, + Rate = #{rate,jdbcType=DECIMAL}, + Freq = #{freq,jdbcType=INTEGER}, + SignalType = #{signaltype,jdbcType=VARCHAR}, + LEDType = #{ledtype,jdbcType=CHAR}, + LEDColor = #{ledcolor,jdbcType=CHAR}, + DirectType = #{directtype,jdbcType=CHAR}, + BizId = #{bizid,jdbcType=VARCHAR}, + BizType = #{biztype,jdbcType=VARCHAR}, + NumTail = #{numtail,jdbcType=VARCHAR}, + prochour = #{prochour,jdbcType=VARCHAR}, + procday = #{procday,jdbcType=VARCHAR}, + procmonth = #{procmonth,jdbcType=VARCHAR}, + ShowName = #{showname,jdbcType=CHAR}, + exp = #{exp,jdbcType=VARCHAR}, + forcemin = #{forcemin,jdbcType=DECIMAL}, + forcemax = #{forcemax,jdbcType=DECIMAL}, + avgmax = #{avgmax,jdbcType=DECIMAL}, + avgmin = #{avgmin,jdbcType=DECIMAL}, + remoteup = #{remoteup,jdbcType=CHAR}, + morder = #{morder,jdbcType=INTEGER}, + TriggerAlarm = #{triggeralarm,jdbcType=CHAR}, + ConfirmAlarm = #{confirmalarm,jdbcType=CHAR}, + flowset = #{flowset,jdbcType=DECIMAL}, + triggerCycle = #{triggercycle,jdbcType=CHAR}, + cyclemax = #{cyclemax,jdbcType=DECIMAL}, + cyclemin = #{cyclemin,jdbcType=DECIMAL}, + triggerMutation = #{triggermutation,jdbcType=CHAR}, + mutationset = #{mutationset,jdbcType=DECIMAL}, + causeset = #{causeset,jdbcType=DECIMAL}, + operateset = #{operateset,jdbcType=DECIMAL}, + resultset = #{resultset,jdbcType=DECIMAL}, + triggerEquOff = #{triggerequoff,jdbcType=CHAR}, + mathop = #{mathop,jdbcType=CHAR}, + valuetype = #{valuetype,jdbcType=VARCHAR}, + active = #{active,jdbcType=VARCHAR}, + SoundAlarm = #{soundalarm,jdbcType=CHAR}, + scdtype = #{scdtype,jdbcType=VARCHAR}, + spanrange = #{spanrange,jdbcType=DECIMAL}, + modbusfigid = #{modbusfigid,jdbcType=VARCHAR}, + register = #{register,jdbcType=VARCHAR}, + processSectionCode = #{processsectioncode,jdbcType=VARCHAR}, + equipmentId = #{equipmentid,jdbcType=VARCHAR}, + pointfunctiondefinition = #{pointfunctiondefinition,jdbcType=VARCHAR}, + type = #{type,jdbcType=VARCHAR} + where ID = #{id,jdbcType=VARCHAR} + + + + delete from + tb_measurepoint + ${where} + + + + + + + + + ${where} + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/user/CompanyDao.xml b/src/main/resources/mybatis/mapper/user/CompanyDao.xml new file mode 100644 index 0000000..1c184d5 --- /dev/null +++ b/src/main/resources/mybatis/mapper/user/CompanyDao.xml @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + id, name, pid, address, tel, website, taskid, post, insdt, insuser, version, morder, + sname, active, type, ename, longitude, latitude,is_count + + + + delete from tb_company + where id = #{id,jdbcType=VARCHAR} + + + insert into tb_company (id, name, pid, + address, tel, website, + taskid, post, insdt, + insuser, version, morder, + sname, active, type, + ename, longitude, latitude,is_count + ) + values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{pid,jdbcType=VARCHAR}, + #{address,jdbcType=VARCHAR}, #{tel,jdbcType=VARCHAR}, #{website,jdbcType=VARCHAR}, + #{taskid,jdbcType=VARCHAR}, #{post,jdbcType=VARCHAR}, #{insdt,jdbcType=TIMESTAMP}, + #{insuser,jdbcType=VARCHAR}, #{version,jdbcType=INTEGER}, #{morder,jdbcType=INTEGER}, + #{sname,jdbcType=VARCHAR}, #{active,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, + #{ename,jdbcType=VARCHAR}, #{longitude,jdbcType=DECIMAL}, #{latitude,jdbcType=DECIMAL}, + #{isCount,jdbcType=VARCHAR} + ) + + + insert into tb_company + + + id, + + + name, + + + pid, + + + address, + + + tel, + + + website, + + + taskid, + + + post, + + + insdt, + + + insuser, + + + version, + + + morder, + + + sname, + + + active, + + + type, + + + ename, + + + longitude, + + + latitude, + + + is_count, + + + + + #{id,jdbcType=VARCHAR}, + + + #{name,jdbcType=VARCHAR}, + + + #{pid,jdbcType=VARCHAR}, + + + #{address,jdbcType=VARCHAR}, + + + #{tel,jdbcType=VARCHAR}, + + + #{website,jdbcType=VARCHAR}, + + + #{taskid,jdbcType=VARCHAR}, + + + #{post,jdbcType=VARCHAR}, + + + #{insdt,jdbcType=TIMESTAMP}, + + + #{insuser,jdbcType=VARCHAR}, + + + #{version,jdbcType=INTEGER}, + + + #{morder,jdbcType=INTEGER}, + + + #{sname,jdbcType=VARCHAR}, + + + #{active,jdbcType=VARCHAR}, + + + #{type,jdbcType=VARCHAR}, + + + #{ename,jdbcType=VARCHAR}, + + + #{longitude,jdbcType=DECIMAL}, + + + #{latitude,jdbcType=DECIMAL}, + + + #{isCount,jdbcType=VARCHAR}, + + + + + update tb_company + + + name = #{name,jdbcType=VARCHAR}, + + + pid = #{pid,jdbcType=VARCHAR}, + + + address = #{address,jdbcType=VARCHAR}, + + + tel = #{tel,jdbcType=VARCHAR}, + + + website = #{website,jdbcType=VARCHAR}, + + + taskid = #{taskid,jdbcType=VARCHAR}, + + + post = #{post,jdbcType=VARCHAR}, + + + insdt = #{insdt,jdbcType=TIMESTAMP}, + + + insuser = #{insuser,jdbcType=VARCHAR}, + + + version = #{version,jdbcType=INTEGER}, + + + morder = #{morder,jdbcType=INTEGER}, + + + sname = #{sname,jdbcType=VARCHAR}, + + + active = #{active,jdbcType=VARCHAR}, + + + type = #{type,jdbcType=VARCHAR}, + + + ename = #{ename,jdbcType=VARCHAR}, + + + longitude = #{longitude,jdbcType=DECIMAL}, + + + latitude = #{latitude,jdbcType=DECIMAL}, + + + is_count = #{isCount,jdbcType=VARCHAR}, + + + where id = #{id,jdbcType=VARCHAR} + + + update tb_company + set name = #{name,jdbcType=VARCHAR}, + pid = #{pid,jdbcType=VARCHAR}, + address = #{address,jdbcType=VARCHAR}, + tel = #{tel,jdbcType=VARCHAR}, + website = #{website,jdbcType=VARCHAR}, + taskid = #{taskid,jdbcType=VARCHAR}, + post = #{post,jdbcType=VARCHAR}, + insdt = #{insdt,jdbcType=TIMESTAMP}, + insuser = #{insuser,jdbcType=VARCHAR}, + version = #{version,jdbcType=INTEGER}, + morder = #{morder,jdbcType=INTEGER}, + sname = #{sname,jdbcType=VARCHAR}, + active = #{active,jdbcType=VARCHAR}, + type = #{type,jdbcType=VARCHAR}, + ename = #{ename,jdbcType=VARCHAR}, + longitude = #{longitude,jdbcType=DECIMAL}, + latitude = #{latitude,jdbcType=DECIMAL}, + is_count = #{isCount,jdbcType=VARCHAR} + where id = #{id,jdbcType=VARCHAR} + + + + \ No newline at end of file diff --git a/src/main/resources/mybatis/mapper/user/UserDao.xml b/src/main/resources/mybatis/mapper/user/UserDao.xml new file mode 100644 index 0000000..31c3945 --- /dev/null +++ b/src/main/resources/mybatis/mapper/user/UserDao.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/index.html b/src/main/resources/templates/index.html new file mode 100644 index 0000000..ac72820 --- /dev/null +++ b/src/main/resources/templates/index.html @@ -0,0 +1,10 @@ + + + + + 棣栭〉 + + + + + \ No newline at end of file diff --git a/src/test/java/com/sipai/SpringbootApplicationTests.java b/src/test/java/com/sipai/SpringbootApplicationTests.java new file mode 100644 index 0000000..be6f534 --- /dev/null +++ b/src/test/java/com/sipai/SpringbootApplicationTests.java @@ -0,0 +1,13 @@ +package com.sipai; + +//import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class EmqxTests { + +// @Test +// void contextLoads() { +// } + +}