Browse Source

3333

燃气自翻炒锅
fyf 11 months ago
parent
commit
c52f264623
23 changed files with 711 additions and 1763 deletions
  1. +11
    -9
      app/build.gradle
  2. +2
    -10
      app/src/main/java/com/bonait/bnframework/business/ConfigData.java
  3. +132
    -246
      app/src/main/java/com/bonait/bnframework/business/ExecuteTheRecipe.java
  4. +19
    -20
      app/src/main/java/com/bonait/bnframework/business/MainInit.java
  5. +98
    -182
      app/src/main/java/com/bonait/bnframework/common/constant/ConfigName.java
  6. +0
    -44
      app/src/main/java/com/bonait/bnframework/common/modbus/ModbusTcpHelper.java
  7. +0
    -718
      app/src/main/java/com/bonait/bnframework/common/modbus/ModbusTcpServer.java
  8. +0
    -15
      app/src/main/java/com/bonait/bnframework/common/modbus/S7/IS7ConnHelper.java
  9. +0
    -136
      app/src/main/java/com/bonait/bnframework/common/modbus/S7/S7ConnHelper.java
  10. +0
    -107
      app/src/main/java/com/bonait/bnframework/common/modbus/S7/S7Listenner.java
  11. +0
    -29
      app/src/main/java/com/bonait/bnframework/common/modbus/S7/mode/MyGunData.java
  12. +0
    -126
      app/src/main/java/com/bonait/bnframework/common/modbus/S7/mode/MyS7Entity.java
  13. +0
    -11
      app/src/main/java/com/bonait/bnframework/common/modbus/S7/mode/MyS7WriteEntity.java
  14. +234
    -0
      app/src/main/java/com/bonait/bnframework/common/modbus/s7/SiemensHelper.java
  15. +169
    -0
      app/src/main/java/com/bonait/bnframework/common/modbus/s7/SiemensHelper1.java
  16. +4
    -5
      app/src/main/java/com/bonait/bnframework/modules/home/activity/BottomNavigation2Activity.java
  17. +4
    -10
      app/src/main/java/com/bonait/bnframework/modules/home/activity/BottomNavigationNewActivity.java
  18. +0
    -1
      app/src/main/java/com/bonait/bnframework/modules/home/fragment/Home1Fragment.java
  19. +0
    -33
      app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/fragment/AutoTestMoreFragment.java
  20. +0
    -22
      app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/fragment/AutoTestOneFragment.java
  21. +34
    -34
      app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/fragment/SystemCsMonitorFragment.java
  22. +0
    -1
      app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/fragment/SystemCsPLCFragment.java
  23. +4
    -4
      app/src/main/res/layout/activity_login.xml

+ 11
- 9
app/build.gradle View File

@@ -19,12 +19,12 @@ android {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

resValue("bool","superAdminTest","false")
resValue("bool", "superAdminTest", "false")
}

debug {
resValue("string", "PORT_NUMBER", "8081")
resValue("bool","superAdminTest","true")
resValue("bool", "superAdminTest", "true")
}
}

@@ -34,6 +34,9 @@ android {
}

compileOptions {
//启用对新语言API的支持的标志
coreLibraryDesugaringEnabled true

sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
@@ -122,7 +125,6 @@ dependencies {
// implementation files('libs/commons-codec-1.6.jar')



//Modbus
implementation 'com.github.licheedev:Modbus4Android:2.0.2'

@@ -151,7 +153,7 @@ dependencies {
implementation 'com.github.zcweng:switch-button:0.0.3@aar'

//阿里云IOT
implementation ('com.aliyun.alink.linksdk:lp-iot-linkkit:1.7.3.2')
implementation('com.aliyun.alink.linksdk:lp-iot-linkkit:1.7.3.2')

implementation 'com.github.SheHuan:NiceImageView:1.0.5'

@@ -159,9 +161,9 @@ dependencies {
// implementation files('libs\\org.eclipse.paho.android.service-1.1.1.jar')
// implementation files('libs\\org.eclipse.paho.client.mqttv3-1.2.5.jar')

//S7系列 PLC读取
implementation 'com.github.s7connector:s7connector:2.0'
//新的plc
implementation 'com.github.xingshuangs:iot-communication:1.5.0'
implementation "org.projectlombok:lombok:1.16.18"
implementation 'org.glassfish:javax.annotation:10.0-b28'
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}

+ 2
- 10
app/src/main/java/com/bonait/bnframework/business/ConfigData.java View File

@@ -6,11 +6,8 @@ import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;

import com.bonait.bnframework.R;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.constant.MessageName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_CLOUDDATA;
@@ -23,14 +20,12 @@ import com.bonait.bnframework.common.db.mode.BPA_PROCESSModel;
import com.bonait.bnframework.common.db.mode.BPA_SYSTEMSET;
import com.bonait.bnframework.common.db.mode.Res_PLCADDRESS;
import com.bonait.bnframework.common.helper.ConfigUtil;
import com.bonait.bnframework.common.helper.I.IRun;
import com.bonait.bnframework.common.helper.I.IRunT;
import com.bonait.bnframework.common.helper.Json;
import com.bonait.bnframework.common.http.callback.json.JsonDialogCallback;
import com.bonait.bnframework.common.image.utils.LocalCacheUtils;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.modbus.ModbusTcpHelper;
import com.bonait.bnframework.common.modbus.ModbusTcpServer;
import com.bonait.bnframework.common.modbus.s7.SiemensHelper1;
import com.bonait.bnframework.common.model.ResAPI;
import com.bonait.bnframework.common.model.mode.ActionJsonMode;
import com.bonait.bnframework.common.model.mode.BPA_GoodsAttributeValue;
@@ -64,14 +59,11 @@ import com.lzy.okgo.model.Response;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
@@ -1136,7 +1128,7 @@ public class ConfigData {
* 关闭PLC
*/
public void ColsePLC() {
ModbusTcpHelper.get().release();//释放modbus
SiemensHelper1.get().Close();//释放modbus
ConfigName.getInstance().PlcIsConnect = false;
}



+ 132
- 246
app/src/main/java/com/bonait/bnframework/business/ExecuteTheRecipe.java View File

@@ -6,44 +6,28 @@ import android.content.ContextWrapper;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;

import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.constant.MessageName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPE;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.db.mode.BPA_PLCADDRESS;
import com.bonait.bnframework.common.db.mode.BPA_SILOS;
import com.bonait.bnframework.common.helper.ByteHelper;
import com.bonait.bnframework.common.helper.I.IRun;
import com.bonait.bnframework.common.helper.I.IRunT;
import com.bonait.bnframework.common.helper.I.IThread;
import com.bonait.bnframework.common.helper.I.IWriteCallBack;
import com.bonait.bnframework.common.helper.ThreadManager;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.modbus.ModbusTcpServer;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.modbus.s7.SiemensHelper1;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.fragment.mode.LocationStatus;
import com.bonait.bnframework.modules.home.fragment.mode.MyStatus;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import kotlin.UShort;

/**
* 执行配方
@@ -100,7 +84,7 @@ public class ExecuteTheRecipe {
/**
* plc 当前版本号
*/
public static String PlcVersion="0001";
public static String PlcVersion = "0001";
/**
* 通知版本号更新显示
*/
@@ -108,6 +92,7 @@ public class ExecuteTheRecipe {
//endregion

//region 强制结束

/**
* 设置强制结束
*/
@@ -125,6 +110,7 @@ public class ExecuteTheRecipe {
//endregion

//region 执行配方

/**
* 执行配方
*
@@ -575,10 +561,9 @@ public class ExecuteTheRecipe {
val = Integer.parseInt(value);
} else {
ToastUtils.info("工序:" + key + "," + value);
if(value.contains("自动打火"))
{
if (value.contains("自动打火")) {
//WritePLC(value,true,null);
}else //手动打火
} else //手动打火
{

}
@@ -718,6 +703,7 @@ public class ExecuteTheRecipe {
//endregion

//region 主页按钮

/**
* 火力点击
*
@@ -798,12 +784,6 @@ public class ExecuteTheRecipe {
}
}

if (ConfigName.getInstance().PlcIsConnect) {
TempControl();
ReadPLCStatus();

}

} catch (Exception ex) {
ToastUtils.error("异常信息:" + ex.getMessage());
}
@@ -842,183 +822,6 @@ public class ExecuteTheRecipe {
}
//endregion

//region PLC基础控制类

/**
* 写PLC数据
*
* @param name
* @param value
*/
public static void WritePLC(String name, Object value, IWriteCallBack callback) {
try {
if (ConfigName.getInstance().PLC_Address.containsKey(name)) {
BPA_PLCADDRESS plcaddress = ConfigName.getInstance().PLC_Address.get(name);
if (!plcaddress.address.isEmpty() && ConfigName.getInstance().PlcIsConnect) {
if (plcaddress.address.toUpperCase().startsWith("VD"))//int
{
ModbusTcpServer.get().WriteInt(plcaddress.address, (int) value, callback);
} else if (plcaddress.address.toUpperCase().startsWith("M"))//bool
{
ModbusTcpServer.get().WriteBool(plcaddress.address, (boolean) value, callback);
} else if (plcaddress.address.toUpperCase().startsWith("VW"))//short
{
ModbusTcpServer.get().WriteShort(plcaddress.address, Short.parseShort(value.toString()), callback);
}
}
}
} catch (Exception ex) {
ToastUtils.error("异常信息:" + ex.getMessage());
} finally {

}
}

/**
* 读PLC数据
*
* @param name
* @return
*/
public static Object ReadPLC(String name) {
final Object[] ReturnsVariable = {null};
try {
if (ConfigName.getInstance().PLC_Address.containsKey(name)) {
BPA_PLCADDRESS plcaddress = ConfigName.getInstance().PLC_Address.get(name);
if (!plcaddress.address.isEmpty() && ConfigName.getInstance().PlcIsConnect) {
if (plcaddress.address.toUpperCase().startsWith("VD"))//int
{
ModbusTcpServer.get().ReadInt(plcaddress.address, 1, ints -> {
ReturnsVariable[0] = ints[0];
});
} else if (plcaddress.address.toUpperCase().startsWith("M"))//bool
{
ModbusTcpServer.get().ReadBool(plcaddress.address, 1, val -> {
ReturnsVariable[0] = val[0];
});
} else if (plcaddress.address.toUpperCase().startsWith("VW"))//short
{
ModbusTcpServer.get().ReadShort(plcaddress.address, 1, val -> {
ReturnsVariable[0] = val[0];
});
}
}
}
} catch (Exception ex) {
ToastUtils.error("异常信息:" + ex.getMessage());
} finally {
return ReturnsVariable[0];
}
}

/**
* 实时状态
*/
public static ConcurrentHashMap<Integer, Boolean> IoStatus = new ConcurrentHashMap<Integer, Boolean>();

/**
* 获取实时状态
*
* @param ch
* @return
*/
public static boolean getConcurrentHash(int ch) {
if (!IoStatus.containsKey(ch)) {
return false;
}
return IoStatus.get(ch);
}

/**
* 获取搅拌电机
*
* @param
* @return
*/
public static int getConcurrentHash_dj(String name) {
if (!ListeningValue.containsKey(name)) {
return 0;
}
Object obj = ListeningValue.get(name);
if (obj == null) {
return 0;
} else {
return (int) obj;
}
}

/**
* 获取监听变量
*
* @param
* @return
*/
public static Object getListingValue(String name) {
if (!ListeningValue.containsKey(name)) {
return null;
}
return ListeningValue.get(name);
}

/**
* 读取状态
*/
public static void ReadPLCStatus() {
try {
if (ConfigName.getInstance().PlcIsConnect) {
ModbusTcpServer.get().ReadStatus("VW354", 1, data -> {
for (int i = 0; i < data.length; i++) {
byte status = data[i];//0x92
IoStatus.put(i * 8 + 0, ByteHelper.getBit(status, 0) == 1);
IoStatus.put(i * 8 + 1, ByteHelper.getBit(status, 1) == 1);
IoStatus.put(i * 8 + 2, ByteHelper.getBit(status, 2) == 1);
IoStatus.put(i * 8 + 3, ByteHelper.getBit(status, 3) == 1);
IoStatus.put(i * 8 + 4, ByteHelper.getBit(status, 4) == 1);
IoStatus.put(i * 8 + 5, ByteHelper.getBit(status, 5) == 1);
IoStatus.put(i * 8 + 6, ByteHelper.getBit(status, 6) == 1);
IoStatus.put(i * 8 + 7, ByteHelper.getBit(status, 7) == 1);
}
});
}
} catch (Exception ex) {
ToastUtils.error("异常信息:" + ex.getMessage());
} finally {
}
}

/**
* 温控
*/
public static void TempControl() {
boolean TempBool = false;
Object val_wd = ExecuteTheRecipe.getListingValue("当前锅底温度");
int dq_wd = val_wd == null ? 0 : (int) val_wd;//当前锅底温度
if (dq_wd >= (ConfigName.getInstance().MaxTemp - 5)) //如果当前温度大于最大温度限制 断开
{
TempBool = true;//设置断开
} else if (dq_wd <= (ConfigName.getInstance().MaxTemp - 20))//需要闭合
{
TempBool = false;//闭合
}

Object tempkg = ExecuteTheRecipe.ReadPLC("温控开关");
if (tempkg != null) {
boolean kg = (boolean) tempkg;
if (TempBool) //设置断开
{
if (kg == false) {
ExecuteTheRecipe.WritePLC("温控开关", true, null);//断开
}
} else //设置闭合
{
if (kg) {
ExecuteTheRecipe.WritePLC("温控开关", false, null);//闭合
}
}
}
}
//endregion

//region 获取基础挡位变量

/**
@@ -1073,6 +876,7 @@ public class ExecuteTheRecipe {
//endregion

//region 延迟函数

/**
* 线程延迟函数(避免线程阻塞等待)
*
@@ -1094,8 +898,8 @@ public class ExecuteTheRecipe {
int time = (int) ((endTime - startTime) / 1000);
ExecuteTheRecipe.showlog("工序线程等待结束-------总耗时:" + time);
}
/**
/**
* 线程等待
*
* @param name
@@ -1159,61 +963,64 @@ public class ExecuteTheRecipe {
//endregion

//region 获取默认工艺

/**
* 获取搅拌
* @param sd 0-50
*
* @param sd 0-50
* @return
*/
public static BPA_GOODSRECIPE Get搅拌(int sd)
{
public static BPA_GOODSRECIPE Get搅拌(int sd) {
BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
pf.materialType=1;
pf.processname="搅拌";
pf.processms="搅拌("+sd+",0)";
pf.processvalue="搅拌速度,"+sd+"|等待(秒),0";
pf.materialType = 1;
pf.processname = "搅拌";
pf.processms = "搅拌(" + sd + ",0)";
pf.processvalue = "搅拌速度," + sd + "|等待(秒),0";
return pf;
}

/**
* 获取搅拌
* @param data 自动打火、手动打火
*
* @param data 自动打火、手动打火
* @return
*/
public static BPA_GOODSRECIPE Get打火(String data)
{
public static BPA_GOODSRECIPE Get打火(String data) {
BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
pf.materialType=1;
pf.processname="打火";
pf.processms="打火("+data+",0)";
pf.processvalue="打火动作,"+data+"|等待(秒),0";
pf.materialType = 1;
pf.processname = "打火";
pf.processms = "打火(" + data + ",0)";
pf.processvalue = "打火动作," + data + "|等待(秒),0";
return pf;
}

/**
* 获取位置
*
* @param
* @return
*/
public static BPA_GOODSRECIPE Get位置(String name)
{
public static BPA_GOODSRECIPE Get位置(String name) {
BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
pf.materialType=1;
pf.processname="位置";
pf.processms="位置("+name+",0)";
pf.processvalue="位置动作,"+name+"|等待(秒),0";
pf.materialType = 1;
pf.processname = "位置";
pf.processms = "位置(" + name + ",0)";
pf.processvalue = "位置动作," + name + "|等待(秒),0";
return pf;
}

/**
* 获取手动主料
*
* @param
* @return
*/
public static BPA_GOODSRECIPE Get主料(int k1,int k2,int k3,int k4,int temp,int zl) {
public static BPA_GOODSRECIPE Get主料(int k1, int k2, int k3, int k4, int temp, int zl) {
BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
pf.materialType = 1;
pf.processname = "主料";
pf.processms = String.format("主料(未知,%d,%d,%d,%d,%d,%d,%d",k1,k2,k3,k4,temp,zl,0);
pf.processvalue = String.format("主料名称,未知|一环功率,%d|二环功率,%d|三环功率,%d|四环功率,%d|温度设定,%d|锅内重量,%d|烹饪(秒),%d",k1,k2,k3,k4,temp,zl,0);
pf.processms = String.format("主料(未知,%d,%d,%d,%d,%d,%d,%d", k1, k2, k3, k4, temp, zl, 0);
pf.processvalue = String.format("主料名称,未知|一环功率,%d|二环功率,%d|三环功率,%d|四环功率,%d|温度设定,%d|锅内重量,%d|烹饪(秒),%d", k1, k2, k3, k4, temp, zl, 0);
return pf;
}

@@ -1223,12 +1030,12 @@ public class ExecuteTheRecipe {
* @param
* @return
*/
public static BPA_GOODSRECIPE Get约束条件(int k1,int k2,int k3,int k4,int temp,int zl) {
public static BPA_GOODSRECIPE Get约束条件(int k1, int k2, int k3, int k4, int temp, int zl) {
BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
pf.materialType = 1;
pf.processname = "约束条件";
pf.processms = String.format("约束条件(%d,%d,%d,%d,%d,%d,%d",k1,k2,k3,k4,temp,zl,0);
pf.processvalue = String.format("一环功率,%d|二环功率,%d|三环功率,%d|四环功率,%d|温度设定,%d|锅内重量,%d|烹饪(秒),%d",k1,k2,k3,k4,temp,zl,0);
pf.processms = String.format("约束条件(%d,%d,%d,%d,%d,%d,%d", k1, k2, k3, k4, temp, zl, 0);
pf.processvalue = String.format("一环功率,%d|二环功率,%d|三环功率,%d|四环功率,%d|温度设定,%d|锅内重量,%d|烹饪(秒),%d", k1, k2, k3, k4, temp, zl, 0);
return pf;
}

@@ -1256,32 +1063,33 @@ public class ExecuteTheRecipe {
return null;
}
}

/**
* 获取延迟
*
* @param time
* @return
*/
public static BPA_GOODSRECIPE Get延迟(int time)
{
public static BPA_GOODSRECIPE Get延迟(int time) {
BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
pf.materialType=1;
pf.processname="延迟";
pf.processms="延迟("+time+")";
pf.processvalue="等待(秒),"+time;
pf.materialType = 1;
pf.processname = "延迟";
pf.processms = "延迟(" + time + ")";
pf.processvalue = "等待(秒)," + time;
return pf;
}

/**
* 获取出菜
*
* @return
*/
public static BPA_GOODSRECIPE Get出菜(int k)
{
public static BPA_GOODSRECIPE Get出菜(int k) {
BPA_GOODSRECIPE pf = new BPA_GOODSRECIPE();
pf.materialType=1;
pf.processname="出菜";
pf.processms="出菜("+k+")";
pf.processvalue="等待(秒),"+k;
pf.materialType = 1;
pf.processname = "出菜";
pf.processms = "出菜(" + k + ")";
pf.processvalue = "等待(秒)," + k;
return pf;
}

@@ -1299,8 +1107,8 @@ public class ExecuteTheRecipe {
return pf;
}
//endregion
//region 显示日志
//region 显示日志

/**
* 显示日志
@@ -1310,4 +1118,82 @@ public class ExecuteTheRecipe {
ToastUtils.info(msg);
}
//endregion

//region PLC控制类

/**
* 写PLC数据
*
* @param name
* @param value
*/
public static void WritePLC(String name, Object value, IWriteCallBack callback) {
try {
if (ConfigName.getInstance().PLC_Address.containsKey(name)) {
BPA_PLCADDRESS plcaddress = ConfigName.getInstance().PLC_Address.get(name);
if (!plcaddress.address.isEmpty() && ConfigName.getInstance().PlcIsConnect) {
SiemensHelper1.get().writePLC(plcaddress.address, value);
}
}
} catch (Exception ex) {
ToastUtils.error("异常信息:" + ex.getMessage());
} finally {
}
}

/**
* 读PLC数据
*
* @param name
* @return
*/
public static Object ReadPLC(String name) {
final Object[] ReturnsVariable = {null};
try {
if (ConfigName.getInstance().PLC_Address.containsKey(name)) {
BPA_PLCADDRESS plcaddress = ConfigName.getInstance().PLC_Address.get(name);
if (!plcaddress.address.isEmpty() && ConfigName.getInstance().PlcIsConnect) {

ReturnsVariable[0] = SiemensHelper1.get().readPLC(plcaddress.address);
}
}
} catch (Exception ex) {
ToastUtils.error("异常信息:" + ex.getMessage());
} finally {
return ReturnsVariable[0];
}
}


/**
* 获取搅拌电机
*
* @param
* @return
*/
public static int getConcurrentHash_dj(String name) {
if (!ListeningValue.containsKey(name)) {
return 0;
}
Object obj = ListeningValue.get(name);
if (obj == null) {
return 0;
} else {
return (int) obj;
}
}

/**
* 获取监听变量
*
* @param
* @return
*/
public static Object getListingValue(String name) {
if (!ListeningValue.containsKey(name)) {
return null;
}
return ListeningValue.get(name);
}
//endregion
}

+ 19
- 20
app/src/main/java/com/bonait/bnframework/business/MainInit.java View File

@@ -26,7 +26,6 @@ import com.bonait.bnframework.common.helper.I.IMessageLogNotify;
import com.bonait.bnframework.common.helper.LogcatHelper;
import com.bonait.bnframework.common.helper.MessageLog;
import com.bonait.bnframework.common.helper.SdCart;
import com.bonait.bnframework.common.modbus.ModbusTcpHelper;
import com.bonait.bnframework.common.notification.MainNotification;
import com.bonait.bnframework.common.utils.AppUtils;
import com.bonait.bnframework.common.utils.NetworkUtils;
@@ -260,29 +259,29 @@ public class MainInit {
public void ErrorMsg(String msg) {
if(msg.contains("msg:com.serotonin.modbus4j.exception"))
{
if(msg.contains("主设备"))
{
// ModbusTcpMainHelper.get().release();//释放modbus
// ConfigName.getInstance().PlcMainIsConnect=false;
// if(msg.contains("主设备"))
// {
//// ModbusTcpMainHelper.get().release();//释放modbus
//// ConfigName.getInstance().PlcMainIsConnect=false;
//// BPA_ALERTLOG log = new BPA_ALERTLOG();
//// log.userID = ConfigName.getInstance().user.userID;
//// log.type=4;
//// log.text = msg+"主程序断开PLC,准备重连机制...";
//// QueryDB.AddAlertlog(log);
//// Log.e("主控PLC", "主控PLC: 连接断开");
//
// }else if(msg.contains("PLC设备"))
// {
// ModbusTcpHelper.get().release();//释放modbus
// ConfigName.getInstance().PlcIsConnect=false;
// BPA_ALERTLOG log = new BPA_ALERTLOG();
// log.userID = ConfigName.getInstance().user.userID;
// log.type=4;
// log.text = msg+"主程序断开PLC,准备重连机制...";
// log.text = msg+"PLC程序断开PLC,准备重连机制...";
// QueryDB.AddAlertlog(log);
// Log.e("主控PLC", "主控PLC: 连接断开");

}else if(msg.contains("PLC设备"))
{
ModbusTcpHelper.get().release();//释放modbus
ConfigName.getInstance().PlcIsConnect=false;
BPA_ALERTLOG log = new BPA_ALERTLOG();
log.userID = ConfigName.getInstance().user.userID;
log.type=4;
log.text = msg+"PLC程序断开PLC,准备重连机制...";
QueryDB.AddAlertlog(log);
Log.e("设备PLC", "设备PLC: 连接断开");

}
// Log.e("设备PLC", "设备PLC: 连接断开");
//
// }

}
}


+ 98
- 182
app/src/main/java/com/bonait/bnframework/common/constant/ConfigName.java View File

@@ -234,159 +234,108 @@ public class ConfigName {
*/
public List<Res_PLCADDRESS> PlcAddress_燃气大炒 = new ArrayList<Res_PLCADDRESS>() {{

//硬件设备 初始化
add(new Res_PLCADDRESS("硬件设备", "-------------", 0, 0));
add(new Res_PLCADDRESS("初始化", "M10.0", 1, 1));
add(new Res_PLCADDRESS("停止", "M10.1", 1, 1));
add(new Res_PLCADDRESS("复位", "M10.2", 0, 1));

//搅拌模型
add(new Res_PLCADDRESS("模型控制", "-------------", 0, 0));
add(new Res_PLCADDRESS("搅拌", "M10.3", 0, 1));
add(new Res_PLCADDRESS("搅拌速度", "VW102", 1, 1));

//翻转正转模型
add(new Res_PLCADDRESS("翻转正转", "M10.4", 0, 1));
add(new Res_PLCADDRESS("翻转反转", "M10.5", 0, 1));
add(new Res_PLCADDRESS("转动速度", "VW104", 1, 1));


//加热模型
add(new Res_PLCADDRESS("加热", "M10.6", 0, 1));
add(new Res_PLCADDRESS("加热功率", "VW100", 1, 1));
add(new Res_PLCADDRESS("温控开关", "M17.6", 1, 1));
add(new Res_PLCADDRESS("暂停开关", "M17.7", 1, 1));

//主料
add(new Res_PLCADDRESS("主料", "M17.4", 0, 1));

//抽水放水
add(new Res_PLCADDRESS("炒锅抽水", "M10.7", 0, 1));
add(new Res_PLCADDRESS("炒锅放水", "M11.0", 0, 1));


//出菜模型
add(new Res_PLCADDRESS("出菜", "M11.5", 0, 1));


//位置动作
add(new Res_PLCADDRESS("原点位", "M11.4", 0, 1));
add(new Res_PLCADDRESS("倒菜位", "M12.7", 0, 1));
add(new Res_PLCADDRESS("抽料位", "M11.7", 0, 1));
add(new Res_PLCADDRESS("清洗位", "M13.0", 0, 1));
add(new Res_PLCADDRESS("炒菜位1", "M12.0", 0, 1));
add(new Res_PLCADDRESS("炒菜位2", "M12.1", 0, 1));
add(new Res_PLCADDRESS("炒菜位3", "M12.2", 0, 1));

add(new Res_PLCADDRESS("出餐启动", "M11.5", 0, 1));
add(new Res_PLCADDRESS("炒锅清洗", "M11.6", 0, 1));

//液体料模型
add(new Res_PLCADDRESS("料仓校准", "-------------", 0, 0));
add(new Res_PLCADDRESS("校准时间", "VW112", 1, 1));
add(new Res_PLCADDRESS("料仓1校准开关", "M12.3", 0, 1));
add(new Res_PLCADDRESS("料仓1校准值", "VW114", 1, 1));
add(new Res_PLCADDRESS("料仓2校准开关", "M12.4", 0, 1));
add(new Res_PLCADDRESS("料仓2校准值", "VW116", 1, 1));
add(new Res_PLCADDRESS("料仓3校准开关", "M12.5", 0, 1));
add(new Res_PLCADDRESS("料仓3校准值", "VW118", 1, 1));
add(new Res_PLCADDRESS("料仓4校准开关", "M13.5", 0, 1));
add(new Res_PLCADDRESS("料仓4校准值", "VW120", 1, 1));
add(new Res_PLCADDRESS("开始校正", "M12.6", 0, 1));

add(new Res_PLCADDRESS("料仓自动", "-------------", 0, 0));
add(new Res_PLCADDRESS("料仓1需求值", "VW106", 1, 1));
add(new Res_PLCADDRESS("料仓1下料", "M11.1", 0, 1));
add(new Res_PLCADDRESS("料仓2需求值", "VW108", 1, 1));
add(new Res_PLCADDRESS("料仓2下料", "M11.2", 0, 1));
add(new Res_PLCADDRESS("料仓3需求值", "VW110", 1, 1));
add(new Res_PLCADDRESS("料仓3下料", "M11.3", 0, 1));
add(new Res_PLCADDRESS("料仓4需求值", "VW122", 1, 1));
add(new Res_PLCADDRESS("料仓4下料", "M13.4", 0, 1));

add(new Res_PLCADDRESS("料仓手动", "-------------", 0, 0));
add(new Res_PLCADDRESS("料仓1手动开关", "M13.1", 1, 1));
add(new Res_PLCADDRESS("料仓2手动开关", "M13.2", 1, 1));
add(new Res_PLCADDRESS("料仓3手动开关", "M13.3", 1, 1));
add(new Res_PLCADDRESS("料仓4手动开关", "M10.7", 1, 1));
//上下限
add(new Res_PLCADDRESS("位置上下限", "-------------", 0, 0));
add(new Res_PLCADDRESS("原点位置下限", "VD150", 1, 1));
add(new Res_PLCADDRESS("原点位置上限", "VD154", 1, 1));
add(new Res_PLCADDRESS("洗锅位置下限", "VD158", 1, 1));
add(new Res_PLCADDRESS("洗锅位置上限", "VD162", 1, 1));
add(new Res_PLCADDRESS("倒菜位置下限", "VD166", 1, 1));
add(new Res_PLCADDRESS("倒菜位置上限", "VD170", 1, 1));
add(new Res_PLCADDRESS("抽调料位置下限", "VD174", 1, 1));
add(new Res_PLCADDRESS("抽调料位置上限", "VD178", 1, 1));
add(new Res_PLCADDRESS("1#炒制位置下限", "VD182", 1, 1));
add(new Res_PLCADDRESS("1#炒制位置上限", "VD186", 1, 1));
add(new Res_PLCADDRESS("2#炒制位置下限", "VD190", 1, 1));
add(new Res_PLCADDRESS("2#炒制位置上限", "VD194", 1, 1));
add(new Res_PLCADDRESS("3#炒制位置下限", "VD198", 1, 1));
add(new Res_PLCADDRESS("3#炒制位置上限", "VD202", 1, 1));
add(new Res_PLCADDRESS("炒锅工作范围下限", "VD206", 1, 1));
add(new Res_PLCADDRESS("炒锅工作范围上限", "VD210", 1, 1));

//反馈信号
add(new Res_PLCADDRESS("反馈信号", "-------------", 0, 0));
add(new Res_PLCADDRESS("初始化完成", "M40.0", 1, 0));
add(new Res_PLCADDRESS("设备急停", "M40.1", 1, 0));
add(new Res_PLCADDRESS("原点位反馈", "M40.2", 1, 0));
add(new Res_PLCADDRESS("抽料位反馈", "M40.3", 1, 0));
add(new Res_PLCADDRESS("炒菜位1反馈", "M40.4", 1, 0));
add(new Res_PLCADDRESS("炒菜位2反馈", "M40.5", 1, 0));
add(new Res_PLCADDRESS("炒菜位3反馈", "M40.6", 1, 0));
add(new Res_PLCADDRESS("倒菜位反馈", "M40.7", 1, 0));
add(new Res_PLCADDRESS("投料位反馈", "M41.0", 1, 0));
add(new Res_PLCADDRESS("清洗位反馈", "M41.1", 1, 0));
add(new Res_PLCADDRESS("料仓1下料完成", "M41.2", 1, 0));
add(new Res_PLCADDRESS("料仓2下料完成", "M41.3", 1, 0));
add(new Res_PLCADDRESS("料仓3下料完成", "M41.4", 1, 0));
add(new Res_PLCADDRESS("料仓4下料完成", "M42.0", 1, 0));
add(new Res_PLCADDRESS("炒锅清洗反馈", "M41.5", 1, 0));
add(new Res_PLCADDRESS("出餐启动反馈", "M41.6", 1, 0));
add(new Res_PLCADDRESS("炒锅倒菜减速位", "M41.7", 1, 0));
add(new Res_PLCADDRESS("心跳位", "VW1000", 0, 1));


//检测信号
add(new Res_PLCADDRESS("监测信号", "-------------", 0, 0));
add(new Res_PLCADDRESS("当前锅底温度", "VD300", 1, 0));
add(new Res_PLCADDRESS("炒锅搅拌转速", "VD304", 1, 0));
add(new Res_PLCADDRESS("当前加热档位", "VD308", 1, 0));
add(new Res_PLCADDRESS("炒锅当前电压", "VD312", 1, 0));
add(new Res_PLCADDRESS("炒锅当前电流", "VD316", 1, 0));
add(new Res_PLCADDRESS("炒锅当前功率", "VD320", 1, 0));
add(new Res_PLCADDRESS("搅拌频率", "VW324", 1, 0));
add(new Res_PLCADDRESS("搅拌电机电流", "VW326", 1, 0));
add(new Res_PLCADDRESS("搅拌电机电压", "VW328", 1, 0));
add(new Res_PLCADDRESS("搅拌变频器温度", "VW330", 1, 0));
add(new Res_PLCADDRESS("翻转频率", "VW332", 1, 0));
add(new Res_PLCADDRESS("翻转电机电流", "VW334", 1, 0));
add(new Res_PLCADDRESS("翻转电机电压", "VW336", 1, 0));
add(new Res_PLCADDRESS("翻转变频器温度", "VW338", 1, 0));
add(new Res_PLCADDRESS("编码器当前位值", "VD340", 1, 0));

//状态上报
add(new Res_PLCADDRESS("状态上报", "-------------", 0, 0));
add(new Res_PLCADDRESS("搅拌电机", "VW350", 1, 0));
add(new Res_PLCADDRESS("翻转电机", "VW352", 1, 0));
add(new Res_PLCADDRESS("炒锅", "VW354", 1, 0));
//PLC输入
add(new Res_PLCADDRESS("监控信号一", "-------------", 0, 0));
add(new Res_PLCADDRESS("监控_急停按钮", "V20.0", 1, 0));
add(new Res_PLCADDRESS("监控_搅拌上限", "V20.1", 1, 0));
add(new Res_PLCADDRESS("监控_搅拌下限", "V20.2", 1, 0));
add(new Res_PLCADDRESS("监控_锅后限位", "V20.3", 1, 0));
add(new Res_PLCADDRESS("监控_搅拌原点", "V20.4", 1, 0));
add(new Res_PLCADDRESS("监控_油泵故障", "V20.5", 1, 0));
add(new Res_PLCADDRESS("监控_变频器故障", "V20.6", 1, 0));
add(new Res_PLCADDRESS("监控_点火正常", "V20.7", 1, 0));
add(new Res_PLCADDRESS("监控_点火异常", "V21.0", 1, 0));
add(new Res_PLCADDRESS("监控_备用输入1", "V21.1", 1, 0));
add(new Res_PLCADDRESS("监控_备用输入2", "V21.2", 1, 0));
add(new Res_PLCADDRESS("监控_备用输入3", "V21.3", 1, 0));
add(new Res_PLCADDRESS("监控_备用输入4", "V21.4", 1, 0));
add(new Res_PLCADDRESS("监控_备用输入5", "V21.5", 1, 0));
add(new Res_PLCADDRESS("监控_备用输入6", "V21.6", 1, 0));
add(new Res_PLCADDRESS("监控_备用输入7", "V21.7", 1, 0));

//监控信号二
add(new Res_PLCADDRESS("监控信号二", "-------------", 0, 0));
add(new Res_PLCADDRESS("监控-油泵", "V50.0", 1, 0));
add(new Res_PLCADDRESS("监控-搅拌", "V50.1", 1, 0));
add(new Res_PLCADDRESS("监控-强火", "V50.2", 1, 0));
add(new Res_PLCADDRESS("监控-小火", "V50.3", 1, 0));
add(new Res_PLCADDRESS("监控-中火", "V50.4", 1, 0));
add(new Res_PLCADDRESS("监控-大火", "V50.5", 1, 0));
add(new Res_PLCADDRESS("监控-点火复位", "V50.6", 1, 0));
add(new Res_PLCADDRESS("监控-点火自动", "V50.7", 1, 0));
add(new Res_PLCADDRESS("监控-点火手动", "V51.0", 1, 0));
add(new Res_PLCADDRESS("监控-报警", "V51.1", 1, 0));
add(new Res_PLCADDRESS("监控-搅拌上升", "V51.2", 1, 0));
add(new Res_PLCADDRESS("监控-搅拌下降", "V51.3", 1, 0));
add(new Res_PLCADDRESS("监控-锅前", "V51.4", 1, 0));
add(new Res_PLCADDRESS("监控-锅后", "V51.5", 1, 0));
add(new Res_PLCADDRESS("监控-备用泵", "V51.6", 1, 0));
add(new Res_PLCADDRESS("监控-备用气缸", "V51.7", 1, 0));

//故障类
add(new Res_PLCADDRESS("故障信号", "-------------", 0, 0));
add(new Res_PLCADDRESS("急停按下!", "V101.0", 1, 0));
add(new Res_PLCADDRESS("油泵故障!", "V101.1", 1, 0));
add(new Res_PLCADDRESS("搅拌故障!", "V101.2", 1, 0));
add(new Res_PLCADDRESS("点火异常!", "V101.3", 1, 0));
add(new Res_PLCADDRESS("高温报警!", "V101.4", 1, 0));
add(new Res_PLCADDRESS("备用故障1", "V101.5", 1, 0));
add(new Res_PLCADDRESS("备用故障2", "V101.5", 1, 0));
add(new Res_PLCADDRESS("备用故障3", "V101.5", 1, 0));

//控制模型
add(new Res_PLCADDRESS("主运行画面", "-------------", 0, 0));
add(new Res_PLCADDRESS("系统启停开关", "V220.0", 0, 1));
add(new Res_PLCADDRESS("超温停气开关", "V220.1", 0, 1));
add(new Res_PLCADDRESS("点火启动开关", "V220.2", 0, 1));
add(new Res_PLCADDRESS("点火复位开关", "V220.3", 0, 1));
add(new Res_PLCADDRESS("点火手自动切换开关", "V220.4", 0, 1));
add(new Res_PLCADDRESS("小火开关(一圈)", "V220.5", 0, 1));
add(new Res_PLCADDRESS("中火开关(二圈)", "V220.6", 0, 1));
add(new Res_PLCADDRESS("大火开关(三圈)", "V220.7", 0, 1));
add(new Res_PLCADDRESS("强火开关(四圈)", "V221.0", 0, 1));
add(new Res_PLCADDRESS("小火比例阀开度", "VD1500", 0, 1));
add(new Res_PLCADDRESS("中火比例阀开度", "VD1504", 0, 1));
add(new Res_PLCADDRESS("大火比例阀开度", "VD1508", 0, 1));
add(new Res_PLCADDRESS("强火比例阀开度", "VD1512", 0, 1));
add(new Res_PLCADDRESS("搅拌点动开关", "V221.1", 0, 1));
add(new Res_PLCADDRESS("搅拌启动开关", "V221.2", 0, 1));
add(new Res_PLCADDRESS("搅拌停止开关", "V221.3", 0, 1));
add(new Res_PLCADDRESS("搅拌速度", "VD1200", 0, 1));
add(new Res_PLCADDRESS("炒锅当前温度", "VD2250", 0, 1));
add(new Res_PLCADDRESS("炒锅温度修正", "VD1204", 0, 1));
add(new Res_PLCADDRESS("炒锅温度上限设置", "VD1828", 0, 1));


//升降画面
add(new Res_PLCADDRESS("升降画面", "-------------", 0, 0));
add(new Res_PLCADDRESS("搅拌上升", "V221.4", 1, 1));
add(new Res_PLCADDRESS("搅拌下降", "V221.5", 1, 1));
add(new Res_PLCADDRESS("锅口向前", "V221.6", 1, 1));
add(new Res_PLCADDRESS("锅口向后", "V221.7", 1, 1));

//称重画面
add(new Res_PLCADDRESS("称重画面", "-------------", 0, 0));
add(new Res_PLCADDRESS("抽油开关", "V222.0", 1, 1));
add(new Res_PLCADDRESS("备用气缸开关", "V222.1", 1, 1));
add(new Res_PLCADDRESS("炒锅当前重量", "VD500", 1, 0));
add(new Res_PLCADDRESS("设定重量", "VD510", 0, 1));
add(new Res_PLCADDRESS("设定提前量", "VD514", 0, 1));

//称重画面
add(new Res_PLCADDRESS("心跳", "-------------", 0, 0));
add(new Res_PLCADDRESS("上位机-PLC", "V280.0", 1, 1));
add(new Res_PLCADDRESS("PLC-上位机", "V280.1", 1, 1));
}};
/**
* 大炒工序模型
*/
public List<ProcessT> Process_燃气大炒 = new ArrayList<ProcessT>() {{
add(new ProcessT("搅拌", Arrays.asList("搅拌速度", "等待(秒)")));
add(new ProcessT("打火", Arrays.asList("打火动作", "等待(秒)")));
add(new ProcessT("位置", Arrays.asList("位置动作", "等待(秒)")));
add(new ProcessT("约束条件", Arrays.asList("一环功率", "二环功率", "三环功率", "四环功率", "温度设定", "锅内重量", "等待(秒)")));
add(new ProcessT("主料", Arrays.asList("主料名称", "一环功率", "二环功率", "三环功率", "四环功率", "温度设定", "锅内重量", "烹饪(秒)")));
add(new ProcessT("物料", Arrays.asList()));
add(new ProcessT("延迟", Arrays.asList("等待(秒)")));
add(new ProcessT("出菜", Arrays.asList("等待(秒)")));
add(new ProcessT("清洗", Arrays.asList("等待(秒)")));
add(new ProcessT("主料", Arrays.asList("主料名称")));
add(new ProcessT("搅拌", Arrays.asList("搅拌速度","搅拌状态")));
add(new ProcessT("火力设置", Arrays.asList("一环功率", "二环功率", "三环功率", "四环功率")));
add(new ProcessT("约束条件", Arrays.asList("温度设定", "锅内重量", "等待(秒)")));
}};

/**
@@ -397,8 +346,8 @@ public class ConfigName {
*/
public String GetProcessTypeVal(String item) {
String data = "";
if (item.equals("打火动作")) {
data = "自动打火、手动打火";
if (item.equals("搅拌状态")) {
data = "启动、停止";
} else if (item.equals("位置动作")) {
data = "炒菜位、倒菜位、清洗位";
}
@@ -468,40 +417,7 @@ public class ConfigName {
add(new StatusMode("搅拌电机变频器通讯异常", false, R.mipmap.bpq, R.mipmap.bpq, 6));
add(new StatusMode("翻转电机变频器通讯异常", false, R.mipmap.bpq, R.mipmap.bpq, 7));
}};
/**
* 电机状态上报信息
*/
public ConcurrentHashMap<Integer, String> statusModes_电机 = new ConcurrentHashMap<Integer, String>() {{
put(0, "无故障");
put(1, "过电流");
put(2, "过电压");
put(3, "IGBT过热");
put(4, "");
put(5, "变频器过负载");
put(6, "电机过负载");
put(7, "过转矩");
put(8, "外部异常");
put(9, "加速中过电流");
put(10, "减速中过电流");
put(11, "恒速中过电流");
put(12, "");
put(13, "电压不足");
put(14, "输入电压缺相");
put(15, "");
put(16, "不适用自动加减速设定");
put(17, "软件参数密码保护");
put(18, "CPU写入异常");
put(19, "CPU读取异常");
put(20, "端子保护线路异常");
put(21, "0V保护线路异常");
put(22, "");
put(23, "");
put(24, "U相硬件异常");
put(25, "V相硬件异常");
put(26, "W相硬件异常");
put(27, "DC,bus 硬件异常");

}};

/**
* Bottom 按钮


+ 0
- 44
app/src/main/java/com/bonait/bnframework/common/modbus/ModbusTcpHelper.java View File

@@ -1,44 +0,0 @@
package com.bonait.bnframework.common.modbus;

import com.licheedev.modbus4android.ModbusWorker;
import com.serotonin.modbus4j.ModbusMaster;


public class ModbusTcpHelper extends ModbusWorker {
private static volatile ModbusTcpHelper instance = null;

public static ModbusTcpHelper get() {
ModbusTcpHelper manager = instance;
if (manager == null) {
synchronized (ModbusTcpHelper.class) {
manager = instance;
if (manager == null) {
manager = new ModbusTcpHelper();
instance = manager;
}
}
}
return manager;
}

private ModbusTcpHelper() {
}

/**
* 释放整个ModbusManager,单例会被置null
*/
public synchronized void release() {
super.release();
instance = null;
}

/**
* 获取
* @return
*/
public synchronized ModbusMaster getModbusMaster()
{
return super.getModbusMaster();
}

}

+ 0
- 718
app/src/main/java/com/bonait/bnframework/common/modbus/ModbusTcpServer.java View File

@@ -1,718 +0,0 @@
package com.bonait.bnframework.common.modbus;


import android.os.Looper;
import android.util.Log;

import com.bonait.bnframework.MainApplication;
import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.helper.DataFormat;
import com.bonait.bnframework.common.helper.I.IReadCallBack;
import com.bonait.bnframework.common.helper.I.IWriteCallBack;
import com.bonait.bnframework.common.helper.MessageLog;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.licheedev.modbus4android.ModbusCallback;
import com.licheedev.modbus4android.ModbusParam;
import com.licheedev.modbus4android.ModbusRespException;
import com.licheedev.modbus4android.param.TcpParam;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.msg.ReadCoilsResponse;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;


public class ModbusTcpServer {
private static volatile ModbusTcpServer instance = null;

public static ModbusTcpServer get() {
ModbusTcpServer manager = instance;
if (manager == null) {
synchronized (ModbusTcpServer.class) {
manager = instance;
if (manager == null) {
manager = new ModbusTcpServer();
instance = manager;
}
}
}
return manager;
}

private ModbusTcpServer() {
}

static ModbusParam param;

private int GetAddress(String address) {
if (address == null) return -1;
if (address.length() > 0) {
address = address.trim();
if (address.toUpperCase().contains("M") && address.length() >= 4) {
String[] res = address.substring(1).split("[.]");
if (res != null && res.length == 2) {
try {
int firstAdd = Integer.parseInt(res[0]);
int endAdd = Integer.parseInt(res[1]);
if (endAdd >= 0 && endAdd <= 7) {
return (firstAdd * 8) + 320 + endAdd;
}
} catch (NumberFormatException e) {
return -1;
}
}
} else if (address.toUpperCase().contains("I") && address.length() >= 4) {
String[] res = address.substring(1).split("[.]");
if (res != null && res.length == 2) {
try {
int firstAdd = Integer.parseInt(res[0]);
int endAdd = Integer.parseInt(res[1]);
if (endAdd >= 0 && endAdd <= 7) {
return (firstAdd * 8) + endAdd;
}
} catch (NumberFormatException e) {
return -1;
}
}
} else if ((address.toUpperCase().contains("VW") || address.toUpperCase().contains("VD")) && address.length() >= 3) {
String res = address.substring(2);
if (res != null) {
try {
int tempAdd = Integer.parseInt(res);
return (tempAdd / 2) + 100;
} catch (NumberFormatException e) {
return -1;
}
}
} else {
try {
return Integer.parseInt(address);
} catch (NumberFormatException e) {
return -1;
}
}
}
return -1;
}

/**
* 获取布尔位地址信息
* 列:M2.5 = getBitSingleAdd("M",2,5);
*
* @param Prefix 地址标头
* @param startAdd 起始地址编号
* @param num 要获取的第几位数量
* @return
*/
public String getBitSingleAdd(String Prefix, int startAdd, int num) {
if (num > 0) {
int FirstAdd = num / 8;
int EndAdd = num % 8;
if (EndAdd == 0) {
FirstAdd--;
EndAdd = 7;
} else {
EndAdd--;
}
return Prefix + FirstAdd + startAdd + "." + EndAdd;
}
return "";
}

/**
* Ping PLC地址是否通畅
* @param address
* @param pingTimes ping的次数
* @param timeOut 超时时间 10
* @return
*/
public static boolean ping2(String address, int pingTimes, int timeOut) {
Process process = null;
try {
process = Runtime.getRuntime().exec( "ping " + "-c " + pingTimes + " -w " + timeOut+ " "+address);
InputStreamReader r = new InputStreamReader(process.getInputStream());

LineNumberReader returnData = new LineNumberReader(r);

String returnMsg="";

String line = "";

while ((line = returnData.readLine()) != null) {

System.out.println(line);

returnMsg += line;

}

if(returnMsg.indexOf("100% packet loss")!=-1){
System.out.println("与 " +address +" 连接不畅通.");
//ToastUtils.info("与 " +address +" 连接不畅通.");
return false;
} else{
System.out.println("与 " +address +" 连接畅通.");
//ToastUtils.info("与 " +address +" 连接不畅通.");
return true;
}
} catch (IOException e) {
// e.printStackTrace();
}
return false;

}

/**
* 连接PLC
*/
public static void ConnectPLC()
{
String host=ConfigName.getInstance().Address;
int port=ConfigName.getInstance().Post;
param = TcpParam.create(host, port)
.setTimeout(1000)
.setRetries(0)
.setEncapsulated(false)
.setKeepAlive(true);
ModbusTcpHelper.get().init(param, new ModbusCallback<ModbusMaster>() {
@Override
public void onSuccess(ModbusMaster modbusMaster) {
ToastUtils.info("设备 " + ConfigName.getInstance().Address + " 连接成功");
MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " 连接成功");
ConfigName.getInstance().PlcIsConnect = true;
ConfigData.getInstance().PLC_Init();
Log.e("设备PLC", "设备PLC: 连接成功");
}

@Override
public void onFailure(Throwable tr) {
ConfigName.getInstance().PlcIsConnect = false;
ToastUtils.info("设备 " + ConfigName.getInstance().Address + " 连接失败:" + tr.getMessage());
MessageLog.ShowError("PLC设备 " + ConfigName.getInstance().Address + " 连接失败:" + tr.getMessage());
Log.e("设备PLC", "设备PLC: 连接断开");
}

@Override
public void onFinally() {

}
});
}


private Float BytesToFloat(byte[] buffers, DataFormat df) {
if (buffers.length == 4) {
byte[] bytes = new byte[4];
if (df == DataFormat.ABCD) {
bytes[0] = buffers[3];
bytes[1] = buffers[2];
bytes[2] = buffers[1];
bytes[3] = buffers[0];
} else if (df == DataFormat.CDAB) {
bytes[0] = buffers[1];
bytes[1] = buffers[0];
bytes[2] = buffers[3];
bytes[3] = buffers[2];
} else if (df == DataFormat.BADC) {
bytes[0] = buffers[2];
bytes[1] = buffers[3];
bytes[2] = buffers[0];
bytes[3] = buffers[1];
} else if (df == DataFormat.DCBA) {
bytes[0] = buffers[0];
bytes[1] = buffers[1];
bytes[2] = buffers[2];
bytes[3] = buffers[3];
}
return ByteBuffer.wrap(bytes).getFloat();
}
return 0.0f;
}

private Integer BytesToInt(byte[] buffers, DataFormat df) {
if (buffers.length == 4) {
byte[] bytes = new byte[4];
if (df == DataFormat.ABCD) {
bytes[0] = buffers[3];
bytes[1] = buffers[2];
bytes[2] = buffers[1];
bytes[3] = buffers[0];
} else if (df == DataFormat.CDAB) {
bytes[0] = buffers[1];
bytes[1] = buffers[0];
bytes[2] = buffers[3];
bytes[3] = buffers[2];
} else if (df == DataFormat.BADC) {
bytes[0] = buffers[2];
bytes[1] = buffers[3];
bytes[2] = buffers[0];
bytes[3] = buffers[1];
} else if (df == DataFormat.DCBA) {
bytes[0] = buffers[0];
bytes[1] = buffers[1];
bytes[2] = buffers[2];
bytes[3] = buffers[3];
}
return ByteBuffer.wrap(bytes).getInt();
}
return 0;
}

private byte[] IntToByte(int number) {
int temp = number;
byte[] b = new byte[4];
for (int i = 0; i < b.length; i++) {
b[i] = new Integer(temp & 0xff).byteValue();// 将最低位保存在最低位
temp = temp >> 8; // 向右移8位
}
return b;
}

private short[] IntToShorts(int value) {
short[] res = new short[2];
int temp = value;
byte[] b = new byte[4];
for (int i = 0; i < b.length; i++) {
b[i] = new Integer(temp & 0xff).byteValue();// 将最低位保存在最低位
temp = temp >> 8; // 向右移8位
}
for (int i = 0; i < res.length; i++) {
short s0 = (short) (b[i * 2] & 0xff);// 最低位
short s1 = (short) (b[i * 2 + 1] & 0xff);
s1 <<= 8;
res[i] = (short) (s0 | s1);
}
return res;
}

public static String GetString(short[] src, int start, int len) throws UnsupportedEncodingException {
short[] temp = new short[len];
for (int i = 0; i < len; i++) {
temp[i] = src[i + start];
}
byte[] bytesTemp = shorts2Bytes(temp);
for (int i = 0; i < bytesTemp.length; i++) {
byte b = bytesTemp[i];
}
String str = new String(bytesTemp, "UTF-8");
return str;
}

public static byte[] shorts2Bytes(short[] data) {
byte[] byteValue = new byte[data.length * 2];
for (int i = 0; i < data.length; i++) {
byteValue[i * 2] = (byte) (data[i] & 0xff);
byteValue[i * 2 + 1] = (byte) ((data[i] & 0xff00) >> 8);
}
return byteValue;
}

/***
*读取实时状态
* @param Address the address
* @param length 读取的长度 3
* @param callback 读取成功的回调
*/
public void ReadStatus(String Address, int length, IReadCallBack<byte[]> callback) {
int add = GetAddress(Address);
if (add < 0) return;
try {
ReadHoldingRegistersResponse res = ModbusTcpHelper.get().syncReadHoldingRegisters(1, add, length);
byte[] data = res.getData();
byte[] tempData = new byte[6];
tempData[0] = data[1];
tempData[1] = data[0];
if (callback != null) callback.onSuccess(tempData);
} catch (InterruptedException e) {
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ExecutionException e) {
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusTransportException e) {
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusInitException e) {
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusRespException e) {
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
}
}

/***
*读取扫码数据
* @param Address the address
* @param length 读取的长度
* @param callback 读取成功的回调
*/
public void ReadString(String Address, int length, IReadCallBack<String> callback) {
int add = GetAddress(Address);
if (add < 0) return;
try {
ReadHoldingRegistersResponse res = ModbusTcpHelper.get().syncReadHoldingRegisters(1, add, length);
byte[] data = res.getData();
byte[] data1 = Arrays.copyOfRange(data, 0, 18);
//36 GUID 18 Number
String id = "";
try {
byte[] tempdata = new byte[18];
for (int i = 0; i < data1.length; i++) {
if (i % 2 == 0) {

tempdata[i + 1] = data1[i];
} else {
tempdata[i - 1] = data1[i];
}
}
id = new String(tempdata, "UTF-8").trim();
} catch (UnsupportedEncodingException ex) {
}
if (callback != null) callback.onSuccess(id);
} catch (InterruptedException e) {
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ExecutionException e) {
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusTransportException e) {
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusInitException e) {
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusRespException e) {
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
}
}

public void WriteString(String Address, int length, IWriteCallBack callback) {
int add = GetAddress(Address);
if (add < 0) return;
short[] send = new short[length];
for (short item : send) {
item = 0;
}
try {
ModbusTcpHelper.get().syncWriteRegisters(1, add, send);
if (callback != null)
callback.onSuccess();
} catch (InterruptedException e) {
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ExecutionException e) {
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ModbusTransportException e) {
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ModbusInitException e) {
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ModbusRespException e) {
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
}
}

public void ReadShort(String Address, int length, IReadCallBack<short[]> callback) {
int add = GetAddress(Address);
if (add < 0) return;
try {
ReadHoldingRegistersResponse res = ModbusTcpHelper.get().syncReadHoldingRegisters(1, add, length);
short[] data = res.getShortData();
if (data.length == length) {
if (callback != null) callback.onSuccess(data);
}
} catch (InterruptedException e) {
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ExecutionException e) {
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusTransportException e) {
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusInitException e) {
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusRespException e) {
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
}
}

public void ReadBool(String Address, int length, IReadCallBack<boolean[]> callback) {
int add = GetAddress(Address);
if (add < 0) return;
try {
ReadCoilsResponse res = ModbusTcpHelper.get().syncReadCoil(1, add, length);
boolean[] data = res.getBooleanData();
boolean[] result = Arrays.copyOfRange(data, 0, length);
if (result.length == length) {
if (callback != null) callback.onSuccess(result);
}
} catch (InterruptedException e) {
MessageLog.ShowError("ReadBool onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ExecutionException e) {
MessageLog.ShowError("ReadBool onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusTransportException e) {
MessageLog.ShowError("ReadBool onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusInitException e) {
MessageLog.ShowError("ReadBool onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusRespException e) {
MessageLog.ShowError("ReadBool onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
}
}

public void ReadFloat(String Address, int length, IReadCallBack<float[]> callback) {
int add = GetAddress(Address);
if (add < 0) return;
try {
ReadHoldingRegistersResponse res = ModbusTcpHelper.get().syncReadHoldingRegisters(1, add, length*2);
byte[] data = res.getData();
float[] tempValues = new float[length];
for (int i = 0; i < length; i++) {
byte[] tempData = new byte[4];
for (int m = 0; m < 4; m++) {
tempData[m] = data[i * 4 + m];
}
tempValues[i] = BytesToFloat(tempData, DataFormat.BADC);
}
if (tempValues.length == length) {
if (callback != null) callback.onSuccess(tempValues);
}
} catch (InterruptedException e) {
MessageLog.ShowError("ReadFloat onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ExecutionException e) {
MessageLog.ShowError("ReadFloat onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusTransportException e) {
MessageLog.ShowError("ReadFloat onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusInitException e) {
MessageLog.ShowError("ReadFloat onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusRespException e) {
MessageLog.ShowError("ReadFloat onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
}
}

public void ReadInt(String Address, int length, IReadCallBack<int[]> callback) {
int add = GetAddress(Address);
if (add < 0) return;
try {
ReadHoldingRegistersResponse res = ModbusTcpHelper.get().syncReadHoldingRegisters(1, add, length * 2);
byte[] data = res.getData();
int[] tempValues = new int[length];
if(data.length>=4)
{
for (int i = 0; i < length; i++) {
byte[] tempData = new byte[4];
for (int m = 0; m < 4; m++) {
tempData[m] = data[i * 4 + m];
}
// Integer a1 = tempValues[i] = BytesToInt(tempData, DataFormat.ABCD);
// Integer a2 = tempValues[i] = BytesToInt(tempData, DataFormat.BADC);
// Integer a3 = tempValues[i] = BytesToInt(tempData, DataFormat.CDAB);
// Integer a4 = tempValues[i] = BytesToInt(tempData, DataFormat.DCBA);
tempValues[i] = BytesToInt(tempData, DataFormat.BADC);
}
}else
{
MessageLog.ShowError("ReadInt onFailure,Address=" );

}
if (callback != null) callback.onSuccess(tempValues);
} catch (InterruptedException e) {
MessageLog.ShowError("ReadInt onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ExecutionException e) {
MessageLog.ShowError("ReadInt onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusTransportException e) {
MessageLog.ShowError("ReadInt onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusInitException e) {
MessageLog.ShowError("ReadInt onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
} catch (ModbusRespException e) {
MessageLog.ShowError("ReadInt onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString());
}
}

public void WriteShort(String Address, short Value, IWriteCallBack callback) {
int add = GetAddress(Address);
if (add < 0) return;
short[] send = new short[1];
send[0] = Value;
try {
ModbusTcpHelper.get().syncWriteRegisters(1, add, send);
if (callback != null)
callback.onSuccess();
} catch (InterruptedException e) {
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ExecutionException e) {
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ModbusTransportException e) {
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ModbusInitException e) {
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ModbusRespException e) {
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
}
}

public void WriteBool(String Address, boolean Value, IWriteCallBack callback) {
int add = GetAddress(Address);
if (add < 0) return;
try {
ModbusTcpHelper.get().syncWriteCoil(1, add, Value);
if (callback != null)
callback.onSuccess();
} catch (InterruptedException e) {
MessageLog.ShowError("WriteBool onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ExecutionException e) {
MessageLog.ShowError("WriteBool onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ModbusTransportException e) {
MessageLog.ShowError("WriteBool onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ModbusInitException e) {
MessageLog.ShowError("WriteBool onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ModbusRespException e) {
MessageLog.ShowError("WriteBool onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
}
}

public void WriteFloat(String Address, float Value, IWriteCallBack callback) {
int add = GetAddress(Address);
if (add < 0) return;
int intBits = Float.floatToRawIntBits(Value);

short[] send = IntToShorts(intBits);
// short[] send = new short[]{(short) ((intBits >> 16) & 0xffff), (short) (intBits & 0xffff)};
try {
ModbusTcpHelper.get().syncWriteRegisters(1, add, send);

if (callback != null) callback.onSuccess();
} catch (InterruptedException e) {
MessageLog.ShowError("WriteFloat onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ExecutionException e) {
MessageLog.ShowError("WriteFloat onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ModbusTransportException e) {
MessageLog.ShowError("WriteFloat onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ModbusInitException e) {
MessageLog.ShowError("WriteFloat onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ModbusRespException e) {
MessageLog.ShowError("WriteFloat onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
}
}

public void WriteInt(String Address, int Value, IWriteCallBack callback) {
int add = GetAddress(Address);
if (add < 0) return;
short[] send = IntToShorts(Value);
try {
ModbusTcpHelper.get().syncWriteRegisters(1, add, send);
if (callback != null) callback.onSuccess();
} catch (InterruptedException e) {
MessageLog.ShowError("WriteInt onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ExecutionException e) {
MessageLog.ShowError("WriteInt onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ModbusTransportException e) {
MessageLog.ShowError("WriteInt onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ModbusInitException e) {
MessageLog.ShowError("WriteInt onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
} catch (ModbusRespException e) {
MessageLog.ShowError("WriteInt onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
if (callback != null) callback.onFailure(e.toString());
}
}

public void WriteShort(String Address, short Value) {
int add = GetAddress(Address);
if (add < 0) return;
short[] send = new short[1];
send[0] = Value;
try {
ModbusTcpHelper.get().syncWriteRegisters(1, add, send);
} catch (InterruptedException e) {
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
} catch (ExecutionException e) {
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
} catch (ModbusTransportException e) {
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
} catch (ModbusInitException e) {
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
} catch (ModbusRespException e) {
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
}
}

public void WriteBool(String Address, boolean Value) {
int add = GetAddress(Address);
if (add < 0) return;

try {
ModbusTcpHelper.get().syncWriteCoil(1, add, Value);
} catch (InterruptedException e) {
MessageLog.ShowError("WriteBool onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
} catch (ExecutionException e) {
MessageLog.ShowError("WriteBool onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
} catch (ModbusTransportException e) {
MessageLog.ShowError("WriteBool onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
} catch (ModbusInitException e) {
MessageLog.ShowError("WriteBool onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
} catch (ModbusRespException e) {
MessageLog.ShowError("WriteBool onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
}
}

public void WriteFloat(String Address, float Value) {
int add = GetAddress(Address);
if (add < 0) return;
int intBits = Float.floatToRawIntBits(Value);
short[] send = new short[]{(short) ((intBits >> 16) & 0xffff), (short) (intBits & 0xffff)};
try {
ModbusTcpHelper.get().syncWriteRegisters(1, add, send);
} catch (InterruptedException e) {
MessageLog.ShowError("WriteFloat onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
} catch (ExecutionException e) {
MessageLog.ShowError("WriteFloat onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
} catch (ModbusTransportException e) {
MessageLog.ShowError("WriteFloat onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
} catch (ModbusInitException e) {
MessageLog.ShowError("WriteFloat onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
} catch (ModbusRespException e) {
MessageLog.ShowError("WriteFloat onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
}
}

public void WriteInt(String Address, int Value) {
int add = GetAddress(Address);
if (add < 0) return;
short[] send = IntToShorts(Value);
try {
ModbusTcpHelper.get().syncWriteRegisters(1, add, send);
} catch (InterruptedException e) {
MessageLog.ShowError("WriteInt onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
} catch (ExecutionException e) {
MessageLog.ShowError("WriteInt onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
} catch (ModbusTransportException e) {
MessageLog.ShowError("WriteInt onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
} catch (ModbusInitException e) {
MessageLog.ShowError("WriteInt onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
} catch (ModbusRespException e) {
MessageLog.ShowError("WriteInt onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString());
}
}

}

+ 0
- 15
app/src/main/java/com/bonait/bnframework/common/modbus/S7/IS7ConnHelper.java View File

@@ -1,15 +0,0 @@
package com.bonait.bnframework.common.modbus.S7;

import com.bonait.bnframework.common.modbus.S7.mode.MyGunData;

import java.io.IOException;

public interface IS7ConnHelper {
void initConnect() throws IOException;
Object readPlcData(Integer dbNum, Class<?> clazz, int offSet);
MyGunData readTheDbData(Integer dbNum, MyGunData clazz, int offSet);
void writePlcData(Integer dbNum, MyGunData clazz, int offSet);

//DB,DB号,偏移量,Byte数组
void writePlcByte(byte[] bytes);
}

+ 0
- 136
app/src/main/java/com/bonait/bnframework/common/modbus/S7/S7ConnHelper.java View File

@@ -1,136 +0,0 @@
package com.bonait.bnframework.common.modbus.S7;

import android.util.Log;

import com.bonait.bnframework.common.modbus.S7.mode.MyGunData;
import com.bonait.bnframework.common.modbus.S7.mode.MyS7Entity;
import com.github.s7connector.api.DaveArea;
import com.github.s7connector.api.S7Connector;
import com.github.s7connector.api.S7Serializer;
import com.github.s7connector.api.factory.S7ConnectorFactory;
import com.github.s7connector.api.factory.S7SerializerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* S7系列读取
*/
public class S7ConnHelper implements IS7ConnHelper {

/**
* ip
*/
public String Ip = "192.168.0.12";
/**
* 端口
*/
public Integer Port = 102;
public S7Connector s7Connector;
public S7Serializer s7Serializer;
public MyS7Entity myDbData; //S7数据返回
private List<MyS7Entity> myDbDatas = new ArrayList<MyS7Entity>();
public Boolean isConnected = false;
private Boolean heart = false;
public Map<String,Object> myMap = new HashMap<>();

@Override
public void initConnect() throws IOException {
if (this.s7Connector == null) {
this.s7Connector = S7ConnectorFactory.buildTCPConnector()
.withHost(Ip)
.withPort(Port)
.withRack(0)//机架号
.withSlot(1)//插槽号
.build();
this.s7Serializer = S7SerializerFactory.buildSerializer(s7Connector);
this.isConnected = true;
}
}

/**
* @param dbNum DB号
* @param clazz 变量
* @param offSet 偏移量
*/
@Override
public Object readPlcData(Integer dbNum, Class<?> clazz, int offSet) {
//第一个参数:DaveArea.DB 表示读取PLC的地址区域为DB
//第二个参数:DB块地址,若plc中是DB1000,则填1000
//第三个参数:数据长度
//第四个参数:偏移量
if (this.isConnected = true) {
this.myDbData = (MyS7Entity) this.s7Serializer.dispense(clazz, dbNum, offSet);

//心跳
if (heart == false) {
this.myDbData.heartBeat = 10;
heart = true;
} else if (heart == true) {
this.myDbData.heartBeat = 20;
heart = false;
}

try {
this.s7Serializer.store(this.myDbData, dbNum, offSet);
}
//断线重连
catch (Exception ex) {
Show("断线重连" + ex.getMessage());
this.isConnected = false;
try {
this.s7Connector.close();
} catch (IOException e) {
e.printStackTrace();
}
this.s7Connector = null;
this.s7Serializer = null;
try {
this.initConnect();
} catch (IOException e) {
e.printStackTrace();
}
}
this.myDbData = (MyS7Entity) this.s7Serializer.dispense(clazz, dbNum, offSet);

// if (myDbDatas.size() < 30) {
// myDbDatas.add(myDbData);
// } else {
// myDbDatas.remove(0);
// }

}

return myDbData;
}

@Override
public MyGunData readTheDbData(Integer dbNum, MyGunData clazz, int offSet) {
MyGunData myData = this.s7Serializer.dispense(clazz.getClass(), dbNum, offSet);
return myData;
}

@Override
public void writePlcData(Integer dbNum, MyGunData clazz, int offSet) {
this.s7Serializer.store(clazz, dbNum, 0);
}

/**
* DB,DB号,偏移量,Byte数组
* @param bytes
*/
@Override
public void writePlcByte(byte[] bytes) {
this.s7Connector.write(DaveArea.DB, 31, 0, bytes);
}

/**
* 显示日志
*/
public void Show(String message) {
Log.e("S7帮助类", message);
}
}

+ 0
- 107
app/src/main/java/com/bonait/bnframework/common/modbus/S7/S7Listenner.java View File

@@ -1,107 +0,0 @@
package com.bonait.bnframework.common.modbus.S7;

import android.util.Log;

import com.bonait.bnframework.common.modbus.S7.mode.MyS7Entity;

import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class S7Listenner {
public S7ConnHelper s7ConnHelper;

Boolean last = false;
Boolean trigIn = false;
Boolean trigQ = false;


public void Conn() throws IOException {
s7ConnHelper.initConnect();
Show("初始化成功!!");
}

//S7
public void Listen(){

try {
s7ConnHelper.readPlcData(1, MyS7Entity.class, 0);
Map<String, Object> myMap = new HashMap<>();
Field[] fields = s7ConnHelper.myDbData.getClass().getFields();
for (Field f :fields
) {
//log.info(f.getType().toString());

if (f.get(s7ConnHelper.myDbData) instanceof Double){
String format = String.format("%.3f", f.get(s7ConnHelper.myDbData));
myMap.put(f.getName(),format);
}
else {
myMap.put(f.getName(),f.get(s7ConnHelper.myDbData));
}

}
s7ConnHelper.myMap=myMap;


java.util.Date date = new Date();//获得当前时间
Timestamp t = new Timestamp(date.getTime());//将时间转换成Timestamp类型,这样便可以存入到Mysql数据库中

for (String key: s7ConnHelper.myMap.keySet()
) {
System.out.println(key);
}
// System.out.println("===============");
// for (Object v: s7ConnHelper.getMyMap().values()
// ) {
// System.out.println(v);
// }
}
catch (Exception ex){
Show(ex.getMessage()+"=====");
s7ConnHelper.s7Connector=null;
s7ConnHelper.s7Serializer=null;
try {
s7ConnHelper.initConnect();
} catch (IOException e) {
e.printStackTrace();
}
}


// java.util.Date date = new Date();//获得当前时间
// Timestamp t = new Timestamp(date.getTime());//将时间转换成Timestamp类型,这样便可以存入到Mysql数据库中
// for (int i = 0 ; i<s7ConnHelper.getActualDatas().size();i++ ){
// String myScale = s7ConnHelper.getActualDatas().get(i).getScale();
// Double scale = Double.parseDouble(myScale);
// Double value =scale * s7ConnHelper.getMyDbDataList().get(i);
// s7ConnHelper.getActualDatas().get(i).setValue(String.format("%.2f",value));
// s7ConnHelper.getActualDatas().get(i).setCreateTime(t);
// }
//
// for (ActualData actualData: s7ConnHelper.getActualDatas()
// ) {
// log.info(actualData.toString());
// }


//写入变量,OK
// MyGunData myGunData = new MyGunData();
// myDbData.setVar1(1);
// myDbData.setVar2(2);
// myDbData.setVar3(3);
// s7ConnHelper.writePlcData(24,myDbData,0);


}

/**
* 显示日志
*/
public void Show(String message) {
Log.e("S7帮助类", message);
}
}

+ 0
- 29
app/src/main/java/com/bonait/bnframework/common/modbus/S7/mode/MyGunData.java View File

@@ -1,29 +0,0 @@
package com.bonait.bnframework.common.modbus.S7.mode;

import com.github.s7connector.api.annotation.S7Variable;
import com.github.s7connector.impl.utils.S7Type;

public class MyGunData {
@S7Variable(byteOffset = 0, type = S7Type.WORD)
public Integer var1;
@S7Variable(byteOffset = 2, type = S7Type.WORD)
public Integer var2;
@S7Variable(byteOffset = 4, type = S7Type.WORD)
public Integer var3;
@S7Variable(byteOffset = 6, type = S7Type.WORD)
public Integer var4;
@S7Variable(byteOffset = 8, type = S7Type.WORD)
public Integer var5;
@S7Variable(byteOffset = 10, type = S7Type.WORD)
public Integer var6;
@S7Variable(byteOffset = 12, type = S7Type.WORD)
public Integer var7;
@S7Variable(byteOffset = 14, type = S7Type.WORD)
public Integer var8;
@S7Variable(byteOffset = 16, type = S7Type.WORD)
public Integer var9;
@S7Variable(byteOffset = 18, type = S7Type.WORD)
public Integer var10;
// @S7Variable(type = S7Type.STRING, byteOffset = 2, bitOffset=0, size=10)
// public String bbb;
}

+ 0
- 126
app/src/main/java/com/bonait/bnframework/common/modbus/S7/mode/MyS7Entity.java View File

@@ -1,126 +0,0 @@
package com.bonait.bnframework.common.modbus.S7.mode;

import com.github.s7connector.api.annotation.S7Variable;
import com.github.s7connector.impl.utils.S7Type;

public class MyS7Entity {
// @TableId(type = IdType.AUTO)
// private Integer id;
//
// public static final Integer dbNum = 30;
// //@Value("${myS7Db.offSet}")
// public static final Integer offSet = 42;
//
// @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
// @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
// private Date createTime;
// @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
// @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
// private Date insertTime;
//S7Type.REAL 对应float或double类型
//S7Type.WORD int
//S7Type.STRING 字符串

//必须为public 否则报错
@S7Variable(byteOffset = 0, type = S7Type.REAL)
public Double aBLineVoltage_PLC;
@S7Variable(byteOffset = 4, type = S7Type.REAL)
public Double bCLineVoltage_PLC;
@S7Variable(byteOffset = 8, type = S7Type.REAL)
public Double aCLineVoltage_PLC;
@S7Variable(byteOffset = 12, type = S7Type.REAL)
public Double aPhaseVoltage_PLC;
@S7Variable(byteOffset = 16, type = S7Type.REAL)
public Double bPhaseVoltage_PLC;
@S7Variable(byteOffset = 20, type = S7Type.REAL)
public Double cPhaseVoltage_PLC;
@S7Variable(byteOffset = 24, type = S7Type.REAL)
public Double aPhaseCurrent_PLC;
@S7Variable(byteOffset = 28, type = S7Type.REAL)
public Double bPhaseCurrent_PLC;
@S7Variable(byteOffset = 32, type = S7Type.REAL)
public Double cPhaseCurrent_PLC;
@S7Variable(byteOffset = 36, type = S7Type.REAL)
public Double allActivePower_PLC;
@S7Variable(byteOffset = 40, type = S7Type.REAL)
public Double aActivePower_PLC;
@S7Variable(byteOffset = 44, type = S7Type.REAL)
public Double bActivePower_PLC;
@S7Variable(byteOffset = 48, type = S7Type.REAL)
public Double cActivePower_PLC;
@S7Variable(byteOffset = 52, type = S7Type.REAL)
public Double allReactivePower_PLC;
@S7Variable(byteOffset = 56, type = S7Type.REAL)
public Double aReactivePower_PLC;
@S7Variable(byteOffset = 60, type = S7Type.REAL)
public Double bReactivePower_PLC;
@S7Variable(byteOffset = 64, type = S7Type.REAL)
public Double cReactivePower_PLC;
@S7Variable(byteOffset = 68, type = S7Type.REAL)
public Double allPowerFactor_PLC;
@S7Variable(byteOffset = 72, type = S7Type.REAL)
public Double aPowerFactor_PLC;
@S7Variable(byteOffset = 76, type = S7Type.REAL)
public Double bPowerFactor_PLC;
@S7Variable(byteOffset = 80, type = S7Type.REAL)
public Double cPowerFactor_PLC;
@S7Variable(byteOffset = 84, type = S7Type.REAL)
public Double aBLineVoltage_Power;
@S7Variable(byteOffset = 88, type = S7Type.REAL)
public Double bCLineVoltage_Power;
@S7Variable(byteOffset = 92, type = S7Type.REAL)
public Double aCLineVoltage_Power;
@S7Variable(byteOffset = 96, type = S7Type.REAL)
public Double aPhaseVoltage_Power;
@S7Variable(byteOffset = 100, type = S7Type.REAL)
public Double bPhaseVoltage_Power;
@S7Variable(byteOffset = 104, type = S7Type.REAL)
public Double cPhaseVoltage_Power;
@S7Variable(byteOffset = 108, type = S7Type.REAL)
public Double aPhaseCurrent_Power;
@S7Variable(byteOffset = 112, type = S7Type.REAL)
public Double bPhaseCurrent_Power;
@S7Variable(byteOffset = 116, type = S7Type.REAL)
public Double cPhaseCurrent_Power;
@S7Variable(byteOffset = 120, type = S7Type.REAL)
public Double allActivePower_Power;
@S7Variable(byteOffset = 124, type = S7Type.REAL)
public Double aActivePower_Power;
@S7Variable(byteOffset = 128, type = S7Type.REAL)
public Double bActivePower_Power;
@S7Variable(byteOffset = 132, type = S7Type.REAL)
public Double cActivePower_Power;
@S7Variable(byteOffset = 136, type = S7Type.REAL)
public Double allReactivePower_Power;
@S7Variable(byteOffset = 140, type = S7Type.REAL)
public Double aReactivePower_Power;
@S7Variable(byteOffset = 144, type = S7Type.REAL)
public Double bReactivePower_Power;
@S7Variable(byteOffset = 148, type = S7Type.REAL)
public Double cReactivePower_Power;
@S7Variable(byteOffset = 152, type = S7Type.REAL)
public Double allPowerFactor_Power;
@S7Variable(byteOffset = 156, type = S7Type.REAL)
public Double aPowerFactor_Power;
@S7Variable(byteOffset = 160, type = S7Type.REAL)
public Double bPowerFactor_Power;
@S7Variable(byteOffset = 164, type = S7Type.REAL)
public Double cPowerFactor_Power;
@S7Variable(byteOffset = 168, type = S7Type.REAL)
public Double testAlarm;
@S7Variable(byteOffset = 404, type = S7Type.WORD)
public Integer heartBeat;

@S7Variable(byteOffset = 606,size = 130, type = S7Type.STRING)
public String var100;
@S7Variable(byteOffset = 738,size = 130, type = S7Type.STRING)
public String var101;

/**
@S7Variable(byteOffset=0, type= S7Type.REAL) public double var1;
@S7Variable(byteOffset=4, type= S7Type.REAL) public double var2;
@S7Variable(byteOffset=8, type= S7Type.REAL) public double var3;
@S7Variable(byteOffset=144, type= S7Type.BOOL) public boolean STATE_P1;
@S7Variable(byteOffset=144, type= S7Type.BOOL,bitOffset = 1) public boolean STATE_P1;
*/
}

+ 0
- 11
app/src/main/java/com/bonait/bnframework/common/modbus/S7/mode/MyS7WriteEntity.java View File

@@ -1,11 +0,0 @@
package com.bonait.bnframework.common.modbus.S7.mode;

import com.github.s7connector.api.annotation.S7Variable;
import com.github.s7connector.impl.utils.S7Type;

public class MyS7WriteEntity {
@S7Variable(byteOffset = 606,size = 130, type = S7Type.STRING)
public String var100;
@S7Variable(byteOffset = 738,size = 130, type = S7Type.STRING)
public String var101;
}

+ 234
- 0
app/src/main/java/com/bonait/bnframework/common/modbus/s7/SiemensHelper.java View File

@@ -0,0 +1,234 @@
package com.bonait.bnframework.common.modbus.s7;

import static com.github.xingshuangs.iot.common.constant.GeneralConst.S7_PORT;

import android.util.Log;

import com.github.xingshuangs.iot.exceptions.SocketRuntimeException;
import com.github.xingshuangs.iot.protocol.s7.enums.EPlcType;
import com.github.xingshuangs.iot.protocol.s7.model.DataItem;
import com.github.xingshuangs.iot.protocol.s7.service.S7PLC;
import com.github.xingshuangs.iot.protocol.s7.utils.AddressUtil;
import com.github.xingshuangs.iot.utils.FloatUtil;
import com.github.xingshuangs.iot.utils.IntegerUtil;
import com.github.xingshuangs.iot.utils.ShortUtil;

import java.lang.reflect.ParameterizedType;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SiemensHelper extends S7PLC {

/**
* 判断PLC连接是否成功
* @return
*/
public boolean IsConnected(){
try {
socket.sendUrgentData(0xff);
return true;
}catch(Exception e){
return false;
}
}

public void Delay(long millis){
try{
Thread.sleep(millis);
}catch(InterruptedException e){

}
}

public boolean ReadBoolean(String address){
try {
return this.readBoolean(address);
}
catch(SocketRuntimeException ex){
this.close();
}
return false;
}

public List<Boolean> ReadBoolean(String... address) {
try {
return this.readBoolean(Arrays.asList(address));
}
catch(SocketRuntimeException ex){
this.close();
}
return new ArrayList<Boolean>();
}

public short ReadInt16(String address) {
try {
DataItem dataItem = this.readS7Data(AddressUtil.parseByte(address, 2));
return ShortUtil.toInt16(dataItem.getData());
}
catch(SocketRuntimeException ex){
this.close();
}
return 0;

}

public List<Short> ReadInt16(String... address) {
try {
return this.readInt16(Arrays.asList(address));
}
catch(SocketRuntimeException ex){
this.close();
}
return new ArrayList<Short>();
}

public int ReadUInt16(String address) {
try {
DataItem dataItem = this.readS7Data(AddressUtil.parseByte(address, 2));
return ShortUtil.toUInt16(dataItem.getData());
}
catch(SocketRuntimeException ex){
this.close();
}
return 0;
}

public List<Integer> ReadUInt16(String... address) {
try {
return this.readUInt16(Arrays.asList(address));
}
catch(SocketRuntimeException ex){
this.close();
}
return new ArrayList<Integer>();
}

public int ReadInt32(String address) {
try {
DataItem dataItem = this.readS7Data(AddressUtil.parseByte(address, 4));
return IntegerUtil.toInt32(dataItem.getData());
}
catch(SocketRuntimeException ex){
this.close();
}
return 0;
}

public List<Integer> ReadInt32(String... address) {
try {
return this.readInt32(Arrays.asList(address));
}
catch(SocketRuntimeException ex){
this.close();
}
return new ArrayList<Integer>();
}

public float ReadFloat32(String address) {
try {
DataItem dataItem = this.readS7Data(AddressUtil.parseByte(address, 4));
return FloatUtil.toFloat32(dataItem.getData());
}
catch(SocketRuntimeException ex){
this.close();
}
return 0;
}

public List<Float> ReadFloat32(String... address) {
try {
return this.readFloat32(Arrays.asList(address));
}
catch(SocketRuntimeException ex){
this.close();
}
return new ArrayList<Float>();
}

public void WriteBoolean(String address, boolean data) {
while (true) {
try {
this.writeS7Data(AddressUtil.parseBit(address), DataItem.createReqByBoolean(data));
break;
}
catch(SocketRuntimeException ex){
this.close();
Delay(100);
}
}
}

public void WriteUInt16(String address, int data) {
while (true) {
try {
this.writeByte(address, ShortUtil.toByteArray(data));
break;
}
catch(SocketRuntimeException ex){
this.close();
Delay(100);
}
}
}

public void WriteInt16(String address, short data) {
while (true) {
try {
Log.e("info","准备写入数据:"+data);
this.writeByte(address, ShortUtil.toByteArray(data));
break;
}
catch(SocketRuntimeException ex){
Log.e("socketException","写入:"+data+"失败");
this.close();
Delay(100);
}
}
}

public void WriteUInt32(String address, long data) {
while (true) {
try {
this.writeByte(address, IntegerUtil.toByteArray(data));
break;
}
catch(SocketRuntimeException ex){
this.close();
Delay(100);
}
}
}

public void WriteInt32(String address, int data) {
while (true) {
try {
this.writeByte(address, IntegerUtil.toByteArray(data));
break;
}
catch(SocketRuntimeException ex){
this.close();
Delay(100);
}
}
}

public void WriteFloat32(String address, float data) {
while (true) {
try {
this.writeByte(address, FloatUtil.toByteArray(data));
break;
}
catch(SocketRuntimeException ex){
this.close();
Delay(100);
}
}
}

public SiemensHelper(EPlcType PlcType, String ip){
super(PlcType, ip);
}

}

+ 169
- 0
app/src/main/java/com/bonait/bnframework/common/modbus/s7/SiemensHelper1.java View File

@@ -0,0 +1,169 @@
package com.bonait.bnframework.common.modbus.s7;

import android.util.Log;

import com.bonait.bnframework.common.constant.ConfigName;
import com.github.xingshuangs.iot.exceptions.SocketRuntimeException;
import com.github.xingshuangs.iot.protocol.s7.enums.EPlcType;
import com.github.xingshuangs.iot.protocol.s7.service.S7PLC;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

/**
* S7
*/
public class SiemensHelper1 extends S7PLC {

//region 单例
private static volatile SiemensHelper1 instance = null;

public static SiemensHelper1 get() {
SiemensHelper1 manager = instance;
if (manager == null) {
synchronized (SiemensHelper1.class) {
manager = instance;
if (manager == null) {
manager = new SiemensHelper1();
instance = manager;
}
}
}
return manager;
}

private SiemensHelper1() {

}
//endregion

//region 变量
/**
* 默认PLC类型
*/
public static EPlcType type = EPlcType.S1500;
public static S7PLC s7PLC = null;
//endregion

//region 公共方法
/**
* Ping PLC地址是否通畅
* @param address
* @param pingTimes ping的次数
* @param timeOut 超时时间 10
* @return
*/
public static boolean ping2(String address, int pingTimes, int timeOut) {
Process process = null;
try {
process = Runtime.getRuntime().exec( "ping " + "-c " + pingTimes + " -w " + timeOut+ " "+address);
InputStreamReader r = new InputStreamReader(process.getInputStream());

LineNumberReader returnData = new LineNumberReader(r);

String returnMsg="";

String line = "";

while ((line = returnData.readLine()) != null) {

System.out.println(line);

returnMsg += line;

}

if(returnMsg.indexOf("100% packet loss")!=-1){
System.out.println("与 " +address +" 连接不畅通.");
//ToastUtils.info("与 " +address +" 连接不畅通.");
return false;
} else{
System.out.println("与 " +address +" 连接畅通.");
//ToastUtils.info("与 " +address +" 连接不畅通.");
return true;
}
} catch (IOException e) {
// e.printStackTrace();
}
return false;

}
/**
* 连接plc
*/
public static void Connect() {
try {
s7PLC = new S7PLC(type, ConfigName.getInstance().Address);
s7PLC.connect();
ConfigName.getInstance().PlcIsConnect = true;
} catch (SocketRuntimeException ex) {
Log.e("SocketRuntimeException", ex.getMessage());
Close();
} catch (Exception ex) {
Log.e("Exception", ex.getMessage());
Close();
}

}

/**
* 关闭
*/
public static void Close() {
try {
if (s7PLC != null) {
s7PLC.close();
}
} catch (SocketRuntimeException ex) {
Log.e("SocketRuntimeException", ex.getMessage());
} catch (Exception ex) {
Log.e("Exception", ex.getMessage());
}
ConfigName.getInstance().PlcIsConnect = false;
}

/**
* 读取数据
* @param address
* @return
*/
public Object readPLC(String address) {
Object res=null;
try {
if (address.contains("V")) {
res = s7PLC.readBoolean(address);
} else if (address.contains("D")) {
res = s7PLC.readUInt32(address);
}
} catch (SocketRuntimeException ex) {
Close();
} catch (Exception ex) {

}
return res;
}

/**
* 写数据
* @param address
* @return
*/
public boolean writePLC(String address,Object data) {
boolean res=false;
try {
if (address.contains("V")) {
s7PLC.writeBoolean(address,(boolean)data);
} else if (address.contains("D")) {
s7PLC.writeInt32(address,(int)data);
}
res=true;
} catch (SocketRuntimeException ex) {
Close();
} catch (Exception ex) {

}
return res;
}
//endregion
}

+ 4
- 5
app/src/main/java/com/bonait/bnframework/modules/home/activity/BottomNavigation2Activity.java View File

@@ -6,11 +6,10 @@ import androidx.annotation.NonNull;

import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.helper.I.IThread;
import com.bonait.bnframework.common.helper.MessageLog;
import com.bonait.bnframework.common.helper.ThreadManager;
import com.bonait.bnframework.common.modbus.ModbusTcpServer;
import com.bonait.bnframework.common.modbus.s7.SiemensHelper1;
import com.bonait.bnframework.common.utils.NetworkUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;

@@ -188,17 +187,17 @@ public class BottomNavigation2Activity extends BaseActivity {
try {
if (ConfigName.getInstance().PlcIsConnect) {
//ping 不通
boolean status = ModbusTcpServer.ping2(ConfigName.getInstance().Address, 1, 1);
boolean status = SiemensHelper1.get().ping2(ConfigName.getInstance().Address, 1, 1);
if (!status) //ping 不通 连接
{
MessageLog.ShowInfo("PLC状态断开,尝试连接...");
ConfigName.getInstance().PlcIsConnect = false;
}
} else {
boolean status = ModbusTcpServer.ping2(ConfigName.getInstance().Address, 1, 1);
boolean status = SiemensHelper1.get().ping2(ConfigName.getInstance().Address, 1, 1);
if (status) {
MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " PLC通讯正常,准备连接!");
ModbusTcpServer.ConnectPLC();
SiemensHelper1.get().Connect();
} else {
MessageLog.ShowInfo("PLC状态断开,尝试连接...");
ConfigName.getInstance().PlcIsConnect = false;


+ 4
- 10
app/src/main/java/com/bonait/bnframework/modules/home/activity/BottomNavigationNewActivity.java View File

@@ -1,13 +1,11 @@
package com.bonait.bnframework.modules.home.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
@@ -28,20 +26,16 @@ import com.bonait.bnframework.common.helper.MessageLog;
import com.bonait.bnframework.common.helper.ThreadManager;
import com.bonait.bnframework.common.message.MessageLooper;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.modbus.ModbusTcpServer;
import com.bonait.bnframework.common.modbus.s7.SiemensHelper1;
import com.bonait.bnframework.common.utils.NetworkUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.BottomNavigationBar;
import com.bonait.bnframework.manager.ActivityLifecycleManager;
import com.bonait.bnframework.modules.home.adapter.FragmentAdapter;
import com.bonait.bnframework.modules.home.fragment.Home1Fragment;
import com.bonait.bnframework.modules.home.fragment.Home2Fragment;
import com.bonait.bnframework.modules.home.fragment.Home4Fragment;
import com.bonait.bnframework.modules.home.fragment.HomeFragmentPR;
import com.bonait.bnframework.modules.home.fragment.HomeFragmentSBKZ;
import com.bonait.bnframework.modules.home.fragment.from.CookingActivity;
import com.bonait.bnframework.modules.mine.fragment.MyFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.lzy.okgo.OkGo;
import com.qmuiteam.qmui.widget.QMUIViewPager;

@@ -286,17 +280,17 @@ public class BottomNavigationNewActivity extends BaseActivity {
try {
if (ConfigName.getInstance().PlcIsConnect) {
//ping 不通
boolean status = ModbusTcpServer.ping2(ConfigName.getInstance().Address, 1, 1);
boolean status = SiemensHelper1.get().ping2(ConfigName.getInstance().Address, 1, 1);
if (!status) //ping 不通 连接
{
MessageLog.ShowInfo("PLC状态断开,尝试连接...");
ConfigName.getInstance().PlcIsConnect = false;
}
} else {
boolean status = ModbusTcpServer.ping2(ConfigName.getInstance().Address, 1, 1);
boolean status = SiemensHelper1.get().ping2(ConfigName.getInstance().Address, 1, 1);
if (status) {
MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " PLC通讯正常,准备连接!");
ModbusTcpServer.ConnectPLC();
SiemensHelper1.get().Connect();
} else {
MessageLog.ShowInfo("PLC状态断开,尝试连接...");
ConfigName.getInstance().PlcIsConnect = false;


+ 0
- 1
app/src/main/java/com/bonait/bnframework/modules/home/fragment/Home1Fragment.java View File

@@ -49,7 +49,6 @@ import com.bonait.bnframework.common.helper.MessageLog;
import com.bonait.bnframework.common.helper.ThreadManager;
import com.bonait.bnframework.common.message.MessageLooper;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.modbus.ModbusTcpServer;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.MyLayoutManager;


+ 0
- 33
app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/fragment/AutoTestMoreFragment.java View File

@@ -209,39 +209,6 @@ public class AutoTestMoreFragment extends BaseFragment {
}
}
}).start();

new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
//故障信息
for (StatusMode item: ConfigName.getInstance().statusModes)
{
if(ExecuteTheRecipe.getConcurrentHash(item.sort))
{
SetMiaosShu1(item.Name);
}
}

String x1= ConfigName.getInstance().statusModes_电机.get(ExecuteTheRecipe.getConcurrentHash_dj("搅拌电机"));
String x2= ConfigName.getInstance().statusModes_电机.get(ExecuteTheRecipe.getConcurrentHash_dj("翻转电机"));
if(!x1.equals("无故障"))
{
SetMiaosShu1("搅拌电机故障代码:"+x1);
}

if(!x2.equals("无故障"))
{
SetMiaosShu1("翻转电机故障代码:"+x2);
}
Thread.sleep(2000);
} catch (Exception ex) {

}
}
}
}).start();
}




+ 0
- 22
app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/fragment/AutoTestOneFragment.java View File

@@ -336,28 +336,6 @@ public class AutoTestOneFragment extends BaseFragment {
break;
}
}

//故障信息
for (StatusMode item:ConfigName.getInstance().statusModes)
{
if(ExecuteTheRecipe.getConcurrentHash(item.sort))
{
SetMiaosShu1(item.Name);
}
}

String x1= ConfigName.getInstance().statusModes_电机.get(ExecuteTheRecipe.getConcurrentHash_dj("搅拌电机"));
String x2= ConfigName.getInstance().statusModes_电机.get(ExecuteTheRecipe.getConcurrentHash_dj("翻转电机"));
if(!x1.equals("无故障"))
{
SetMiaosShu1("搅拌电机故障代码:"+x1);
}

if(!x2.equals("无故障"))
{
SetMiaosShu1("翻转电机故障代码:"+x2);
}

Thread.sleep(2000);
} catch (Exception ex) {



+ 34
- 34
app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/fragment/SystemCsMonitorFragment.java View File

@@ -81,40 +81,40 @@ public class SystemCsMonitorFragment extends BaseFragment {
* 实时显示线程
*/
public void Run() {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Activity activity=getActivity();
if(activity!=null)
{
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
for (StatusMode item:ConfigName.getInstance().statusModes)
{
item.Status= ExecuteTheRecipe.getConcurrentHash(item.sort);
}
jiaobandianji.setText( ConfigName.getInstance().statusModes_电机.get(ExecuteTheRecipe.getConcurrentHash_dj("搅拌电机")));
fanzhuandianji.setText( ConfigName.getInstance().statusModes_电机.get(ExecuteTheRecipe.getConcurrentHash_dj("翻转电机")));
adapter.refresh();
} catch (Exception e) {
}
}
});
}
Thread.sleep(1000);
} catch (InterruptedException e) {
ToastUtils.info("异常信息:" + e.getMessage());
}
}
}
}).start();
// new Thread(new Runnable() {
// @Override
// public void run() {
// while (true) {
// try {
// Activity activity=getActivity();
// if(activity!=null)
// {
// activity.runOnUiThread(new Runnable() {
// @Override
// public void run() {
// try {
// for (StatusMode item:ConfigName.getInstance().statusModes)
// {
// item.Status= ExecuteTheRecipe.getConcurrentHash(item.sort);
// }
//
// jiaobandianji.setText( ConfigName.getInstance().statusModes_电机.get(ExecuteTheRecipe.getConcurrentHash_dj("搅拌电机")));
// fanzhuandianji.setText( ConfigName.getInstance().statusModes_电机.get(ExecuteTheRecipe.getConcurrentHash_dj("翻转电机")));
//
// adapter.refresh();
// } catch (Exception e) {
//
// }
// }
// });
// }
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// ToastUtils.info("异常信息:" + e.getMessage());
// }
// }
// }
// }).start();
}
@Override
public void onDestroy() {


+ 0
- 1
app/src/main/java/com/bonait/bnframework/modules/home/fragment/from/fragment/SystemCsPLCFragment.java View File

@@ -22,7 +22,6 @@ import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.db.mode.BPA_PLCADDRESS;
import com.bonait.bnframework.common.modbus.ModbusTcpServer;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.NetworkUtils;
import com.bonait.bnframework.common.utils.ToastUtils;


+ 4
- 4
app/src/main/res/layout/activity_login.xml View File

@@ -14,10 +14,10 @@
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.bonait.bnframework.common.bg.SnowView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/transparent" />
<!-- <com.bonait.bnframework.common.bg.SnowView-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="match_parent"-->
<!-- android:background="@color/transparent" />-->

<androidx.core.widget.NestedScrollView
android:id="@+id/scrollView"


Loading…
Cancel
Save