├── README.md ├── src ├── test │ └── java │ │ └── com │ │ └── opc │ │ └── client │ │ ├── UATest.java │ │ └── DcomTest.java └── main │ ├── java │ └── com │ │ └── opc │ │ └── client │ │ ├── security │ │ ├── TokenException.java │ │ ├── BaseException.java │ │ ├── User.java │ │ ├── Role.java │ │ ├── UserDetailsServiceImpl.java │ │ ├── JWTAuthenticationProvider.java │ │ ├── JWTAuthenticationFilter.java │ │ └── JWTLoginFilter.java │ │ ├── model │ │ ├── OpcDataType.java │ │ ├── OpcEntity.java │ │ └── FieldAndItem.java │ │ ├── StartProgram.java │ │ ├── config │ │ ├── ExecutorConfig.java │ │ ├── SchedulingConfig.java │ │ ├── JwtSettings.java │ │ ├── AppConfig.java │ │ ├── SwaggerConfig.java │ │ ├── WebSecurityConfig.java │ │ └── WebServerConfig.java │ │ ├── util │ │ └── OpcClient.java │ │ └── controller │ │ └── OpcClientControl.java │ └── resources │ ├── application.yml │ └── logback.xml ├── .gitignore ├── pom.xml └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | # OpcClient 2 | OpcClient Java Demo 3 | -------------------------------------------------------------------------------- /src/test/java/com/opc/client/UATest.java: -------------------------------------------------------------------------------- 1 | package com.opc.client; 2 | 3 | public class UATest { 4 | } 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .project 2 | .classpath 3 | .settings/ 4 | log/ 5 | .DS_Store 6 | *.iml 7 | *.db 8 | .idea/ 9 | logs/ 10 | target/ -------------------------------------------------------------------------------- /src/main/java/com/opc/client/security/TokenException.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.security; 2 | 3 | public class TokenException extends BaseException { 4 | 5 | private static final long serialVersionUID = 1L; 6 | 7 | public TokenException(String message) { 8 | super(message); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/model/OpcDataType.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.model; 2 | 3 | /** 4 | * OpcServer变量类型 5 | * 6 | * @author 刘源 7 | */ 8 | public enum OpcDataType { 9 | Boolean, 10 | String, 11 | Date, 12 | Char, 13 | Int, 14 | Double, 15 | Long, 16 | Float, 17 | Short; 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/security/BaseException.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.security; 2 | 3 | 4 | public class BaseException extends RuntimeException { 5 | 6 | public BaseException(String message) { 7 | super(message); 8 | } 9 | 10 | public BaseException(String message, Throwable cause) { 11 | super(message, cause); 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/StartProgram.java: -------------------------------------------------------------------------------- 1 | package com.opc.client; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | 7 | @SpringBootApplication 8 | public class StartProgram { 9 | 10 | public static void main(String[] args) { 11 | SpringApplication.run(StartProgram.class, args); 12 | } 13 | 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/security/User.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.security; 2 | 3 | public class User { 4 | private String username; 5 | private String password; 6 | 7 | public String getUsername() { 8 | return username; 9 | } 10 | 11 | public void setUsername(String username) { 12 | this.username = username; 13 | } 14 | 15 | public String getPassword() { 16 | return password; 17 | } 18 | 19 | public void setPassword(String password) { 20 | this.password = password; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | app-config: 2 | host: 192.168.141.176 3 | progId: KingView.View.1 4 | user: Administrator 5 | password: 123456 6 | #PLC编号映射 7 | plcNumberDictionary: 8 | 6010403001: 111 9 | 6010403002: 112 10 | 6010403003: 113 11 | 6010403004: 114 12 | 6010402001: 115 13 | 14 | 15 | server: 16 | # WebServer bind port 17 | port: 9011 18 | tomcat: 19 | uri-encoding: UTF-8 20 | spring: 21 | http: 22 | encoding: 23 | charset: UTF-8 24 | enabled: true 25 | force: true 26 | security: 27 | jwt: 28 | login: 29 | username: OpcAdmin 30 | password: SummitOpcAdmin 31 | token: 32 | secret-key: secret-key 33 | #单位小时 34 | expire-length: 24 35 | 36 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/security/Role.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.security; 2 | 3 | import org.springframework.security.core.GrantedAuthority; 4 | 5 | /** 6 | * 用户角色种类 7 | * 8 | * @author Administrator 9 | */ 10 | public enum Role implements GrantedAuthority { 11 | /** 12 | * 管理员 13 | */ 14 | ROLE_ADMIN, 15 | /** 16 | * 游客 17 | */ 18 | ROLE_GUEST; 19 | 20 | public static Role findRoleByName(String roleName) { 21 | for (Role role : values()) { 22 | if (role.name().equals(roleName)) { 23 | return role; 24 | } 25 | } 26 | return null; 27 | } 28 | 29 | @Override 30 | public String getAuthority() { 31 | return name(); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/model/OpcEntity.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.model; 2 | 3 | public class OpcEntity { 4 | private String timestamp; 5 | private FieldAndItem fieldAndItem; 6 | private Object value; 7 | 8 | public OpcEntity(String timestamp, FieldAndItem fieldAndItem, Object value) { 9 | this.timestamp = timestamp; 10 | this.fieldAndItem = fieldAndItem; 11 | this.value = value; 12 | } 13 | 14 | public String getTimestamp() { 15 | return timestamp; 16 | } 17 | 18 | public void setTimestamp(String timestamp) { 19 | this.timestamp = timestamp; 20 | } 21 | 22 | public FieldAndItem getFieldAndItem() { 23 | return fieldAndItem; 24 | } 25 | 26 | public void setFieldAndItem(FieldAndItem fieldAndItem) { 27 | this.fieldAndItem = fieldAndItem; 28 | } 29 | 30 | public Object getValue() { 31 | return value; 32 | } 33 | 34 | public void setValue(Object value) { 35 | this.value = value; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/config/ExecutorConfig.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.config; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; 8 | import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; 9 | 10 | 11 | @Configuration 12 | public class ExecutorConfig { 13 | private static final Logger LOGGER = LoggerFactory 14 | .getLogger(ExecutorConfig.class); 15 | 16 | 17 | 18 | @Bean(name = "taskScheduler") 19 | public ThreadPoolTaskScheduler taskScheduler() { 20 | ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); 21 | scheduler.setPoolSize(10); 22 | scheduler.setDaemon(true); 23 | scheduler.setThreadNamePrefix("taskScheduler-"); 24 | return scheduler; 25 | } 26 | 27 | @Bean(name = "taskExecutor") 28 | public ThreadPoolTaskExecutor taskExecutor() { 29 | ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); 30 | executor.setCorePoolSize(5); 31 | executor.setMaxPoolSize(10); 32 | executor.setQueueCapacity(10); 33 | executor.setDaemon(true); 34 | executor.setThreadNamePrefix("taskExecutor-"); 35 | return executor; 36 | } 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/config/SchedulingConfig.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.config; 2 | 3 | import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; 4 | import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; 5 | import org.springframework.scheduling.annotation.AsyncConfigurer; 6 | import org.springframework.scheduling.annotation.EnableAsync; 7 | import org.springframework.scheduling.annotation.EnableScheduling; 8 | import org.springframework.scheduling.annotation.SchedulingConfigurer; 9 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; 10 | import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; 11 | import org.springframework.scheduling.config.ScheduledTaskRegistrar; 12 | import org.springframework.stereotype.Component; 13 | 14 | import javax.annotation.Resource; 15 | import java.util.concurrent.Executor; 16 | 17 | @Component 18 | @EnableScheduling 19 | @EnableAsync 20 | public class SchedulingConfig implements SchedulingConfigurer, AsyncConfigurer { 21 | 22 | @Resource(name = "taskScheduler") 23 | ThreadPoolTaskScheduler taskScheduler; 24 | 25 | @Resource(name = "taskExecutor") 26 | ThreadPoolTaskExecutor taskExecutor; 27 | 28 | @Override 29 | public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { 30 | taskRegistrar.setScheduler(taskScheduler); 31 | } 32 | 33 | @Override 34 | public Executor getAsyncExecutor() { 35 | return taskExecutor; 36 | } 37 | 38 | @Override 39 | public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { 40 | return new SimpleAsyncUncaughtExceptionHandler(); 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/config/JwtSettings.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright © 2016-2018 The Thingsboard Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.opc.client.config; 17 | 18 | import org.springframework.beans.factory.annotation.Value; 19 | import org.springframework.stereotype.Component; 20 | 21 | @Component 22 | public class JwtSettings { 23 | 24 | @Value("${security.jwt.login.username}") 25 | private String username; 26 | @Value("${security.jwt.login.password}") 27 | private String password; 28 | @Value("${security.jwt.token.secret-key}") 29 | private String secretKey; 30 | @Value("${security.jwt.token.expire-length}") 31 | private int expireLength; 32 | 33 | public String getUsername() { 34 | return username; 35 | } 36 | 37 | public void setUsername(String username) { 38 | this.username = username; 39 | } 40 | 41 | public String getPassword() { 42 | return password; 43 | } 44 | 45 | public void setPassword(String password) { 46 | this.password = password; 47 | } 48 | 49 | public String getSecretKey() { 50 | return secretKey; 51 | } 52 | 53 | public void setSecretKey(String secretKey) { 54 | this.secretKey = secretKey; 55 | } 56 | 57 | public int getExpireLength() { 58 | return expireLength; 59 | } 60 | 61 | public void setExpireLength(int expireLength) { 62 | this.expireLength = expireLength; 63 | } 64 | } -------------------------------------------------------------------------------- /src/main/java/com/opc/client/config/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.config; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.stereotype.Component; 5 | 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | 9 | /** 10 | * 应用程序配置属性. 11 | */ 12 | @Component 13 | @ConfigurationProperties(prefix = "app-config") 14 | public class AppConfig { 15 | 16 | 17 | private String host; 18 | private String domain = ""; 19 | private String progId; 20 | private String user; 21 | private String password; 22 | /** 23 | * Key是PLC业务编码,Value是OpcServer对应的PLC编码 24 | */ 25 | private Map plcNumberDictionary = new HashMap(); 26 | private String [] plcNumbers; 27 | 28 | 29 | 30 | 31 | public String getHost() { 32 | return host; 33 | } 34 | 35 | public void setHost(String host) { 36 | this.host = host; 37 | } 38 | 39 | public String getDomain() { 40 | return domain; 41 | } 42 | 43 | public void setDomain(String domain) { 44 | this.domain = domain; 45 | } 46 | 47 | public String getProgId() { 48 | return progId; 49 | } 50 | 51 | public void setProgId(String progId) { 52 | this.progId = progId; 53 | } 54 | 55 | public String getUser() { 56 | return user; 57 | } 58 | 59 | public void setUser(String user) { 60 | this.user = user; 61 | } 62 | 63 | public String getPassword() { 64 | return password; 65 | } 66 | 67 | public void setPassword(String password) { 68 | this.password = password; 69 | } 70 | 71 | public Map getPlcNumberDictionary() { 72 | return plcNumberDictionary; 73 | } 74 | 75 | public void setPlcNumberDictionary(Map plcNumberDictionary) { 76 | this.plcNumberDictionary = plcNumberDictionary; 77 | this.plcNumbers=plcNumberDictionary.values().toArray(new String[0]); 78 | } 79 | 80 | public String[] getPlcNumbers() { 81 | return plcNumbers; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/security/UserDetailsServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.security; 2 | 3 | import com.opc.client.config.JwtSettings; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.security.core.GrantedAuthority; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | import org.springframework.security.core.userdetails.UserDetailsService; 8 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 9 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 10 | import org.springframework.stereotype.Component; 11 | 12 | import java.util.ArrayList; 13 | 14 | @Component 15 | public class UserDetailsServiceImpl implements UserDetailsService { 16 | 17 | @Autowired 18 | JwtSettings jwtSettings; 19 | 20 | @Autowired 21 | BCryptPasswordEncoder bCryptPasswordEncoder; 22 | 23 | @Override 24 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 25 | if (!jwtSettings.getUsername().equals(username)) { 26 | throw new UsernameNotFoundException("User '" + username + "' not found"); 27 | } 28 | String password = bCryptPasswordEncoder.encode(jwtSettings.getPassword()); 29 | //TODO:可以是其他获取用户信息的途径 30 | // final User user = userRepository.findByUsername(username); 31 | // if (user == null) { 32 | // throw new UsernameNotFoundException("User '" + username + "' not found"); 33 | // } 34 | 35 | // 这里设置权限和角色 36 | ArrayList authorities = new ArrayList<>(); 37 | authorities.add(Role.ROLE_ADMIN); 38 | authorities.add(Role.ROLE_GUEST); 39 | 40 | 41 | return org.springframework.security.core.userdetails.User 42 | .withUsername(username) 43 | .password(password) 44 | .authorities(authorities) 45 | .accountExpired(false) 46 | .accountLocked(false) 47 | .credentialsExpired(false) 48 | .disabled(false) 49 | .build(); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/model/FieldAndItem.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.model; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Opc变量名称. 8 | * 9 | * @author 刘源 10 | */ 11 | public enum FieldAndItem { 12 | voltmeter("电压表",OpcDataType.Float), 13 | ammeter("电流表",OpcDataType.Float), 14 | controlWord("控制字",OpcDataType.Int), 15 | setCacheValue("设定缓存值",OpcDataType.Int), 16 | warningTimeCache("预警时间缓存",OpcDataType.Int), 17 | opening("开度",OpcDataType.Int), 18 | load("荷重",OpcDataType.Int), 19 | load90("荷重九十",OpcDataType.Int), 20 | load110("荷重一百一",OpcDataType.Int), 21 | motorFailure("电机故障",OpcDataType.Int), 22 | upperLimit("上限",OpcDataType.Int), 23 | lowerLimit("下限",OpcDataType.Int), 24 | setting("设定",OpcDataType.Int), 25 | warning("预警",OpcDataType.Int); 26 | 27 | private String itemName; 28 | private OpcDataType opcDataType; 29 | 30 | FieldAndItem(String itemName,OpcDataType opcDataType) { 31 | this.itemName = itemName; 32 | this.opcDataType=opcDataType; 33 | } 34 | 35 | public static FieldAndItem[] getAllItems() { 36 | return values(); 37 | } 38 | 39 | /** 40 | * 获取指定编号的PLC对应的OpcServer的变量名 41 | * 42 | * @param plcNumber 43 | * @return 44 | */ 45 | public static Map getAllItemsByPlcNumber(String plcNumber) { 46 | MapallItemsName=new HashMap<>(); 47 | for (FieldAndItem item : values()) { 48 | allItemsName.put(item.getItemNameByPlcNumber(plcNumber),item); 49 | } 50 | return allItemsName; 51 | } 52 | 53 | /** 54 | * 获取所有PLC对应的OpcServer的变量名 55 | * 56 | * @param plcNumbers 57 | * @return 58 | */ 59 | public static Map getAllItemsByPlcNumbers(String[] plcNumbers) { 60 | Map allPlcItemsName = new HashMap<>(); 61 | for (String plcNumber : plcNumbers) { 62 | allPlcItemsName.putAll(getAllItemsByPlcNumber(plcNumber)); 63 | } 64 | return allPlcItemsName; 65 | } 66 | 67 | public String getItemName() { 68 | return this.itemName; 69 | } 70 | 71 | public String getItemNameByPlcNumber(String plcNumber) { 72 | return this.itemName + plcNumber + ".Value"; 73 | } 74 | 75 | public OpcDataType getOpcDataType() { 76 | return opcDataType; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/security/JWTAuthenticationProvider.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.security; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.authentication.AuthenticationProvider; 5 | import org.springframework.security.authentication.BadCredentialsException; 6 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 7 | import org.springframework.security.core.Authentication; 8 | import org.springframework.security.core.AuthenticationException; 9 | import org.springframework.security.core.userdetails.UserDetails; 10 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 11 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 12 | import org.springframework.stereotype.Component; 13 | 14 | @Component 15 | public class JWTAuthenticationProvider implements AuthenticationProvider { 16 | 17 | @Autowired 18 | UserDetailsServiceImpl userDetailsServiceImpl; 19 | @Autowired 20 | BCryptPasswordEncoder bCryptPasswordEncoder; 21 | 22 | /** 23 | * 认证逻辑 24 | * @param authentication 认证请求 25 | * @return 返回认证结果 26 | * @throws AuthenticationException 27 | */ 28 | @Override 29 | public Authentication authenticate(Authentication authentication) throws AuthenticationException { 30 | // 获取认证的用户名 & 密码 31 | String username = authentication.getName(); 32 | String password = authentication.getCredentials().toString(); 33 | // 通过用户名取出用户相关信息 34 | UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(username); 35 | if (null != userDetails) { 36 | //比对用户信息中的密码和登录时的密码 37 | if (bCryptPasswordEncoder.matches(password, userDetails.getPassword())) { 38 | // 生成令牌 这里令牌里面存入了:name,password,authorities, 当然你也可以放其他内容 39 | Authentication auth = new UsernamePasswordAuthenticationToken(username, null, userDetails.getAuthorities()); 40 | return auth; 41 | } else { 42 | throw new BadCredentialsException("密码错误"); 43 | } 44 | } else { 45 | throw new UsernameNotFoundException("用户不存在"); 46 | } 47 | } 48 | 49 | /** 50 | * 表示该认证实现类支持UsernamePasswordAuthenticationToken类型的token认证 51 | * @param authentication 52 | * @return 53 | */ 54 | @Override 55 | public boolean supports(Class authentication) { 56 | return authentication.equals(UsernamePasswordAuthenticationToken.class); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/config/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.config; 2 | 3 | 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import springfox.documentation.builders.ApiInfoBuilder; 7 | import springfox.documentation.builders.PathSelectors; 8 | import springfox.documentation.service.ApiInfo; 9 | import springfox.documentation.service.ApiKey; 10 | import springfox.documentation.service.AuthorizationScope; 11 | import springfox.documentation.service.Contact; 12 | import springfox.documentation.service.SecurityReference; 13 | import springfox.documentation.spi.DocumentationType; 14 | import springfox.documentation.spi.service.contexts.SecurityContext; 15 | import springfox.documentation.spring.web.plugins.Docket; 16 | 17 | import java.util.List; 18 | import java.util.function.Predicate; 19 | 20 | import static com.google.common.collect.Lists.newArrayList; 21 | import static springfox.documentation.builders.PathSelectors.regex; 22 | 23 | @Configuration 24 | public class SwaggerConfig { 25 | @Bean 26 | public Docket createRestApi() { 27 | 28 | return new Docket(DocumentationType.SWAGGER_2) 29 | .apiInfo(apiInfo()) 30 | .select() 31 | .paths(PathSelectors.regex("/error.*").negate()) 32 | .build() 33 | .securitySchemes(newArrayList(new ApiKey("Authorization", "Authorization", "header"))) 34 | .securityContexts(newArrayList(securityContexts())); 35 | } 36 | 37 | private List securityContexts() { 38 | return newArrayList( 39 | SecurityContext.builder() 40 | .securityReferences(defaultAuth()) 41 | .forPaths(securityPaths()) 42 | .build() 43 | ); 44 | } 45 | 46 | 47 | private List defaultAuth() { 48 | AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; 49 | authorizationScopes[0] = new AuthorizationScope("global", "accessEverything"); 50 | return newArrayList(new SecurityReference("Authorization", authorizationScopes)); 51 | } 52 | 53 | private Predicate securityPaths() { 54 | return regex("/api.*").and(regex("/login").negate()); 55 | } 56 | 57 | private ApiInfo apiInfo() { 58 | return new ApiInfoBuilder() 59 | .title("NandCloud Restful APIs") 60 | .description("接口说明与调试界面") 61 | .contact(new Contact("NandCloud.com", "", "")) 62 | .version("1.0") 63 | .build(); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | System.out 8 | 9 | %d-%c-%t-%5p: %m%n 10 | 11 | 12 | 13 | 14 | 16 | log/all.log 17 | true 18 | 19 | ALL 20 | 21 | 22 | log/all-%d{yyyy-MM-dd,aux}/all-%d{yyyy-MM-dd}.%i.zip 23 | 32MB 24 | 25 | 26 | utf-8 27 | %d-%c-%t-%5p: %m%n 28 | 29 | 30 | 32 | true 33 | log/error/error.log 34 | 35 | utf-8 36 | %d-%c-%t-%5p: %m%n 37 | 38 | 39 | ERROR 40 | 41 | 42 | log/error/error-%d{yyyy-MM-dd,aux}/error-%d{yyyy-MM-dd}.%i.zip 43 | 32MB 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.config; 2 | 3 | import com.opc.client.security.JWTAuthenticationFilter; 4 | import com.opc.client.security.JWTAuthenticationProvider; 5 | import com.opc.client.security.JWTLoginFilter; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.http.HttpMethod; 10 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 11 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 12 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 13 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 14 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 15 | import org.springframework.security.config.http.SessionCreationPolicy; 16 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 17 | import org.springframework.web.filter.CorsFilter; 18 | 19 | /** 20 | * SpringSecurity的配置 21 | * 22 | * @author Administrator 23 | */ 24 | @Configuration 25 | @EnableWebSecurity(debug = true) 26 | @EnableGlobalMethodSecurity(prePostEnabled = true) 27 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 28 | /** 29 | * 需要放行的URL 30 | */ 31 | private static final String[] AUTH_WHITELIST = { 32 | // -- register url 33 | 34 | // -- swagger ui 35 | "/v2/api-docs", 36 | "/swagger-resources/**", 37 | "/configuration/**", 38 | "/swagger-ui/**", 39 | "/webjars/**" 40 | }; 41 | 42 | 43 | @Autowired 44 | private JWTAuthenticationProvider jwtAuthenticationProvider; 45 | 46 | @Bean 47 | public BCryptPasswordEncoder bCryptPasswordEncoder() { 48 | return new BCryptPasswordEncoder(); 49 | } 50 | 51 | 52 | @Bean 53 | protected JWTLoginFilter buildJWTLoginFilter() throws Exception { 54 | JWTLoginFilter filter = new JWTLoginFilter(); 55 | filter.setAuthenticationManager(authenticationManagerBean()); 56 | return filter; 57 | } 58 | 59 | @Bean 60 | protected JWTAuthenticationFilter buildJWTAuthenticationFilter() throws Exception { 61 | return new JWTAuthenticationFilter(authenticationManagerBean()); 62 | } 63 | 64 | // 设置 HTTP 验证规则 65 | @Override 66 | protected void configure(HttpSecurity http) throws Exception { 67 | http.csrf().disable(); 68 | http.cors().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); 69 | http.authorizeRequests() 70 | .antMatchers(HttpMethod.OPTIONS).permitAll() 71 | .antMatchers(AUTH_WHITELIST).permitAll() 72 | .anyRequest() 73 | .authenticated() 74 | .and()// 所有请求需要身份认证 75 | .addFilterAfter(buildJWTAuthenticationFilter(), CorsFilter.class) 76 | .addFilterAfter(buildJWTLoginFilter(), JWTAuthenticationFilter.class); 77 | 78 | } 79 | 80 | // 该方法是登录的时候会进入 81 | @Override 82 | public void configure(AuthenticationManagerBuilder auth) throws Exception { 83 | // 使用自定义身份验证组件 84 | auth.authenticationProvider(jwtAuthenticationProvider); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/config/WebServerConfig.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.config; 2 | 3 | import org.apache.catalina.connector.Connector; 4 | import org.apache.coyote.http11.AbstractHttp11Protocol; 5 | import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer; 6 | import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; 7 | import org.springframework.boot.web.servlet.ServletRegistrationBean; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.http.converter.HttpMessageConverter; 11 | import org.springframework.http.converter.StringHttpMessageConverter; 12 | import org.springframework.web.servlet.DispatcherServlet; 13 | import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; 14 | import org.springframework.web.servlet.config.annotation.CorsRegistry; 15 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 16 | 17 | import java.nio.charset.Charset; 18 | import java.time.Duration; 19 | import java.util.List; 20 | 21 | @Configuration 22 | public class WebServerConfig { 23 | 24 | /** 25 | * tomcat配置 26 | */ 27 | @Bean 28 | public TomcatServletWebServerFactory servletContainer() { 29 | TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); 30 | factory.getSession().setTimeout(Duration.ofMinutes(10)); 31 | factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { 32 | @Override 33 | public void customize(Connector connector) { 34 | AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler(); 35 | httpProtocol.setCompression("on"); 36 | httpProtocol.setCompressibleMimeType("text/html,text/xml,text/plain,application/json,application/xml"); 37 | } 38 | }); 39 | return factory; 40 | } 41 | 42 | /** 43 | * 修改默认dispatcherServlet配置 44 | */ 45 | @Bean 46 | public ServletRegistrationBean servletRegistrationBean(DispatcherServlet dispatcherServlet) { 47 | ServletRegistrationBean registration = new ServletRegistrationBean<>(dispatcherServlet); 48 | registration.getUrlMappings().clear(); 49 | registration.addUrlMappings("/"); 50 | registration.setAsyncSupported(true); 51 | return registration; 52 | } 53 | 54 | @Bean 55 | public HttpMessageConverter responseBodyConverter() { 56 | StringHttpMessageConverter stringHttpMessageConverter=new StringHttpMessageConverter(Charset.forName("UTF-8")); 57 | stringHttpMessageConverter.setWriteAcceptCharset(false); 58 | return stringHttpMessageConverter; 59 | } 60 | 61 | /** 62 | * SpringMVC配置 63 | */ 64 | @Bean 65 | public WebMvcConfigurer corsConfigurer() { 66 | 67 | return new WebMvcConfigurer() { 68 | /** 69 | * 跨域配置 70 | */ 71 | @Override 72 | public void addCorsMappings(CorsRegistry registry) { 73 | registry.addMapping("/**") 74 | .allowCredentials(true) 75 | .allowedOrigins("*") 76 | .allowedMethods("*") 77 | .allowedHeaders("*") 78 | .exposedHeaders("Authorization") 79 | .maxAge(1800); 80 | } 81 | 82 | /** 83 | * 资源加载配置 84 | */ 85 | // @Override 86 | // public void addResourceHandlers(ResourceHandlerRegistry registry) { 87 | //// registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); 88 | // registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources" + 89 | // "/webjars/"); 90 | // } 91 | 92 | @Override 93 | public void configureMessageConverters(List> converters) { 94 | converters.add(responseBodyConverter()); 95 | } 96 | 97 | @Override 98 | public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { 99 | configurer.favorPathExtension(false); 100 | } 101 | }; 102 | } 103 | 104 | 105 | } 106 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/security/JWTAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.security; 2 | 3 | import com.fasterxml.jackson.databind.JsonNode; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.opc.client.config.JwtSettings; 6 | import io.jsonwebtoken.Claims; 7 | import io.jsonwebtoken.ExpiredJwtException; 8 | import io.jsonwebtoken.Jwts; 9 | import io.jsonwebtoken.MalformedJwtException; 10 | import io.jsonwebtoken.SignatureException; 11 | import io.jsonwebtoken.UnsupportedJwtException; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.security.authentication.AuthenticationManager; 16 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 17 | import org.springframework.security.core.GrantedAuthority; 18 | import org.springframework.security.core.context.SecurityContextHolder; 19 | import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; 20 | 21 | import javax.servlet.FilterChain; 22 | import javax.servlet.ServletException; 23 | import javax.servlet.http.HttpServletRequest; 24 | import javax.servlet.http.HttpServletResponse; 25 | import java.io.IOException; 26 | import java.util.ArrayList; 27 | 28 | /** 29 | * 自定义JWT认证过滤器 30 | * 该类继承自BasicAuthenticationFilter,在doFilterInternal方法中, 31 | * 从http头的Authorization 项读取token数据,然后用Jwts包提供的方法校验token的合法性。 32 | * 如果校验通过,就认为这是一个取得授权的合法请求 33 | * 34 | * @author Administrator 35 | */ 36 | public class JWTAuthenticationFilter extends BasicAuthenticationFilter { 37 | 38 | 39 | private static final Logger logger = LoggerFactory.getLogger(JWTAuthenticationFilter.class); 40 | @Autowired 41 | JwtSettings jwtSettings; 42 | 43 | private ObjectMapper objectMapper = new ObjectMapper(); 44 | 45 | public JWTAuthenticationFilter(AuthenticationManager authenticationManager) { 46 | super(authenticationManager); 47 | } 48 | 49 | @Override 50 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { 51 | String header = request.getHeader("Authorization"); 52 | if (header == null || !header.startsWith("Bearer ")) { 53 | chain.doFilter(request, response); 54 | return; 55 | } 56 | UsernamePasswordAuthenticationToken authentication = getAuthentication(request); 57 | SecurityContextHolder.getContext().setAuthentication(authentication); 58 | chain.doFilter(request, response); 59 | } 60 | 61 | private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) { 62 | long start = System.currentTimeMillis(); 63 | String token = request.getHeader("Authorization"); 64 | if (token == null || token.isEmpty()) { 65 | throw new TokenException("Token为空"); 66 | } 67 | // parse the token. 68 | String user = null; 69 | try { 70 | Claims claims = Jwts.parser() 71 | .setSigningKey(jwtSettings.getSecretKey()) 72 | .parseClaimsJws(token.replace("Bearer ", "")) 73 | .getBody(); 74 | //获取用户名 75 | user = claims.getSubject(); 76 | JsonNode jsonNode = objectMapper.readTree(claims.get("auth", String.class)); 77 | long end = System.currentTimeMillis(); 78 | logger.info("执行时间: {}", (end - start) + " 毫秒"); 79 | if (user != null) { 80 | ArrayList authorities = new ArrayList<>(); 81 | for (JsonNode name : jsonNode) { 82 | authorities.add(Role.findRoleByName(name.asText())); 83 | } 84 | return new UsernamePasswordAuthenticationToken(user, null, authorities); 85 | } 86 | 87 | } catch (ExpiredJwtException e) { 88 | logger.error("Token已过期: {} " + e); 89 | throw new TokenException("Token已过期"); 90 | } catch (UnsupportedJwtException | IOException e) { 91 | logger.error("Token格式错误: {} " + e); 92 | throw new TokenException("Token格式错误"); 93 | } catch (MalformedJwtException | SignatureException e) { 94 | logger.error("Token没有被正确构造: {} " + e); 95 | throw new TokenException("Token没有被正确构造"); 96 | } catch (IllegalArgumentException e) { 97 | logger.error("非法参数异常: {} " + e); 98 | throw new TokenException("非法参数异常"); 99 | } 100 | return null; 101 | } 102 | 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/security/JWTLoginFilter.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.security; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.fasterxml.jackson.databind.node.ArrayNode; 5 | import com.opc.client.config.JwtSettings; 6 | import io.jsonwebtoken.Claims; 7 | import io.jsonwebtoken.Jwts; 8 | import io.jsonwebtoken.SignatureAlgorithm; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 11 | import org.springframework.security.core.Authentication; 12 | import org.springframework.security.core.AuthenticationException; 13 | import org.springframework.security.core.GrantedAuthority; 14 | import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; 15 | import org.springframework.security.web.util.matcher.AntPathRequestMatcher; 16 | 17 | import javax.servlet.FilterChain; 18 | import javax.servlet.ServletException; 19 | import javax.servlet.ServletInputStream; 20 | import javax.servlet.http.HttpServletRequest; 21 | import javax.servlet.http.HttpServletResponse; 22 | import java.io.IOException; 23 | import java.io.PrintWriter; 24 | import java.util.ArrayList; 25 | import java.util.Calendar; 26 | import java.util.Collection; 27 | import java.util.Date; 28 | import java.util.regex.Matcher; 29 | import java.util.regex.Pattern; 30 | 31 | /** 32 | * 验证用户名密码正确后,生成一个token,并将token返回给客户端 33 | * AbstractAuthenticationProcessingFilter,重写了其中的2个方法 34 | * attemptAuthentication :接收并解析用户凭证。 35 | * successfulAuthentication :用户成功登录后,这个方法会被调用,我们在这个方法里生成token。 36 | * 37 | * @author Administrator 38 | */ 39 | public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter { 40 | private static final Pattern p = Pattern.compile("\\s*|\t|\r|\n"); 41 | 42 | @Autowired 43 | JwtSettings jwtSettings; 44 | private ObjectMapper objectMapper = new ObjectMapper(); 45 | 46 | 47 | public JWTLoginFilter() { 48 | super(new AntPathRequestMatcher("/login", "POST")); 49 | } 50 | 51 | /** 52 | * 接收并解析用户凭证 53 | * 54 | * @param req 55 | * @param res 56 | * @return 57 | * @throws AuthenticationException 58 | */ 59 | @Override 60 | public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException { 61 | try { 62 | int len = req.getContentLength(); 63 | ServletInputStream inputStream = req.getInputStream(); 64 | byte[] buffer = new byte[len]; 65 | inputStream.read(buffer, 0, len); 66 | String body = new String(buffer); 67 | Matcher m = p.matcher(body); 68 | body = m.replaceAll(""); 69 | 70 | User user = new ObjectMapper().readValue(body, User.class); 71 | //封装认证请求 72 | UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( 73 | user.getUsername(), 74 | user.getPassword(), 75 | new ArrayList<>()); 76 | // Allow subclasses to set the "details" property 77 | setDetails(req, authRequest); 78 | return this.getAuthenticationManager().authenticate(authRequest); 79 | } catch (Exception e) { 80 | throw new RuntimeException(e); 81 | } 82 | } 83 | 84 | /** 85 | * 用户成功登录后,这个方法会被调用,我们在这个方法里生成token 86 | * 87 | * @param request 88 | * @param response 89 | * @param chain 90 | * @param auth 91 | * @throws IOException 92 | * @throws ServletException 93 | */ 94 | @Override 95 | protected void successfulAuthentication(HttpServletRequest request, 96 | HttpServletResponse response, 97 | FilterChain chain, 98 | Authentication auth) throws IOException, ServletException { 99 | try { 100 | Collection authorities = auth.getAuthorities(); 101 | // 定义存放角色集合的对象 102 | ArrayNode arrayNode = objectMapper.createArrayNode(); 103 | for (GrantedAuthority grantedAuthority : authorities) { 104 | arrayNode.add(grantedAuthority.getAuthority()); 105 | } 106 | // 设置过期时间 107 | Calendar calendar = Calendar.getInstance(); 108 | calendar.add(Calendar.HOUR_OF_DAY, jwtSettings.getExpireLength()); 109 | Date time = calendar.getTime(); 110 | //获取用户名称 111 | Claims claims = Jwts.claims().setSubject(auth.getName()); 112 | claims.put("auth", arrayNode.toString()); 113 | String token = Jwts.builder() 114 | .setClaims(claims) 115 | .setExpiration(time) // 设置过期时间 116 | .signWith(SignatureAlgorithm.HS512, jwtSettings.getSecretKey()) 117 | .compact(); 118 | // 登录成功后,返回token到header里面 119 | response.addHeader("Authorization", "Bearer " + token); 120 | response.setCharacterEncoding("UTF-8"); 121 | response.setContentType("application/json; charset=utf-8"); 122 | PrintWriter printWriter = response.getWriter(); 123 | printWriter.write("{\"status\":\"success\"}"); 124 | printWriter.close(); 125 | } catch (Exception e) { 126 | e.printStackTrace(); 127 | } 128 | } 129 | 130 | /** 131 | * Provided so that subclasses may configure what is put into the authentication 132 | * request's details property. 133 | * 134 | * @param request that an authentication request is being created for 135 | * @param authRequest the authentication request object that should have its details 136 | * set 137 | */ 138 | private void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) { 139 | authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); 140 | } 141 | 142 | } 143 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/util/OpcClient.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.util; 2 | 3 | 4 | import com.opc.client.config.AppConfig; 5 | import com.opc.client.model.FieldAndItem; 6 | import com.opc.client.model.OpcDataType; 7 | import com.opc.client.model.OpcEntity; 8 | import org.jinterop.dcom.core.JIVariant; 9 | import org.joda.time.DateTime; 10 | import org.joda.time.format.DateTimeFormat; 11 | import org.joda.time.format.DateTimeFormatter; 12 | import org.openscada.opc.dcom.list.ClassDetails; 13 | import org.openscada.opc.lib.common.ConnectionInformation; 14 | import org.openscada.opc.lib.da.Group; 15 | import org.openscada.opc.lib.da.Item; 16 | import org.openscada.opc.lib.da.ItemState; 17 | import org.openscada.opc.lib.da.Server; 18 | import org.openscada.opc.lib.list.Categories; 19 | import org.openscada.opc.lib.list.Category; 20 | import org.openscada.opc.lib.list.ServerList; 21 | import org.slf4j.Logger; 22 | import org.slf4j.LoggerFactory; 23 | import org.springframework.beans.factory.annotation.Autowired; 24 | import org.springframework.scheduling.annotation.Scheduled; 25 | import org.springframework.stereotype.Component; 26 | 27 | import javax.annotation.PostConstruct; 28 | import javax.annotation.PreDestroy; 29 | import java.util.ArrayList; 30 | import java.util.Collection; 31 | import java.util.HashMap; 32 | import java.util.List; 33 | import java.util.Map; 34 | import java.util.Set; 35 | import java.util.concurrent.Executors; 36 | import java.util.concurrent.ScheduledExecutorService; 37 | 38 | @Component 39 | public class OpcClient { 40 | public static final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); 41 | @Autowired 42 | AppConfig appConfig; 43 | private Server server; 44 | private Logger LOGGER = LoggerFactory.getLogger(OpcClient.class); 45 | private volatile boolean isConnect = false; 46 | private Group group; 47 | private Map itemMap; 48 | 49 | @PostConstruct 50 | public void init() { 51 | try { 52 | ServerList serverList = new ServerList(appConfig.getHost(), appConfig.getUser(), appConfig.getPassword(), 53 | appConfig.getDomain()); 54 | final Collection detailsList = 55 | serverList.listServersWithDetails(new Category[]{Categories.OPCDAServer20}, new Category[]{}); 56 | for (final ClassDetails details : detailsList) { 57 | LOGGER.debug("ProgID:{}", details.getProgId()); 58 | LOGGER.debug("ClsId:{}", details.getClsId()); 59 | LOGGER.debug("Description:{}", details.getDescription()); 60 | } 61 | ConnectionInformation ci = new ConnectionInformation(); 62 | ci.setHost(appConfig.getHost()); 63 | ci.setClsid(serverList.getClsIdFromProgId(appConfig.getProgId())); 64 | ci.setUser(appConfig.getUser()); 65 | ci.setPassword(appConfig.getPassword()); 66 | ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); 67 | server = new Server(ci, exec); 68 | } catch (Exception e) { 69 | LOGGER.error("OpcServer客户端初始化错误", e); 70 | } 71 | } 72 | 73 | @Scheduled(fixedDelay = 2000) 74 | public void reconnectHandlerTaskExecutor() { 75 | try { 76 | if (!isConnect) { 77 | connect(); 78 | } 79 | Map> allPlcItemValues = getAllPlcItemValues(); 80 | printAllPlcItemLog(allPlcItemValues); 81 | } catch (Exception e) { 82 | LOGGER.error("OpcServer连接错误,尝试重新连接", e); 83 | isConnect = false; 84 | if (server != null) { 85 | server.disconnect(); 86 | } 87 | } 88 | } 89 | 90 | 91 | private void connect() throws Exception { 92 | if (server != null) { 93 | server.disconnect(); 94 | } 95 | if (group != null) { 96 | group.clear(); 97 | group.remove(); 98 | } 99 | server.connect(); 100 | group = server.addGroup(); 101 | Map allPlcItemsName = FieldAndItem.getAllItemsByPlcNumbers(appConfig.getPlcNumbers()); 102 | String[] itemNames = allPlcItemsName.keySet().toArray(new String[0]); 103 | itemMap = group.addItems(itemNames); 104 | isConnect = true; 105 | } 106 | 107 | 108 | public Map> getAllPlcItemValues() { 109 | Map> allPlcItemValues = new HashMap<>(); 110 | String[] plcNumbers = appConfig.getPlcNumbers(); 111 | for (String plcNumber : plcNumbers) { 112 | List plcItemValues = getPlcItemValuesByPlcNumber(plcNumber); 113 | allPlcItemValues.put(plcNumber, plcItemValues); 114 | } 115 | return allPlcItemValues; 116 | } 117 | 118 | 119 | public List getPlcItemValuesByPlcNumber(String plcNumber) { 120 | List plcItemValues = new ArrayList<>(); 121 | try { 122 | Set> plcItemNames = 123 | FieldAndItem.getAllItemsByPlcNumber(plcNumber).entrySet(); 124 | for (Map.Entry item : plcItemNames) { 125 | ItemState state = itemMap.get(item.getKey()).read(true); 126 | String timestamp = formatter.print(new DateTime(state.getTimestamp().getTime())); 127 | Object value = state.getValue().getObject(); 128 | plcItemValues.add(new OpcEntity(timestamp, item.getValue(), value)); 129 | } 130 | } catch (Exception e) { 131 | LOGGER.error("获取变量数据出错", e); 132 | isConnect = false; 133 | } 134 | return plcItemValues; 135 | } 136 | 137 | private void printAllPlcItemLog(Map> allPlcItemValues) { 138 | 139 | for (Map.Entry> plcItemValue : allPlcItemValues.entrySet()) { 140 | String plcNumber = plcItemValue.getKey(); 141 | List plcItem = plcItemValue.getValue(); 142 | for (OpcEntity entity : plcItem) { 143 | OpcDataType opcDataType = entity.getFieldAndItem().getOpcDataType(); 144 | switch (opcDataType) { 145 | case Short: 146 | case Int: 147 | int valueInt = (Integer) entity.getValue(); 148 | LOGGER.debug("PLC编号:{} 获取时间:{} 变量名:{} 变量值:{}", plcNumber, entity.getTimestamp(), 149 | entity.getFieldAndItem().getItemName(), valueInt); 150 | break; 151 | case Float: 152 | float valueFloat = (Float) entity.getValue(); 153 | LOGGER.debug("PLC编号:{} 获取时间:{} 变量名:{} 变量值:{}", plcNumber, entity.getTimestamp(), 154 | entity.getFieldAndItem().getItemName(), valueFloat); 155 | break; 156 | default: 157 | break; 158 | } 159 | } 160 | } 161 | } 162 | 163 | public void setItemValue(FieldAndItem fieldAndItem, String plcNumber, String value) { 164 | try { 165 | String itemName = fieldAndItem.getItemNameByPlcNumber(plcNumber); 166 | Item item = itemMap.get(itemName); 167 | JIVariant itemValue; 168 | switch (fieldAndItem.getOpcDataType()) { 169 | case Short: 170 | itemValue = new JIVariant(Short.valueOf(value)); 171 | break; 172 | case Int: 173 | itemValue = new JIVariant(Integer.valueOf(value)); 174 | break; 175 | default: 176 | itemValue = new JIVariant(""); 177 | break; 178 | } 179 | item.write(itemValue); 180 | } catch (Exception e) { 181 | LOGGER.error("OpcServe写入Item错误,尝试重新连接", e); 182 | isConnect = false; 183 | if (server != null) { 184 | server.disconnect(); 185 | } 186 | } 187 | } 188 | 189 | public Object getItemValue(FieldAndItem fieldAndItem, String plcNumber) { 190 | try { 191 | String itemName = fieldAndItem.getItemNameByPlcNumber(plcNumber); 192 | ItemState state = itemMap.get(itemName).read(true); 193 | return state.getValue().getObject(); 194 | } catch (Exception e) { 195 | LOGGER.error("OpcServe读取Item错误,尝试重新连接", e); 196 | isConnect = false; 197 | if (server != null) { 198 | server.disconnect(); 199 | } 200 | } 201 | return null; 202 | } 203 | 204 | @PreDestroy 205 | public void destroy() { 206 | if (server != null) { 207 | server.disconnect(); 208 | } 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 4.0.0 6 | 7 | OpcClient 8 | org.opc.client 9 | 1.0 10 | jar 11 | 12 | 13 | org.springframework.boot 14 | spring-boot-dependencies 15 | 2.3.2.RELEASE 16 | 17 | 18 | OpcClient 19 | 20 | UTF-8 21 | UTF-8 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | org.openscada.utgard 31 | org.openscada.opc.lib 32 | 1.5.0 33 | 34 | 35 | org.bouncycastle 36 | bcprov-jdk15on 37 | 1.59 38 | 39 | 40 | org.bouncycastle 41 | bcpkix-jdk15on 42 | 1.59 43 | 44 | 45 | org.eclipse.milo 46 | sdk-client 47 | 0.4.2 48 | 49 | 50 | 51 | 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-starter-web 56 | 57 | 58 | 59 | org.springframework.boot 60 | spring-boot-starter-security 61 | 62 | 63 | 64 | org.springframework.security 65 | spring-security-test 66 | test 67 | 68 | 69 | 70 | org.springframework.boot 71 | spring-boot-starter-test 72 | 73 | 74 | commons-logging 75 | commons-logging 76 | 77 | 78 | 79 | 80 | 81 | org.springframework.boot 82 | spring-boot-configuration-processor 83 | 84 | 85 | 86 | org.jadira.usertype 87 | usertype.core 88 | 6.0.1.GA 89 | 90 | 91 | io.springfox 92 | springfox-boot-starter 93 | 3.0.0 94 | 95 | 96 | 97 | 98 | org.springframework.boot 99 | spring-boot-devtools 100 | 101 | 102 | 103 | joda-time 104 | joda-time 105 | 2.10.6 106 | 107 | 108 | 109 | 110 | com.fasterxml.jackson.jaxrs 111 | jackson-jaxrs-json-provider 112 | 113 | 114 | com.fasterxml.jackson.datatype 115 | jackson-datatype-joda 116 | 117 | 118 | 119 | 120 | org.javassist 121 | javassist 122 | 3.22.0-GA 123 | 124 | 125 | 126 | 127 | net.logstash.logback 128 | logstash-logback-encoder 129 | 4.7 130 | 131 | 132 | 133 | io.jsonwebtoken 134 | jjwt 135 | 0.9.1 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | src/main/resources 145 | 146 | 147 | 148 | 149 | org.springframework.boot 150 | spring-boot-maven-plugin 151 | 152 | 153 | org.apache.maven.plugins 154 | maven-resources-plugin 155 | 2.4 156 | 157 | 158 | copy-resources 159 | package 160 | 161 | copy-resources 162 | 163 | 164 | UTF-8 165 | ${project.build.directory}/config 166 | 167 | 168 | 169 | src/main/resources 170 | 171 | logback.xml 172 | *.properties 173 | *.yml 174 | db/*.sql 175 | 176 | true 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | org.apache.maven.plugins 186 | maven-dependency-plugin 187 | 2.7 188 | 189 | 190 | copy-dependencies 191 | package 192 | 193 | copy-dependencies 194 | 195 | 196 | ${project.build.directory}/lib 197 | false 198 | false 199 | true 200 | 201 | 202 | 203 | 204 | 205 | org.apache.maven.plugins 206 | maven-jar-plugin 207 | 2.4 208 | 209 | 210 | 211 | true 212 | com.opc.client.StartProgram 213 | lib/ 214 | 215 | 216 | config/ 217 | 218 | 219 | 220 | 221 | *.properties 222 | *.yml 223 | logback.xml 224 | db/ 225 | 226 | 227 | 228 | 229 | 230 | org.apache.maven.plugins 231 | maven-surefire-plugin 232 | 2.18.1 233 | 234 | true 235 | 236 | 237 | 238 | org.apache.maven.plugins 239 | maven-compiler-plugin 240 | 3.7.0 241 | 242 | 1.8 243 | 1.8 244 | UTF-8 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | jitpack.io 253 | https://jitpack.io 254 | 255 | 256 | 257 | -------------------------------------------------------------------------------- /src/test/java/com/opc/client/DcomTest.java: -------------------------------------------------------------------------------- 1 | package com.opc.client; 2 | 3 | import com.fasterxml.jackson.databind.JsonNode; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.fasterxml.jackson.databind.node.ArrayNode; 6 | import com.fasterxml.jackson.databind.node.ObjectNode; 7 | import com.opc.client.config.AppConfig; 8 | import com.opc.client.model.FieldAndItem; 9 | import org.jinterop.dcom.core.JIVariant; 10 | import org.joda.time.DateTime; 11 | import org.joda.time.format.DateTimeFormat; 12 | import org.joda.time.format.DateTimeFormatter; 13 | import org.junit.Test; 14 | import org.openscada.opc.lib.common.ConnectionInformation; 15 | import org.openscada.opc.lib.da.AccessBase; 16 | import org.openscada.opc.lib.da.Async20Access; 17 | import org.openscada.opc.lib.da.AutoReconnectController; 18 | import org.openscada.opc.lib.da.DataCallback; 19 | import org.openscada.opc.lib.da.Group; 20 | import org.openscada.opc.lib.da.Item; 21 | import org.openscada.opc.lib.da.ItemState; 22 | import org.openscada.opc.lib.da.Server; 23 | import org.openscada.opc.lib.list.ServerList; 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | import sun.security.util.BitArray; 27 | 28 | import java.io.IOException; 29 | import java.nio.ByteBuffer; 30 | import java.text.SimpleDateFormat; 31 | import java.util.Date; 32 | import java.util.HashMap; 33 | import java.util.Map; 34 | import java.util.Random; 35 | import java.util.concurrent.CountDownLatch; 36 | import java.util.concurrent.Executors; 37 | import java.util.concurrent.ScheduledExecutorService; 38 | 39 | // 40 | //@RunWith(SpringRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持! 41 | //@SpringBootTest(classes = StartProgram.class) 42 | public class DcomTest { 43 | private static String host = "192.168.141.176"; 44 | private static String domain = ""; 45 | private static String progId = "KingView.View.1"; 46 | private static String user = "Administrator"; 47 | private static String password = "123456"; 48 | SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 49 | String itemName = "channel1.device1.控制字1"; 50 | String item2 = "channelone.device1.tag3"; 51 | String item3 = "channelone.device1.tag4"; 52 | // KingView.View.1 53 | //Kepware.KEPServerEX.V6 54 | 55 | String item5 = "开度111.Value"; 56 | String item6 = "channelone.device1.Value"; 57 | // @Autowired 58 | AppConfig appConfig; 59 | private Logger LOGGER = LoggerFactory.getLogger(DcomTest.class); 60 | private ServerList serverList; 61 | private ConnectionInformation ci; 62 | 63 | // @Before 64 | // public void getOpcServerList() throws Exception { 65 | // serverList = new ServerList(host, user, password, domain); 66 | // final Collection detailsList = 67 | // serverList.listServersWithDetails(new Category[]{Categories.OPCDAServer20}, new Category[]{}); 68 | // for (final ClassDetails details : detailsList) { 69 | // LOGGER.debug("ProgID:{}", details.getProgId()); 70 | // LOGGER.debug("ClsId:{}", details.getClsId()); 71 | // LOGGER.debug("Description:{}", details.getDescription()); 72 | // } 73 | // ci = new ConnectionInformation(); 74 | // ci.setHost(host); 75 | // ci.setClsid(serverList.getClsIdFromProgId(progId)); 76 | // ci.setUser(user); 77 | // ci.setPassword(password); 78 | // } 79 | 80 | @Test 81 | public void syncReadOpcItem() { 82 | ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); 83 | Server server = new Server(ci, exec); 84 | 85 | try { 86 | server.connect(); 87 | 88 | Group group = server.addGroup(); 89 | Item item = group.addItem(item5); 90 | while (true) { 91 | ItemState state = item.read(true); 92 | Thread.sleep(2000); 93 | LOGGER.debug("获取时间:{} 标签值:{}", df.format(state.getTimestamp().getTime()), 94 | state.getValue().getObjectAsInt()); 95 | } 96 | } catch (Exception e) { 97 | LOGGER.error("连接异常", e); 98 | } 99 | } 100 | 101 | @Test 102 | public void asyncReadOpcItem() throws Exception { 103 | ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); 104 | Server server = new Server(ci, exec); 105 | AutoReconnectController controller = new AutoReconnectController(server); 106 | controller.connect(); 107 | /** 108 | * 其中100单位为毫秒,为每次从OPC获取刷新的间隔时间 109 | */ 110 | AccessBase access = new Async20Access(server, 1000, false); 111 | 112 | /** 113 | * 只有Item的值有变化的时候才会触发CallBack函数 114 | */ 115 | access.addItem(item5, new DataCallback() { 116 | public void changed(Item item, ItemState itemstate) { 117 | try { 118 | LOGGER.debug("获取时间:{} 标签值:{}", df.format(itemstate.getTimestamp().getTime()), 119 | itemstate.getValue().getObjectAsInt()); 120 | } catch (Exception e) { 121 | LOGGER.error("数据获取失败", e); 122 | } 123 | } 124 | }); 125 | /** 开始监听 */ 126 | access.bind(); 127 | 128 | CountDownLatch countDownLatch = new CountDownLatch(1); 129 | try { 130 | countDownLatch.await(); 131 | } catch (InterruptedException e) { 132 | LOGGER.error("系统异常", e); 133 | } 134 | /** 监听 结束 */ 135 | access.unbind(); 136 | 137 | controller.disconnect(); 138 | } 139 | 140 | 141 | @Test 142 | public void syncWriteAndAsyncReadOpcItem() throws Exception { 143 | ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); 144 | Server server = new Server(ci, exec); 145 | AutoReconnectController controller = new AutoReconnectController(server); 146 | controller.connect(); 147 | 148 | /** 149 | * 其中100单位为毫秒,为每次从OPC获取刷新的间隔时间 150 | */ 151 | AccessBase access = new Async20Access(server, 1000, false); 152 | 153 | /** 154 | * 只有Item的值有变化的时候才会触发CallBack函数 155 | */ 156 | access.addItem(item5, new DataCallback() { 157 | public void changed(Item item, ItemState itemstate) { 158 | try { 159 | LOGGER.debug("获取时间:{} 标签值:{}", df.format(itemstate.getTimestamp().getTime()), 160 | itemstate.getValue().getObjectAsInt()); 161 | } catch (Exception e) { 162 | LOGGER.error("数据获取失败", e); 163 | } 164 | } 165 | }); 166 | /** 开始监听 */ 167 | access.bind(); 168 | 169 | Group group = server.addGroup(); 170 | Item item = group.addItem(item5); 171 | 172 | while (true) { 173 | Thread.sleep(2000); 174 | JIVariant value = new JIVariant((short) new Random().nextInt(Short.MAX_VALUE + 1)); 175 | item.write(value); 176 | } 177 | } 178 | 179 | @Test 180 | public void syncWriteOpcItem() throws Exception { 181 | ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); 182 | Server server = new Server(ci, exec); 183 | try { 184 | server.connect(); 185 | Group group = server.addGroup(); 186 | Item item = group.addItem(item5); 187 | JIVariant value = new JIVariant(255); 188 | item.write(value); 189 | } catch (Exception e) { 190 | LOGGER.error("连接异常", e); 191 | } 192 | } 193 | 194 | @Test 195 | public void test1() { 196 | 197 | String[] arrayStr = appConfig.getPlcNumberDictionary().values().toArray(new String[0]); 198 | 199 | 200 | String[] itemName = FieldAndItem.getAllItemsByPlcNumbers(arrayStr).keySet().toArray(new String[0]); 201 | 202 | for (String s : itemName) { 203 | System.out.println(s); 204 | 205 | } 206 | 207 | } 208 | 209 | @Test 210 | public void test2() throws Exception { 211 | ObjectMapper objectMapper = new ObjectMapper(); 212 | ArrayNode arrayNode = objectMapper.createArrayNode(); 213 | ObjectNode objectNode = objectMapper.createObjectNode(); 214 | objectNode.put("哈哈", "嘿嘿"); 215 | ObjectNode objectNode1 = objectMapper.createObjectNode(); 216 | objectNode1.put("哈哈", "刘源"); 217 | arrayNode.add(objectNode); 218 | arrayNode.add(objectNode1); 219 | String jsonStr = objectMapper.writeValueAsString(arrayNode); 220 | System.out.println(jsonStr); 221 | ArrayNode arrayNode1 = (ArrayNode) objectMapper.readTree(jsonStr); 222 | for (JsonNode haha : arrayNode1) { 223 | System.out.println(haha.get("哈哈").asText()); 224 | } 225 | } 226 | 227 | @Test 228 | public void test3() { 229 | DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); 230 | System.out.println(formatter.print(new DateTime(new Date()))); 231 | 232 | 233 | System.out.println(new DateTime(new Date()).toString("yyyy-MM-dd HH:mm:ss")); 234 | 235 | } 236 | 237 | @Test 238 | public void test4() { 239 | HashMap haha = new HashMap<>(); 240 | haha.put("haha", FieldAndItem.setCacheValue); 241 | haha.put("heihei", FieldAndItem.lowerLimit); 242 | 243 | HashMap heihei = new HashMap<>(); 244 | heihei.put("liuyuan", FieldAndItem.controlWord); 245 | heihei.put("nicai", FieldAndItem.ammeter); 246 | haha.putAll(heihei); 247 | 248 | for (Map.Entry entity : haha.entrySet()) { 249 | 250 | System.out.println(entity.getKey()); 251 | System.out.println(entity.getValue().getItemName()); 252 | 253 | } 254 | } 255 | 256 | @Test 257 | public void test5() { 258 | byte[] intArray = ByteBuffer.allocate(4).putInt(5).array(); 259 | BitArray bitArray = new BitArray(intArray.length * 8, intArray); 260 | for (int i = 0; i < bitArray.length(); i++) { 261 | System.out.println(bitArray.get(bitArray.length() - 1 - i)); 262 | 263 | } 264 | 265 | 266 | } 267 | 268 | @Test 269 | public void test6() { 270 | 271 | byte[] intArray = ByteBuffer.allocate(4).putInt(1).array(); 272 | BitArray bitArray = new BitArray(intArray.length * 8, intArray); 273 | bitArray.set(bitArray.length() - 1 - 1, true); 274 | System.out.println(ByteBuffer.wrap(bitArray.toByteArray()).getInt()); 275 | } 276 | 277 | @Test 278 | public void test7() throws IOException { 279 | ObjectMapper objectMapper = new ObjectMapper(); 280 | ArrayNode arrayNode = objectMapper.createArrayNode(); 281 | 282 | arrayNode.add("哈哈"); 283 | arrayNode.add("嘿嘿"); 284 | 285 | System.out.println(arrayNode.toString()); 286 | 287 | JsonNode haha = objectMapper.readTree(arrayNode.toString()); 288 | for (JsonNode heihei :haha) { 289 | System.out.println(heihei.asText()); 290 | 291 | } 292 | 293 | } 294 | 295 | } 296 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/main/java/com/opc/client/controller/OpcClientControl.java: -------------------------------------------------------------------------------- 1 | package com.opc.client.controller; 2 | 3 | 4 | import com.fasterxml.jackson.core.JsonProcessingException; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import com.fasterxml.jackson.databind.node.ObjectNode; 7 | import com.opc.client.config.AppConfig; 8 | import com.opc.client.model.FieldAndItem; 9 | import com.opc.client.model.OpcEntity; 10 | import com.opc.client.util.OpcClient; 11 | import io.swagger.annotations.Api; 12 | import io.swagger.annotations.ApiOperation; 13 | import org.joda.time.DateTime; 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.security.access.prepost.PreAuthorize; 18 | import org.springframework.web.bind.annotation.PathVariable; 19 | import org.springframework.web.bind.annotation.RequestMapping; 20 | import org.springframework.web.bind.annotation.RequestMethod; 21 | import org.springframework.web.bind.annotation.RequestParam; 22 | import org.springframework.web.bind.annotation.RestController; 23 | import sun.security.util.BitArray; 24 | 25 | import java.nio.ByteBuffer; 26 | import java.util.List; 27 | 28 | @Api(tags = "PlcManagement", description = "Plc管理") 29 | @RestController 30 | @RequestMapping(path = "/api") 31 | @PreAuthorize("hasRole('ROLE_ADMIN') and hasRole('ROLE_GUEST')") 32 | public class OpcClientControl { 33 | private static final Logger LOGGER = LoggerFactory.getLogger(OpcClientControl.class); 34 | 35 | @Autowired 36 | OpcClient opcClient; 37 | @Autowired 38 | AppConfig appConfig; 39 | 40 | private ObjectMapper objectMapper = new ObjectMapper(); 41 | 42 | 43 | @ApiOperation(value = "获取指定plc所有参数", notes = "获取指定plc所有参数") 44 | @RequestMapping(path = "/items/value/{plcNumber}", method = RequestMethod.GET) 45 | public String getAllItemValue(@PathVariable String plcNumber) { 46 | try { 47 | //转换成OpcServer配置的plc序号 48 | String opcPlcNumber = appConfig.getPlcNumberDictionary().get(plcNumber); 49 | List plcItemValues = opcClient.getPlcItemValuesByPlcNumber(opcPlcNumber); 50 | ObjectNode rootNode = objectMapper.createObjectNode(); 51 | for (OpcEntity entity : plcItemValues) { 52 | if (entity.getFieldAndItem() == FieldAndItem.motorFailure) { 53 | 54 | int failureCode = (Integer) entity.getValue(); 55 | byte[] intArray = ByteBuffer.allocate(4).putInt(failureCode).array(); 56 | BitArray bitArray = new BitArray(intArray.length * 8, intArray); 57 | ObjectNode itemNode = objectMapper.createObjectNode(); 58 | itemNode.put("timestamp", entity.getTimestamp()); 59 | itemNode.put("value", bitArray.get(bitArray.length() - 1 - 0)); 60 | rootNode.set("远程自动", itemNode); 61 | 62 | itemNode = objectMapper.createObjectNode(); 63 | itemNode.put("timestamp", entity.getTimestamp()); 64 | itemNode.put("value", bitArray.get(bitArray.length() - 1 - 1)); 65 | rootNode.set("主回路升", itemNode); 66 | 67 | itemNode = objectMapper.createObjectNode(); 68 | itemNode.put("timestamp", entity.getTimestamp()); 69 | itemNode.put("value", bitArray.get(bitArray.length() - 1 - 2)); 70 | rootNode.set("主回路降", itemNode); 71 | 72 | itemNode = objectMapper.createObjectNode(); 73 | itemNode.put("timestamp", entity.getTimestamp()); 74 | itemNode.put("value", bitArray.get(bitArray.length() - 1 - 3)); 75 | rootNode.set("故障保护", itemNode); 76 | 77 | itemNode = objectMapper.createObjectNode(); 78 | itemNode.put("timestamp", entity.getTimestamp()); 79 | itemNode.put("value", bitArray.get(bitArray.length() - 1 - 4)); 80 | rootNode.set("机械上限", itemNode); 81 | 82 | itemNode = objectMapper.createObjectNode(); 83 | itemNode.put("timestamp", entity.getTimestamp()); 84 | itemNode.put("value", bitArray.get(bitArray.length() - 1 - 5)); 85 | rootNode.set("机械下限", itemNode); 86 | 87 | itemNode = objectMapper.createObjectNode(); 88 | itemNode.put("timestamp", entity.getTimestamp()); 89 | itemNode.put("value", bitArray.get(bitArray.length() - 1 - 8)); 90 | rootNode.set("仪表上限", itemNode); 91 | 92 | itemNode = objectMapper.createObjectNode(); 93 | itemNode.put("timestamp", entity.getTimestamp()); 94 | itemNode.put("value", bitArray.get(bitArray.length() - 1 - 9)); 95 | rootNode.set("仪表下限", itemNode); 96 | 97 | itemNode = objectMapper.createObjectNode(); 98 | itemNode.put("timestamp", entity.getTimestamp()); 99 | itemNode.put("value", bitArray.get(bitArray.length() - 1 - 10)); 100 | rootNode.set("仪表上升", itemNode); 101 | 102 | itemNode = objectMapper.createObjectNode(); 103 | itemNode.put("timestamp", entity.getTimestamp()); 104 | itemNode.put("value", bitArray.get(bitArray.length() - 1 - 11)); 105 | rootNode.set("仪表下降", itemNode); 106 | 107 | itemNode = objectMapper.createObjectNode(); 108 | itemNode.put("timestamp", entity.getTimestamp()); 109 | itemNode.put("value", bitArray.get(bitArray.length() - 1 - 12)); 110 | rootNode.set("荷重90%", itemNode); 111 | 112 | itemNode = objectMapper.createObjectNode(); 113 | itemNode.put("timestamp", entity.getTimestamp()); 114 | itemNode.put("value", bitArray.get(bitArray.length() - 1 - 13)); 115 | rootNode.set("荷重110%", itemNode); 116 | 117 | } else { 118 | ObjectNode itemNode = objectMapper.createObjectNode(); 119 | itemNode.put("timestamp", entity.getTimestamp()); 120 | switch (entity.getFieldAndItem().getOpcDataType()) { 121 | case Short: 122 | case Int: 123 | itemNode.put("value", (Integer) entity.getValue()); 124 | break; 125 | case Float: 126 | itemNode.put("value", (Float) entity.getValue()); 127 | break; 128 | default: 129 | break; 130 | } 131 | rootNode.set(entity.getFieldAndItem().getItemName(), itemNode); 132 | } 133 | } 134 | rootNode.put("采集时间", OpcClient.formatter.print(DateTime.now())); 135 | return objectMapper.writeValueAsString(rootNode); 136 | } catch (JsonProcessingException e) { 137 | return ""; 138 | } 139 | } 140 | 141 | @ApiOperation(value = "设置指定plc的参数", notes = "设置指定plc的参数") 142 | @RequestMapping(path = "/items/value/", method = RequestMethod.PUT) 143 | public String setItemValue(@RequestParam String plcNumber, @RequestParam FieldAndItem itemName, 144 | @RequestParam String itemValue) { 145 | 146 | try { 147 | //转换成OpcServer配置的plc序号 148 | String opcPlcNumber = appConfig.getPlcNumberDictionary().get(plcNumber); 149 | opcClient.setItemValue(itemName, opcPlcNumber, itemValue); 150 | int value = (int) opcClient.getItemValue(FieldAndItem.controlWord, opcPlcNumber); 151 | byte[] intArray = ByteBuffer.allocate(4).putInt(value).array(); 152 | BitArray bitArray = new BitArray(intArray.length * 8, intArray); 153 | if (itemName == FieldAndItem.setCacheValue) { 154 | bitArray.set(bitArray.length() - 1 - 4, true); 155 | String valueStr = String.valueOf(ByteBuffer.wrap(bitArray.toByteArray()).getInt()); 156 | opcClient.setItemValue(FieldAndItem.controlWord, opcPlcNumber, valueStr); 157 | Thread.sleep(500); 158 | value = (int) opcClient.getItemValue(FieldAndItem.controlWord, opcPlcNumber); 159 | intArray = ByteBuffer.allocate(4).putInt(value).array(); 160 | bitArray = new BitArray(intArray.length * 8, intArray); 161 | bitArray.set(bitArray.length() - 1 - 4, false); 162 | valueStr = String.valueOf(ByteBuffer.wrap(bitArray.toByteArray()).getInt()); 163 | opcClient.setItemValue(FieldAndItem.controlWord, opcPlcNumber, valueStr); 164 | 165 | } else if (itemName == FieldAndItem.warningTimeCache) { 166 | bitArray.set(bitArray.length() - 1 - 6, true); 167 | String valueStr = String.valueOf(ByteBuffer.wrap(bitArray.toByteArray()).getInt()); 168 | opcClient.setItemValue(FieldAndItem.controlWord, opcPlcNumber, valueStr); 169 | Thread.sleep(500); 170 | value = (int) opcClient.getItemValue(FieldAndItem.controlWord, opcPlcNumber); 171 | intArray = ByteBuffer.allocate(4).putInt(value).array(); 172 | bitArray = new BitArray(intArray.length * 8, intArray); 173 | bitArray.set(bitArray.length() - 1 - 6, false); 174 | valueStr = String.valueOf(ByteBuffer.wrap(bitArray.toByteArray()).getInt()); 175 | opcClient.setItemValue(FieldAndItem.controlWord, opcPlcNumber, valueStr); 176 | } 177 | } catch (Exception e) { 178 | LOGGER.error("设置出错", e); 179 | return "error"; 180 | } 181 | return getAllItemValue(plcNumber); 182 | } 183 | 184 | @ApiOperation(value = "启动闸门", notes = "启动闸门") 185 | @RequestMapping(path = "/gate/start", method = RequestMethod.PUT) 186 | public String startGate(@RequestParam String plcNumber) { 187 | 188 | try { 189 | //转换成OpcServer配置的plc序号 190 | String opcPlcNumber = appConfig.getPlcNumberDictionary().get(plcNumber); 191 | int value = (int) opcClient.getItemValue(FieldAndItem.controlWord, opcPlcNumber); 192 | byte[] intArray = ByteBuffer.allocate(4).putInt(value).array(); 193 | BitArray bitArray = new BitArray(intArray.length * 8, intArray); 194 | bitArray.set(bitArray.length() - 1 - 0, true); 195 | String valueStr = String.valueOf(ByteBuffer.wrap(bitArray.toByteArray()).getInt()); 196 | opcClient.setItemValue(FieldAndItem.controlWord, opcPlcNumber, valueStr); 197 | Thread.sleep(500); 198 | value = (int) opcClient.getItemValue(FieldAndItem.controlWord, opcPlcNumber); 199 | intArray = ByteBuffer.allocate(4).putInt(value).array(); 200 | bitArray = new BitArray(intArray.length * 8, intArray); 201 | bitArray.set(bitArray.length() - 1 - 0, false); 202 | valueStr = String.valueOf(ByteBuffer.wrap(bitArray.toByteArray()).getInt()); 203 | opcClient.setItemValue(FieldAndItem.controlWord, opcPlcNumber, valueStr); 204 | } catch (Exception e) { 205 | LOGGER.error("闸门开启出错", e); 206 | } 207 | return getAllItemValue(plcNumber); 208 | } 209 | 210 | @ApiOperation(value = "停止闸门", notes = "停止闸门") 211 | @RequestMapping(path = "/gate/stop", method = RequestMethod.PUT) 212 | public String stopGate(@RequestParam String plcNumber) { 213 | 214 | try { 215 | //转换成OpcServer配置的plc序号 216 | String opcPlcNumber = appConfig.getPlcNumberDictionary().get(plcNumber); 217 | int value = (int) opcClient.getItemValue(FieldAndItem.controlWord, opcPlcNumber); 218 | byte[] intArray = ByteBuffer.allocate(4).putInt(value).array(); 219 | BitArray bitArray = new BitArray(intArray.length * 8, intArray); 220 | bitArray.set(bitArray.length() - 1 - 1, true); 221 | String valueStr = String.valueOf(ByteBuffer.wrap(bitArray.toByteArray()).getInt()); 222 | opcClient.setItemValue(FieldAndItem.controlWord, opcPlcNumber, valueStr); 223 | Thread.sleep(500); 224 | value = (int) opcClient.getItemValue(FieldAndItem.controlWord, opcPlcNumber); 225 | intArray = ByteBuffer.allocate(4).putInt(value).array(); 226 | bitArray = new BitArray(intArray.length * 8, intArray); 227 | bitArray.set(bitArray.length() - 1 - 1, false); 228 | valueStr = String.valueOf(ByteBuffer.wrap(bitArray.toByteArray()).getInt()); 229 | opcClient.setItemValue(FieldAndItem.controlWord, opcPlcNumber, valueStr); 230 | } catch (Exception e) { 231 | LOGGER.error("闸门停止出错", e); 232 | } 233 | return getAllItemValue(plcNumber); 234 | } 235 | 236 | 237 | } 238 | --------------------------------------------------------------------------------