diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9154f4c --- /dev/null +++ b/.gitignore @@ -0,0 +1,26 @@ +# ---> Java +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..0128c24 --- /dev/null +++ b/pom.xml @@ -0,0 +1,174 @@ + + 4.0.0 + + com.integrated_yjb_dataDocking + integrated_yjb_dataDocking + 1.0 + jar + + integrated_yjb_dataDocking + http://maven.apache.org + + + org.springframework.boot + spring-boot-starter-parent + 2.3.12.RELEASE + + + + + UTF-8 + 1.8 + 2.0.4 + 5.8.25 + 1.16.18 + 5.4.0 + 2.3.12.RELEASE + + + + + org.springframework.boot + spring-boot-starter-validation + + + com.ghgande + j2mod + 3.1.1 + + + org.postgresql + postgresql + 42.5.0 + + + com.alibaba + fastjson + 1.2.44 + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-redis + + + + org.springframework.boot + spring-boot-starter-aop + + + mysql + mysql-connector-java + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 1.3.2 + + + com.alibaba + druid + 1.1.13 + + + com.alibaba + jconsole + + + com.alibaba + tools + + + + + + + + + + + + com.github.xiaoymin + knife4j-spring-boot-starter + ${knife4j.version} + + + + + cn.hutool + hutool-core + ${hutool.version} + + + + + org.projectlombok + lombok + ${lombok.version} + true + + + + + net.java.dev.jna + jna + ${jna.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${jdk.version} + ${jdk.version} + ${project.build.sourceEncoding} + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + + + repackage + + + + + + + + + src/main/resources + + **/*.* + + + + res + false + + **/*.properties + **/*.xml + + + + libs + false + + **/*.dll + + + + + diff --git a/readme.md b/readme.md index 9d07aa0..e86b136 100644 --- a/readme.md +++ b/readme.md @@ -1 +1,3 @@ -111 \ No newline at end of file +# integrated_yjb_dataDocking + +龙钢与省厅modbus协议对接 \ No newline at end of file diff --git a/src/main/java/com/netsdk/DahuaApplication.java b/src/main/java/com/netsdk/DahuaApplication.java new file mode 100644 index 0000000..c798f24 --- /dev/null +++ b/src/main/java/com/netsdk/DahuaApplication.java @@ -0,0 +1,23 @@ +package com.netsdk; + +import com.ghgande.j2mod.modbus.slave.ModbusSlave; +import com.ghgande.j2mod.modbus.slave.ModbusSlaveFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; + +/** + * 主启动 + * + * @author Yan Xu + * @version 1.0 + * @date 2021/8/6 + * Copyright © goodits + */ +@SpringBootApplication +@EnableScheduling +public class DahuaApplication { + public static void main(String[] args) { + SpringApplication.run(DahuaApplication.class,args); + } +} diff --git a/src/main/java/com/netsdk/StartModBusTcpServer.java b/src/main/java/com/netsdk/StartModBusTcpServer.java new file mode 100644 index 0000000..e5f752f --- /dev/null +++ b/src/main/java/com/netsdk/StartModBusTcpServer.java @@ -0,0 +1,48 @@ +package com.netsdk; + +import com.ghgande.j2mod.modbus.slave.ModbusSlave; +import com.ghgande.j2mod.modbus.slave.ModbusSlaveFactory; +import com.netsdk.service.DeviceService; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; + +/** + * spring boot 启动后启动 modbusTcp服务 + * + * @author lin + */ +@Component +@Order(value = 1) +public class StartModBusTcpServer implements ApplicationRunner { + + @Resource + private DeviceService deviceService; + + + // 线圈(Coils) 01,05,15 00000-09999 读写 开关量输出new SimpleDigitalOut(true); + // 离散输入(DI) 02 10000-19999 只读 开关量输入new SimpleDigitalIn(false); + // 保持寄存器 读写 new SimpleRegister(251); + // 输入寄存器 只读 new SimpleInputRegister(45); + @Override + public void run(ApplicationArguments args) throws Exception { + deviceService.initMqOrderList(); + // 离散输入(DI) 02 10000-1FFFF 10001-19999 只读位 + // 输入寄存器(IR) 04 30000-3FFFF 30001-39999 只读16位值 + ModbusSlave slave = ModbusSlaveFactory.createTCPSlave(1888, 5); + // 高炉 + slave.addProcessImage(1, deviceService.getGlProcessImage()); + // 转炉 + slave.addProcessImage(2, deviceService.getZlProcessImage()); + // 精炼炉 + slave.addProcessImage(3, deviceService.getLfProcessImage()); + // 煤气报警器 + slave.addProcessImage(4, deviceService.getMqProcessImage()); + slave.open(); + + } +} diff --git a/src/main/java/com/netsdk/config/Knife4jConfiguration.java b/src/main/java/com/netsdk/config/Knife4jConfiguration.java new file mode 100644 index 0000000..434b190 --- /dev/null +++ b/src/main/java/com/netsdk/config/Knife4jConfiguration.java @@ -0,0 +1,67 @@ +package com.netsdk.config; + +import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; +import com.google.common.base.Predicates; +import springfox.documentation.service.Contact; +import org.springframework.boot.autoconfigure.web.ServerProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +/** + * 接口文档配置 + * @author Yan Xu + * @version 1.0 + * @date 2021/8/7 + * Copyright © goodits + */ +@Configuration +@EnableSwagger2 +@EnableKnife4j +public class Knife4jConfiguration { + + + private final ServerProperties serverProperties; + private final SysInfoProperties sysInfoProperties; + + public Knife4jConfiguration(ServerProperties serverProperties, SysInfoProperties sysInfoProperties) { + this.serverProperties = serverProperties; + this.sysInfoProperties = sysInfoProperties; + } + + private ApiInfo apiInfo() { + String serviceUrl = "http://localhost:" + serverProperties.getPort(); + return new ApiInfoBuilder() + .title(sysInfoProperties.getChineseName()+"后台接口文档") + .description(sysInfoProperties.getDescription()) + .termsOfServiceUrl(serviceUrl) + .version(sysInfoProperties.getVersion()) + .contact(new Contact(sysInfoProperties.getPic(), null, "2366528143@qq.com")) + .build(); + } + + @Bean(value = "defaultApi2") + public Docket defaultApi2() { + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + //分组名称 + .groupName("defaultApi2") + .select() + //这里指定Controller扫描包路径 + //.apis(RequestHandlerSelectors.basePackage("com.goodits.controller")) + // 对所有api进行监控 + .apis(RequestHandlerSelectors.any()) + //错误路径不监控 + .paths(Predicates.not(PathSelectors.regex("/error.*"))) + //服务质量检测路径不监控 + .paths(Predicates.not(PathSelectors.regex("/actuator.*"))) + .paths(PathSelectors.any()) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/netsdk/config/MasterDataSourceConfig.java b/src/main/java/com/netsdk/config/MasterDataSourceConfig.java new file mode 100644 index 0000000..3fd4236 --- /dev/null +++ b/src/main/java/com/netsdk/config/MasterDataSourceConfig.java @@ -0,0 +1,71 @@ +package com.netsdk.config; + +import com.alibaba.druid.pool.DruidDataSource; +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.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; + +import javax.sql.DataSource; + +/** + * 说明:第一数据源配置 + * 作者:luoxiaobao + * 官网:www.qdkjchina.com + */ +@Configuration +@MapperScan(basePackages = MasterDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "masterSqlSessionFactory") //扫描 Mapper 接口并容器管理 +public class MasterDataSourceConfig { + + static final String PACKAGE = "com.netsdk.mapper.datasource"; //master 目录 + static final String MAPPER_LOCATION = "classpath:mybatis/datasource/*/*.xml"; //扫描的 xml 目录 + static final String CONFIG_LOCATION = "classpath:mybatis/datasource/mybatis-config.xml"; //自定义的mybatis config 文件位置 + static final String TYPE_ALIASES_PACKAGE = "com.netsdk.entity"; //扫描的 实体类 目录 + + @Value("${spring.datasource.url}") + private String url; + + @Value("${spring.datasource.username}") + private String user; + + @Value("${spring.datasource.password}") + private String password; + + @Value("${spring.datasource.driver-class-name}") + private String driverClass; + + @Bean(name = "masterDataSource") + @Primary + public DataSource masterDataSource() { + DruidDataSource dataSource = new DruidDataSource(); + dataSource.setDriverClassName(driverClass); + dataSource.setUrl(url); + dataSource.setUsername(user); + dataSource.setPassword(password); + return dataSource; + } + + @Bean(name = "masterTransactionManager") + @Primary + public DataSourceTransactionManager masterTransactionManager() { + return new DataSourceTransactionManager(masterDataSource()); + } + + @Bean(name = "masterSqlSessionFactory") + @Primary + public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource)throws Exception { + final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); + sessionFactory.setDataSource(masterDataSource); + sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MasterDataSourceConfig.MAPPER_LOCATION)); + sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(MasterDataSourceConfig.CONFIG_LOCATION)); + sessionFactory.setTypeAliasesPackage(MasterDataSourceConfig.TYPE_ALIASES_PACKAGE); + return sessionFactory.getObject(); + } +} diff --git a/src/main/java/com/netsdk/config/RedisConfig.java b/src/main/java/com/netsdk/config/RedisConfig.java new file mode 100644 index 0000000..af56555 --- /dev/null +++ b/src/main/java/com/netsdk/config/RedisConfig.java @@ -0,0 +1,44 @@ +package com.netsdk.config; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +/** + * 说明:Redis + + + */ +@Configuration +public class RedisConfig { + + @Bean + @SuppressWarnings("all") + public RedisTemplate redisTemplate(RedisConnectionFactory factory) { + RedisTemplate template = new RedisTemplate(); + template.setConnectionFactory(factory); + Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); + jackson2JsonRedisSerializer.setObjectMapper(om); + StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); + // key采用String的序列化方式 + template.setKeySerializer(stringRedisSerializer); + // hash的key也采用String的序列化方式 + template.setHashKeySerializer(stringRedisSerializer); + // value序列化方式采用jackson + template.setValueSerializer(jackson2JsonRedisSerializer); + // hash的value序列化方式采用jackson + template.setHashValueSerializer(jackson2JsonRedisSerializer); + template.afterPropertiesSet(); + return template; + } + +} diff --git a/src/main/java/com/netsdk/config/StaticFileConfig.java b/src/main/java/com/netsdk/config/StaticFileConfig.java new file mode 100644 index 0000000..3ad174e --- /dev/null +++ b/src/main/java/com/netsdk/config/StaticFileConfig.java @@ -0,0 +1,23 @@ +package com.netsdk.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * 静态文件访问映射 + * + * @author Yan Xu + * @version 1.0 + * @date 2021/8/7 + * Copyright © goodits + */ +@Configuration +public class StaticFileConfig implements WebMvcConfigurer { + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + //访问 /img/**会被解析为/static/img/** + registry.addResourceHandler("/img/**").addResourceLocations("classpath:/static/img/"); + } +} diff --git a/src/main/java/com/netsdk/config/SysInfoProperties.java b/src/main/java/com/netsdk/config/SysInfoProperties.java new file mode 100644 index 0000000..802accb --- /dev/null +++ b/src/main/java/com/netsdk/config/SysInfoProperties.java @@ -0,0 +1,27 @@ +package com.netsdk.config; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Component +// 注册为组件 +@EnableConfigurationProperties +// 启用配置自动注入功能 +@ConfigurationProperties(prefix = "project") +//指定类对应的配置项前缀 +@ApiModel(description = "系统描述") +public class SysInfoProperties { + @ApiModelProperty(value = "应用中文名") + private String chineseName; + @ApiModelProperty(value = "应用描述") + private String description; + @ApiModelProperty(value = "版本") + private String version; + @ApiModelProperty(value = "开发") + private String pic; +} \ No newline at end of file diff --git a/src/main/java/com/netsdk/entity/PageData.java b/src/main/java/com/netsdk/entity/PageData.java new file mode 100644 index 0000000..b5458ef --- /dev/null +++ b/src/main/java/com/netsdk/entity/PageData.java @@ -0,0 +1,149 @@ +package com.netsdk.entity; + +import com.alibaba.druid.proxy.jdbc.ClobProxyImpl; + +import javax.servlet.http.HttpServletRequest; +import java.io.BufferedReader; +import java.io.Reader; +import java.util.*; + +/** + * 说明:参数封装Map + + + */ +public class PageData extends HashMap implements Map { + + private static final long serialVersionUID = 1L; + + Map map = null; + HttpServletRequest request; + + public PageData(HttpServletRequest request) { + this.request = request; + Map properties = request.getParameterMap(); + Map returnMap = new HashMap(); + Iterator entries = properties.entrySet().iterator(); + Entry entry; + String name = ""; + String value = ""; + while (entries.hasNext()) { + entry = (Entry) entries.next(); + name = (String) entry.getKey(); + Object valueObj = entry.getValue(); + if (null == valueObj) { + value = ""; + } else if (valueObj instanceof String[]) { + String[] values = (String[]) valueObj; + for (int i = 0; i < values.length; i++) { + value = values[i] + ","; + } + value = value.substring(0, value.length() - 1); + } else { + value = valueObj.toString(); + } + returnMap.put(name, value); + } + map = returnMap; + } + + public PageData() { + map = new HashMap(); + } + + + @Override + public Object get(Object key) { + Object obj = null; + if (map.get(key) instanceof Object[]) { + Object[] arr = (Object[]) map.get(key); + obj = request == null ? arr : (request.getParameter((String) key) == null ? arr : arr[0]); + } else { + obj = map.get(key); + } + return obj; + } + + public String getString(Object key) { + return get(key) == null ? null : get(key).toString().trim(); + } + public String getStringOrDefault(Object key,String defaultValue) { + return get(key) == null ? defaultValue : get(key).toString().trim(); + } + @Override + public Object getOrDefault(Object key,Object defaultValue) { + return map.getOrDefault(key,defaultValue); + } + @Override + public Object put(Object key, Object value) { + if (value instanceof ClobProxyImpl) { // 读取oracle Clob类型数据 + try { + ClobProxyImpl cpi = (ClobProxyImpl) value; + Reader is = cpi.getCharacterStream(); // 获取流 + BufferedReader br = new BufferedReader(is); + String str = br.readLine(); + StringBuffer sb = new StringBuffer(); + while (str != null) { // 循环读取数据拼接到字符串 + sb.append(str); + sb.append("\n"); + str = br.readLine(); + } + value = sb.toString(); + } catch (Exception e) { + e.printStackTrace(); + } + } + return map.put(key, value); + } + + @Override + public Object remove(Object key) { + return map.remove(key); + } + + public void clear() { + map.clear(); + } + + public boolean containsKey(Object key) { + // TODO Auto-generated method stub + return map.containsKey(key); + } + + public boolean containsValue(Object value) { + // TODO Auto-generated method stub + return map.containsValue(value); + } + + public Set entrySet() { + // TODO Auto-generated method stub + return map.entrySet(); + } + + public boolean isEmpty() { + // TODO Auto-generated method stub + return map.isEmpty(); + } + + public Set keySet() { + // TODO Auto-generated method stub + return map.keySet(); + } + + @SuppressWarnings("unchecked") + public void putAll(Map t) { + // TODO Auto-generated method stub + map.putAll(t); + } + + public int size() { + // TODO Auto-generated method stub + return map.size(); + } + + public Collection values() { + // TODO Auto-generated method stub + return map.values(); + } + +} diff --git a/src/main/java/com/netsdk/exception/ServiceException.java b/src/main/java/com/netsdk/exception/ServiceException.java new file mode 100644 index 0000000..3da30dd --- /dev/null +++ b/src/main/java/com/netsdk/exception/ServiceException.java @@ -0,0 +1,22 @@ +package com.netsdk.exception; + +/** + * 自定义服务异常 + * @author Yan Xu + * @version 1.0 + * @date 2023/4/19 + */ +public class ServiceException extends RuntimeException{ + + public ServiceException() { + super(); + } + + public ServiceException(String message) { + super(message); + } + + public ServiceException(Throwable cause) { + super(cause); + } +} diff --git a/src/main/java/com/netsdk/mapper/datasource/other/OtherMapper.java b/src/main/java/com/netsdk/mapper/datasource/other/OtherMapper.java new file mode 100644 index 0000000..07f177a --- /dev/null +++ b/src/main/java/com/netsdk/mapper/datasource/other/OtherMapper.java @@ -0,0 +1,14 @@ +package com.netsdk.mapper.datasource.other; + +import org.apache.ibatis.annotations.Mapper; + +import java.util.ArrayList; +import java.util.HashMap; + +/** + * @author lin + */ +@Mapper +public interface OtherMapper { + ArrayList> getAllMqOrderList(); +} diff --git a/src/main/java/com/netsdk/service/DeviceService.java b/src/main/java/com/netsdk/service/DeviceService.java new file mode 100644 index 0000000..edcaeca --- /dev/null +++ b/src/main/java/com/netsdk/service/DeviceService.java @@ -0,0 +1,17 @@ +package com.netsdk.service; + +import com.ghgande.j2mod.modbus.procimg.ProcessImage; + +/** + * @author lin + */ +public interface DeviceService { + ProcessImage getGlProcessImage(); + + ProcessImage getZlProcessImage(); + + ProcessImage getLfProcessImage(); + + ProcessImage getMqProcessImage(); + void initMqOrderList(); +} diff --git a/src/main/java/com/netsdk/service/impl/DeviceServiceImpl.java b/src/main/java/com/netsdk/service/impl/DeviceServiceImpl.java new file mode 100644 index 0000000..ec837a2 --- /dev/null +++ b/src/main/java/com/netsdk/service/impl/DeviceServiceImpl.java @@ -0,0 +1,332 @@ +package com.netsdk.service.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.JSONPObject; +import com.ghgande.j2mod.modbus.procimg.ProcessImage; +import com.ghgande.j2mod.modbus.procimg.SimpleDigitalIn; +import com.ghgande.j2mod.modbus.procimg.SimpleInputRegister; +import com.ghgande.j2mod.modbus.procimg.SimpleProcessImage; +import com.netsdk.mapper.datasource.other.OtherMapper; +import com.netsdk.service.DeviceService; +import com.netsdk.utils.OtherInputRegister; +import com.netsdk.utils.RedisUtil; +import com.netsdk.utils.SyncGlScheduledTasks; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashMap; + + +/** + * @author lin + */ +@Service +public class DeviceServiceImpl implements DeviceService { + @Resource + private RedisUtil redisUtil; + @Resource + private OtherMapper otherMapper; + + @Override + public ProcessImage getGlProcessImage() { + // 高炉设备初始话获取数据 + JSONArray objects = JSONObject.parseArray((String) redisUtil.get("GL_LIST")); + // SBXH-GL-1 高炉#炉顶工作压力 + // 高炉#炉顶放散阀联锁投入状态#东大放散阀状态-关到位 SBXH-GL-2-2 + // 高炉#炉顶放散阀联锁投入状态#东大放散阀状态-开到位 SBXH-GL-2-1 + // 高炉#炉顶放散阀联锁投入状态#西大放散阀状态-开到位 SBXH-GL-2-3 + // 高炉#炉顶放散阀联锁投入状态#西大放散阀状态-关到位 SBXH-GL-2-4 + SimpleProcessImage spi = new SimpleProcessImage(); + // 离散输入(DI) 02 10000-1FFFF 10001-19999 只读位 + SimpleInputRegister SBXH_GL_2_5 = new SimpleInputRegister(); + SimpleInputRegister dynamicRegHig = new SimpleInputRegister(0); + SimpleInputRegister dynamicReglow = new SimpleInputRegister(0); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-GL-1" + "hig", dynamicRegHig); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-GL-1" + "low", dynamicReglow); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-GL-2-5", SBXH_GL_2_5); + + for (int i = 0; i < objects.size(); i++) { + JSONObject jsonObject = objects.getJSONObject(i); + if ("SBXH-GL-1".equals(jsonObject.getString("IPCDEVICE_ID"))) { + float intValue = jsonObject.getFloatValue("CURRENT_VALUE"); + int bits = Float.floatToIntBits(intValue); + dynamicRegHig.setValue((bits >> 16) & 0xFFFF); + dynamicReglow.setValue(bits & 0xFFFF); + } + if ("SBXH-GL-2-5".equals(jsonObject.getString("IPCDEVICE_ID"))) { + double intValue = jsonObject.getDouble("CURRENT_VALUE"); + SBXH_GL_2_5.setValue((int) intValue); + } + + } + // SBXH-GL-1 高炉#炉顶工作压力 + // 输入寄存器(IR) 04 30000-3FFFF 30001-39999 只读16位值 + spi.addInputRegister(dynamicRegHig); + spi.addInputRegister(dynamicReglow); + spi.addInputRegister(SBXH_GL_2_5); + int inputRegisterCount = spi.getInputRegisterCount(); + for (int i = inputRegisterCount; i < 1000; i++) { + spi.addInputRegister(new SimpleInputRegister(0)); + } + return spi; + } + + @Override + public ProcessImage getZlProcessImage() { + JSONArray objects = JSONObject.parseArray((String) redisUtil.get("ZL_LIST")); + SimpleProcessImage spi = new SimpleProcessImage(); + initZlSimpleInputRegister(spi); + for (int i = 0; i < objects.size(); i++) { + JSONObject jsonObject = objects.getJSONObject(i); + float intValue = jsonObject.getFloatValue("CURRENT_VALUE"); + if ("1".equals(jsonObject.getString("SIGNAL_TYPE"))) { + // 模拟量 + SimpleInputRegister simpleInputRegister_hig = SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.get(jsonObject.getString("IPCDEVICE_ID") + "hig"); + SimpleInputRegister simpleInputRegister_low = SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.get(jsonObject.getString("IPCDEVICE_ID") + "low"); + if (simpleInputRegister_hig != null) { + int bits = Float.floatToIntBits(intValue); + simpleInputRegister_hig.setValue((bits >> 16) & 0xFFFF); + simpleInputRegister_low.setValue(bits & 0xFFFF); + } + } else { + SimpleInputRegister simpleInputRegister = SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.get(jsonObject.getString("IPCDEVICE_ID")); + if (simpleInputRegister == null) continue; + // 开关量 + simpleInputRegister.setValue((int) intValue); + } + } + // 这个别删除、省局要求 寄存器数量不能少于1000个哪怕没数据 + int inputRegisterCount = spi.getInputRegisterCount(); + for (int i = inputRegisterCount; i < 1000; i++) { + spi.addInputRegister(new SimpleInputRegister(0)); + } + return spi; + } + + private void initZlSimpleInputRegister(SimpleProcessImage spi) { + SimpleInputRegister SBXH_ZL_1_1_hig = new SimpleInputRegister(0); + SimpleInputRegister SBXH_ZL_1_1_low = new SimpleInputRegister(0); + SimpleInputRegister SBXH_ZL_1_2_hig = new SimpleInputRegister(0); + SimpleInputRegister SBXH_ZL_1_2_low = new SimpleInputRegister(0); + SimpleInputRegister SBXH_ZL_2_1_hig = new SimpleInputRegister(0); + SimpleInputRegister SBXH_ZL_2_1_low = new SimpleInputRegister(0); + SimpleInputRegister SBXH_ZL_2_2_hig = new SimpleInputRegister(0); + SimpleInputRegister SBXH_ZL_2_2_low = new SimpleInputRegister(0); + SimpleInputRegister SBXH_ZL_4_1_hig = new SimpleInputRegister(0); + SimpleInputRegister SBXH_ZL_4_1_low = new SimpleInputRegister(0); + SimpleInputRegister SBXH_ZL_4_2_hig = new SimpleInputRegister(0); + SimpleInputRegister SBXH_ZL_4_2_low = new SimpleInputRegister(0); + SimpleInputRegister SBXH_ZL_5_1_hig = new SimpleInputRegister(0); + SimpleInputRegister SBXH_ZL_5_1_low = new SimpleInputRegister(0); + SimpleInputRegister SBXH_ZL_5_2_hig = new SimpleInputRegister(0); + SimpleInputRegister SBXH_ZL_5_2_low = new SimpleInputRegister(0); + + + // 水冷氧枪-氧气压力1#枪氧气压力 + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-1-1" + "hig", SBXH_ZL_1_1_hig); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-1-1" + "low", SBXH_ZL_1_1_low); + // 水冷氧枪-氧气压力2#枪氧气压力 + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-1-2" + "hig", SBXH_ZL_1_2_hig); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-1-2" + "low", SBXH_ZL_1_2_low); + // 水冷氧枪-冷却水进水流量 1#枪冷却水进水流量 + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-2-1" + "hig", SBXH_ZL_2_1_hig); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-2-1" + "low", SBXH_ZL_2_1_low); + // 水冷氧枪-冷却水进水流量 2#枪冷却水进水流量 + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-2-2" + "hig", SBXH_ZL_2_2_hig); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-2-2" + "low", SBXH_ZL_2_2_low); + // 水冷氧枪-冷却水出水温度1#枪冷却水出水温度 + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-4-1" + "hig", SBXH_ZL_4_1_hig); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-4-1" + "low", SBXH_ZL_4_1_low); + // 水冷氧枪-冷却水出水温度2#枪冷却水出水温度 + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-4-2" + "hig", SBXH_ZL_4_2_hig); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-4-2" + "low", SBXH_ZL_4_2_low); + // 水冷氧枪-冷却水进出水流量差 SBXH-ZL_5-1 1#枪冷却水进出水流量差 + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL_5-1" + "hig", SBXH_ZL_5_1_hig); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL_5-1" + "low", SBXH_ZL_5_1_low); + // 水冷氧枪-冷却水进出水流量差 SBXH-ZL_5-2 2#枪冷却水进出水流量差 + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL_5-2" + "hig", SBXH_ZL_5_2_hig); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL_5-2" + "low", SBXH_ZL_5_2_low); + + + // 氧气压力与氧枪自动升起联锁投入状态 + SimpleInputRegister SBXH_ZL_5 = new SimpleInputRegister(); + // 冷却水进水流量与氧枪自动升起联锁投入状态 + SimpleInputRegister SBXH_ZL_6 = new SimpleInputRegister(); + // 冷却水出水温度与氧枪自动升起联锁投入状态 + SimpleInputRegister SBXH_ZL_7 = new SimpleInputRegister(); + // 进出水流量差与氧枪自动升起联锁投入状态 + SimpleInputRegister SBXH_ZL_8 = new SimpleInputRegister(); + // 冷却水进出水流量差与炉体倾动联锁投入状态 + SimpleInputRegister SBXH_ZL_9 = new SimpleInputRegister(); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-5", SBXH_ZL_5); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-6", SBXH_ZL_6); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-7", SBXH_ZL_7); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-8", SBXH_ZL_8); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-ZL-9", SBXH_ZL_9); + spi.addInputRegister(SBXH_ZL_1_1_hig); + spi.addInputRegister(SBXH_ZL_1_1_low); + spi.addInputRegister(SBXH_ZL_1_2_hig); + spi.addInputRegister(SBXH_ZL_1_2_low); + spi.addInputRegister(SBXH_ZL_2_1_hig); + spi.addInputRegister(SBXH_ZL_2_1_low); + spi.addInputRegister(SBXH_ZL_2_2_hig); + spi.addInputRegister(SBXH_ZL_2_2_low); + spi.addInputRegister(SBXH_ZL_5_1_hig); + spi.addInputRegister(SBXH_ZL_5_1_low); + spi.addInputRegister(SBXH_ZL_5_2_hig); + spi.addInputRegister(SBXH_ZL_5_2_low); + spi.addInputRegister(SBXH_ZL_4_1_hig); + spi.addInputRegister(SBXH_ZL_4_1_low); + spi.addInputRegister(SBXH_ZL_4_2_hig); + spi.addInputRegister(SBXH_ZL_4_2_low); + + spi.addInputRegister(SBXH_ZL_5); + spi.addInputRegister(SBXH_ZL_6); + spi.addInputRegister(SBXH_ZL_7); + spi.addInputRegister(SBXH_ZL_8); + spi.addInputRegister(SBXH_ZL_9); + } + + @Override + public ProcessImage getLfProcessImage() { + JSONArray objects = JSONObject.parseArray((String) redisUtil.get("JL_LIST")); + SimpleProcessImage spi = new SimpleProcessImage(); + initLfSimpleInputRegister(spi); + for (int i = 0; i < objects.size(); i++) { + JSONObject jsonObject = objects.getJSONObject(i); + float intValue = jsonObject.getFloatValue("CURRENT_VALUE"); + if ("1".equals(jsonObject.getString("SIGNAL_TYPE"))) { + // 模拟量 + SimpleInputRegister simpleInputRegister_hig = SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.get(jsonObject.getString("IPCDEVICE_ID") + "hig"); + SimpleInputRegister simpleInputRegister_low = SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.get(jsonObject.getString("IPCDEVICE_ID") + "low"); + if (simpleInputRegister_hig != null) { + int bits = Float.floatToIntBits(intValue); + simpleInputRegister_hig.setValue((bits >> 16) & 0xFFFF); + simpleInputRegister_low.setValue(bits & 0xFFFF); + } + } else { + SimpleInputRegister simpleInputRegister = SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.get(jsonObject.getString("IPCDEVICE_ID")); +// SBXH-JL-3 + SimpleInputRegister simpleInputRegister1 = SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.get(jsonObject.getString("IPCDEVICE_ID") + "_1"); + if (simpleInputRegister1 != null) { + simpleInputRegister1.setValue((int) intValue); + } + if (simpleInputRegister == null) continue; + // 开关量 + simpleInputRegister.setValue((int) intValue); + } + } + int inputRegisterCount = spi.getInputRegisterCount(); + for (int i = inputRegisterCount; i < 1000; i++) { + spi.addInputRegister(new SimpleInputRegister(0)); + } +// 冷却水出水温度与电极自动断 电联锁投入状态 +// 冷却水出水温度与电极升起联锁投入状态 +// 进出水流量差与电极自动断电联锁投入状态 +// 进出水流量差与电极升起联锁投入状态 + return spi; + } + + @Override + public ProcessImage getMqProcessImage() { + JSONArray objects = JSONObject.parseArray((String) redisUtil.get("MQ_LIST")); + SimpleProcessImage spi = new SimpleProcessImage(); + initMqSimpleInputRegister(spi); + for (int i = 0; i < objects.size(); i++) { + JSONObject jsonObject = objects.getJSONObject(i); + float intValue = jsonObject.getFloatValue("CURRENT_VALUE"); + SimpleInputRegister simpleInputRegister = SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.get(jsonObject.getString("IPCDEVICE_ID")); + if (simpleInputRegister == null) continue; + // 开关量 + simpleInputRegister.setValue((int) intValue); + } + int inputRegisterCount = spi.getInputRegisterCount(); + for (int i = inputRegisterCount; i < 1000; i++) { + spi.addInputRegister(new SimpleInputRegister(0)); + } + return spi; + } + + @Override + public void initMqOrderList() { + ArrayList> allMqOrderList = otherMapper.getAllMqOrderList(); + for (HashMap hashMap : allMqOrderList) { + SyncGlScheduledTasks.MQ_ORDER_MAP.put(Integer.parseInt(String.valueOf(hashMap.get("ID"))), hashMap.get("IPCDEVICE_ID")); + } + + } + + private void initMqSimpleInputRegister(SimpleProcessImage spi) { + int size = SyncGlScheduledTasks.MQ_ORDER_MAP.size(); + for (int i = 0; i < size; i++) { + SimpleInputRegister simpleInputRegister = new SimpleInputRegister(); + spi.addInputRegister(simpleInputRegister); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put(SyncGlScheduledTasks.MQ_ORDER_MAP.get(i), simpleInputRegister); + } + } + + private void initLfSimpleInputRegister(SimpleProcessImage spi) { + // 冷却水出水温度 +// SBXH-JL-1-1 1#冷却水出水温度 +// SBXH-JL-1-2 2#冷却水出水温度 + //冷却水进出水流量差 +// SBXH-JL-3-1 1#冷却水进出水流量差 +// SBXH-JL-3-2 2#冷却水进出水流量差 + SimpleInputRegister SBXH_JL_1_1_hig = new SimpleInputRegister(0); + SimpleInputRegister SBXH_JL_1_1_low = new SimpleInputRegister(0); + SimpleInputRegister SBXH_JL_1_2_hig = new SimpleInputRegister(0); + SimpleInputRegister SBXH_JL_1_2_low = new SimpleInputRegister(0); + SimpleInputRegister SBXH_JL_3_1_hig = new SimpleInputRegister(0); + SimpleInputRegister SBXH_JL_3_1_low = new SimpleInputRegister(0); + SimpleInputRegister SBXH_JL_3_2_hig = new SimpleInputRegister(0); + SimpleInputRegister SBXH_JL_3_2_low = new SimpleInputRegister(0); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-JL-1-1" + "hig", SBXH_JL_1_1_hig); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-JL-1-1" + "low", SBXH_JL_1_1_low); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-JL-1-2" + "hig", SBXH_JL_1_2_hig); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-JL-1-2" + "low", SBXH_JL_1_2_low); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-JL-3-1" + "hig", SBXH_JL_3_1_hig); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-JL-3-1" + "low", SBXH_JL_3_1_low); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-JL-3-2" + "hig", SBXH_JL_3_2_hig); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-JL-3-2" + "low", SBXH_JL_3_2_low); + // 冷却水出水温度与电极自动断电联锁投入状态 冷却水出水温度与电极升起联锁投入状态 1#炉盖回水温度联锁 + SimpleInputRegister SBXH_JL_3 = new SimpleInputRegister(); + SimpleInputRegister SBXH_JL_3_1 = new SimpleInputRegister(); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-JL-3", SBXH_JL_3); + // 冷却水出水温度与电极升起联锁投入状态 1#炉盖回水温度联锁 + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-JL-3_1", SBXH_JL_3); + // 冷却水出水温度与电极自动断电联锁投入状态 冷却水出水温度与电极升起联锁投入状态 2#炉盖回水温度联锁 + SimpleInputRegister SBXH_JL_4 = new SimpleInputRegister(); + SimpleInputRegister SBXH_JL_4_1 = new SimpleInputRegister(); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-JL-4", SBXH_JL_4); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-JL-4_1", SBXH_JL_4); + // 进出水流量差与电极自动断电联锁投入状态 进出水流量差与电极升起联锁投入状态 1#炉盖回水流量差联锁 + SimpleInputRegister SBXH_JL_5 = new SimpleInputRegister(); + SimpleInputRegister SBXH_JL_5_1 = new SimpleInputRegister(); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-JL-5", SBXH_JL_5); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-JL-5_1", SBXH_JL_5); + // 进出水流量差与电极自动断电联锁投入状态 进出水流量差与电极升起联锁投入状态 2#炉盖回水流量差联锁 + SimpleInputRegister SBXH_JL_6 = new SimpleInputRegister(); + SimpleInputRegister SBXH_JL_6_1 = new SimpleInputRegister(); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-JL-6", SBXH_JL_6); + SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.put("SBXH-JL-6_1", SBXH_JL_6); + spi.addInputRegister(SBXH_JL_1_1_hig); + spi.addInputRegister(SBXH_JL_1_2_low); + spi.addInputRegister(SBXH_JL_1_2_hig); + spi.addInputRegister(SBXH_JL_1_2_low); + spi.addInputRegister(SBXH_JL_3_1_hig); + spi.addInputRegister(SBXH_JL_3_1_low); + spi.addInputRegister(SBXH_JL_3_2_hig); + spi.addInputRegister(SBXH_JL_3_2_low); + spi.addInputRegister(SBXH_JL_3); + spi.addInputRegister(SBXH_JL_4); + spi.addInputRegister(SBXH_JL_5); + spi.addInputRegister(SBXH_JL_6); + spi.addInputRegister(SBXH_JL_3_1); + spi.addInputRegister(SBXH_JL_4_1); + spi.addInputRegister(SBXH_JL_5_1); + spi.addInputRegister(SBXH_JL_6_1); + + } +} diff --git a/src/main/java/com/netsdk/utils/DateUtil.java b/src/main/java/com/netsdk/utils/DateUtil.java new file mode 100644 index 0000000..0129176 --- /dev/null +++ b/src/main/java/com/netsdk/utils/DateUtil.java @@ -0,0 +1,1037 @@ +package com.netsdk.utils; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Duration; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +/** + * 说明:日期处理 + * 作者:luoxiaobao + * 官网:www.qdkjchina.com + */ +public class DateUtil { + + private final static SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy"); + private final static SimpleDateFormat sdfMonth = new SimpleDateFormat("MM"); + private final static SimpleDateFormat sdfOnlyDay = new SimpleDateFormat("dd"); + private final static SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd"); + private final static SimpleDateFormat sdfMDay = new SimpleDateFormat("yyyy-M-d"); + private final static SimpleDateFormat sdfDays = new SimpleDateFormat("yyyyMMdd"); + private final static SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + private final static SimpleDateFormat sdfTimes = new SimpleDateFormat("yyyyMMddHHmmss"); + private static final DateTimeFormatter FORMATTER = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + private static final DateTimeFormatter FORMATTERV2 = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + /** + * 获取YYYY格式 + * @return + */ + public static String getSdfTimes() { + return sdfTimes.format(new Date()); + } + + /** + * 获取YYYY格式 + * @return + */ + public static String getYear() { + return sdfYear.format(new Date()); + } + public static String getMonth() { + return sdfMonth.format(new Date()); + } + + /** + * 获取DD格式 + * @return + */ + public static String getOnlyDay() { + return sdfOnlyDay.format(new Date()); + } + + /** + * 获取YYYY-MM-DD格式 + * @return + */ + public static String getDay() { + return sdfDay.format(new Date()); + } + public static String MDay() { + return sdfMDay.format(new Date()); + } + + /** + * 获取YYYYMMDD格式 + * @return + */ + public static String getDays(){ + return sdfDays.format(new Date()); + } + + /** + * 获取YYYY-MM-DD HH:mm:ss格式 + * @return + */ + public static String getTime() { + return sdfTime.format(new Date()); + } + + /** + * @Title: compareDate + * @Description: TODO(日期比较,如果s>=e 返回true 否则返回false) + * @param s + * @param e + * @return boolean + * @throws + * @author fh + */ + public static boolean compareDate(String s, String e) { + if(fomatDate(s)==null||fomatDate(e)==null){ + return false; + } + return fomatDate(s).getTime() >=fomatDate(e).getTime(); + } + /** + * 格式化日期 + * @return + */ + public static Date fomatDate(String date,String pattern) { + DateFormat fmt = new SimpleDateFormat(pattern); + try { + return fmt.parse(date); + } catch (ParseException e) { + e.printStackTrace(); + return null; + } + } + /** + * 格式化日期 + * @return + */ + public static Date fomatDate(String date) { + DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); + try { + return fmt.parse(date); + } catch (ParseException e) { + e.printStackTrace(); + return null; + } + } + public static boolean isFirstDateGreaterOrEqual(String dateStr1, String dateStr2) { + // 定义日期格式 + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + // 解析字符串为LocalDate对象 + LocalDate date1 = LocalDate.parse(dateStr1, formatter); + LocalDate date2 = LocalDate.parse(dateStr2, formatter); + + // 比较日期,date1是否等于或晚于date2 + return date1.isEqual(date2) || date1.isAfter(date2); + } + /** + * 格式化日期 + * @return + */ + public static Date fomatDateTime(String date) { + DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + try { + return fmt.parse(date); + } catch (ParseException e) { + e.printStackTrace(); + return null; + } + } + + /** + * 格式化日期 + * @return + */ + public static String fomatDateByYMDHMS(String date) { + DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + try { + Date time = fmt.parse(date); + return sdfTimes.format(time); + } catch (ParseException e) { + e.printStackTrace(); + return null; + } + } + + /** + * 校验日期是否合法 + * @return + */ + public static boolean isValidDate(String s) { + DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); + try { + fmt.parse(s); + return true; + } catch (Exception e) { + return false; // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对 + } + } + + /** + * @param startTime + * @param endTime + * @return + */ + public static int getDiffYear(String startTime,String endTime) { + DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); + try { + int years=(int) (((fmt.parse(endTime).getTime()-fmt.parse(startTime).getTime())/ (1000 * 60 * 60 * 24))/365); + return years; + } catch (Exception e) { + return 0; // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对 + } + } + + /** + *
  • 功能描述:时间相减得到天数 + * @param beginDateStr + * @param endDateStr + * @return + * long + * @author Administrator + */ + public static long getDaySub(String beginDateStr,String endDateStr){ + long day=0; + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + Date beginDate = null; + Date endDate = null; + try { + beginDate = format.parse(beginDateStr); + endDate= format.parse(endDateStr); + } catch (ParseException e) { + e.printStackTrace(); + } + day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000); + //System.out.println("相隔的天数="+day); + return day; + } + + /** + * 得到n天之后的日期 + * @param days + * @return + */ + public static String getAfterDayDate(String days) { + int daysInt = Integer.parseInt(days); + Calendar canlendar = Calendar.getInstance(); // java.util包 + canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动 + Date date = canlendar.getTime(); + SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String dateStr = sdfd.format(date); + return dateStr; + } + + /** + * 得到n天之后是周几 + * @param days + * @return + */ + public static String getAfterDayWeek(String days) { + int daysInt = Integer.parseInt(days); + Calendar canlendar = Calendar.getInstance(); // java.util包 + canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动 + Date date = canlendar.getTime(); + SimpleDateFormat sdf = new SimpleDateFormat("E"); + String dateStr = sdf.format(date); + return dateStr; + } + + /** + * 按照yyyy-MM-dd HH:mm:ss的格式,日期转字符串 + * @param date + * @return yyyy-MM-dd HH:mm:ss + */ + public static String date2Str(Date date){ + return date2Str(date,"yyyy-MM-dd HH:mm:ss"); + } + public static String date3Str(Date date){ + return date2Str(date,"yyyy-M-d"); + } + + + /** + * 把时间根据时、分、秒转换为时间段 + * @param StrDate + */ + public static String getTimes(String StrDate){ + String resultTimes = ""; + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date now; + try { + now = new Date(); + Date date=df.parse(StrDate); + long times = now.getTime()-date.getTime(); + long day = times/(24*60*60*1000); + long hour = (times/(60*60*1000)-day*24); + long min = ((times/(60*1000))-day*24*60-hour*60); + long sec = (times/1000-day*24*60*60-hour*60*60-min*60); + + StringBuffer sb = new StringBuffer(); + //sb.append("发表于:"); + if(hour>0 ){ + sb.append(hour+"小时前"); + } else if(min>0){ + sb.append(min+"分钟前"); + } else{ + sb.append(sec+"秒前"); + } + resultTimes = sb.toString(); + } catch (ParseException e) { + e.printStackTrace(); + } + return resultTimes; + } + + /** + * 按照参数format的格式,日期转字符串 + * @param date + * @param format + * @return + */ + public static String date2Str(Date date,String format){ + if(date!=null){ + SimpleDateFormat sdf = new SimpleDateFormat(format); + return sdf.format(date); + }else{ + return ""; + } + } + + /** + * 获取当年的第一天 + * @param + * @author zhangyue + * @return + */ + public static String getCurrYearFirst(){ + Calendar currCal=Calendar.getInstance(); + int currentYear = currCal.get(Calendar.YEAR); + Calendar calendar = Calendar.getInstance(); + calendar.clear(); + calendar.set(Calendar.YEAR, currentYear); + Date currYearFirst = calendar.getTime(); + return sdfDay.format(currYearFirst); + } + + /** + * 获取当年的最后一天 + * @param + * @author zhangyue + * @return + */ + public static String getCurrYearLast(){ + Calendar currCal=Calendar.getInstance(); + int currentYear = currCal.get(Calendar.YEAR); + Calendar calendar = Calendar.getInstance(); + calendar.clear(); + calendar.set(Calendar.YEAR, currentYear); + calendar.roll(Calendar.DAY_OF_YEAR, -1); + Date currYearLast = calendar.getTime(); + return sdfDay.format(currYearLast); + } + + + + /** + * 获取当前季度第一天 + * @author zhangyue + * @return + */ + public static String quarterStart() { + Date dBegin = new Date(); + Calendar calBegin = Calendar.getInstance(); + calBegin.setTime(dBegin); + int remainder = calBegin.get(Calendar.MONTH) % 3; + int month = remainder != 0 ? calBegin.get(Calendar.MONTH) - remainder: calBegin.get(Calendar.MONTH); + + calBegin.set(Calendar.MONTH, month); + calBegin.set(Calendar.DAY_OF_MONTH, calBegin.getActualMinimum(Calendar.DAY_OF_MONTH)); + + calBegin.setTime(calBegin.getTime()); + return sdfDay.format(calBegin.getTime()); + } + + /** + * 获取当前季度最后一天 + * @author zhangyue + * @return + */ + public static String quarterEnd() { + Date dEnd = new Date(); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(dEnd); + int remainder = (calendar.get(Calendar.MONTH) + 1) % 3; + int month = remainder != 0 ? calendar.get(Calendar.MONTH) + (3 - remainder) : calendar.get(Calendar.MONTH); + calendar.set(Calendar.MONTH, month); + calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); + calendar.setTime(calendar.getTime()); + return sdfDay.format(calendar.getTime()); + } + + /** + * 获取本月第一天日期 + * @return + */ + public static String getMonthFirstDay() { + Calendar thisMonthFirstDateCal = Calendar.getInstance(); + thisMonthFirstDateCal.set(Calendar.DAY_OF_MONTH, 1); + String thisMonthFirstTime = sdfDay.format(thisMonthFirstDateCal.getTime()); + return thisMonthFirstTime; + } + + /** + * 获取本月最后一天日期 + * @return + */ + public static String getMonthEndDay() { + Calendar thisMonthEndDateCal = Calendar.getInstance(); + thisMonthEndDateCal.set(Calendar.DAY_OF_MONTH, thisMonthEndDateCal.getActualMaximum(Calendar.DAY_OF_MONTH)); + String thisMonthEndTime = sdfDay.format(thisMonthEndDateCal.getTime()); + return thisMonthEndTime; + } + public static boolean timeCalendar(Date nowTime, Date amBeginTime, Date amEndTime) { + //设置当前时间 + Calendar date = Calendar.getInstance(); + date.setTime(nowTime); + //设置开始时间 + Calendar amBegin = Calendar.getInstance(); + amBegin.setTime(amBeginTime);//上午开始时间 + //设置结束时间 + Calendar amEnd = Calendar.getInstance(); + amEnd.setTime(amEndTime);//上午结束时间 + //处于开始时间之后,和结束时间之前的判断 + if ((date.after(amBegin) && date.before(amEnd))) { + return true; + } else { + return false; + } + } + + /** + * 获取本周的第一天 + * @return String + * **/ + public static String getWeekStart(){ + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 设置时间格式 + Calendar cal = Calendar.getInstance(); + // Calendar c = Calendar.getInstance(); + cal.add(Calendar.DAY_OF_MONTH, 0); + // cal.setTime(time); + + // 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了 + int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天 + if (1 == dayWeek) { + cal.add(Calendar.DAY_OF_MONTH, -1); + } + + cal.setFirstDayOfWeek(Calendar.MONDAY);// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一 + + int day = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天 + cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值 + /* + * cal.add(Calendar.DATE, 6); + * System.out.println("所在周星期日的日期:"+sdf.format(cal.getTime())); + */ + + return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()) + " 00:00:00"; + } + /** + * 获取本周的最后一天 + * @return String + * **/ + public static String getWeekEnd(){ + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 设置时间格式 + Calendar cal = Calendar.getInstance(); + // Calendar c = Calendar.getInstance(); + cal.add(Calendar.DAY_OF_MONTH, 0); + // cal.setTime(time); + + // 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了 + int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天 + if (1 == dayWeek) { + cal.add(Calendar.DAY_OF_MONTH, -1); + } + + cal.setFirstDayOfWeek(Calendar.MONDAY);// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一 + + int day = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天 + cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值 + + cal.add(Calendar.DATE, 6); + + return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()) + " 23:59:59"; + } + + + + /** + * 判断时间格式 格式必须为“YYYY-MM-dd” + * 2004-2-30 是无效的 + * 2003-2-29 是无效的 + * @param sDate + * @return + */ + public static boolean isLegalDate(String sDate) { + int legalLen = 10; + if ((sDate == null) || (sDate.length() != legalLen)) { + return false; + } + + DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); + try { + Date date = formatter.parse(sDate); + return sDate.equals(formatter.format(date)); + } catch (Exception e) { + return false; + } + } + + /** + * 时间比较 + * @param amBeginTime + * @param amEndTime + * @return + */ + public static boolean timeCompare(Date amBeginTime, Date amEndTime) { + //设置开始时间 + Calendar amBegin = Calendar.getInstance(); + amBegin.setTime(amBeginTime);//上午开始时间 + //设置结束时间 + Calendar amEnd = Calendar.getInstance(); + amEnd.setTime(amEndTime);//上午结束时间 + //开始时间是否早于结束时间 + if (amBegin.before(amEnd)) { + return true; + } else { + return false; + } + } + + /** + * 获取6个月内月份日期 + * @param flag 结果是否显示年份 + * @return + */ + public static List getHalfYearMonth(boolean flag) { + Calendar c = Calendar.getInstance(); + c.add(Calendar.MONTH, -4); + String before_six = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH);// 六个月前 + List result = new ArrayList(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");// 格式化为年月 + Calendar min = Calendar.getInstance(); + Calendar max = Calendar.getInstance(); + try { + min.setTime(sdf.parse(before_six)); + min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1); + max.setTime(sdf.parse(sdf.format(new Date()))); + + //不含当前月 + + /* int month = max.get(Calendar.MONTH); + max.set(Calendar.MONTH, month-1); + */ + } catch (ParseException e) { + e.printStackTrace(); + } + max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2); + Calendar curr = min; + while (curr.before(max)) { + if (flag) { + result.add(sdf.format(curr.getTime())); + } else { + result.add(curr.get(Calendar.MONTH) + 1 + "月"); + } + curr.add(Calendar.MONTH, 1); + } + return result; + } + //根据当前日期获得最近n周的日期区间(不包含本周) + public static String getFromToDate(SimpleDateFormat sdf, Date date, int n, int option, int k) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1; + int offset = 0 == option ? 1 - dayOfWeek : 7 - dayOfWeek; + int amount = 0 == option ? offset - (n - 1 + k) * 7 : offset - k * 7; + calendar.add(Calendar.DATE, amount); + return sdf.format(calendar.getTime()); + } + public static SimpleDateFormat sdf() { + return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + } + // 获取上周的开始时间 + public static String getBeginDayOfLastWeek() { + //上周日期 + SimpleDateFormat sdf = sdf(); + String beginDate = getFromToDate(sdf, new Date(), 1, 0, 1); + + Calendar calendar = Calendar.getInstance(); + try { + calendar.setTime(sdf.parse(beginDate)); + }catch (Exception e){ + e.printStackTrace(); + } + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); + return sdf.format(calendar.getTime()); + } + + // 获取上周的结束时间 + public static String getEndDayOfLastWeek() { + //上周日期 + SimpleDateFormat sdf = sdf(); + String endDate = getFromToDate(sdf, new Date(), 1, 1, 1); + + Calendar calendar = Calendar.getInstance(); + try { + calendar.setTime(sdf.parse(endDate)); + }catch (Exception e){ + e.printStackTrace(); + } + calendar.set(Calendar.HOUR_OF_DAY, 23); + calendar.set(Calendar.MINUTE, 59); + calendar.set(Calendar.SECOND, 59); + return sdf.format(calendar.getTime()); + } + + // 获得上月第一天0点时间 + public static String getTimesLastMonthmorning() { + //上月日期 + Calendar c=Calendar.getInstance(); + c.add(Calendar.MONTH, -1); + SimpleDateFormat sdf = sdf(); + String gtimelast = sdf.format(c.getTime()); //上月 + int lastMonthMaxDay=c.getActualMaximum(Calendar.DAY_OF_MONTH); + c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), lastMonthMaxDay, 23, 59, 59); + + //按格式输出 + SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-01 00:00:00"); + String gtime = sdf2.format(c.getTime()); //上月第一天 + return gtime; + } + // 获得上月最后一天24点时间 + public static String getTimesLastMonthnight() { + //上月日期 + Calendar c=Calendar.getInstance(); + c.add(Calendar.MONTH, -1); + SimpleDateFormat sdf = sdf(); + String gtimelast = sdf.format(c.getTime()); //上月 + int lastMonthMaxDay=c.getActualMaximum(Calendar.DAY_OF_MONTH); + c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), lastMonthMaxDay, 23, 59, 59); + + //按格式输出 + String gtime = sdf.format(c.getTime()); //上月最后一天 + return gtime; + } + /** + * 获取上一季度 开始和结束时间 + * + * @return + */ + public static String[] getLastQuarter() { + SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd"); + String[] range = new String[2]; + Calendar startCalendar = Calendar.getInstance(); + startCalendar.set(Calendar.MONTH, ((int) startCalendar.get(Calendar.MONTH) / 3 - 1) * 3); + startCalendar.set(Calendar.DAY_OF_MONTH, 1); + Date startDate = startCalendar.getTime(); + range[0] = sdfd.format(startDate); + + Calendar endCalendar = Calendar.getInstance(); + endCalendar.set(Calendar.MONTH, ((int) endCalendar.get(Calendar.MONTH) / 3 - 1) * 3 + 2); + endCalendar.set(Calendar.DAY_OF_MONTH, endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH)); + Date endDate = endCalendar.getTime(); + range[1] = sdfd.format(endDate); + return range; + } + + /** + * 获取当日期前/后某个月的所有日期 0 本月 负数 之前的月份 。正数 之后的月份 + * + * @param months + * @return + */ + public static List getDayListOfMonth(Integer months) { + List list = new ArrayList<>(); + Calendar cal = Calendar.getInstance(); + cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + months); + int month = cal.get(Calendar.MONTH) + 1; + String monthStr = month < 10 ? "0" + month : String.valueOf(month); + int year = cal.get(Calendar.YEAR); + int day = cal.getActualMaximum(Calendar.DATE); + for (int i = 1; i <= day; i++) { + String d = String.valueOf(i); + if (i < 10) { + d = "0" + d; + } + list.add(year + "-" + monthStr + "-" + d); + } + return list; + } + + /** + * 计算两个日期之间相差的天数 + * + * @param smdate 较小的时间 + * @param bdate 较大的时间 + * @return 相差天数 + * @throws ParseException + */ + public static int daysBetween(Date smdate, Date bdate) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + + try { + smdate = sdf.parse(sdf.format(smdate)); + bdate = sdf.parse(sdf.format(bdate)); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Calendar cal = Calendar.getInstance(); + cal.setTime(smdate); + long time1 = cal.getTimeInMillis(); + cal.setTime(bdate); + long time2 = cal.getTimeInMillis(); + long between_days = (time2 - time1) / (1000 * 3600 * 24); + + return Integer.parseInt(String.valueOf(between_days)); + } + + /** + * 字符串的日期格式的计算 + */ + public static int daysBetween(String smdate, String bdate) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Calendar cal = Calendar.getInstance(); + long time1 = 0; + long time2 = 0; + try { + cal.setTime(sdf.parse(smdate)); + time1 = cal.getTimeInMillis(); + cal.setTime(sdf.parse(bdate)); + time2 = cal.getTimeInMillis(); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + long between_days = (time2 - time1) / (1000 * 3600 * 24); + + return Integer.parseInt(String.valueOf(between_days)); + } + + /** + * 得到几天前的时间 + * + * @param d + * @param day + * @return + */ + public static Date getDateBefore(Date d, int day) { + Calendar now = Calendar.getInstance(); + now.setTime(d); + now.set(Calendar.DATE, now.get(Calendar.DATE) - day); + return now.getTime(); + } + + /** + * 得到几天后的时间 + * + * @param d + * @param day + * @return + */ + public static Date getDateAfter(Date d, int day) { + Calendar now = Calendar.getInstance(); + now.setTime(d); + now.set(Calendar.DATE, now.get(Calendar.DATE) + day); + return now.getTime(); + } + + + + + private final static SimpleDateFormat utsTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + + public static String parseCSTToUTC(String CSTStr){ + Date date = null; + String cstTime = null; + Calendar calendar = null; + try { + date = sdfTime.parse(CSTStr); + calendar = Calendar.getInstance(); + calendar.setTime(date); + //注意这里,需要+8小时 + calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR)-8); + cstTime = utsTime.format(calendar.getTime()); + } catch (ParseException e) { + e.printStackTrace(); + } + return cstTime; + } + + public static int getCurrentHour() { + LocalDateTime now = LocalDateTime.now(); + return now.getHour(); + } + public static String getCurrentHourAndMinute() { + LocalDateTime now = LocalDateTime.now(); + return now.getHour()+ ":59"; + } + + public static String dateCheckToday(int i,int type) { + + return getTimeSlotRange(type)[i]; + } + public static String[] getTimeSlotRange(int type) { + // 获取当前时间 + Calendar calendar = Calendar.getInstance(); + Date currentDate = calendar.getTime(); + + // 格式化当前时间为 HH:mm:ss + SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); + String currentTime = timeFormat.format(currentDate); + + // 获取当前小时 + int currentHour = calendar.get(Calendar.HOUR_OF_DAY); + + // 获取当前时间的时段起始时间 + int startHour = (currentHour / 2) * 2; + // 每2小时一个时段 + calendar.set(Calendar.HOUR_OF_DAY, startHour); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + String startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime()); + + // 获取当前时段的结束时间,当前时段的最后一秒 + calendar.set(Calendar.HOUR_OF_DAY, startHour + type-1); + calendar.set(Calendar.MINUTE, 59); + calendar.set(Calendar.SECOND, 59); + String endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime()); + + return new String[]{startTime, endTime}; + } + public static String[] getTimeSlotRangeApp(int type) { + // 获取当前时间 + Calendar calendar = Calendar.getInstance(); + // 获取当前小时 + int currentHour = calendar.get(Calendar.HOUR_OF_DAY); + if (currentHour == 23) { + return new String[]{getDay()+" "+(23-type+1)+":00", getDay()+" 24:00"}; + } + if (currentHour == 22) { + return new String[]{getDay()+" "+(23-type+1)+":00", getDay()+" 24:00"}; + } + if (type == 2 ) { + if (currentHour % 2 != 0) { + currentHour = currentHour-1; + } + } + // 获取当前时间的时段起始时间 + int startHour = (int) ((double) currentHour /2*2); + // 每2小时一个时段 + if (type == 1) { + calendar.set(Calendar.HOUR_OF_DAY, startHour==0?currentHour:startHour); + }else { + calendar.set(Calendar.HOUR_OF_DAY, startHour); + } + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + String startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(calendar.getTime()); + if (startHour + type >=24) { + return new String[]{startTime, getDay()+" 24:00"}; + } + // 获取当前时段的结束时间,当前时段的最后一秒 + if (type == 1) { + calendar.set(Calendar.HOUR_OF_DAY, startHour+1); + }else { + calendar.set(Calendar.HOUR_OF_DAY, startHour + type); + } + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + String endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(calendar.getTime()); + + return new String[]{startTime, endTime}; + } + public static String[] getTimeSlotRangeApp(int type,int currentHour) { + // 获取当前时间 + Calendar calendar = Calendar.getInstance(); + // 获取当前小时 +// int currentHour = calendar.get(Calendar.HOUR_OF_DAY); + if (currentHour == 23) { + return new String[]{getDay()+" "+(23-type+1)+":00", getDay()+" 24:00"}; + } + if (currentHour == 22) { + return new String[]{getDay()+" "+(23-type+1)+":00", getDay()+" 24:00"}; + } + if (type == 2 ) { + if (currentHour % 2 != 0) { + currentHour = currentHour-1; + } + } + // 获取当前时间的时段起始时间 + int startHour = (int) ((double) currentHour /2*2); + // 每2小时一个时段 + if (type == 1) { + calendar.set(Calendar.HOUR_OF_DAY, startHour==0?currentHour:startHour); + }else { + calendar.set(Calendar.HOUR_OF_DAY, startHour); + } + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + String startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(calendar.getTime()); + if (startHour + type >=24) { + return new String[]{startTime, getDay()+" 24:00"}; + } + // 获取当前时段的结束时间,当前时段的最后一秒 + if (type == 1) { + calendar.set(Calendar.HOUR_OF_DAY, startHour+1); + }else { + calendar.set(Calendar.HOUR_OF_DAY, startHour + type); + } + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + String endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(calendar.getTime()); + + return new String[]{startTime, endTime}; + } + public static String[] getTimeSlotRangeAppV1(int type,int currentHour) { + // 获取当前时间 + Calendar calendar = Calendar.getInstance(); + // 获取当前小时 +// int currentHour = calendar.get(Calendar.HOUR_OF_DAY); + if (currentHour == 23) { + return new String[]{getDay()+" "+(23-type+1)+":00", getDay()+" 24:00"}; + } + // 获取当前时间的时段起始时间 +// int startHour = (currentHour / 2) * 2; + + int startHour = (int) ((double) currentHour /2*2); + + // 每2小时一个时段 + calendar.set(Calendar.HOUR_OF_DAY, startHour); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + String startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(calendar.getTime()); + + if (startHour + type >=24) { + return new String[]{startTime, getDay()+" 24:00"}; + } + // 获取当前时段的结束时间,当前时段的最后一秒 + calendar.set(Calendar.HOUR_OF_DAY, startHour + type); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + String endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(calendar.getTime()); + + return new String[]{startTime, endTime}; + } + public static String[] getTimeSlotRangeAppV2(int type,int currentHour) { + // 获取当前时间 + Calendar calendar = Calendar.getInstance(); + // 获取当前小时 +// int currentHour = calendar.get(Calendar.HOUR_OF_DAY); + if (currentHour == 23) { + return new String[]{getDay()+" "+(23-type+1)+":00", getDay()+" 24:00"}; + } + if (type == 2 ) { + if (currentHour % 2 != 0) { + currentHour = currentHour-1; + } + } + // 获取当前时间的时段起始时间 + int startHour = (int) ((double) currentHour /2*2); + // 每2小时一个时段 + calendar.set(Calendar.HOUR_OF_DAY, startHour); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + String startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(calendar.getTime()); + + if (startHour + type >=24) { + return new String[]{startTime, getDay()+" 24:00"}; + } + // 获取当前时段的结束时间,当前时段的最后一秒 + calendar.set(Calendar.HOUR_OF_DAY, startHour + type); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + String endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(calendar.getTime()); + + return new String[]{startTime, endTime}; + } + + public static long getDiffMinutes(String creatTime, String periodend) { + // 解析时间字符串 + LocalDateTime time1 = LocalDateTime.parse(creatTime, FORMATTER); + LocalDateTime time2 = LocalDateTime.parse(periodend, FORMATTER); + return Duration.between(time2, time1).toMinutes(); + } + public static long getDiffMinutesV2(String creatTime, String periodend) { + // 解析时间字符串 + LocalDateTime time1 = LocalDateTime.parse(creatTime, FORMATTER); + LocalDateTime time2 = LocalDateTime.parse(periodend, FORMATTERV2); + return Duration.between(time2, time1).toMinutes(); + } + public static void main(String[] args) { + System.out.println(getTimeSlotRangeApp(1,0)[0]); + System.out.println(getTimeSlotRangeApp(1,0)[1]); + System.out.println(getTimeSlotRangeApp(1,1)[0]); + System.out.println(getTimeSlotRangeApp(1,1)[1]); + System.out.println(getTimeSlotRangeApp(1,10)[0]); + System.out.println(getTimeSlotRangeApp(1,10)[1]); + System.out.println(getTimeSlotRangeApp(1,11)[0]); + System.out.println(getTimeSlotRangeApp(1,11)[1]); + System.out.println(getTimeSlotRangeApp(1,17)[0]); + System.out.println(getTimeSlotRangeApp(1,17)[1]); + System.out.println(getTimeSlotRangeApp(1,20)[0]); + System.out.println(getTimeSlotRangeApp(1,20)[1]); + System.out.println(getTimeSlotRangeApp(1,23)[0]); + System.out.println(getTimeSlotRangeApp(1,23)[1]); +// +// System.out.println(getTimeSlotRangeAppV1(1,22)[0]); +// System.out.println(getTimeSlotRangeAppV1(1,22)[1]); +// System.out.println(getTimeSlotRangeAppV1(1,23)[0]); +// System.out.println(getTimeSlotRangeAppV1(1,23)[1]); + System.out.println("==========="); + System.out.println(getTimeSlotRangeApp(2,0)[0]); + System.out.println(getTimeSlotRangeApp(2,0)[1]); + System.out.println(getTimeSlotRangeApp(2,1)[0]); + System.out.println(getTimeSlotRangeApp(2,1)[1]); + System.out.println(getTimeSlotRangeApp(2,2)[0]); + System.out.println(getTimeSlotRangeApp(2,2)[1]); + System.out.println(getTimeSlotRangeApp(2,3)[0]); + System.out.println(getTimeSlotRangeApp(2,3)[1]); + System.out.println(getTimeSlotRangeApp(2,16)[0]); + System.out.println(getTimeSlotRangeApp(2,16)[1]); + System.out.println(getTimeSlotRangeApp(2,17)[0]); + System.out.println(getTimeSlotRangeApp(2,17)[1]); + System.out.println(getTimeSlotRangeApp(2,18)[0]); + System.out.println(getTimeSlotRangeApp(2,18)[1]); + System.out.println(getTimeSlotRangeApp(2,19)[0]); + System.out.println(getTimeSlotRangeApp(2,19)[1]); + System.out.println(getTimeSlotRangeApp(2,20)[0]); + System.out.println(getTimeSlotRangeApp(2,20)[1]); + System.out.println(getTimeSlotRangeApp(2,21)[0]); + System.out.println(getTimeSlotRangeApp(2,21)[1]); + System.out.println(getTimeSlotRangeApp(2,22)[0]); + System.out.println(getTimeSlotRangeApp(2,22)[1]); + System.out.println(getTimeSlotRangeApp(2,23)[0]); + System.out.println(getTimeSlotRangeApp(2,23)[1]); + System.out.println("==========="); + + } +} diff --git a/src/main/java/com/netsdk/utils/FilePathUtils.java b/src/main/java/com/netsdk/utils/FilePathUtils.java new file mode 100644 index 0000000..afdfcd5 --- /dev/null +++ b/src/main/java/com/netsdk/utils/FilePathUtils.java @@ -0,0 +1,42 @@ +package com.netsdk.utils; + +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; + +import javax.servlet.http.HttpServletRequest; +import java.io.File; + +/** + * 文件工具类 + * + * @author Yan Xu + * @version 1.0 + * @date 2021/8/7 + * Copyright © goodits + */ +@Slf4j +public class FilePathUtils { + + //路径前加.号代表项目根目录 + private static final String DIR_PATH = "./static/img"; + + @SneakyThrows + public static String getUploadDir() { + //如果目录不存在,自动创建文件夹 + File dir = new File(DIR_PATH); + if (!dir.exists()) { + //文件 + boolean mkdir = dir.mkdirs(); + if (Boolean.FALSE.equals(mkdir)) { + log.warn("创建目录{}失败", DIR_PATH); + return null; + } + } + return dir.getAbsolutePath(); + } + + public static String getUrlPathByFileName(HttpServletRequest request, String fileName) { + return request.getScheme() + "://" + request.getServerName() + ":" + + request.getServerPort() + "/img/" + fileName; + } +} diff --git a/src/main/java/com/netsdk/utils/ModBusUtils.java b/src/main/java/com/netsdk/utils/ModBusUtils.java new file mode 100644 index 0000000..1f20717 --- /dev/null +++ b/src/main/java/com/netsdk/utils/ModBusUtils.java @@ -0,0 +1,9 @@ +package com.netsdk.utils; + +import org.springframework.stereotype.Component; + +@Component +public class ModBusUtils { + + +} diff --git a/src/main/java/com/netsdk/utils/OtherInputRegister.java b/src/main/java/com/netsdk/utils/OtherInputRegister.java new file mode 100644 index 0000000..bd36f1a --- /dev/null +++ b/src/main/java/com/netsdk/utils/OtherInputRegister.java @@ -0,0 +1,27 @@ +package com.netsdk.utils; + +import com.ghgande.j2mod.modbus.procimg.IllegalAddressException; +import com.ghgande.j2mod.modbus.procimg.SimpleInputRegister; + + +/** + * @author lin + */ +public class OtherInputRegister extends SimpleInputRegister { + public OtherInputRegister() { + } + + public synchronized void setFloatValue(float f) { + if (this.register == null) { + throw new IllegalAddressException(); + } + // 将浮点数转换为32位整数 + int intBits = Float.floatToIntBits(f); + + // 拆分成两个16位寄存器 + this.register[0] = (byte) ((intBits >> 16) & 0xFF); + // 高16位 + this.register[1] = (byte) (intBits & 0xFF); + // 低16位 + } +} diff --git a/src/main/java/com/netsdk/utils/RedisUtil.java b/src/main/java/com/netsdk/utils/RedisUtil.java new file mode 100644 index 0000000..8978bda --- /dev/null +++ b/src/main/java/com/netsdk/utils/RedisUtil.java @@ -0,0 +1,720 @@ +package com.netsdk.utils; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; + +import java.util.*; +import java.util.concurrent.TimeUnit; + +@Component +public final class RedisUtil { + + @Autowired + private RedisTemplate redisTemplate; + + // =============================common============================ + + /** + * 指定缓存失效时间 + * + * @param key 键 + * @param time 时间(秒) + * @return + */ + public boolean expire(String key, long time) { + try { + if (time > 0) { + redisTemplate.expire(key, time, TimeUnit.SECONDS); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public boolean expire(String key, long time, TimeUnit timeUnit) { + try { + if (time > 0) { + redisTemplate.expire(key, time, timeUnit); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 根据key 获取过期时间 + * + * @param key 键 不能为null + * @return 时间(秒) 返回0代表为永久有效 + */ + public long getExpire(String key) { + return redisTemplate.getExpire(key, TimeUnit.SECONDS); + } + + /** + * 判断key是否存在 + * + * @param key 键 + * @return true 存在 false不存在 + */ + public boolean hasKey(String key) { + try { + return redisTemplate.hasKey(key); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 删除缓存 + * + * @param key 可以传一个值 或多个 + */ + @SuppressWarnings("unchecked") + public void del(String... key) { + if (key != null && key.length > 0) { + if (key.length == 1) { + redisTemplate.delete(key[0]); + } else { + redisTemplate.delete(CollectionUtils.arrayToList(key)); + } + } + } + + // ============================String============================= + + /** + * 普通缓存获取 + * + * @param key 键 + * @return 值 + */ + public Object get(String key) { + return key == null ? null : redisTemplate.opsForValue().get(key); + } + + /** + * 普通缓存放入 + * + * @param key 键 + * @param value 值 + * @return true成功 false失败 + */ + public boolean set(String key, Object value) { + try { + redisTemplate.opsForValue().set(key, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 普通缓存放入并设置时间 + * + * @param key 键 + * @param value 值 + * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 + * @return true成功 false 失败 + */ + + public boolean set(String key, Object value, long time) { + try { + if (time > 0) { + redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); + } else { + set(key, value); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + public boolean set(String key, Object value, long time, TimeUnit timeUnit) { + try { + if (time > 0) { + redisTemplate.opsForValue().set(key, value, time, timeUnit); + } else { + set(key, value); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 递增 + * + * @param key 键 + * @param delta 要增加几(大于0) + * @return + */ + + public long incr(String key, long delta) { + if (delta < 0) { + throw new RuntimeException("递增因子必须大于0"); + } + return redisTemplate.opsForValue().increment(key, delta); + } + + /** + * 递减 + * + * @param key 键 + * @param delta 要减少几(小于0) + * @return + */ + public long decr(String key, long delta) { + if (delta < 0) { + throw new RuntimeException("递减因子必须大于0"); + } + return redisTemplate.opsForValue().increment(key, -delta); + } + + // ================================Map================================= + + /** + * HashGet + * + * @param key 键 不能为null + * @param item 项 不能为null + * @return 值 + */ + public Object hget(String key, String item) { + return redisTemplate.opsForHash().get(key, item); + } + + /** + * 只有当给定的键不存在时,才设置键值对 + * @param hashKey 是哈希表的键,用于定位到Redis中的特定哈希表。 + * @param key 键 不能为null + * @param value 项 不能为null + * @return 值 + */ + public Object hPutIfAbsent(String hashKey, String key, Object value) { + return redisTemplate.opsForHash().putIfAbsent(hashKey, key, value); + } + + /** + * 获取hashKey对应的所有键值 + * + * @param key 键 + * @return 对应的多个键值 + */ + public Map hmget(String key) { + return redisTemplate.opsForHash().entries(key); + } + + /** + * HashSet + * + * @param key 键 + * @param map 对应多个键值 + * @return true 成功 false 失败 + */ + public boolean hmset(String key, Map map) { + try { + redisTemplate.opsForHash().putAll(key, map); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * HashSet 并设置时间 + * + * @param key 键 + * @param map 对应多个键值 + * @param time 时间(秒) + * @return true成功 false失败 + */ + public boolean hmset(String key, Map map, long time) { + try { + redisTemplate.opsForHash().putAll(key, map); + if (time > 0) { + expire(key, time); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 向一张hash表中放入数据,如果不存在将创建 + * + * @param key 键 + * @param item 项 + * @param value 值 + * @return true 成功 false失败 + */ + public boolean hset(String key, String item, Object value) { + try { + redisTemplate.opsForHash().put(key, item, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 向一张hash表中放入数据,如果不存在将创建 + * + * @param key 键 + * @param item 项 + * @param value 值 + * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间 + * @return true 成功 false失败 + */ + public boolean hset(String key, String item, Object value, long time) { + try { + redisTemplate.opsForHash().put(key, item, value); + if (time > 0) { + expire(key, time); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 删除hash表中的值 + * + * @param key 键 不能为null + * @param item 项 可以使多个 不能为null + */ + public void hdel(String key, Object... item) { + redisTemplate.opsForHash().delete(key, item); + } + + /** + * 判断hash表中是否有该项的值 + * + * @param key 键 不能为null + * @param item 项 不能为null + * @return true 存在 false不存在 + */ + public boolean hHasKey(String key, String item) { + return redisTemplate.opsForHash().hasKey(key, item); + } + + /** + * hash递增 如果不存在,就会创建一个 并把新增后的值返回 + * + * @param key 键 + * @param item 项 + * @param by 要增加几(大于0) + * @return + */ + public double hincr(String key, String item, double by) { + return redisTemplate.opsForHash().increment(key, item, by); + } + + /** + * hash递减 + * + * @param key 键 + * @param item 项 + * @param by 要减少记(小于0) + * @return + */ + public double hdecr(String key, String item, double by) { + return redisTemplate.opsForHash().increment(key, item, -by); + } + + // ============================set============================= + + /** + * 根据key获取Set中的所有值 + * + * @param key 键 + * @return + */ + public Set sGet(String key) { + try { + return redisTemplate.opsForSet().members(key); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * 根据value从一个set中查询,是否存在 + * + * @param key 键 + * @param value 值 + * @return true 存在 false不存在 + */ + public boolean sHasKey(String key, Object value) { + try { + return redisTemplate.opsForSet().isMember(key, value); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 将数据放入set缓存 + * + * @param key 键 + * @param values 值 可以是多个 + * @return 成功个数 + */ + public long sSet(String key, Object... values) { + try { + return redisTemplate.opsForSet().add(key, values); + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 将set数据放入缓存 + * + * @param key 键 + * @param time 时间(秒) + * @param values 值 可以是多个 + * @return 成功个数 + */ + public long sSetAndTime(String key, long time, Object... values) { + try { + Long count = redisTemplate.opsForSet().add(key, values); + if (time > 0) expire(key, time); + return count; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 获取set缓存的长度 + * + * @param key 键 + * @return + */ + public long sGetSetSize(String key) { + try { + return redisTemplate.opsForSet().size(key); + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + /** + * 移除值为value的 + * + * @param key 键 + * @param values 值 可以是多个 + * @return 移除的个数 + */ + public long setRemove(String key, Object... values) { + try { + Long count = redisTemplate.opsForSet().remove(key, values); + return count; + } catch (Exception e) { + e.printStackTrace(); + return 0; + } + } + + // ===============================list================================= + + /** ------------------------list相关操作---------------------------- */ + + /** + * 通过索引获取列表中的元素 + * + * @param key + * @param index + * @return + */ + public Object lIndex(String key, long index) { + return redisTemplate.opsForList().index(key, index); + } + + /** + * 获取列表指定范围内的元素 + * + * @param key + * @param start 开始位置, 0是开始位置 + * @param end 结束位置, -1返回所有 + * @return + */ + public List lRange(String key, long start, long end) { + return redisTemplate.opsForList().range(key, start, end); + } + + /** + * 存储在list头部 + * + * @param key + * @param value + * @return + */ + public Long lLeftPush(String key, String value) { + return redisTemplate.opsForList().leftPush(key, value); + } + + /** + * @param key + * @param value + * @return + */ + public Long lLeftPushAll(String key, String... value) { + return redisTemplate.opsForList().leftPushAll(key, value); + } + + /** + * @param key + * @param value + * @return + */ + public Long lLeftPushAll(String key, Collection value) { + return redisTemplate.opsForList().leftPushAll(key, value); + } + + /** + * 当list存在的时候才加入 + * + * @param key + * @param value + * @return + */ + public Long lLeftPushIfPresent(String key, String value) { + return redisTemplate.opsForList().leftPushIfPresent(key, value); + } + + /** + * 如果pivot存在,再pivot前面添加 + * + * @param key + * @param pivot + * @param value + * @return + */ + public Long lLeftPush(String key, String pivot, String value) { + return redisTemplate.opsForList().leftPush(key, pivot, value); + } + + /** + * @param key + * @param value + * @return + */ + public Long lRightPush(String key, String value) { + return redisTemplate.opsForList().rightPush(key, value); + } + + /** + * @param key + * @param value + * @return + */ + public Long lRightPushAll(String key, String... value) { + return redisTemplate.opsForList().rightPushAll(key, value); + } + + /** + * @param key + * @param value + * @return + */ + public Long lRightPushAll(String key, Collection value) { + return redisTemplate.opsForList().rightPushAll(key, value); + } + + /** + * 为已存在的列表添加值 + * + * @param key + * @param value + * @return + */ + public Long lRightPushIfPresent(String key, String value) { + return redisTemplate.opsForList().rightPushIfPresent(key, value); + } + + /** + * 在pivot元素的右边添加值 + * + * @param key + * @param pivot + * @param value + * @return + */ + public Long lRightPush(String key, String pivot, String value) { + return redisTemplate.opsForList().rightPush(key, pivot, value); + } + + /** + * 通过索引设置列表元素的值 + * + * @param key + * @param index 位置 + * @param value + */ + public void lSet(String key, long index, String value) { + redisTemplate.opsForList().set(key, index, value); + } + + /** + * 移出并获取列表的第一个元素 + * + * @param key + * @return 删除的元素 + */ + public Object lLeftPop(String key) { + return redisTemplate.opsForList().leftPop(key); + } + + /** + * 移出并获取列表的第一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止 + * + * @param key + * @param timeout 等待时间 + * @param unit 时间单位 + * @return + */ + public Object lBLeftPop(String key, long timeout, TimeUnit unit) { + return redisTemplate.opsForList().leftPop(key, timeout, unit); + } + + /** + * 移除并获取列表最后一个元素 + * + * @param key + * @return 删除的元素 + */ + public Object lRightPop(String key) { + return redisTemplate.opsForList().rightPop(key); + } + + /** + * 移出并获取列表的最后一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止 + * + * @param key + * @param timeout 等待时间 + * @param unit 时间单位 + * @return + */ + public Object lBRightPop(String key, long timeout, TimeUnit unit) { + return redisTemplate.opsForList().rightPop(key, timeout, unit); + } + + /** + * 移除列表的最后一个元素,并将该元素添加到另一个列表并返回 + * + * @param sourceKey + * @param destinationKey + * @return + */ + public Object lRightPopAndLeftPush(String sourceKey, String destinationKey) { + return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, destinationKey); + } + + /** + * 从列表中弹出一个值,将弹出的元素插入到另外一个列表中并返回它; 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止 + * + * @param sourceKey + * @param destinationKey + * @param timeout + * @param unit + * @return + */ + public Object lBRightPopAndLeftPush(String sourceKey, String destinationKey, long timeout, TimeUnit unit) { + return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, destinationKey, timeout, unit); + } + + /** + * 删除集合中值等于value得元素 + * + * @param key + * @param index index=0, 删除所有值等于value的元素; index>0, 从头部开始删除第一个值等于value的元素; + * index<0, 从尾部开始删除第一个值等于value的元素; + * @param value + * @return + */ + public Long lRemove(String key, long index, String value) { + return redisTemplate.opsForList().remove(key, index, value); + } + + /** + * 裁剪list + * + * @param key + * @param start + * @param end + */ + public void lTrim(String key, long start, long end) { + redisTemplate.opsForList().trim(key, start, end); + } + + /** + * 获取列表长度 + * + * @param key + * @return + */ + public Long lLen(String key) { + return redisTemplate.opsForList().size(key); + } + + /** + * 加锁方法 + * + * @param lockKey 锁的键 + * @param value 锁的值(通常为唯一标识,如时间戳或UUID) + * @param expireMs 锁的过期时间(毫秒) + * @return true 加锁成功 false 加锁失败 + */ + public boolean lock(String lockKey, String value, long expireMs) { + try { + Boolean result = redisTemplate.opsForValue().setIfAbsent(lockKey, value, expireMs, TimeUnit.MILLISECONDS); + return Boolean.TRUE.equals(result); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 解锁方法 + * + * @param lockKey 锁的键 + * @param value 锁的值(用于校验是否为当前持有锁的客户端) + * @return true 解锁成功 false 解锁失败 + */ + public boolean unlock(String lockKey, String value) { + try { + String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; + Object result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Collections.singletonList(lockKey), value); + return result != null && (Long) result == 1L; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } +} diff --git a/src/main/java/com/netsdk/utils/SyncGlScheduledTasks.java b/src/main/java/com/netsdk/utils/SyncGlScheduledTasks.java new file mode 100644 index 0000000..7b7a440 --- /dev/null +++ b/src/main/java/com/netsdk/utils/SyncGlScheduledTasks.java @@ -0,0 +1,103 @@ +package com.netsdk.utils; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.ghgande.j2mod.modbus.procimg.SimpleDigitalIn; +import com.ghgande.j2mod.modbus.procimg.SimpleInputRegister; +import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.*; + +/** + * @author lin + */ +@Component +public class SyncGlScheduledTasks { + // 开关量 +// public static final Map SIMPLE_DIGITAL_INMAP = new LinkedHashMap<>(16); + public static final Map SIMPLE_DIGITAL_INMAP_2 = new LinkedHashMap<>(16); + public static final Map MQ_ORDER_MAP = new LinkedHashMap<>(16); + // 模拟量 +// public static final Map SIMPLE_INPUT_REGISTER_MAP = new LinkedHashMap<>(16); + + @Resource + private RedisUtil redisUtil; + + // 每五秒执行一次 + @Scheduled(fixedDelay = 5000) + @Async + public void taskWithFixedDelay() { + JSONArray objects = JSONObject.parseArray((String) redisUtil.get("GL_LIST")); + JSONArray zLobjects = JSONObject.parseArray((String) redisUtil.get("ZL_LIST")); + JSONArray lFobjects = JSONObject.parseArray((String) redisUtil.get("JL_LIST")); + JSONArray mQobjects = JSONObject.parseArray((String) redisUtil.get("MQ_LIST")); + objects.addAll(zLobjects); + objects.addAll(lFobjects); + for (int i = 0; i < objects.size(); i++) { + JSONObject jsonObject = objects.getJSONObject(i); + float intValue = jsonObject.getFloatValue("CURRENT_VALUE"); + + if ("1".equals(jsonObject.getString("SIGNAL_TYPE"))) { + // 模拟量 + SimpleInputRegister simpleInputRegister_hig = SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.get(jsonObject.getString("IPCDEVICE_ID") + "hig"); + SimpleInputRegister simpleInputRegister_low = SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.get(jsonObject.getString("IPCDEVICE_ID") + "low"); + if (simpleInputRegister_hig != null) { + int bits = Float.floatToIntBits(intValue); + simpleInputRegister_hig.setValue((bits >> 16) & 0xFFFF); + simpleInputRegister_low.setValue(bits & 0xFFFF); + } + } else { + SimpleInputRegister simpleInputRegister = SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.get(jsonObject.getString("IPCDEVICE_ID")); + SimpleInputRegister simpleInputRegister1 = SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.get(jsonObject.getString("IPCDEVICE_ID")+"_1"); + if (simpleInputRegister1 != null) { + simpleInputRegister1.setValue((int) intValue); + } + if (simpleInputRegister == null) continue; + // 开关量 + simpleInputRegister.setValue((int) intValue); + } + } + for (int i = 0; i < mQobjects.size(); i++) { + JSONObject jsonObject = mQobjects.getJSONObject(i); + float intValue = jsonObject.getFloatValue("CURRENT_VALUE"); + SimpleInputRegister simpleInputRegister = SyncGlScheduledTasks.SIMPLE_DIGITAL_INMAP_2.get(jsonObject.getString("IPCDEVICE_ID")); + if (simpleInputRegister == null) continue; + // 开关量 + simpleInputRegister.setValue((int) intValue); + } + + } +// @Scheduled(fixedDelay = 5000) +// @Async +// public void taskWithZlFixedDelay() { +// JSONArray objects = JSONObject.parseArray((String) redisUtil.get("ZL_LIST")); +// System.out.println("更新转炉炉数据:"+DateUtil.date2Str(new Date())); +// for (int i = 0; i < objects.size(); i++) { +// JSONObject jsonObject = objects.getJSONObject(i); +// double intValue = jsonObject.getDouble("CURRENT_VALUE"); +// if ("2".equals(jsonObject.getString("SIGNAL_TYPE"))) { +// // 开关量 +// SimpleDigitalIn simpleDigitalIn = SIMPLE_DIGITAL_INMAP.get(jsonObject.getString("IPCDEVICE_ID")); +// if (simpleDigitalIn != null) { +// SIMPLE_DIGITAL_INMAP.get(jsonObject.getString("IPCDEVICE_ID")).set((int) intValue == 1); +// } +// } else { +// SimpleInputRegister simpleInputRegister = SIMPLE_INPUT_REGISTER_MAP.get(jsonObject.getString("IPCDEVICE_ID")); +// if (simpleInputRegister != null) { +// SIMPLE_INPUT_REGISTER_MAP.get(jsonObject.getString("IPCDEVICE_ID")).setValue((int) intValue); +// } +// } +// } +// } + + public static void main(String[] args) { + } + +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..4184212 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,17 @@ +server: + port: 19393 +spring: + application: + name: integrated_yjb_dataDocking + datasource: + driver-class-name: org.postgresql.Driver + url: jdbc:postgresql://10.199.64.30:15431/postgres?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false&serverTimezone=UTC + password: rT)?DjIGYM8k0h! + username: postgres + redis: + host: 10.199.64.30 + password: 5.5pYdZqHxpR#9%W. + database: 1 + port: 16379 +modbus: + port: 18888 diff --git a/src/main/resources/mybatis/datasource/mybatis-config.xml b/src/main/resources/mybatis/datasource/mybatis-config.xml new file mode 100644 index 0000000..2aa20fd --- /dev/null +++ b/src/main/resources/mybatis/datasource/mybatis-config.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + diff --git a/src/main/resources/mybatis/datasource/other/MkPeopleAccessMapper.xml b/src/main/resources/mybatis/datasource/other/MkPeopleAccessMapper.xml new file mode 100644 index 0000000..6132a57 --- /dev/null +++ b/src/main/resources/mybatis/datasource/other/MkPeopleAccessMapper.xml @@ -0,0 +1,10 @@ + + + + + +