This commit is contained in:
caixiang 2023-02-25 14:19:33 +08:00
parent cdc06bd733
commit fed8f82ff0
20 changed files with 666 additions and 1710 deletions

View File

@ -72,6 +72,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
"/swagger-ui/**",
"/webjars/**",
"/websocket/**",
"/test/**",
"/**/expert",
"/captcha",
"druid/**").anonymous()
// .antMatchers("/testCors").hasAuthority("system:dept:list222")

View File

@ -61,14 +61,14 @@ dynamic:
# username: root
# password: 1qaz@WSX3edc$RFV
## camline系统
# camline:
# driver-class-name: com.mysql.cj.jdbc.Driver
# url: jdbc:mysql://mysql.picaiba.com:30307/mt_cigs4?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
# username: root
# password: 1qaz@WSX3edc$RFV
#
camline:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://mysql.picaiba.com:30307/mt_cigs4?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
username: root
password: 1qaz@WSX3edc$RFV
camline:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://10.0.1.23:3306/mt_cigs4?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
url: jdbc:mysql://10.0.1.23:3306/synapse?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
username: offline_data
password: tpvmfab4

View File

@ -15,7 +15,7 @@
<!-- <property name="logging.eqlog" value="C:/qgs_logger/s7" />-->
<property name="logging.eqlog" value="/usr/local/logger/EQCommunicationLog" />
<property name="logging.packing" value="/usr/local/logger/Packing" />
@ -80,7 +80,32 @@
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!-- rollover daily -->
<fileNamePattern>${logging.eqlog}/s7-log-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<fileNamePattern>${logging.eqlog}/s7-eq-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<!-- each file should be at most 100MB, keep 60 days worth of history, but at most 20GB -->
<maxFileSize>100MB</maxFileSize>
<maxHistory>999</maxHistory>
<totalSizeCap>200GB</totalSizeCap>
</rollingPolicy>
<!-- 此日志文档只记录debug级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>debug</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="PACKING_LOG_DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文档的路径及文档名 -->
<file>${logging.packing}/debug/packing-log-debug.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 设置字符集 -->
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!-- rollover daily -->
<fileNamePattern>${logging.packing}/packing-log-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<!-- each file should be at most 100MB, keep 60 days worth of history, but at most 20GB -->
<maxFileSize>100MB</maxFileSize>
@ -144,6 +169,30 @@
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="PACKING_LOG_INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文档的路径及文档名 -->
<file>${logging.packing}/info/packing-log-info.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!-- rollover daily -->
<fileNamePattern>${logging.packing}/packing-log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<!-- each file should be at most 100MB, keep 60 days worth of history, but at most 20GB -->
<maxFileSize>100MB</maxFileSize>
<maxHistory>999</maxHistory>
<totalSizeCap>200GB</totalSizeCap>
</rollingPolicy>
<!-- 此日志文档只记录info级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>info</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 2.3 level为 WARN 日志,时间滚动输出 -->
<appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
@ -203,6 +252,30 @@
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="PACKING_LOG_WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文档的路径及文档名 -->
<file>${logging.packing}/warn/packing-log-warn.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!-- rollover daily -->
<fileNamePattern>${logging.packing}/packing-log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<!-- each file should be at most 100MB, keep 60 days worth of history, but at most 20GB -->
<maxFileSize>100MB</maxFileSize>
<maxHistory>999</maxHistory>
<totalSizeCap>200GB</totalSizeCap>
</rollingPolicy>
<!-- 此日志文档只记录warn级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>warn</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 2.4 level为 ERROR 日志,时间滚动输出 -->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
@ -264,6 +337,31 @@
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="PACKING_LOG_ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文档的路径及文档名 -->
<file>${logging.packing}/error/packing-log-error.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!-- rollover daily -->
<fileNamePattern>${logging.packing}/packing-log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<!-- each file should be at most 100MB, keep 60 days worth of history, but at most 20GB -->
<maxFileSize>100MB</maxFileSize>
<maxHistory>999</maxHistory>
<totalSizeCap>200GB</totalSizeCap>
</rollingPolicy>
<!-- 此日志文档只记录ERROR级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!--
<logger>用来设置某一个包或者具体的某一个类的日志打印级别、
@ -294,13 +392,20 @@
<!-- name就是包名这个包下的 所有logger 输出就以下配置这里的logger只会输出代码里 你指定打印的log -->
<logger name="com.cnbm.packing.dispatch" additivity="false">
<logger name="com.cnbm.dispatch" additivity="false">
<appender-ref ref="EQ_COMM_LOG_DEBUG_FILE" />
<appender-ref ref="EQ_COMM_LOG_INFO_FILE" />
<appender-ref ref="EQ_COMM_LOG_WARN_FILE" />
<appender-ref ref="EQ_COMM_LOG_ERROR_FILE" />
</logger>
<logger name="com.cnbm.packing" additivity="false">
<appender-ref ref="PACKING_LOG_DEBUG_FILE" />
<appender-ref ref="PACKING_LOG_INFO_FILE" />
<appender-ref ref="PACKING_LOG_WARN_FILE" />
<appender-ref ref="PACKING_LOG_ERROR_FILE" />
</logger>
<!-- work这个目录 是所有控制台信息 + 第三方jar包 输出的信息 -->
<root level="info">
<appender-ref ref="CONSOLE" />

View File

@ -0,0 +1,430 @@
package com.cnbm.dispatch;
import cn.hutool.core.date.DateUtil;
import com.cnbm.dispatch.enums.kuka.step1.Step1Mes2PlcVar;
import com.cnbm.dispatch.enums.kuka.step1.Step1Plc2MesVar;
import com.cnbm.dispatch.enums.kuka.step2.Step2Mes2PlcVar;
import com.cnbm.dispatch.enums.kuka.step2.Step2Plc2MesVar;
import com.cnbm.dispatch.enums.kuka.step3.Step3Mes2PlcVar;
import com.cnbm.dispatch.enums.kuka.step3.Step3Plc2MesVar;
import com.cnbm.packing.service.*;
import com.cnbm.s7.s7connector.enmuc.S7Client;
import com.cnbm.s7.s7connector.type.PlcVar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @Desc: ""
* @Author: caixiang
* @DATE: 2022/12/23 12:33
*/
@Component
@Order(value = 1)
public class KukaJoinThread implements ApplicationRunner {
private static final Logger logger = LoggerFactory.getLogger(KukaJoinThread.class);
@Autowired
DynamicDataSourceService service;
@Autowired
WoPowerLevelServiceBiz levelServiceBiz;
@Autowired
WoCompensationPowerServiceBiz compensationPowerServiceBiz;
@Autowired
WoPackagingBoxSubstrateServiceBiz substrateServiceBiz;
@Autowired
WoPackagingBoxServiceBiz boxServiceBiz;
public KukaJoinThread(){
this.kukaStep1 = Executors.newScheduledThreadPool(1);
this.kukaStep2 = Executors.newScheduledThreadPool(1);
this.kukaStep3 = Executors.newScheduledThreadPool(1);
}
private ScheduledExecutorService kukaStep1;
private ScheduledExecutorService kukaStep2;
private ScheduledExecutorService kukaStep3;
/**
* return
* 成功 返回相应的object对象
* 失败 返回null
* */
private Object read(S7Client s7Client,Step1Plc2MesVar var) {
try {
return s7Client.read(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getLength(), var.getStrSize(), var.getType());
}catch (Exception e){
logger.error("host:"+s7Client.getHost()+" ; read 操作出现问题: "+e.getMessage());
e.printStackTrace();
return null;
}
}
private void write(S7Client s7Client, Step1Mes2PlcVar var, Object newValue) {
if(var.getType().equals(PlcVar.STRING_Array)){
String[] s = (String[])newValue;
String[] ss = (String[])newValue;
if(s.length > var.getLength() ){
ss = new String[var.getLength()];
for(int i=0;i< var.getLength();i++){
ss[i] = s[i];
}
}
s7Client.write(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getStrSize(), var.getType(),ss);
}else {
s7Client.write(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getStrSize(), var.getType(),newValue);
}
}
private Object read(S7Client s7Client, Step2Plc2MesVar var) {
try {
return s7Client.read(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getLength(), var.getStrSize(), var.getType());
}catch (Exception e){
logger.error("host:"+s7Client.getHost()+" ; read 操作出现问题: "+e.getMessage());
e.printStackTrace();
return null;
}
}
private void write(S7Client s7Client, Step2Mes2PlcVar var, Object newValue) {
if(var.getType().equals(PlcVar.STRING_Array)){
String[] s = (String[])newValue;
String[] ss = (String[])newValue;
if(s.length > var.getLength() ){
ss = new String[var.getLength()];
for(int i=0;i< var.getLength();i++){
ss[i] = s[i];
}
}
s7Client.write(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getStrSize(), var.getType(),ss);
}else {
s7Client.write(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getStrSize(), var.getType(),newValue);
}
}
private Object read(S7Client s7Client, Step3Plc2MesVar var) {
try {
return s7Client.read(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getLength(), var.getStrSize(), var.getType());
}catch (Exception e){
logger.error("host:"+s7Client.getHost()+" ; read 操作出现问题: "+e.getMessage());
e.printStackTrace();
return null;
}
}
private void write(S7Client s7Client, Step3Mes2PlcVar var, Object newValue) {
if(var.getType().equals(PlcVar.STRING_Array)){
String[] s = (String[])newValue;
String[] ss = (String[])newValue;
if(s.length > var.getLength() ){
ss = new String[var.getLength()];
for(int i=0;i< var.getLength();i++){
ss[i] = s[i];
}
}
s7Client.write(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getStrSize(), var.getType(),ss);
}else {
s7Client.write(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getStrSize(), var.getType(),newValue);
}
}
public String getBoxId(String sapMaterial){
Integer todayBoxNum = service.getTodayBoxNum();
String nowTime = DateUtil.format(new Date(), "yyMMdd");
String res = "301"+sapMaterial+nowTime+todayBoxNum;
return res;
}
@Override
public void run(ApplicationArguments args) throws Exception {
kukaStep1.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
logger.info("================= 现在开始执行 过程一 任务 ==================");
}
},1,1, TimeUnit.SECONDS);
// kukaStep1.scheduleAtFixedRate(new Runnable() {
// @Override
// public void run() {
// //调度开始
//// logger.info("");
//// logger.info("================= 现在开始执行 过程一 任务 ==================");
// Integer subArrived = waitingForTarget(Step1Plc2MesVar.SubArrivedToMes, true);
// if(subArrived != 1){
// logger.info("失败"+" --- "+" MES监听 Step1Plc2MesVar.SubArrivedToMes 是否 等于 1 失败");
// }
//
// //. 从plc 中获取 subId lineNum
// String subId = (String) read(S7Client.S7_KUKA,Step1Plc2MesVar.SubIdToMes);
// Integer lineNum = (Integer) read(S7Client.S7_KUKA,Step1Plc2MesVar.LineNum);
// logger.info("采集到 基板ID: "+subId+", 线边号:"+lineNum);
//
// //. MES 业务
// //=============== MES 业务 开始 =================
// //1. 从comline数据库中获取 实际pmpp
// float pmppBySubId = service.getPMPPBySubId(subId);
// //2. 匹配和计算补偿功率
// float actualPMPP = compensationPowerServiceBiz.calculCompensationPMPP(pmppBySubId,lineNum);
// //3. 依据补偿功率获取工艺参数并且把这些工艺参数传给kuka
// WoPowerLevel argByPMPP = levelServiceBiz.getArgByPMPP(actualPMPP, lineNum);
// write(S7Client.S7_KUKA,Step1Mes2PlcVar.dLable_Pnom,Integer.valueOf(argByPMPP.getPowerClass()));
// write(S7Client.S7_KUKA,Step1Mes2PlcVar.dLable_Voc,argByPMPP.getLableVoc());
// write(S7Client.S7_KUKA,Step1Mes2PlcVar.dLable_Isc,argByPMPP.getLableIsc());
// write(S7Client.S7_KUKA,Step1Mes2PlcVar.dLable_Vmpp,argByPMPP.getLableVmpp());
// write(S7Client.S7_KUKA,Step1Mes2PlcVar.dLable_Impp,argByPMPP.getLableImpp());
//
//
//
// //4. 把基板录到数据库
// WoPackagingBoxSubstrate woPackagingBoxSubstrate = new WoPackagingBoxSubstrate();
// woPackagingBoxSubstrate.setLineBody(lineNum);
// woPackagingBoxSubstrate.setPowerLevel(argByPMPP.getPowerClass());
// woPackagingBoxSubstrate.setSapMaterial(argByPMPP.getSapMaterialNum());
// woPackagingBoxSubstrate.setWoSubstrateId(subId);
//
// //5. 从camline那里获取可变字段
// CamlineExtendArgDTO extendArgFromCamline = service.getExtendArgFromCamline(subId);
// woPackagingBoxSubstrate.setLastUpdateTime(extendArgFromCamline.getLastUpdateTime());
// woPackagingBoxSubstrate.setPmpp(actualPMPP);
// woPackagingBoxSubstrate.setOrderName(extendArgFromCamline.getOrderName());
// woPackagingBoxSubstrate.setBinclassFl1(extendArgFromCamline.getBinclassFl1());
// woPackagingBoxSubstrate.setBinclassFl2(extendArgFromCamline.getBinclassFl2());
// woPackagingBoxSubstrate.setEtaFl1(extendArgFromCamline.getEtaFl1());
// woPackagingBoxSubstrate.setEtaFl2(extendArgFromCamline.getEtaFl2());
// woPackagingBoxSubstrate.setFfFl1(extendArgFromCamline.getFfFl1());
// woPackagingBoxSubstrate.setFfFl2(extendArgFromCamline.getFfFl2());
// woPackagingBoxSubstrate.setImppFl1(extendArgFromCamline.getImppFl1());
// woPackagingBoxSubstrate.setImppFl2(extendArgFromCamline.getImppFl2());
// woPackagingBoxSubstrate.setInsolflashcontrolFl1(extendArgFromCamline.getInsolflashcontrolFl1());
// woPackagingBoxSubstrate.setInsolflashcontrolFl2(extendArgFromCamline.getInsolflashcontrolFl2());
// woPackagingBoxSubstrate.setInsolmppFl1(extendArgFromCamline.getInsolmppFl1());
// woPackagingBoxSubstrate.setInsolmppFl2(extendArgFromCamline.getInsolmppFl2());
// woPackagingBoxSubstrate.setInsolvocFl1(extendArgFromCamline.getInsolvocFl1());
// woPackagingBoxSubstrate.setInsolvocFl2(extendArgFromCamline.getInsolvocFl2());
// woPackagingBoxSubstrate.setInsolFl1(extendArgFromCamline.getInsolFl1());
// woPackagingBoxSubstrate.setInsolFl2(extendArgFromCamline.getInsolFl2());
// woPackagingBoxSubstrate.setIscFl1(extendArgFromCamline.getIscFl1());
// woPackagingBoxSubstrate.setIscFl2(extendArgFromCamline.getIscFl2());
// woPackagingBoxSubstrate.setMeasTimeFl1(extendArgFromCamline.getMeasTimeFl1());
// woPackagingBoxSubstrate.setMeasTimeFl2(extendArgFromCamline.getMeasTimeFl2());
// woPackagingBoxSubstrate.setPmppFl1(extendArgFromCamline.getPmppFl1());
// woPackagingBoxSubstrate.setPmppFl2(extendArgFromCamline.getPmppFl2());
// woPackagingBoxSubstrate.setTcellFl1(extendArgFromCamline.getTcellFl1());
// woPackagingBoxSubstrate.setTcellFl2(extendArgFromCamline.getTcellFl2());
// woPackagingBoxSubstrate.setTmonicellFl1(extendArgFromCamline.getTmonicellFl1());
// woPackagingBoxSubstrate.setTmonicellFl2(extendArgFromCamline.getTmonicellFl2());
// woPackagingBoxSubstrate.setUmppFl1(extendArgFromCamline.getUmppFl1());
// woPackagingBoxSubstrate.setUmppFl2(extendArgFromCamline.getUmppFl2());
// woPackagingBoxSubstrate.setUocFl1(extendArgFromCamline.getUocFl1());
// woPackagingBoxSubstrate.setUocFl1(extendArgFromCamline.getUocFl2());
//
// substrateServiceBiz.insert(woPackagingBoxSubstrate);
// //=============== MES 业务 结束 =================
//
// //. 当MES完成任务后把MesToPlc.SubArrivedFinish变量置为true告诉plc我操作完成了
// write(S7Client.S7_KUKA,Step1Mes2PlcVar.SubArrivedFinish,true);
//
// //. mes 监控 到PlcToMes.SubArrived==false就把MesToPlc.SubArrivedFinish置为false
// Integer subArrived2 = waitingForTarget(Step1Plc2MesVar.SubArrivedToMes, false);
// if(subArrived2 != 1){
// logger.info("失败"+" --- "+"MES监听 Step1Plc2MesVar.SubArrivedToMes 是否 等于 1 失败");
// }
// write(S7Client.S7_KUKA,Step1Mes2PlcVar.SubArrivedFinish,false);
// }
// },1,1, TimeUnit.SECONDS);
//
//
// kukaStep2.scheduleAtFixedRate(new Runnable() {
// @Override
// public void run() {
// //调度开始
//
// Integer shelfIsFull = waitingForTarget(Step2Plc2MesVar.ShelfIsFull, true);
// if(shelfIsFull != 1){
// logger.info("失败"+" --- "+"MES监听 Step2Plc2MesVar.ShelfIsFull 是否 等于 1 失败");
// }
//
// //. 从plc 中获取 subIdList lineNum
// String[] subIdList = (String[])read(S7Client.S7_KUKA,Step2Plc2MesVar.SubIdList);
//// Integer lineNum = (Integer) read(S7Client.S7_KUKA,Step2Plc2MesVar.LineNum);
// logger.info("获取到基板列表:"+ Arrays.toString(subIdList));
//
// //. MES 业务
// //=============== MES 业务 开始 =================
// //1.MES 生成BoxId
// if(subIdList.length<=0){
// logger.info("失败"+" --- "+"从plc里面获取到的基板列表 为空");
// }
// WoPackagingBoxSubstrate bySubId = substrateServiceBiz.getBySubId(subIdList[0]);
// String boxId = getBoxId(bySubId.getSapMaterial());
// logger.info("mes 生成的boxId :"+ boxId);
// //2. 依次update 基板表把boxId 赋予这些基板
// for(int i=0;i<subIdList.length;i++){
// substrateServiceBiz.updatePackagingBoxIdByWoSubstrateId(boxId,subIdList[i]);
// }
// //3.去camline数据库 查询此基板ID 对应的订单
// String orderNameBySubId = service.getOrderNameBySubId(subIdList[0]);
// //4. box信息录入到box表
// WoPackagingBox woPackagingBox = new WoPackagingBox();
// woPackagingBox.setBoxNo(boxId);
// woPackagingBox.setPackagingTime(LocalDateTime.now());
// woPackagingBox.setPowerLevel(bySubId.getPowerLevel());
// woPackagingBox.setLineBody(bySubId.getLineBody());
// woPackagingBox.setSapMaterial(bySubId.getSapMaterial());
// woPackagingBox.setOrderNum(orderNameBySubId);
// //1-手动模式2-自动模式
// woPackagingBox.setModel(2);
// boxServiceBiz.insert(woPackagingBox);
// //=============== MES 业务 结束 =================
//
// //. 把生成的BoxId 告诉kuka
// write(S7Client.S7_KUKA,Step2Mes2PlcVar.BoxId,boxId);
//
// //. 当MES完成任务后把MesToPlc.ShelfIsFullFinish变量置为true告诉plc我操作完成了
// write(S7Client.S7_KUKA,Step2Mes2PlcVar.ShelfIsFullFinish,true);
//
// //. mes 监控 到PlcToMes.SubArrived==false就把MesToPlc.SubArrivedFinish置为false
// Integer subArrived2 = waitingForTarget(Step2Plc2MesVar.ShelfIsFull, false);
// if(subArrived2 != 1){
// logger.info("失败"+" --- "+"步骤1. MES监听 Step1Plc2MesVar.SubArrivedToMes 是否 等于 1 失败");
// }
// write(S7Client.S7_KUKA,Step2Mes2PlcVar.ShelfIsFullFinish,false);
// }
// },1,1, TimeUnit.SECONDS);
//
//
// kukaStep3.scheduleAtFixedRate(new Runnable() {
// @Override
// public void run() {
// //调度开始
// Integer shelfIsFull = waitingForTarget(Step3Plc2MesVar.ShelfIsFullArrived, true);
// if(shelfIsFull != 1){
// logger.info("失败"+" --- "+"MES监听 Step3Plc2MesVar.ShelfIsFullArrived 是否 等于 1 失败");
// }
//
// //. 从plc 中获取 subIdList lineNum
// String boxId = (String)read(S7Client.S7_KUKA,Step3Plc2MesVar.BoxId);
// Integer lineNum = (Integer) read(S7Client.S7_KUKA,Step3Plc2MesVar.LineNum);
// logger.info("到达站台的boxId :"+boxId);
//
// //. MES 业务
// //=============== MES 业务 开始 =================
// //1. box信息录入到box表
// boxServiceBiz.updateIsArrivedByBoxNo(1,boxId);
// //=============== MES 业务 结束 =================
//
//
// //. 当MES完成任务后把MesToPlc.ShelfIsFullArrivedFinish变量置为true告诉plc我操作完成了
// write(S7Client.S7_KUKA,Step3Mes2PlcVar.ShelfIsFullArrivedFinish,true);
//
// //. mes 监控 到PlcToMes.SubArrived==false就把MesToPlc.SubArrivedFinish置为false
// Integer subArrived2 = waitingForTarget(Step3Plc2MesVar.ShelfIsFullArrived, false);
// if(subArrived2 != 1){
// logger.info("失败"+" --- "+"步骤1. MES监听 Step3Plc2MesVar.ShelfIsFullArrived 是否 等于 1 失败");
// }
// write(S7Client.S7_KUKA,Step3Mes2PlcVar.ShelfIsFullArrivedFinish,false);
//
//
// }
// },1,1, TimeUnit.SECONDS);
}
/**
*
* arg:
* Step1Plc2MesVar 参数类型
* targetValue 目的值
* return:
* 2 s7 访问异常;
* 1 成功;
* */
private Integer waitingForTarget(Step1Plc2MesVar var, Boolean targetValue) {
Integer res = 0;
while (true){
try {
Boolean now = (Boolean) read(S7Client.S7_KUKA,var);
if(targetValue.equals(now)){
res = 1;
break;
}
Thread.sleep(200);
}catch (Exception e){
logger.info("S7 数据采集 异常。");
res = 2;
break;
}
}
return res;
}
/**
*
* arg:
* Step2Plc2MesVar 参数类型
* targetValue 目的值
* return:
* 2 s7 访问异常;
* 1 成功;
* */
private Integer waitingForTarget(Step2Plc2MesVar var, Boolean targetValue) {
Integer res = 0;
while (true){
try {
Boolean now = (Boolean) read(S7Client.S7_KUKA,var);
if(targetValue.equals(now)){
res = 1;
break;
}
Thread.sleep(200);
}catch (Exception e){
logger.info("S7 数据采集 异常。");
res = 2;
break;
}
}
return res;
}
/**
*
* arg:
* Step3Plc2MesVar 参数类型
* targetValue 目的值
* return:
* 2 s7 访问异常;
* 1 成功;
* */
private Integer waitingForTarget(Step3Plc2MesVar var, Boolean targetValue) {
Integer res = 0;
while (true){
try {
Boolean now = (Boolean) read(S7Client.S7_KUKA,var);
if(targetValue.equals(now)){
res = 1;
break;
}
Thread.sleep(200);
}catch (Exception e){
logger.info("S7 数据采集 异常。");
res = 2;
break;
}
}
return res;
}
}

View File

@ -1,4 +1,4 @@
package com.cnbm.packing.dispatch.enums;
package com.cnbm.dispatch.enums;
/**
* @Author: 蔡翔

View File

@ -1,4 +1,4 @@
package com.cnbm.packing.dispatch.enums.kuka.step1;
package com.cnbm.dispatch.enums.kuka.step1;
import com.cnbm.s7.s7connector.api.DaveArea;
import com.cnbm.s7.s7connector.type.PlcVar;

View File

@ -1,4 +1,4 @@
package com.cnbm.packing.dispatch.enums.kuka.step1;
package com.cnbm.dispatch.enums.kuka.step1;
import com.cnbm.s7.s7connector.api.DaveArea;
import com.cnbm.s7.s7connector.type.PlcVar;

View File

@ -1,4 +1,4 @@
package com.cnbm.packing.dispatch.enums.kuka.step2;
package com.cnbm.dispatch.enums.kuka.step2;
import com.cnbm.s7.s7connector.api.DaveArea;
import com.cnbm.s7.s7connector.type.PlcVar;

View File

@ -1,4 +1,4 @@
package com.cnbm.packing.dispatch.enums.kuka.step2;
package com.cnbm.dispatch.enums.kuka.step2;
import com.cnbm.s7.s7connector.api.DaveArea;
import com.cnbm.s7.s7connector.type.PlcVar;

View File

@ -1,4 +1,4 @@
package com.cnbm.packing.dispatch.enums.kuka.step3;
package com.cnbm.dispatch.enums.kuka.step3;
import com.cnbm.s7.s7connector.api.DaveArea;
import com.cnbm.s7.s7connector.type.PlcVar;

View File

@ -1,4 +1,4 @@
package com.cnbm.packing.dispatch.enums.kuka.step3;
package com.cnbm.dispatch.enums.kuka.step3;
import com.cnbm.s7.s7connector.api.DaveArea;
import com.cnbm.s7.s7connector.type.PlcVar;

View File

@ -1,17 +1,29 @@
package com.cnbm.packing.controller;
import com.cnbm.common.constant.Constant;
import com.cnbm.dispatch.enums.kuka.step1.Step1Mes2PlcVar;
import com.cnbm.dispatch.enums.kuka.step1.Step1Plc2MesVar;
import com.cnbm.dispatch.enums.kuka.step2.Step2Mes2PlcVar;
import com.cnbm.dispatch.enums.kuka.step2.Step2Plc2MesVar;
import com.cnbm.dispatch.enums.kuka.step3.Step3Mes2PlcVar;
import com.cnbm.dispatch.enums.kuka.step3.Step3Plc2MesVar;
import com.cnbm.packing.service.DynamicDataSourceService;
import com.cnbm.s7.entity.R;
import com.cnbm.s7.s7connector.enmuc.S7Client;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.cnbm.common.utils.Result;
import springfox.documentation.annotations.ApiIgnore;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Map;
/**
* @Author weihongyang
* @Date 2022/6/24 8:57 AM
@ -22,8 +34,104 @@ import java.util.Map;
@Api(tags="测试接口")
public class TestController {
private static final Logger logger = LoggerFactory.getLogger(TestController.class);
@Autowired
DynamicDataSourceService service;
private Object read(S7Client s7Client,Step1Plc2MesVar var) throws UnsupportedEncodingException, ParseException {
try {
return s7Client.read(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getLength(), var.getStrSize(), var.getType());
}catch (Exception e){
e.printStackTrace();
return null;
}
}
private Object read(S7Client s7Client,Step1Mes2PlcVar var) throws UnsupportedEncodingException, ParseException {
try {
return s7Client.read(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getLength(), var.getStrSize(), var.getType());
}catch (Exception e){
e.printStackTrace();
return null;
}
}
private Object read(S7Client s7Client,Step2Plc2MesVar var) throws UnsupportedEncodingException, ParseException {
try {
return s7Client.read(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getLength(), var.getStrSize(), var.getType());
}catch (Exception e){
e.printStackTrace();
return null;
}
}
private Object read(S7Client s7Client,Step2Mes2PlcVar var) throws UnsupportedEncodingException, ParseException {
try {
return s7Client.read(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getLength(), var.getStrSize(), var.getType());
}catch (Exception e){
e.printStackTrace();
return null;
}
}
private Object read(S7Client s7Client,Step3Plc2MesVar var) throws UnsupportedEncodingException, ParseException {
try {
return s7Client.read(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getLength(), var.getStrSize(), var.getType());
}catch (Exception e){
e.printStackTrace();
return null;
}
}
private Object read(S7Client s7Client,Step3Mes2PlcVar var) throws UnsupportedEncodingException, ParseException {
try {
return s7Client.read(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getLength(), var.getStrSize(), var.getType());
}catch (Exception e){
e.printStackTrace();
return null;
}
}
@PostMapping("/testReadAll")
public R testReadAll() throws UnsupportedEncodingException, ParseException {
for(Step1Plc2MesVar actual:Step1Plc2MesVar.values()){
logger.info(read(S7Client.S7_KUKA,actual).toString());
System.out.println(actual.getName().toString()+" : "+read(S7Client.S7_KUKA,actual).toString());
}
for(Step1Mes2PlcVar actual:Step1Mes2PlcVar.values()){
logger.info(read(S7Client.S7_KUKA,actual).toString());
System.out.println(actual.getName().toString()+" : "+read(S7Client.S7_KUKA,actual).toString());
}
for(Step2Plc2MesVar actual:Step2Plc2MesVar.values()){
logger.info(read(S7Client.S7_KUKA,actual).toString());
System.out.println(actual.getName().toString()+" : "+read(S7Client.S7_KUKA,actual).toString());
}
for(Step2Mes2PlcVar actual:Step2Mes2PlcVar.values()){
logger.info(read(S7Client.S7_KUKA,actual).toString());
System.out.println(actual.getName().toString()+" : "+read(S7Client.S7_KUKA,actual).toString());
}
for(Step3Plc2MesVar actual:Step3Plc2MesVar.values()){
logger.info(read(S7Client.S7_KUKA,actual).toString());
System.out.println(actual.getName().toString()+" : "+read(S7Client.S7_KUKA,actual).toString());
}
for(Step3Mes2PlcVar actual:Step3Mes2PlcVar.values()){
logger.info(read(S7Client.S7_KUKA,actual).toString());
System.out.println(actual.getName().toString()+" : "+read(S7Client.S7_KUKA,actual).toString());
}
return R.ok();
}
@PostMapping("/testlogger")
public R testlogger() {
logger.info("test logger");
System.out.println("test logger");
return R.ok();
}
@PostMapping("getPMPPBySubId")
@ApiImplicitParams({
@ApiImplicitParam(name = "subId", value = "基板ID", paramType = "query", required = true, dataTypeClass=Integer.class) ,

View File

@ -1,429 +0,0 @@
package com.cnbm.packing.dispatch;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.cnbm.packing.dispatch.enums.kuka.step1.Step1Mes2PlcVar;
import com.cnbm.packing.dispatch.enums.kuka.step1.Step1Plc2MesVar;
import com.cnbm.packing.dispatch.enums.kuka.step2.Step2Mes2PlcVar;
import com.cnbm.packing.dispatch.enums.kuka.step2.Step2Plc2MesVar;
import com.cnbm.packing.dispatch.enums.kuka.step3.Step3Mes2PlcVar;
import com.cnbm.packing.dispatch.enums.kuka.step3.Step3Plc2MesVar;
import com.cnbm.packing.dto.CamlineExtendArgDTO;
import com.cnbm.packing.dto.WoPowerLevelDTO;
import com.cnbm.packing.entity.WoPackagingBox;
import com.cnbm.packing.entity.WoPackagingBoxSubstrate;
import com.cnbm.packing.entity.WoPowerLevel;
import com.cnbm.packing.service.*;
import com.cnbm.s7.s7connector.enmuc.S7Client;
import com.cnbm.s7.s7connector.type.PlcVar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @Desc: ""
* @Author: caixiang
* @DATE: 2022/12/23 12:33
*/
@Component
@Order(value = 1)
public class KukaJoinThread implements ApplicationRunner {
private static final Logger logger = LoggerFactory.getLogger(KukaJoinThread.class);
@Autowired
DynamicDataSourceService service;
@Autowired
WoPowerLevelServiceBiz levelServiceBiz;
@Autowired
WoCompensationPowerServiceBiz compensationPowerServiceBiz;
@Autowired
WoPackagingBoxSubstrateServiceBiz substrateServiceBiz;
@Autowired
WoPackagingBoxServiceBiz boxServiceBiz;
public KukaJoinThread(){
this.kukaStep1 = Executors.newScheduledThreadPool(1);
this.kukaStep2 = Executors.newScheduledThreadPool(1);
this.kukaStep3 = Executors.newScheduledThreadPool(1);
}
private ScheduledExecutorService kukaStep1;
private ScheduledExecutorService kukaStep2;
private ScheduledExecutorService kukaStep3;
/**
* return
* 成功 返回相应的object对象
* 失败 返回null
* */
private Object read(S7Client s7Client,Step1Plc2MesVar var) {
try {
return s7Client.read(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getLength(), var.getStrSize(), var.getType());
}catch (Exception e){
logger.error("host:"+s7Client.getHost()+" ; read 操作出现问题: "+e.getMessage());
e.printStackTrace();
return null;
}
}
private void write(S7Client s7Client, Step1Mes2PlcVar var, Object newValue) {
if(var.getType().equals(PlcVar.STRING_Array)){
String[] s = (String[])newValue;
String[] ss = (String[])newValue;
if(s.length > var.getLength() ){
ss = new String[var.getLength()];
for(int i=0;i< var.getLength();i++){
ss[i] = s[i];
}
}
s7Client.write(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getStrSize(), var.getType(),ss);
}else {
s7Client.write(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getStrSize(), var.getType(),newValue);
}
}
private Object read(S7Client s7Client, Step2Plc2MesVar var) {
try {
return s7Client.read(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getLength(), var.getStrSize(), var.getType());
}catch (Exception e){
logger.error("host:"+s7Client.getHost()+" ; read 操作出现问题: "+e.getMessage());
e.printStackTrace();
return null;
}
}
private void write(S7Client s7Client, Step2Mes2PlcVar var, Object newValue) {
if(var.getType().equals(PlcVar.STRING_Array)){
String[] s = (String[])newValue;
String[] ss = (String[])newValue;
if(s.length > var.getLength() ){
ss = new String[var.getLength()];
for(int i=0;i< var.getLength();i++){
ss[i] = s[i];
}
}
s7Client.write(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getStrSize(), var.getType(),ss);
}else {
s7Client.write(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getStrSize(), var.getType(),newValue);
}
}
private Object read(S7Client s7Client, Step3Plc2MesVar var) {
try {
return s7Client.read(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getLength(), var.getStrSize(), var.getType());
}catch (Exception e){
logger.error("host:"+s7Client.getHost()+" ; read 操作出现问题: "+e.getMessage());
e.printStackTrace();
return null;
}
}
private void write(S7Client s7Client, Step3Mes2PlcVar var, Object newValue) {
if(var.getType().equals(PlcVar.STRING_Array)){
String[] s = (String[])newValue;
String[] ss = (String[])newValue;
if(s.length > var.getLength() ){
ss = new String[var.getLength()];
for(int i=0;i< var.getLength();i++){
ss[i] = s[i];
}
}
s7Client.write(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getStrSize(), var.getType(),ss);
}else {
s7Client.write(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getStrSize(), var.getType(),newValue);
}
}
public String getBoxId(String sapMaterial){
Integer todayBoxNum = service.getTodayBoxNum();
String nowTime = DateUtil.format(new Date(), "yyMMdd");
String res = "301"+sapMaterial+nowTime+todayBoxNum;
return res;
}
@Override
public void run(ApplicationArguments args) throws Exception {
kukaStep1.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
//调度开始
// logger.info("");
// logger.info("================= 现在开始执行 过程一 任务 ==================");
Integer subArrived = waitingForTarget(Step1Plc2MesVar.SubArrivedToMes, true);
if(subArrived != 1){
logger.info("失败"+" --- "+" MES监听 Step1Plc2MesVar.SubArrivedToMes 是否 等于 1 失败");
}
//. 从plc 中获取 subId lineNum
String subId = (String) read(S7Client.S7_KUKA,Step1Plc2MesVar.SubIdToMes);
Integer lineNum = (Integer) read(S7Client.S7_KUKA,Step1Plc2MesVar.LineNum);
logger.info("采集到 基板ID: "+subId+", 线边号:"+lineNum);
//. MES 业务
//=============== MES 业务 开始 =================
//1. 从comline数据库中获取 实际pmpp
float pmppBySubId = service.getPMPPBySubId(subId);
//2. 匹配和计算补偿功率
float actualPMPP = compensationPowerServiceBiz.calculCompensationPMPP(pmppBySubId,lineNum);
//3. 依据补偿功率获取工艺参数并且把这些工艺参数传给kuka
WoPowerLevel argByPMPP = levelServiceBiz.getArgByPMPP(actualPMPP, lineNum);
write(S7Client.S7_KUKA,Step1Mes2PlcVar.dLable_Pnom,Integer.valueOf(argByPMPP.getPowerClass()));
write(S7Client.S7_KUKA,Step1Mes2PlcVar.dLable_Voc,argByPMPP.getLableVoc());
write(S7Client.S7_KUKA,Step1Mes2PlcVar.dLable_Isc,argByPMPP.getLableIsc());
write(S7Client.S7_KUKA,Step1Mes2PlcVar.dLable_Vmpp,argByPMPP.getLableVmpp());
write(S7Client.S7_KUKA,Step1Mes2PlcVar.dLable_Impp,argByPMPP.getLableImpp());
//4. 把基板录到数据库
WoPackagingBoxSubstrate woPackagingBoxSubstrate = new WoPackagingBoxSubstrate();
woPackagingBoxSubstrate.setLineBody(lineNum);
woPackagingBoxSubstrate.setPowerLevel(argByPMPP.getPowerClass());
woPackagingBoxSubstrate.setSapMaterial(argByPMPP.getSapMaterialNum());
woPackagingBoxSubstrate.setWoSubstrateId(subId);
//5. 从camline那里获取可变字段
CamlineExtendArgDTO extendArgFromCamline = service.getExtendArgFromCamline(subId);
woPackagingBoxSubstrate.setLastUpdateTime(extendArgFromCamline.getLastUpdateTime());
woPackagingBoxSubstrate.setPmpp(actualPMPP);
woPackagingBoxSubstrate.setOrderName(extendArgFromCamline.getOrderName());
woPackagingBoxSubstrate.setBinclassFl1(extendArgFromCamline.getBinclassFl1());
woPackagingBoxSubstrate.setBinclassFl2(extendArgFromCamline.getBinclassFl2());
woPackagingBoxSubstrate.setEtaFl1(extendArgFromCamline.getEtaFl1());
woPackagingBoxSubstrate.setEtaFl2(extendArgFromCamline.getEtaFl2());
woPackagingBoxSubstrate.setFfFl1(extendArgFromCamline.getFfFl1());
woPackagingBoxSubstrate.setFfFl2(extendArgFromCamline.getFfFl2());
woPackagingBoxSubstrate.setImppFl1(extendArgFromCamline.getImppFl1());
woPackagingBoxSubstrate.setImppFl2(extendArgFromCamline.getImppFl2());
woPackagingBoxSubstrate.setInsolflashcontrolFl1(extendArgFromCamline.getInsolflashcontrolFl1());
woPackagingBoxSubstrate.setInsolflashcontrolFl2(extendArgFromCamline.getInsolflashcontrolFl2());
woPackagingBoxSubstrate.setInsolmppFl1(extendArgFromCamline.getInsolmppFl1());
woPackagingBoxSubstrate.setInsolmppFl2(extendArgFromCamline.getInsolmppFl2());
woPackagingBoxSubstrate.setInsolvocFl1(extendArgFromCamline.getInsolvocFl1());
woPackagingBoxSubstrate.setInsolvocFl2(extendArgFromCamline.getInsolvocFl2());
woPackagingBoxSubstrate.setInsolFl1(extendArgFromCamline.getInsolFl1());
woPackagingBoxSubstrate.setInsolFl2(extendArgFromCamline.getInsolFl2());
woPackagingBoxSubstrate.setIscFl1(extendArgFromCamline.getIscFl1());
woPackagingBoxSubstrate.setIscFl2(extendArgFromCamline.getIscFl2());
woPackagingBoxSubstrate.setMeasTimeFl1(extendArgFromCamline.getMeasTimeFl1());
woPackagingBoxSubstrate.setMeasTimeFl2(extendArgFromCamline.getMeasTimeFl2());
woPackagingBoxSubstrate.setPmppFl1(extendArgFromCamline.getPmppFl1());
woPackagingBoxSubstrate.setPmppFl2(extendArgFromCamline.getPmppFl2());
woPackagingBoxSubstrate.setTcellFl1(extendArgFromCamline.getTcellFl1());
woPackagingBoxSubstrate.setTcellFl2(extendArgFromCamline.getTcellFl2());
woPackagingBoxSubstrate.setTmonicellFl1(extendArgFromCamline.getTmonicellFl1());
woPackagingBoxSubstrate.setTmonicellFl2(extendArgFromCamline.getTmonicellFl2());
woPackagingBoxSubstrate.setUmppFl1(extendArgFromCamline.getUmppFl1());
woPackagingBoxSubstrate.setUmppFl2(extendArgFromCamline.getUmppFl2());
woPackagingBoxSubstrate.setUocFl1(extendArgFromCamline.getUocFl1());
woPackagingBoxSubstrate.setUocFl1(extendArgFromCamline.getUocFl2());
substrateServiceBiz.insert(woPackagingBoxSubstrate);
//=============== MES 业务 结束 =================
//. 当MES完成任务后把MesToPlc.SubArrivedFinish变量置为true告诉plc我操作完成了
write(S7Client.S7_KUKA,Step1Mes2PlcVar.SubArrivedFinish,true);
//. mes 监控 到PlcToMes.SubArrived==false就把MesToPlc.SubArrivedFinish置为false
Integer subArrived2 = waitingForTarget(Step1Plc2MesVar.SubArrivedToMes, false);
if(subArrived2 != 1){
logger.info("失败"+" --- "+"MES监听 Step1Plc2MesVar.SubArrivedToMes 是否 等于 1 失败");
}
write(S7Client.S7_KUKA,Step1Mes2PlcVar.SubArrivedFinish,false);
}
},1,1, TimeUnit.SECONDS);
kukaStep2.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
//调度开始
Integer shelfIsFull = waitingForTarget(Step2Plc2MesVar.ShelfIsFull, true);
if(shelfIsFull != 1){
logger.info("失败"+" --- "+"MES监听 Step2Plc2MesVar.ShelfIsFull 是否 等于 1 失败");
}
//. 从plc 中获取 subIdList lineNum
String[] subIdList = (String[])read(S7Client.S7_KUKA,Step2Plc2MesVar.SubIdList);
// Integer lineNum = (Integer) read(S7Client.S7_KUKA,Step2Plc2MesVar.LineNum);
logger.info("获取到基板列表:"+ Arrays.toString(subIdList));
//. MES 业务
//=============== MES 业务 开始 =================
//1.MES 生成BoxId
if(subIdList.length<=0){
logger.info("失败"+" --- "+"从plc里面获取到的基板列表 为空");
}
WoPackagingBoxSubstrate bySubId = substrateServiceBiz.getBySubId(subIdList[0]);
String boxId = getBoxId(bySubId.getSapMaterial());
logger.info("mes 生成的boxId :"+ boxId);
//2. 依次update 基板表把boxId 赋予这些基板
for(int i=0;i<subIdList.length;i++){
substrateServiceBiz.updatePackagingBoxIdByWoSubstrateId(boxId,subIdList[i]);
}
//3.去camline数据库 查询此基板ID 对应的订单
String orderNameBySubId = service.getOrderNameBySubId(subIdList[0]);
//4. box信息录入到box表
WoPackagingBox woPackagingBox = new WoPackagingBox();
woPackagingBox.setBoxNo(boxId);
woPackagingBox.setPackagingTime(LocalDateTime.now());
woPackagingBox.setPowerLevel(bySubId.getPowerLevel());
woPackagingBox.setLineBody(bySubId.getLineBody());
woPackagingBox.setSapMaterial(bySubId.getSapMaterial());
woPackagingBox.setOrderNum(orderNameBySubId);
//1-手动模式2-自动模式
woPackagingBox.setModel(2);
boxServiceBiz.insert(woPackagingBox);
//=============== MES 业务 结束 =================
//. 把生成的BoxId 告诉kuka
write(S7Client.S7_KUKA,Step2Mes2PlcVar.BoxId,boxId);
//. 当MES完成任务后把MesToPlc.ShelfIsFullFinish变量置为true告诉plc我操作完成了
write(S7Client.S7_KUKA,Step2Mes2PlcVar.ShelfIsFullFinish,true);
//. mes 监控 到PlcToMes.SubArrived==false就把MesToPlc.SubArrivedFinish置为false
Integer subArrived2 = waitingForTarget(Step2Plc2MesVar.ShelfIsFull, false);
if(subArrived2 != 1){
logger.info("失败"+" --- "+"步骤1. MES监听 Step1Plc2MesVar.SubArrivedToMes 是否 等于 1 失败");
}
write(S7Client.S7_KUKA,Step2Mes2PlcVar.ShelfIsFullFinish,false);
}
},1,1, TimeUnit.SECONDS);
kukaStep3.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
//调度开始
Integer shelfIsFull = waitingForTarget(Step3Plc2MesVar.ShelfIsFullArrived, true);
if(shelfIsFull != 1){
logger.info("失败"+" --- "+"MES监听 Step3Plc2MesVar.ShelfIsFullArrived 是否 等于 1 失败");
}
//. 从plc 中获取 subIdList lineNum
String boxId = (String)read(S7Client.S7_KUKA,Step3Plc2MesVar.BoxId);
Integer lineNum = (Integer) read(S7Client.S7_KUKA,Step3Plc2MesVar.LineNum);
logger.info("到达站台的boxId :"+boxId);
//. MES 业务
//=============== MES 业务 开始 =================
//1. box信息录入到box表
boxServiceBiz.updateIsArrivedByBoxNo(1,boxId);
//=============== MES 业务 结束 =================
//. 当MES完成任务后把MesToPlc.ShelfIsFullArrivedFinish变量置为true告诉plc我操作完成了
write(S7Client.S7_KUKA,Step3Mes2PlcVar.ShelfIsFullArrivedFinish,true);
//. mes 监控 到PlcToMes.SubArrived==false就把MesToPlc.SubArrivedFinish置为false
Integer subArrived2 = waitingForTarget(Step3Plc2MesVar.ShelfIsFullArrived, false);
if(subArrived2 != 1){
logger.info("失败"+" --- "+"步骤1. MES监听 Step3Plc2MesVar.ShelfIsFullArrived 是否 等于 1 失败");
}
write(S7Client.S7_KUKA,Step3Mes2PlcVar.ShelfIsFullArrivedFinish,false);
}
},1,1, TimeUnit.SECONDS);
}
/**
*
* arg:
* Step1Plc2MesVar 参数类型
* targetValue 目的值
* return:
* 2 s7 访问异常;
* 1 成功;
* */
private Integer waitingForTarget(Step1Plc2MesVar var, Boolean targetValue) {
Integer res = 0;
while (true){
try {
Boolean now = (Boolean) read(S7Client.S7_KUKA,var);
if(targetValue.equals(now)){
res = 1;
break;
}
Thread.sleep(200);
}catch (Exception e){
logger.info("S7 数据采集 异常。");
res = 2;
break;
}
}
return res;
}
/**
*
* arg:
* Step2Plc2MesVar 参数类型
* targetValue 目的值
* return:
* 2 s7 访问异常;
* 1 成功;
* */
private Integer waitingForTarget(Step2Plc2MesVar var, Boolean targetValue) {
Integer res = 0;
while (true){
try {
Boolean now = (Boolean) read(S7Client.S7_KUKA,var);
if(targetValue.equals(now)){
res = 1;
break;
}
Thread.sleep(200);
}catch (Exception e){
logger.info("S7 数据采集 异常。");
res = 2;
break;
}
}
return res;
}
/**
*
* arg:
* Step3Plc2MesVar 参数类型
* targetValue 目的值
* return:
* 2 s7 访问异常;
* 1 成功;
* */
private Integer waitingForTarget(Step3Plc2MesVar var, Boolean targetValue) {
Integer res = 0;
while (true){
try {
Boolean now = (Boolean) read(S7Client.S7_KUKA,var);
if(targetValue.equals(now)){
res = 1;
break;
}
Thread.sleep(200);
}catch (Exception e){
logger.info("S7 数据采集 异常。");
res = 2;
break;
}
}
return res;
}
}

View File

@ -1,270 +0,0 @@
package com.cnbm.s7.controller;
import com.cnbm.s7.entity.R;
import com.cnbm.s7.entity.AGVInfoCallBack;
import com.cnbm.s7.s7connector.enmuc.PlcVarActual;
import com.cnbm.s7.s7connector.enmuc.S7Client;
import com.cnbm.s7.s7connector.type.PlcVar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
@RestController
@RequestMapping("/s7")
public class S7DemoController {
private static final Logger logger = LoggerFactory.getLogger(S7DemoController.class);
// @Autowired
// InfluxDBClient influxDBClient;
//
// @PostMapping("/insert")
// public void insert() throws InterruptedException {
// Event event = new Event();
// event.setTime(Instant.now());
// event.setTransationId("asasd11");
// event.setArgName("argName11");
// event.setArgValue(7d);
// Point asProcessCompleteEvent = insert(event, "ASProcessCompleteEventSSS");
// influxDBClient.makeWriteApi().writePoint(asProcessCompleteEvent);
// }
@PostMapping(value = "testFor")
private void testFor(@RequestBody AGVInfoCallBack agvInfoCallBack) {
System.out.println(agvInfoCallBack.toString());
}
//demo1
@PostMapping("/testReadAll")
public R testReadAll() throws UnsupportedEncodingException, ParseException {
for(PlcVarActual actual:PlcVarActual.values()){
System.out.println(read(S7Client.S7_1500,actual));
}
return R.ok();
}
// public Point insert(Event event, String measurement){
// Point point = Point.measurement(measurement)
// .addTag("transationId", event.getTransationId())
// .addTag("argName", event.getArgName())
// .addField("argValue", event.getArgValue())
// .time(event.getTime().toEpochMilli(), WritePrecision.MS);
// return point;
// }
//demo2
@PostMapping("/readTest")
public R getTestForS7() throws UnsupportedEncodingException, ParseException {
Boolean heartBeat = (Boolean)read(S7Client.S7_1500,PlcVarActual.HeartBeat);
String ddtl = (String)read(S7Client.S7_1500,PlcVarActual.DTL);
List<Character> characters = (List<Character>)read(S7Client.S7_1500,PlcVarActual.CharArrays);
List<Boolean> booleans = (List<Boolean>)read(S7Client.S7_1500,PlcVarActual.BooleanArrays);
String stri = (String)read(S7Client.S7_1500,PlcVarActual.STRING1);
return R.ok().put("res",heartBeat).put("characters",characters).put("ddtl",ddtl).put("bools",booleans).put("str",stri);
}
@PostMapping("/readTest2")
public R getTest2ForS7() throws Exception {
// List<Character> characters = (List<Character>)read(PlcVarActual.CharArrays,S7Client.S7_1500);
//
// List<Boolean> booleans = (List<Boolean>)read(PlcVarActual.BooleanArrays,S7Client.S7_1500);
// String stri = (String)read(PlcVarActual.STRING1,S7Client.S7_1500);
//
// return R.ok().put("res",heartBeat).put("characters",characters).put("ddtl",ddtl).put("bools",booleans).put("str",stri);
String con = "1233ADSDA";
write(S7Client.S7_1500,PlcVarActual.STRING1, con);
String read = (String)read(S7Client.S7_1500,PlcVarActual.STRING1);
String sub0 = (String)read(S7Client.S7_1500,PlcVarActual.SUBID0);
return R.ok().put("str",read).put("sub0",sub0);
}
@PostMapping("/testWriteBooleanArray")
public R testWriteBooleanArray() throws Exception {
List<Boolean> string = (List<Boolean>)read(S7Client.S7_1500,PlcVarActual.BooleanArrays1200);
System.out.println();
boolean[] res = new boolean[15];
res[0] = false;
res[1] = true;
res[2] = false;
res[3] = true;
res[4] = false;
res[5] = true;
res[6] = false;
res[7] = false;
res[8] = false;
res[9] = true;
res[10] = false;
res[11] = false;
res[12] = true;
res[13] = false;
res[14] = true;
write(S7Client.S7_1500,PlcVarActual.BooleanArrays1200, res);
System.out.println();
return R.ok();
}
@PostMapping("/testForString")
public R testForStrings() throws Exception {
//测试结果 l => 66ms
long l = System.currentTimeMillis();
String[] subs = (String[])read(S7Client.S7_1500,PlcVarActual.SubIdArrays);
long l1 = System.currentTimeMillis();
long dl = System.currentTimeMillis();
String string = (String)read(S7Client.S7_1500,PlcVarActual.STRING1);
long dl1 = System.currentTimeMillis();
String[] toWrite = new String[60];
for(int i=0;i<60;i++){
int i1 = new Random().nextInt(100);
toWrite[i] = "2212"+ i1;
}
////测试结果 c => 57ms
long c1 = System.currentTimeMillis();
write(S7Client.S7_1500,PlcVarActual.SubIdArrays,toWrite);
long c2 = System.currentTimeMillis();
String s = "cai xiang";
write(S7Client.S7_1500,PlcVarActual.STRING1,s);
String string2 = (String)read(S7Client.S7_1500,PlcVarActual.STRING1);
String[] subs2 = (String[])read(S7Client.S7_1500,PlcVarActual.SubIdArrays);
return R.ok().put("l",(l1-l)).put("c",(c2-c1)).put("dl",(dl1-dl));
}
@PostMapping("/testForString1200")
public R testForString1200() throws Exception {
//测试结果 l => 66ms
long l = System.currentTimeMillis();
String[] subs = (String[])read(S7Client.S7_1500,PlcVarActual.SubIdArrays1200); //65ms
long l1 = System.currentTimeMillis();
//System.out.println(Arrays.toString(subs));
String[] toWrite = new String[63];
for(int i=0;i<63;i++){
//int i1 = new Random().nextInt(100);
toWrite[i] = "abcd-"+ i;
}
////测试结果 c => 57ms
long c1 = System.currentTimeMillis();
write(S7Client.S7_1500,PlcVarActual.SubIdArrays1200,toWrite);
long c2 = System.currentTimeMillis();
String[] subs2 = (String[])read(S7Client.S7_1500,PlcVarActual.SubIdArrays1200);
logger.info("正常测试: l:"+(l1-l)+"c:"+(c2-c1)+";;read1:"+Arrays.toString(subs)+";;read2:"+Arrays.toString(subs2));
return R.ok().put("l",(l1-l)).put("c",(c2-c1));
}
@PostMapping("/testForString1500")
public R testForString1500() throws Exception {
//测试结果 l => 66ms
long l = System.currentTimeMillis();
String[] subs = (String[])read(S7Client.S7_1500,PlcVarActual.SubIdArrays); //25ms
long l1 = System.currentTimeMillis();
System.out.println(Arrays.toString(subs));
String[] toWrite = new String[63];
for(int i=0;i<63;i++){
//int i1 = new Random().nextInt(100);
toWrite[i] = "abcd-"+ i;
}
////测试结果 c => 57ms
long c1 = System.currentTimeMillis();
write(S7Client.S7_1500,PlcVarActual.SubIdArrays,toWrite);
long c2 = System.currentTimeMillis();
String[] subs2 = (String[])read(S7Client.S7_1500,PlcVarActual.SubIdArrays);
return R.ok().put("l",(l1-l)).put("c",(c2-c1));
}
@PostMapping("/testFor1200")
public R testFor1200() throws Exception {
//Object subs = read(PlcVarActual.INT1200, S7Client.S7_1500);
Object read = read(S7Client.S7_1500, PlcVarActual.SubIdArrays1200);
String[] toWrite = new String[60];
for(int i=0;i<60;i++){
int i1 = new Random().nextInt(100);
toWrite[i] = "2212"+ i1;
}
write(S7Client.S7_1500,PlcVarActual.SubIdArrays1200,toWrite);
Object read2 = read(S7Client.S7_1500, PlcVarActual.SubIdArrays1200);
return R.ok();
}
//PlcVarActual 到时候改成你们的 xxxPlcToWcs 或者 xxxWcsToPlc
/**
* return
* 成功 返回相应的object对象
* 失败 返回null
* */
private Object read(S7Client s7Client,PlcVarActual var) throws UnsupportedEncodingException, ParseException {
try {
return s7Client.read(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getLength(), var.getStrSize(), var.getType());
}catch (Exception e){
logger.error("host:"+s7Client.getHost()+" ; read 操作出现问题: "+e.getMessage());
e.printStackTrace();
return null;
}
}
private void write(S7Client s7Client,PlcVarActual var,Object newValue) throws Exception {
if(var.getType().equals(PlcVar.STRING_Array)){
String[] s = (String[])newValue;
String[] ss = (String[])newValue;
if(s.length > var.getLength() ){
ss = new String[var.getLength()];
for(int i=0;i< var.getLength();i++){
ss[i] = s[i];
}
}
s7Client.write(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getStrSize(), var.getType(),ss);
}else {
s7Client.write(var.getArea(), var.getAreaNumber(), var.getByteOffset(), var.getBitOffset(), var.getStrSize(), var.getType(),newValue);
}
}
// //demo3
// @PostMapping("/writeTest")
// public R writeTest() throws PlcConnectionException, UnsupportedEncodingException {
// write(S7Client.S7_1500,PlcVarActual.HeartBeat, false);
//
// char[] charArrays_content = new char[2];
// charArrays_content[0] = '1';
// charArrays_content[1] = 'c';
// write( S7Client.S7_1500,PlcVarActual.CharArrays, charArrays_content);
//
// boolean[] boolArrays_content = new boolean[2];
// boolArrays_content[0] = true;
// boolArrays_content[1] = false;
// write(S7Client.S7_1500,PlcVarActual.BooleanArrays, boolArrays_content);
//
// String str = "你好啊aa";
// //todo string 的读写有问题 待会看看
// write(S7Client.S7_1500,PlcVarActual.STRING1, str);
// return R.ok().put("res",true);
// }
}

View File

@ -1,233 +0,0 @@
package com.cnbm.s7.s7connector;
import cn.hutool.core.util.ByteUtil;
import java.math.BigInteger;
import java.util.Stack;
/**
* @Desc: ""
* @Author: caixiang
* @DATE: 2021/12/10 11:22
*/
public class Main2 {
public static byte[] double2Bytes(double d) {
long value = Double.doubleToRawLongBits(d);
byte[] byteRet = new byte[8];
for (int i = 0; i < 8; i++) {
byteRet[i] = (byte) ((value >> 8 * i) & 0xff);
}
return byteRet;
}
/**
* 1个字节byte[] 转成有符号的short
* */
public static Integer toInt(byte bytes) {
return Integer.valueOf(Byte.toString(bytes));
}
public static Integer toUInt(byte bytes) {
return Integer.valueOf(Byte.toUnsignedInt(bytes));
}
public static void main(String[] args) {
byte[] bytes = new byte[2];
bytes[0] = -1; //内部是 补码形式存在 //todo 搞清楚 补码和原码什么时候转化
bytes[1] = -111;
//-1 原码 1000 0001 -1 补码 1111 1111
//1000 0001 1110 1111 //原码形式
//1111 1111 1001 0001 //补码形式在计算机内部是以补码形式存储的当赋值给2个字节后是无符号整形的 要强制转化成short类型后,如果之前首位是1 就会被java强制转化成补码
//1000 0000 0110 1111 //
//1+16+128+256+512+1024+2048+4096+4096*2+4096*3+4096*4
//1024*(63)
//1000 0000 0110 1111 //-111
System.out.println(toInt(bytes[0]));
System.out.println(toUInt(bytes[0]));
System.out.println(toInt(bytes[1]));
System.out.println(toUInt(bytes[1]));
System.out.println("无符号 "+(bytes[1] & 0xff | (bytes[0] & 0xff) << Byte.SIZE));
System.out.println("有符号 "+(short)(bytes[1] & 0xff | (bytes[0] & 0xff) << Byte.SIZE));
// //byte类型的数字要&0xff再赋值给int类型其本质原因就是想保持二进制补码的一致性 0xff 其实就是0000 0000 0000 0000 0000 0000 1111 0100
short l = 0;
l<<=8; //<<=和我们的 +=是一样的意思就是 l = l << 8
//注意 移位并不会增加原来字节长度被挤掉的数据就没了而且是以补码的形式移动的
l |= (bytes[0] & 0xff); //和上面也是一样的 l = l | (b[i]&0xff) // 255 补码 1111 1111
l<<=7;
l<<=1;
//l<<=8; //<<=和我们的 +=是一样的意思就是 l = l << 8
l |= (bytes[1] & 0xff); //和上面也是一样的 l = l | (b[i]&0xff)
short c = 0;
c<<=8; //<<=和我们的 +=是一样的意思就是 l = l << 8
//注意 移位并不会增加原来字节长度被挤掉的数据就没了而且是以补码的形式移动的
c |= ((byte)1 & 0xff); //和上面也是一样的 l = l | (b[i]&0xff) // 255 补码 1111 1111
c<<=7;
c<<=1;
//l<<=8; //<<=和我们的 +=是一样的意思就是 l = l << 8
c |= ((byte)2 & 0xff); //和上面也是一样的 l = l | (b[i]&0xff)
byte bb = -1;
bb<<=8;
System.out.println(bb);
System.out.println(l);
System.out.println(Byte.valueOf((byte) 0x81)); //有符号 因为0x81 会自动被java 转成byte而byte会以补码 有符号的形式存在
System.out.println(0x81); //无符号
byte[] lrealBuffer = new byte[8];
Number lrealNumber = new Double(-12.1);
byte[] bytesss = ByteUtil.numberToBytes(lrealNumber);
Number intNumber = new Integer(-12);
byte[] bytessss = ByteUtil.numberToBytes(intNumber);
Integer s = new Integer(-999);
byte b = s.byteValue();
System.out.println();
}
public static double bytes2Double(byte[] arr) {
long value = 0;
for (int i = 0; i < 8; i++) {
value |= ((long) (arr[i] & 0xff)) << (8 * i);
}
return Double.longBitsToDouble(value);
}
public static byte[] short2byte(short s){
byte[] b = new byte[2];
for(int i = 0; i < 2; i++){
int offset = 16 - (i+1)*8; //因为byte占4个字节所以要计算偏移量
b[i] = (byte)((s >> offset)&0xff); //把16位分为2个8位进行分别存储
}
return b;
}
/**
* 将byte[]转为各种进制的字符串
* @param bytes byte[]
* @param radix 基数可以转换进制的范围从Character.MIN_RADIX到Character.MAX_RADIX超出范围后变为10进制
* @return 转换后的字符串
*/
public static String binary(byte[] bytes, int radix){
return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数
}
public static String byteToBit(byte b) {
return ""
+ (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
+ (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1) +","
+ (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
+ (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
}
public static short byte2short(byte[] b){
short l = 0;
for (int i = 0; i < 2; i++) {
l<<=8; //<<=和我们的 +=是一样的意思就是 l = l << 8
l |= (b[i] & 0xff); //和上面也是一样的 l = l | (b[i]&0xff)
}
return l;
}
public static byte[] int2byte(int s){
byte[] b = new byte[2];
for(int i = 0; i < 4; i++){
int offset = 16 - (i+1)*8; //因为byte占4个字节所以要计算偏移量
b[i] = (byte)((s >> offset)&0xff); //把32位分为4个8位进行分别存储
}
return b;
}
public static int byte2int(byte[] b){
int l = 0;
for (int i = 0; i < 4; i++) {
l<<=8; //<<=和我们的 +=是一样的意思就是 l = l << 8
l |= (b[i] & 0xff); //和上面也是一样的 l = l | (b[i]&0xff)
}
return l;
}
/**
* int到byte[](byte数组4个字节)
* @param i
* @return
*/
public static byte[] intToByteArray(int i) {
byte[] result = new byte[4];
//由高位到低位
result[0] = (byte)((i >> 24) & 0xFF);
result[1] = (byte)((i >> 16) & 0xFF); //如果查过128 那么会被java自动转成负数
result[2] = (byte)((i >> 8) & 0xFF);
result[3] = (byte)(i & 0xFF);
return result;
}
/**
* 4个字节的byte[]转int
* @param
* @return
*/
public static Integer byteArrayToInt(byte[] in) {
byte[] bytes = new byte[4];
//如果传进来数组不满足4个字节,自动填充
if(in.length>4){
return null;
}else if(in.length!=4){
Stack<Byte> st = new Stack<Byte>();
int c = 4-in.length;
in = invert(in);
for(int i=0;i<in.length;i++){
st.push(in[i]);
}
for(int i=0;i<c;i++){
st.push(Byte.valueOf((byte) 0));
}
for(int i=0;i<4;i++){
bytes[i] = st.pop();
}
}else {
bytes = in;
}
int value=0;
//由高位到低位
for(int i = 0; i < 4; i++) {
int shift= (4-1-i) * 8;
value +=(bytes[i] & 0x000000FF) << shift;//往高位游
}
return value;
}
public static Integer byteToUSInt(byte bytes) {
int value=0;
value +=(bytes & 0xFF);
return value;
}
public static Integer byteToSInt(byte bytes) {
return Byte.valueOf(bytes).intValue();
}
public static byte[] invert(byte[] a){
byte[] b = new byte[a.length];
Stack<Byte> st = new Stack<Byte>();
for(int i=0;i<a.length;i++){
st.push(a[i]);
}
for(int i=0;i<a.length;i++){
b[i] = st.pop();
}
return b;
}
}

View File

@ -1,294 +0,0 @@
package com.cnbm.s7.s7connector;
import java.io.UnsupportedEncodingException;
/**
* @Desc: ""
* @Author: caixiang
* @DATE: 2021/12/10 10:17
*/
public class MainForRead {
/**
* 将byte转换为一个长度为8的boolean数组(每bit代表一个boolean值)
*
* @param b byte, return(将数组翻转过来)
* @return boolean数组
*/
public static boolean[] getBooleanArray(byte b,boolean returns) {
boolean[] array = new boolean[8];
for (int i = 7; i >= 0; i--) { //对于byte的每bit进行判定
array[i] = (b & 1) == 1; //判定byte的最后一位是否为1若为1则是true否则是false
b = (byte) (b >> 1); //将byte右移一位
}
if(returns){
boolean[] array1 = new boolean[8];
array1[0] = array[7];
array1[1] = array[6];
array1[2] = array[5];
array1[3] = array[4];
array1[4] = array[3];
array1[5] = array[2];
array1[6] = array[1];
array1[7] = array[0];
array = array1;
}
return array;
}
public static void main(String[] args) throws UnsupportedEncodingException {
//1000 0101
//1010 0001
}
// public static void main(String[] args) throws Exception {
// //前言
// //DB3.1.1 中间那个1是byte区后面那个1 是bit
// //缺陷 不支持 DB3.1.1
//
// //Create connection
//// S7Connector connector =
//// S7ConnectorFactory
//// .buildTCPConnector()
//// .withHost("192.168.0.51")
//// .withRack(0) //optional rack 是机架号
//// .withSlot(0) //optional slot 是插槽号
//// .build();
//
// S7Connector connector = S7Client.S7_1500.getConnector();
//
// // // [0]
//// byte[] bool = connector.read(DaveArea.DB, 3, 1, 3266,0);
//// byte[] bool2 = connector.read(DaveArea.DB, 3, 1, 3266,1);
//// System.out.println("DB3.0-bool : " + ByteUtils.toBoolean(bool));
//// System.out.println("DB3.0-bool2 : " + ByteUtils.toBoolean(bool2));
//
//
//
// //bool3 => [1] 0000 0001 ==> 1000 0000 10.......
// //bool3 => [3] 0000 0011 ==> 1100 0000 11.......
// //bool3 => [10] 0000 1010 ==> 0101 0000 0101.....
// //bool3 => [25] 0001 1001 ==> 1001 1000 10011....
// byte[] bool3 = connector.read(DaveArea.DB, 3, 1, 3267);
// System.out.println("DB3.0-bool3 : " + ByteUtils.toBoolean(bool3));
//
// byte[] boolArrays = connector.read(DaveArea.DB, 3, 11, 3262);
// List<Boolean> booleans = ByteUtils.toBoolArray(boolArrays);
// System.out.println("DB3.830-boolArrays : " +booleans );
//
// byte[] boolArrays14 = connector.read(DaveArea.DB, 3, 16, 3264);
// List<Boolean> booleans14 = ByteUtils.toBoolArray(boolArrays14);
// System.out.println("DB3.3268-boolArrays : " +booleans14 );
//
// //
//// byte[] bool4 = connector.read(DaveArea.DB, 3, 1, 0);
//// System.out.println("DB3.0-bool3 : " + ByteUtils.toBoolean(bool3));
//
////
////
//// //非常规
//// {
//// //注意1:
//// //lreal 要小端拿到字节流要翻转一下
//// //参数一读取方式一般默认是DB区域块
//// //参数二区域块编号
//// //参数三区域数据类型大小int 2字节real 4字节
//// //参数四区域偏移量
//// //[-64, 40, 51, 51, 51, 51, 51, 51] -64==0xc0(要翻转一下才能用)
//// //1100 0000 0010 1000 0011 0011 0011 0011 0011 0011 0011 0011 0011 0011 0011 0011
////
//// byte[] lreal = connector.read(DaveArea.DB, 3, 8, 26,0);
//// System.out.println("DB3.26-lreal : "+ ByteUtils.forLReal(lreal));
////
//// byte[] real = connector.read(DaveArea.DB, 3, 4, 22,0);
//// System.out.println("DB3.22-real : "+ ByteUtils.forReal(real));
////
//// }
//
//// {
//// //data 是有符号的双字节
//// //注意2
//// //[2, -38] 就就代表1990-1-1 因为这就是其实位置 后续位置要1990+n的 D#1992-01-01
//// //[4, 72] 1993-1-1
//// //0000 0100 0100 1000 72+1024=1096 1990-1-1 + 1096() = 1993-1-1
//// byte[] date = connector.read(DaveArea.DB, 3, 2, 42);
////// System.out.println("DB3.42-DATE : "+addDate("1990-01-01",byte2short(date)));
//// Long aLong = Long.valueOf(ByteUtils.toInt(date[0], date[1]).toString());
//// System.out.println("DB3.42-DATE : "+ByteUtils.addDate("1990-01-01",aLong));
//// }
////
//// {
//// //[7, -78, 1, 1, 5, 0, 0, 0, 0, 0, 0, 0] DTL#1970-01-01-00:00:00 1998-1-1 星期五 0.0.0.0
//// //0000 0111 (1100 1110)=>(1011 0010 178) 178+256+512+1024=1970
//// //(注意第二个字节是负数要转成补码形式表示(因为在通行传输中 字节是原码形式传输的但是java中long int byte... 都是以补码形式保存的 java帮你自动保存了其实这是不对的所以你要转换一下) 参考https://blog.csdn.net/csdn_ds/article/details/79106006)
//// //[7, -68, 1, 21, 2, 0, 0, 0, 0, 0, 0, 0]
//// //0000 0111 (1100 0100)=>(1011 1100 188) 188+256+512+1024=1980
//// byte[] dtl = connector.read(DaveArea.DB, 3, 12, 44);
//// byte[] year = new byte[2];
//// year[0] = dtl[0];
//// year[1] = dtl[1];
//// byte[] month = new byte[1];
//// month[0] = dtl[2];
////// System.out.println("DB3.12-DTL : " + byteArrayByteUtils.toUInt(year)+"-"+byteArrayByteUtils.toUInt(month));
//// System.out.println("DB3.44-DTL : " + ByteUtils.toInt(year[0],year[1])+"-"+ByteUtils.toInt(month[0]));
//// }
////
//// {
//// //[59, -102, -55, -1] T#11D_13H_46M_39S_999MS
//// //0011 1011
//// byte[] time = connector.read(DaveArea.DB, 3, 4, 34);
//// System.out.println("DB3.34-time : " + ByteUtils.toInt(time[0],time[1],time[2],time[3]) +" ms");
//// }
////
//// //常规
//// {
//// // [0]
//// byte[] bool = connector.read(DaveArea.DB, 3, 1, 0);
//// System.out.println("DB3.0-bool : " + ByteUtils.toBoolean(bool));
////
//// //todo 就像这种情况的话这个工具就无法读取了 这个后续可以改他的源码 就是addreesByte/Bit那里 后续再说好了
//// byte[] bool2 = connector.read(DaveArea.DB, 3, 1, 3266);
//// System.out.println("DB3.3266-bool : " + ByteUtils.toBoolean(bool2));
////
////
//// //byte 目前读取以 有符号的十进制
//// //[8]
//// //[-63]
//// //1011 1111
//// byte[] byteOne = connector.read(DaveArea.DB, 3, 1, 1);
//// System.out.println("DB3.1-byteOne-有符号 : " + ByteUtils.toInt(byteOne[0])); //有符号 整形
////
//// System.out.println("DB3.1-byteOne-无符号 : " + ByteUtils.toUInt(byteOne[0])); //无符号 整形
////
////
//// // [0, 5] word 2/8/16进制 可无符号 可有符号就看你真没用
//// byte[] word = connector.read(DaveArea.DB, 3, 2, 2);
//// System.out.println("DB3.2-word : " + ByteUtils.toInt(word[0],word[1]));
////
//// // [-1, -1, -1, -4] 把java自动转换成byte类型 的补码形式 ,如果电控变量是这个要问下他是无符号还是有符号的
//// // [FF, FF, FF, FC] 原码
//// byte[] dword = connector.read(DaveArea.DB, 3, 4, 4);
//// System.out.println("DB3.4-dword : " + ByteUtils.toInt(dword[0],dword[1],dword[2],dword[3])); //带符号的 整形
////
//// //[11]
//// byte[] usint = connector.read(DaveArea.DB, 3, 1, 8);
//// System.out.println("DB3.8-usint : " + ByteUtils.toUInt(usint[0]));
////
//// byte[] sint = connector.read(DaveArea.DB, 3, 1, 9);
//// System.out.println("DB3.9-sint : " + ByteUtils.toInt(sint[0]));
////
//// byte[] uint = connector.read(DaveArea.DB, 3, 2, 10);
//// System.out.println("DB3.10-uint : " + ByteUtils.toUInt(uint[0],uint[1]));
////
//// //[-1, -111] -111
//// //[-1, -64] -64
//// //[-4, 25] -999
//// byte[] ints = connector.read(DaveArea.DB, 3, 2, 12);
//// System.out.println("DB3.12-ints : " + ByteUtils.toInt(ints[0],ints[1]));
////
//// byte[] dint = connector.read(DaveArea.DB, 3, 4, 14);
//// System.out.println("DB3.14-dint : " + ByteUtils.toInt(dint[0],dint[1],dint[2],dint[3]));
////
//// byte[] udint = connector.read(DaveArea.DB, 3, 4, 18);
//// System.out.println("DB3.18-udint : " + ByteUtils.toUInt(udint[0],udint[1],udint[2],udint[3]));
////
//// //plc 中char 是1个字节 注意char wchar 都是ascii码格式的
//// byte[] chars = connector.read(DaveArea.DB, 3, 1, 58);
//// Character charss = ByteUtils.toChar(chars);
//// System.out.println("DB3.58-char : " + charss);
//// //plc 中wchar 是2个字节
//// byte[] wchar = connector.read(DaveArea.DB, 3, 2, 60);
//// Character wchars =ByteUtils.toChar(wchar);
//// System.out.println("DB3.60-wchar : " + wchars);
////
//// //n+2 个字节 这里的n 就是实际content的字节数 "123"=> n=3 ;; "@123" ==> n=4
//// //[-2, 4, 64, 65, 83, 68] @ASD 前面-2 4两个字节就是上面的2字节 是无用的
//// //-2 代表 字符串中存储最大的总字节数 4代表字符数 后面跟着的 是内容最多256个字节
//// byte[] str = connector.read(DaveArea.DB, 3, 6, 62);
//// String string = ByteUtils.toStr(str);
//// System.out.println("DB3.62-str : " +string );
////
//// }
////
//// {
//// try {
//// //byte 占用一个字节如果是数组的话就读取2个要事先知道点表规定数组长度实际就是读取 DB3.830
//// //bytes = byteLength * arrayLength 举例1byteLength * 2arrayLength =2bytes
//// byte[] boolArrays = connector.read(DaveArea.DB, 3, 2, 830);
//// List<Boolean> booleans = ByteUtils.toBoolArray(boolArrays);
//// System.out.println("DB3.830-boolArrays : " +booleans );
////
//// byte[] byteArrays = connector.read(DaveArea.DB, 3, 2, 832);
//// List<Byte> bytes = ByteUtils.toByteArray(byteArrays);
//// System.out.println("DB3.832-byteArrays : " +bytes );
////
//// byte[] charArrays = connector.read(DaveArea.DB, 3, 2, 834);
//// List<Character> chars = ByteUtils.toCharArray(charArrays);
//// System.out.println("DB3.834-charArrays : " +chars );
////
//// byte[] wordArrays = connector.read(DaveArea.DB, 3, 4, 836);
//// List<Integer> words = ByteUtils.toWordArray(wordArrays);
//// System.out.println("DB3.836-wordArrays : " +words );
////
//// byte[] dwordArrays = connector.read(DaveArea.DB, 3, 8, 840);
//// List<Integer> dwords = ByteUtils.toDWordArray(dwordArrays);
//// System.out.println("DB3.840-dwordArrays : " +dwords );
////
//// byte[] sintArrays = connector.read(DaveArea.DB, 3, 2, 852);
//// List<Integer> sints = ByteUtils.toSIntArray(sintArrays);
//// System.out.println("DB3.852-sintArrays : " +sints );
////
//// byte[] intArrays = connector.read(DaveArea.DB, 3, 4, 848);
//// List<Integer> ints = ByteUtils.toIntArray(intArrays);
//// System.out.println("DB3.848-intArrays : " +ints );
////
//// byte[] dintArrays = connector.read(DaveArea.DB, 3, 8, 854);
//// List<Integer> dints = ByteUtils.toDIntArray(dintArrays);
//// System.out.println("DB3.852-dintArrays : " +dints);
////
////
//// byte[] usintArrays = connector.read(DaveArea.DB, 3, 3, 3240);
//// List<Integer> usints = ByteUtils.toUSIntArray(usintArrays);
//// System.out.println("DB3.3240-usintArrays : " +usints );
////
//// byte[] uintArrays = connector.read(DaveArea.DB, 3, 6, 3256);
//// List<Integer> uints = ByteUtils.toUIntArray(uintArrays);
//// System.out.println("DB3.3256-uintArrays : " +uints );
////
//// byte[] udintArrays = connector.read(DaveArea.DB, 3, 12, 3244);
//// List<Long> udints = ByteUtils.toUDIntArray(udintArrays);
//// System.out.println("DB3.852-udintArrays : " +udints);
//// }catch (Exception e){
//// e.printStackTrace();
//// }
////
//// };
//
//
//
//
//
// //Write to DB100 10 bytes
//
//
//
// //connector.write(DaveArea.DB, 3, 830, byteArrays);
//
// //Close connection
//
// //connector.close();
// }
//
}

View File

@ -1,70 +0,0 @@
package com.cnbm.s7.s7connector;
import com.cnbm.s7.s7connector.api.DaveArea;
import com.cnbm.s7.s7connector.api.S7Connector;
import com.cnbm.s7.s7connector.api.utils.ByteUtils;
import com.cnbm.s7.s7connector.enmuc.S7Client;
/**
* @Desc: ""
* @Author: caixiang
* @DATE: 2021/12/10 10:17
*/
public class MainForReadDemo {
public static void main(String[] args) throws Exception {
// //1200 部分
// S7Connector connector1200 = S7Client.S7_1200.getConnector();
//
// byte[] bool3_1200 = connector1200.read(DaveArea.DB, 1, 1, 0);
// System.out.println("DB1-bool3_1200 : " + ByteUtils.toBoolean(bool3_1200));
//// byte[] bool4_1200 = connector1200.read(DaveArea.DB, 3, 1, 3267,5,PlcVar.BOOL.getTransportSize());
//// System.out.println("DB1-bool4_1200 : " + ByteUtils.toBoolean(bool4_1200));
//1500 部分
S7Connector connector1500 = S7Client.S7_1500.getConnector();
// byte[] bool11 = connector1500.read(DaveArea.DB, 3, 1, 3267);
// //30110012105301115
// //[18, 17, 51, 48, 49, 49, 48, 48, 49, 50, 49, 48, 53, 51, 48, 49, 49, 49, 53, 0]
// // 3 0
// byte[] str1500 = connector1500.read(DaveArea.DB, 3, 20, 3270);
// byte[] str15001 = connector1500.read(DaveArea.DB, 3, 20, 3290);
// byte[] bool1 = connector1500.read(DaveArea.DB, 3, 1, 3267,4, PlcVar.BOOL.getTransportSize());
// String str1500s = ByteUtils.toStr(str1500);
// System.out.println("DB3.0-str1500 : " + str1500s);
// System.out.println("DB3.0-bool1 : " + ByteUtils.toBoolean(bool1));
//String
//write
String one = "12111";
byte[] bytes1 = ByteUtils.strToBytes(one, 18);
connector1500.write(DaveArea.DB,3,3270,bytes1);
//read
byte[] str_1500 = connector1500.read(DaveArea.DB, 3, 20, 3270);
String string = ByteUtils.toStr(str_1500);
System.out.println(string);
//StringArray
//write
String[] src = new String[3];
src[0]= "1";
src[1]= "30110012105301117222";
src[2]= "3";
byte[] bytes = ByteUtils.strArrayToBytes(src, 18);
connector1500.write(DaveArea.DB,3,3270,bytes);
//read
byte[] strList_1500 = connector1500.read(DaveArea.DB, 3, 60, 3270);
String[] strings = ByteUtils.toStrArray(strList_1500, 3, 18);
System.out.println(strings);
}
}

View File

@ -1,391 +0,0 @@
package com.cnbm.s7.s7connector;
import com.cnbm.s7.s7connector.api.DaveArea;
import com.cnbm.s7.s7connector.api.S7Connector;
import com.cnbm.s7.s7connector.api.factory.S7ConnectorFactory;
import com.cnbm.s7.s7connector.api.utils.ByteUtils;
import com.cnbm.s7.s7connector.type.PlcVar;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.List;
/**
* @Desc: ""
* @Author: caixiang
* @DATE: 2021/12/10 10:17
*/
public class MainForWrite {
public static void main(String[] args) throws Exception {
//Create connection
S7Connector connector =
S7ConnectorFactory
.buildTCPConnector()
.withHost("192.168.0.51")
.withRack(0) //optional rack 是机架号
.withSlot(0) //optional slot 是插槽号
.build();
{
connector.write(DaveArea.DB, 3, 3266,1,ByteUtils.boolToBytes(true), PlcVar.BOOL);
// byte[] bool = connector.read(DaveArea.DB, 3, 1, 3266,1);
// Boolean b = (Boolean)PlcVar.BOOL.toObject(bool);
// System.out.println("DB3.3266.1-boolean : " + b);
}
//非常规
{
//注意1:
//lreal 要小端拿到字节流要翻转一下
//参数一读取方式一般默认是DB区域块
//参数二区域块编号
//参数三区域数据类型大小int 2字节real 4字节
//参数四区域偏移量
//[-64, 40, 51, 51, 51, 51, 51, 51] -64==0xc0(要翻转一下才能用)
//1100 0000 0010 1000 0011 0011 0011 0011 0011 0011 0011 0011 0011 0011 0011 0011
// byte[] lreal_content = ByteUtils.lrealToBytes(Double.parseDouble("-111.1"));
byte[] lreal_content = PlcVar.LREAL.toBytes(-121.1);
connector.write(DaveArea.DB, 3, 26,lreal_content);
byte[] lreal = connector.read(DaveArea.DB, 3, 8, 26);
// Double aDouble = ByteUtils.lrealbytesToDouble(lreal);
Double ad = (Double)PlcVar.LREAL.toObject(lreal);
System.out.println("DB3.26-lreal : "+ ad);
//byte[] real_content = ByteUtils.realToBytes(Float.valueOf("-11.2"));
byte[] real_content = PlcVar.REAL.toBytes(-12.1);
connector.write(DaveArea.DB, 3, 22,real_content);
byte[] real = connector.read(DaveArea.DB, 3, 4, 22);
//ByteUtils.realbytesToFloat(real)
Float o = (Float)PlcVar.REAL.toObject(real);
System.out.println("DB3.22-real : "+ o);
}
{
//data 是有符号的双字节
//注意2
//[2, -38] 就就代表1990-1-1 因为这就是其实位置 后续位置要1990+n的 D#1992-01-01
//[4, 72] 1993-1-1
//0000 0100 0100 1000 72+1024=1096 1990-1-1 + 1096() = 1993-1-1
byte[] date = connector.read(DaveArea.DB, 3, 2, 42);
// System.out.println("DB3.42-DATE : "+addDate("1990-01-01",byte2short(date)));
// Long aLong = Long.valueOf(ByteUtils.toInt(date[0], date[1]).toString());
// String s = ByteUtils.addDate("1990-01-01", aLong);
String s = (String) PlcVar.DATE.toObject(date);
System.out.println("DB3.42-DATE : "+s);
}
{
//[7, -78, 1, 1, 5, 0, 0, 0, 0, 0, 0, 0] DTL#1970-01-01-00:00:00 1998-1-1 星期五 0.0.0.0
//0000 0111 (1100 1110)=>(1011 0010 178) 178+256+512+1024=1970
//(注意第二个字节是负数要转成补码形式表示(因为在通行传输中 字节是原码形式传输的但是java中long int byte... 都是以补码形式保存的 java帮你自动保存了其实这是不对的所以你要转换一下) 参考https://blog.csdn.net/csdn_ds/article/details/79106006)
//[7, -68, 1, 21, 2, 0, 0, 0, 0, 0, 0, 0]
//0000 0111 (1100 0100)=>(1011 1100 188) 188+256+512+1024=1980
byte[] dtl = connector.read(DaveArea.DB, 3, 12, 44);
// byte[] year = new byte[2];
// year[0] = dtl[0];
// year[1] = dtl[1];
// Integer yearInt = ByteUtils.toInt(year[0], year[1]);
// Integer monthInt = ByteUtils.toInt(dtl[2]);
// Integer dayInt = ByteUtils.toInt(dtl[3]);
// Integer worddayInt = ByteUtils.toInt(dtl[4]);
// Integer hourInt = ByteUtils.toInt(dtl[5]);
// Integer minuInt = ByteUtils.toInt(dtl[6]);
// Integer secondInt = ByteUtils.toInt(dtl[7]);
// System.out.println("DB3.12-DTL : " + byteArrayByteUtils.toUInt(year)+"-"+byteArrayByteUtils.toUInt(month));
String o = (String)PlcVar.DTL.toObject(dtl);
System.out.println("DB3.44-DTL : " + o );
}
{
//[59, -102, -55, -1] T#11D_13H_46M_39S_999MS
//0011 1011
byte[] time = connector.read(DaveArea.DB, 3, 4, 34);
// Integer integer = ByteUtils.toInt(time[0], time[1], time[2], time[3]);
Integer i = (Integer) PlcVar.TIME.toObject(time);
System.out.println("DB3.34-time : " + i +" ms");
}
//常规
//int 相关sintintdint usintuintudint
{
//[11] //[9] ==>2304
// byte[] usint_content = ByteUtils.usintToBytes(9);
byte[] usint_content = PlcVar.USINT.toBytes(9);
connector.write(DaveArea.DB, 3, 8,usint_content);
byte[] usint = connector.read(DaveArea.DB, 3, 1, 8);
// Integer integer = ByteUtils.toUInt(usint[0]);
Integer integer = (Integer) PlcVar.USINT.toObject(usint);
System.out.println("DB3.8-usint : " + integer);
// byte[] bytes = ByteUtils.sintToBytes(-9);
byte[] bytes = PlcVar.SINT.toBytes(-9);
connector.write(DaveArea.DB, 3, 9,bytes);
byte[] sint = connector.read(DaveArea.DB, 3, 1, 9);
// Integer integer1 = ByteUtils.toInt(sint[0]);
Integer integer1 = (Integer) PlcVar.SINT.toObject(usint);
System.out.println("DB3.9-sint : " + integer1);
// byte[] unit_content = ByteUtils.uintToBytes(9);
byte[] unit_content = PlcVar.UINT.toBytes(9);
connector.write(DaveArea.DB, 3, 10,unit_content);
byte[] uint = connector.read(DaveArea.DB, 3, 2, 10);
System.out.println("DB3.10-uint : " + ByteUtils.toUInt(uint[0],uint[1]));
//[-1, -111] -111
//[-1, -64] -64
//[-4, 25] -999
//byte[] bytes1 = ByteUtils.intToBytes(-99);
byte[] bytes1 = PlcVar.INT.toBytes(-99);
connector.write(DaveArea.DB, 3, 12,bytes1);
byte[] ints = connector.read(DaveArea.DB, 3, 2, 12);
System.out.println("DB3.12-ints : " + ByteUtils.toInt(ints[0],ints[1]));
// byte[] bytes2 = ByteUtils.dintToBytes(-999);
byte[] bytes2 = PlcVar.DINT.toBytes(-999);
connector.write(DaveArea.DB, 3, 14,bytes2);
byte[] dint = connector.read(DaveArea.DB, 3, 4, 14);
System.out.println("DB3.14-dint : " + ByteUtils.toInt(dint[0],dint[1],dint[2],dint[3]));
// byte[] bytes3 = ByteUtils.udintToBytes(99);
byte[] bytes3 = PlcVar.UDINT.toBytes(99);
connector.write(DaveArea.DB, 3, 18,bytes3);
byte[] udint = connector.read(DaveArea.DB, 3, 4, 18);
System.out.println("DB3.18-udint : " + ByteUtils.toUInt(udint[0],udint[1],udint[2],udint[3]));
}
{
// [0]
// byte[] bytes = ByteUtils.boolToBytes(false);
byte[] bytes = PlcVar.BOOL.toBytes(false);
connector.write(DaveArea.DB, 3, 0,bytes);
byte[] bool = connector.read(DaveArea.DB, 3, 1, 0);
System.out.println("DB3.0-boolean : " + ByteUtils.toBoolean(bool));
//byte 目前读取以 有符号的十进制
//[8]
//[-63]
//1011 1111
// byte[] setbytes = ByteUtils.setbytes(Byte.valueOf((byte) 0xFF));
byte[] setbytes = PlcVar.BYTE.toBytes((byte)0xFF);
connector.write(DaveArea.DB, 3, 1,setbytes);
byte[] byteOne = connector.read(DaveArea.DB, 3, 1, 1);
System.out.println("DB3.1-byteOne-有符号 : " + ByteUtils.toInt(byteOne[0])); //有符号 整形
System.out.println("DB3.1-byteOne-无符号 : " + ByteUtils.toUInt(byteOne[0])); //无符号 整形
// [0, 5] word 2/8/16进制 可无符号 可有符号就看你真没用
// byte[] bytes1 = ByteUtils.wordToBytes(Short.valueOf("-55"));
byte[] bytes1 = PlcVar.WORD.toBytes(-55);
connector.write(DaveArea.DB, 3, 2,bytes1);
byte[] word = connector.read(DaveArea.DB, 3, 2, 2);
System.out.println("DB3.2-word : " + ByteUtils.toInt(word[0],word[1]));
// [-1, -1, -1, -4] 把java自动转换成byte类型 的补码形式 ,如果电控变量是这个要问下他是无符号还是有符号的
// [FF, FF, FF, FC] 原码
byte[] bytes2 = PlcVar.DWORD.toBytes(-99);
connector.write(DaveArea.DB, 3, 4,bytes2);
byte[] dword = connector.read(DaveArea.DB, 3, 4, 4);
System.out.println("DB3.4-dword : " + ByteUtils.toInt(dword[0],dword[1],dword[2],dword[3])); //带符号的 整形
//plc 中char 是1个字节 注意char wchar 都是ascii码格式的
// byte[] bytes3 = ByteUtils.charToBytes('b');
byte[] bytes3 = PlcVar.CHAR.toBytes('b');
connector.write(DaveArea.DB, 3, 58,bytes3);
byte[] chars = connector.read(DaveArea.DB, 3, 1, 58);
System.out.println("DB3.58-char : " + ByteUtils.toChar(chars));
//plc 中wchar 是2个字节 '菜' =[-125, -36]
// byte[] bytes4 = ByteUtils.wcharToBytes('菜');
byte[] bytes4 = PlcVar.WCHAR.toBytes('翔');
connector.write(DaveArea.DB, 3, 60,bytes4);
byte[] wchar = connector.read(DaveArea.DB, 3, 2, 60);
System.out.println("DB3.60-wchar : " + ByteUtils.toChar(wchar));
//n+2 个字节 这里的n 就是实际content的字节数 "123"=> n=3 ;; "@123" ==> n=4
//[-2, 4, 64, 65, 83, 68] @ASD 前面-2 4两个字节就是上面的2字节 是无用的
//-2 代表 字符串中存储最大的总字节数 4代表字符数 后面跟着的 是内容最多256个字节
//[-2, 4, 64, 65, 83, 68] @ASD
//[-2, 4, 64, 64, 64, 64] @ASD
//读取字符串 要事先知道长度否则可能读取的字符串长度不完整
String s = "你好啊呢";
// byte[] str_content = ByteUtils.strToBytes(s);
// byte[] str_content = PlcVar.STRING.toBytes(s);
// connector.write(DaveArea.DB, 3, 62 , str_content);
//byte[] str = connector.read(DaveArea.DB, 3, str_content.length, 62);
//[-2, 6, -60, -29, -70, -61]
//[-2, 8, -53, -58, -75, -60]
byte[] str = connector.read(DaveArea.DB, 3, 10, 62);
String string = ByteUtils.toStr(str);
System.out.println("DB3.62-str : " +string );
//下面这种方式读取字符串是指定长度的
//byte[] str2 = connector.read(DaveArea.DB, 3, 7, 62);
}
{
//byte 占用一个字节如果是数组的话就读取2个要事先知道点表规定数组长度实际就是读取 DB3.830
//bytes = byteLength * arrayLength 举例1byteLength * 2arrayLength =2bytes
boolean[] booleanArray = new boolean[2];
booleanArray[0] = true;
booleanArray[1] = true;
// byte[] bytes1 = ByteUtils.booleanArrayToBytes(booleanArray);
byte[] bytes1 = PlcVar.BOOL_Array.toBytes(booleanArray);
connector.write(DaveArea.DB, 3, 830 , bytes1);
byte[] boolArrays = connector.read(DaveArea.DB, 3, 2, 830);
// List<Boolean> booleans = ByteUtils.toBoolArray(boolArrays);
List<Boolean> booleans = (List<Boolean>) PlcVar.BOOL_Array.toObject(boolArrays);
System.out.println("DB3.830-boolArrays : " +booleans );
//注意 write的长度要和plc中定义的长度要一致
byte[] write_byteArrays = new byte[2];
write_byteArrays[0] = 1;
write_byteArrays[1] = 2;
byte[] bytes2 = PlcVar.BYTE_Array.toBytes(write_byteArrays);
connector.write(DaveArea.DB, 3, 832 , bytes2);
byte[] byteArrays = connector.read(DaveArea.DB, 3, 2, 832);
// List<Byte> bytes = ByteUtils.toByteArray(byteArrays);
List<Byte> bytes = (List<Byte>) PlcVar.BYTE_Array.toObject(boolArrays);
System.out.println("DB3.832-byteArrays : " +bytes );
short[] shortArrays_content = new short[2];
shortArrays_content[0] = 1;
shortArrays_content[1] = -1;
// byte[] bytes4 = ByteUtils.wordArrayToBytes(shortArrays_content);
byte[] bytes4 = PlcVar.WORD_Array.toBytes(shortArrays_content);
connector.write(DaveArea.DB, 3, 836 ,bytes4);
byte[] wordArrays = connector.read(DaveArea.DB, 3, 4, 836);
List<Integer> words = ByteUtils.toWordArray(wordArrays);
System.out.println("DB3.836-wordArrays : " +words );
int[] intArrays_content = new int[2];
intArrays_content[0] = 1;
intArrays_content[1] = -1;
// byte[] bytes5 = ByteUtils.dwordArrayToBytes(intArrays_content);
byte[] bytes5 = PlcVar.DWORD_Array.toBytes(intArrays_content);
connector.write(DaveArea.DB, 3, 840 ,bytes5);
byte[] dwordArrays = connector.read(DaveArea.DB, 3, 8, 840);
List<Integer> dwords = ByteUtils.toDWordArray(dwordArrays);
System.out.println("DB3.840-dwordArrays : " +dwords );
char[] charArrays_content = new char[2];
charArrays_content[0] = '1';
charArrays_content[1] = 'b';
// byte[] bytes3 = ByteUtils.charArrayToBytes(charArrays_content);
byte[] bytes3 = PlcVar.CHAR_Array.toBytes(charArrays_content);
connector.write(DaveArea.DB, 3, 834 ,bytes3);
byte[] charArrays = connector.read(DaveArea.DB, 3, 2, 834);
List<Character> chars = ByteUtils.toCharArray(charArrays);
System.out.println("DB3.834-charArrays : " +chars );
int[] sintArrays_content = new int[2];
sintArrays_content[0] = 1;
sintArrays_content[1] = -1;
// byte[] bytes6 = ByteUtils.sintArrayToBytes(sintArrays_content);
byte[] bytes6 = PlcVar.SINT_Array.toBytes(sintArrays_content);
connector.write(DaveArea.DB, 3, 852 ,bytes6);
byte[] sintArrays = connector.read(DaveArea.DB, 3, 2, 852);
List<Integer> sints = ByteUtils.toSIntArray(sintArrays);
System.out.println("DB3.852-sintArrays : " +sints );
int[] iintArrays_content = new int[2];
iintArrays_content[0] = 12;
iintArrays_content[1] = -21;
// byte[] bytes7 = ByteUtils.intArrayToBytes(iintArrays_content);
byte[] bytes7 = PlcVar.INT_Array.toBytes(iintArrays_content);
connector.write(DaveArea.DB, 3, 848 ,bytes7);
byte[] intArrays = connector.read(DaveArea.DB, 3, 4, 848);
List<Integer> ints = ByteUtils.toIntArray(intArrays);
System.out.println("DB3.848-intArrays : " +ints );
//todo here
int[] dintArrays_content = new int[2];
dintArrays_content[0] = 12;
dintArrays_content[1] = -21;
//ByteUtils.dintArrayToBytes(dintArrays_content)
byte[] bytes11 =PlcVar.DINT_Array.toBytes(dintArrays_content);
connector.write(DaveArea.DB, 3, 854 ,bytes11);
byte[] dintArrays = connector.read(DaveArea.DB, 3, 8, 854);
List<Integer> dints = ByteUtils.toDIntArray(dintArrays);
System.out.println("DB3.852-dintArrays : " +dints);
int[] uintArrays_content = new int[3];
uintArrays_content[0] = 12;
uintArrays_content[1] = 99;
uintArrays_content[2] = 1;
//byte[] bytes9 = ByteUtils.uintArrayToBytes(uintArrays_content);
byte[] bytes9 = PlcVar.UINT_Array.toBytes(uintArrays_content);
connector.write(DaveArea.DB, 3, 3256 ,bytes9);
byte[] uintArrays = connector.read(DaveArea.DB, 3, 6, 3256);
List<Integer> uints = ByteUtils.toUIntArray(uintArrays);
System.out.println("DB3.3256-uintArrays : " +uints );
int[] usintArrays_content = new int[3];
usintArrays_content[0] = 12;
usintArrays_content[1] = 99;
usintArrays_content[2] = 1;
// byte[] bytes8 = ByteUtils.usintArrayToBytes(usintArrays_content);
byte[] bytes8 = PlcVar.USINT_Array.toBytes(usintArrays_content);
connector.write(DaveArea.DB, 3, 3240 ,bytes8);
byte[] usintArrays = connector.read(DaveArea.DB, 3, 3, 3240);
List<Integer> usints = ByteUtils.toUSIntArray(usintArrays);
System.out.println("DB3.3240-usintArrays : " +usints );
int[] udintArrays_content = new int[3];
udintArrays_content[0] = 12;
udintArrays_content[1] = 99;
udintArrays_content[2] = 1;
// byte[] bytes10 = ByteUtils.udintArrayToBytes(udintArrays_content);
byte[] bytes10 = PlcVar.UDINT_Array.toBytes(udintArrays_content);
connector.write(DaveArea.DB, 3, 3244 ,bytes10);
byte[] udintArrays = connector.read(DaveArea.DB, 3, 12, 3244);
List<Long> udints = ByteUtils.toUDIntArray(udintArrays);
System.out.println("DB3.852-udintArrays : " +udints);
}
//Write to DB100 10 bytes
//connector.write(DaveArea.DB, 3, 830, byteArrays);
//Close connection
connector.close();
}
}

View File

@ -25,9 +25,9 @@ public enum S7Client {
//TODO 步骤1 这里是配置多PLC 有多个plc 就在这里配置一个枚举类
//1500 西门子200smart12001500默认的 机架号=0 槽位号=1; 300/400 默认的 机架-0 插槽-2
// S7_1200("192.168.0.52",0,1,1,PlcVarActual.HeartBeatFor1200),
S7_15001("192.168.0.51",0,1,1),
S7_1500("192.168.0.51",0,1,1),
S7_KUKA("192.168.0.51",0,1,2),
// S7_15001("192.168.0.51",0,1,1),
// S7_1500("192.168.0.51",0,1,1),
S7_KUKA("10.10.3.158",0,1,1),
//1500 机架-0 插槽-1
//后续 在这里扩展 多PLC应用
;

View File

@ -15,11 +15,9 @@ limitations under the License.
*/
package com.cnbm.s7.s7connector.impl;
import com.cnbm.s7.controller.S7DemoController;
import com.cnbm.s7.s7connector.api.DaveArea;
import com.cnbm.s7.s7connector.api.S7Connector;
import com.cnbm.s7.s7connector.exception.S7CheckResultException;
import com.cnbm.s7.s7connector.exception.S7Exception;
import com.cnbm.s7.s7connector.impl.nodave.Nodave;
import com.cnbm.s7.s7connector.impl.nodave.S7Connection;
import com.cnbm.s7.s7connector.type.PlcVar;