diff --git a/app/build.gradle b/app/build.gradle index 7eb01605..f55eac0d 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -119,6 +119,8 @@ dependencies { // implementation files('libs/commons-codec-1.6.jar') + //USB串口 + implementation 'com.github.cl-6666:serialPort:V3.1.3' //Modbus implementation 'com.github.licheedev:Modbus4Android:2.0.2' diff --git a/app/src/main/java/com/bonait/bnframework/business/ConfigData.java b/app/src/main/java/com/bonait/bnframework/business/ConfigData.java index ffca7ff8..1815a4b9 100644 --- a/app/src/main/java/com/bonait/bnframework/business/ConfigData.java +++ b/app/src/main/java/com/bonait/bnframework/business/ConfigData.java @@ -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; @@ -25,19 +22,17 @@ import com.bonait.bnframework.common.db.mode.BPA_SILOSANDMATERIAL; 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.ModbusBasis; +import com.bonait.bnframework.common.modbus.ModbusClient; import com.bonait.bnframework.common.model.ResAPI; import com.bonait.bnframework.common.model.mode.ActionJsonMode; import com.bonait.bnframework.common.model.mode.BomTechnologyActionInfo; import com.bonait.bnframework.common.model.mode.BomTypeInfo; -import com.bonait.bnframework.common.model.mode.ProcessT; import com.bonait.bnframework.common.model.mode.ResGoodProcess; import com.bonait.bnframework.common.model.mode.ResSilosModel; import com.bonait.bnframework.common.model.mode.TechnologyValueMode; @@ -65,14 +60,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; @@ -901,7 +893,9 @@ public class ConfigData { List resSilosModels=ConfigName.getInstance().Silos_奶茶机; if (ConfigName.getInstance().versionSelectionEnum.equals("配料吧台")) { - plcaddresses = ConfigName.getInstance().PlcAddress_配料吧台; + + plcaddresses = ConfigName.getInstance().PLCAddress_调味吧台; +// plcaddresses = ConfigName.getInstance().PlcAddress_配料吧台; resSilosModels=ConfigName.getInstance().Silos_配料吧台; }else if (ConfigName.getInstance().versionSelectionEnum.equals("奶茶机")) { @@ -909,6 +903,8 @@ public class ConfigData { resSilosModels=ConfigName.getInstance().Silos_奶茶机; }else if (ConfigName.getInstance().versionSelectionEnum.equals("味魔方")) { + + plcaddresses = ConfigName.getInstance().PlcAddress_味魔方; resSilosModels=ConfigName.getInstance().Silos_味魔方; } @@ -974,7 +970,7 @@ public class ConfigData { @Override public void run() { try { - ModbusTcpServer.get().Connect(); +// ModbusClient.get().Connect(); } catch (Exception e) { } @@ -985,7 +981,7 @@ public class ConfigData { * 关闭PLC */ public void ColsePLC() { - ModbusTcpHelper.get().release();//释放modbus + ModbusBasis.get().release();//释放modbus ConfigName.getInstance().PlcIsConnect=false; } /** diff --git a/app/src/main/java/com/bonait/bnframework/business/ExecuteTheRecipe.java b/app/src/main/java/com/bonait/bnframework/business/ExecuteTheRecipe.java index eadd7a0e..b4a9f13f 100644 --- a/app/src/main/java/com/bonait/bnframework/business/ExecuteTheRecipe.java +++ b/app/src/main/java/com/bonait/bnframework/business/ExecuteTheRecipe.java @@ -1,55 +1,37 @@ package com.bonait.bnframework.business; -import android.app.Activity; -import android.content.Context; -import android.content.ContextWrapper; -import android.media.MediaPlayer; import android.os.Handler; import android.os.Looper; import android.util.Log; -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.db.QueryDB; -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.db.res.AlertLogEnum; import com.bonait.bnframework.common.db.res.ResGoodsMake; import com.bonait.bnframework.common.db.res.ResGoodsRecipe; -import com.bonait.bnframework.common.db.res.SilosLsjyMode; import com.bonait.bnframework.common.db.res.UserLogEnum; import com.bonait.bnframework.common.helper.ByteHelper; -import com.bonait.bnframework.common.helper.DataFormat; import com.bonait.bnframework.common.helper.I.IReadCallBack; 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.MediaPlayerHelper; import com.bonait.bnframework.common.helper.MessageLog; import com.bonait.bnframework.common.helper.RTrig; import com.bonait.bnframework.common.helper.ThreadManager; -import com.bonait.bnframework.common.modbus.ModbusTcpServer; -import com.bonait.bnframework.common.utils.AlertDialogUtils; +import com.bonait.bnframework.common.modbus.ModbusClient; +import com.bonait.bnframework.common.modbus.ModbusMaster; import com.bonait.bnframework.common.utils.ToastUtils; -import com.qmuiteam.qmui.widget.dialog.QMUIDialog; -import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction; import java.util.ArrayList; import java.util.HashMap; -import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import kotlin.UShort; - /** * 执行配方 */ @@ -489,12 +471,14 @@ public class ExecuteTheRecipe { 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 + if (plcaddress.address.toUpperCase().startsWith("D"))//int { - ModbusTcpServer.get().WriteInt(plcaddress.address, (int) value, callback); + ModbusMaster.get().WriteShort(plcaddress.address,(short) value,1,callback); +// ModbusClient.get().WriteInt(plcaddress.address, (int) value, callback); } else if (plcaddress.address.toUpperCase().startsWith("M"))//bool { - ModbusTcpServer.get().WriteBool(plcaddress.address, (boolean) value, callback); + ModbusMaster.get().WriteInt(plcaddress.address,(int) value,1,callback); +// ModbusClient.get().WriteBool(plcaddress.address, (boolean) value, callback); } else if (plcaddress.address.toUpperCase().startsWith("VW"))//short { if(plcaddress.address.contains(".")) @@ -502,21 +486,21 @@ public class ExecuteTheRecipe { String[] res = plcaddress.address.split("[.]"); String firstAdd = res[0]; //VW100 int endAdd = Integer.parseInt(res[1]); //1 //第几位 - ModbusTcpServer.get().ReadShort(firstAdd, 1, new IReadCallBack() { - @Override - public void onSuccess(short[] shorts) { - Short val=shorts[0]; - Short valk= ByteHelper.setBit(val,endAdd,(boolean) value); - ModbusTcpServer.get().WriteShort(firstAdd, valk, null); - } - }); +// ModbusClient.get().ReadShort(firstAdd, 1, new IReadCallBack() { +// @Override +// public void onSuccess(short[] shorts) { +// Short val=shorts[0]; +// Short valk= ByteHelper.setBit(val,endAdd,(boolean) value); +// ModbusClient.get().WriteShort(firstAdd, valk, null); +// } +// }); }else { - ModbusTcpServer.get().WriteShort(plcaddress.address, Short.parseShort(value.toString()), callback); +// ModbusClient.get().WriteShort(plcaddress.address, Short.parseShort(value.toString()), callback); } }else if (plcaddress.address.toUpperCase().startsWith("VR"))//float { - ModbusTcpServer.get().WriteFloat(plcaddress.address, Float.parseFloat(value.toString()), callback); +// ModbusClient.get().WriteFloat(plcaddress.address, Float.parseFloat(value.toString()), callback); } } } @@ -541,36 +525,53 @@ public class ExecuteTheRecipe { 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]; + ModbusMaster.get().ReadInt(plcaddress.address,1,1,value->{ + ReturnsVariable[0] = value[0]; }); + +// ModbusClient.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]; + + ModbusMaster.get().ReadBool(plcaddress.address,1,1,value->{ + ReturnsVariable[0] = value[0]; }); + +// ModbusClient.get().ReadBool(plcaddress.address, 1, val -> { +// ReturnsVariable[0] = val[0]; +// }); } else if (plcaddress.address.toUpperCase().startsWith("VW"))//short { if(plcaddress.address.contains(".")) { - String[] res = plcaddress.address.split("[.]"); - String firstAdd = res[0].replace("V","VW"); //VW194 - int endAdd = Integer.parseInt(res[1]); //1 //第几位 - ModbusTcpServer.get().ReadbcStatus(firstAdd, 1, data -> { - byte status=data[0];//0x92 - ReturnsVariable[0] = ByteHelper.getBit(status,endAdd)==1; - }); +// String[] res = plcaddress.address.split("[.]"); +// String firstAdd = res[0].replace("V","VW"); //VW194 +// int endAdd = Integer.parseInt(res[1]); //1 //第几位 +// ModbusClient.get().ReadbcStatus(firstAdd, 1, data -> { +// byte status=data[0];//0x92 +// ReturnsVariable[0] = ByteHelper.getBit(status,endAdd)==1; +// }); }else { - ModbusTcpServer.get().ReadShort(plcaddress.address, 1, val -> { - ReturnsVariable[0] = val[0]; + ModbusMaster.get().ReadShort(plcaddress.address,1,1,value->{ + ReturnsVariable[0] = value[0]; }); +// ModbusClient.get().ReadShort(plcaddress.address, 1, val -> { +// ReturnsVariable[0] = val[0]; +// }); } } else if (plcaddress.address.toUpperCase().startsWith("VR"))//float { - ModbusTcpServer.get().ReadFloat(plcaddress.address, 1, val -> { - ReturnsVariable[0] = val[0]; + + ModbusMaster.get().ReadFloat(plcaddress.address,1,1,value->{ + ReturnsVariable[0] = value[0]; }); + +// ModbusClient.get().ReadFloat(plcaddress.address, 1, val -> { +// ReturnsVariable[0] = val[0]; +// }); } } } @@ -595,32 +596,57 @@ public class ExecuteTheRecipe { if (!plcaddress.address.isEmpty() && ConfigName.getInstance().PlcIsConnect) { if (plcaddress.address.toUpperCase().startsWith("VD"))//int { - ModbusTcpServer.get().ReadInt(plcaddress.address, length, val -> { + ModbusMaster.get().ReadInt(plcaddress.address,length,1,value->{ for (int i = 0; i < length; i++) { - ReturnsVariable[i] = val[i]; + ReturnsVariable[i] = value[i]; } }); + +// ModbusClient.get().ReadInt(plcaddress.address, length, val -> { +// for (int i = 0; i < length; i++) { +// ReturnsVariable[i] = val[i]; +// } +// }); } else if (plcaddress.address.toUpperCase().startsWith("M"))//bool { - ModbusTcpServer.get().ReadBool(plcaddress.address, length, val -> { + ModbusMaster.get().ReadBool(plcaddress.address,length,1,value->{ for (int i = 0; i < length; i++) { - ReturnsVariable[i] = val[i]; + ReturnsVariable[i] = value[i]; } }); + +// ModbusClient.get().ReadBool(plcaddress.address, length, val -> { +// for (int i = 0; i < length; i++) { +// ReturnsVariable[i] = val[i]; +// } +// }); } else if (plcaddress.address.toUpperCase().startsWith("VW"))//short { - ModbusTcpServer.get().ReadShort(plcaddress.address, length, val -> { + ModbusMaster.get().ReadShort(plcaddress.address,length,1,value->{ for (int i = 0; i < length; i++) { - ReturnsVariable[i] = val[i]; + ReturnsVariable[i] = value[i]; } }); + +// ModbusClient.get().ReadShort(plcaddress.address, length, val -> { +// for (int i = 0; i < length; i++) { +// ReturnsVariable[i] = val[i]; +// } +// }); } else if (plcaddress.address.toUpperCase().startsWith("VR"))//float { - ModbusTcpServer.get().ReadFloat(plcaddress.address, length, val -> { + + ModbusMaster.get().ReadFloat(plcaddress.address,length,1,value->{ for (int i = 0; i < length; i++) { - ReturnsVariable[i] = val[i]; + ReturnsVariable[i] = value[i]; } }); + +// ModbusClient.get().ReadFloat(plcaddress.address, length, val -> { +// for (int i = 0; i < length; i++) { +// ReturnsVariable[i] = val[i]; +// } +// }); } } } @@ -639,7 +665,7 @@ public class ExecuteTheRecipe { public static void WritePLCSD(String address ,boolean value, IWriteCallBack callback) { try { if (ConfigName.getInstance().PlcIsConnect) { - ModbusTcpServer.get().WriteBool(address, (boolean) value, callback); +// ModbusClient.get().WriteBool(address, (boolean) value, callback); } } catch (Exception ex) { ToastUtils.error("异常信息:" + ex.getMessage()); @@ -681,19 +707,19 @@ public class ExecuteTheRecipe { if (ConfigName.getInstance().PLC_Address.containsKey("实时状态")) { BPA_PLCADDRESS plcaddress = ConfigName.getInstance().PLC_Address.get("实时状态"); if (!plcaddress.address.isEmpty() && ConfigName.getInstance().PlcIsConnect) { - ModbusTcpServer.get().ReadStatus(plcaddress.address, 4, (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); - } - }); +// ModbusClient.get().ReadStatus(plcaddress.address, 4, (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) { @@ -710,18 +736,18 @@ public class ExecuteTheRecipe { if (ConfigName.getInstance().PLC_Address.containsKey("扫码数据")) { BPA_PLCADDRESS plcaddress = ConfigName.getInstance().PLC_Address.get("扫码数据"); if (!plcaddress.address.isEmpty() && ConfigName.getInstance().PlcIsConnect) { - ModbusTcpServer.get().ReadString(plcaddress.address, 40, (data) -> { - - if(!data.isEmpty() && !Code.equals(data) && OnScanTheCodeInformationT != null) - { - Log.d("信息", "扫码数据: "+data); - OnScanTheCodeInformationT.Run(data); - ModbusTcpServer.get().WriteString(plcaddress.address, 40, null); - } - - //记录上一次读取PLC 扫码数据 - Code = data; - }); +// ModbusClient.get().ReadString(plcaddress.address, 40, (data) -> { +// +// if(!data.isEmpty() && !Code.equals(data) && OnScanTheCodeInformationT != null) +// { +// Log.d("信息", "扫码数据: "+data); +// OnScanTheCodeInformationT.Run(data); +// ModbusClient.get().WriteString(plcaddress.address, 40, null); +// } +// +// //记录上一次读取PLC 扫码数据 +// Code = data; +// }); } } @@ -851,12 +877,12 @@ public class ExecuteTheRecipe { if (ConfigName.getInstance().PLC_Address.containsKey(name)) { BPA_PLCADDRESS plcaddress = ConfigName.getInstance().PLC_Address.get(name); if (!plcaddress.address.isEmpty() && ConfigName.getInstance().PlcIsConnect) { - ModbusTcpServer.get().ReadBool(plcaddress.address, 1, booleans -> { - RTrig.get(name).Start(booleans[0], () -> { - if (callback != null) - callback.Run(); - }); - }); +// ModbusClient.get().ReadBool(plcaddress.address, 1, booleans -> { +// RTrig.get(name).Start(booleans[0], () -> { +// if (callback != null) +// callback.Run(); +// }); +// }); } } } diff --git a/app/src/main/java/com/bonait/bnframework/business/MainInit.java b/app/src/main/java/com/bonait/bnframework/business/MainInit.java index f8634aad..0da31785 100644 --- a/app/src/main/java/com/bonait/bnframework/business/MainInit.java +++ b/app/src/main/java/com/bonait/bnframework/business/MainInit.java @@ -9,30 +9,22 @@ import com.bonait.bnframework.common.constant.ConfigName; import com.bonait.bnframework.common.constant.Constants; import com.bonait.bnframework.common.constant.DataBus; import com.bonait.bnframework.common.db.QueryDB; -import com.bonait.bnframework.common.db.file.DBHelper; import com.bonait.bnframework.common.db.mode.BPA_ALERTLOG; -import com.bonait.bnframework.common.db.mode.BPA_CLOUDDATA; 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_LOG; -import com.bonait.bnframework.common.db.mode.BPA_PLCADDRESS; -import com.bonait.bnframework.common.db.mode.BPA_SILOS; -import com.bonait.bnframework.common.db.mode.BPA_SILOSANDMATERIAL; import com.bonait.bnframework.common.db.mode.BPA_USER; import com.bonait.bnframework.common.db.res.AlertLogEnum; -import com.bonait.bnframework.common.db.res.ResGoodsRecipe; import com.bonait.bnframework.common.db.res.UserLogEnum; import com.bonait.bnframework.common.helper.CrashHandler; import com.bonait.bnframework.common.helper.I.IMessageLogNotify; 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.modbus.ModbusBasis; import com.bonait.bnframework.common.notification.MainNotification; import com.bonait.bnframework.common.utils.AppUtils; -import com.bonait.bnframework.common.utils.NetworkUtils; import com.bonait.bnframework.common.utils.PreferenceUtils; import com.bonait.bnframework.common.utils.ToastUtils; -import com.bonait.bnframework.common.utils.WifiInterceptor; import com.bonait.bnframework.manager.ActivityLifecycleManager; import com.lzy.okgo.OkGo; import com.lzy.okgo.cache.CacheEntity; @@ -215,7 +207,7 @@ public class MainInit { public void ErrorMsg(String msg) { if(msg.contains("msg:com.serotonin.modbus4j.exception")) { - ModbusTcpHelper.get().release();//释放modbus + ModbusBasis.get().release();//释放modbus ConfigName.getInstance().PlcIsConnect=false; BPA_ALERTLOG log = new BPA_ALERTLOG(); diff --git a/app/src/main/java/com/bonait/bnframework/common/constant/ConfigName.java b/app/src/main/java/com/bonait/bnframework/common/constant/ConfigName.java index 8561c1e5..ef8ff18f 100644 --- a/app/src/main/java/com/bonait/bnframework/common/constant/ConfigName.java +++ b/app/src/main/java/com/bonait/bnframework/common/constant/ConfigName.java @@ -172,6 +172,17 @@ public class ConfigName { * Plc地址 */ public String Address = "192.168.1.100"; + + /** + * Rtu串口端口号 + */ + public String SerialPortName="/dev/ttyCOM0"; + + /** + * ttl usb 端口号,扫码枪端口号 + */ + public String UsbSerialPortName="/dev/ttyS0"; + /** * Plc端口 */ @@ -868,6 +879,51 @@ public class ConfigName { // add(new Res_ZDSF("外置通道(十)","VW194.9","VW162","VW62","VW186")); }}; + + /** + * 新版调味吧台 + */ + public List PLCAddress_调味吧台 = new ArrayList() {{ + add(new Res_PLCADDRESS("心跳时间","D0",1 , 1 )); + add(new Res_PLCADDRESS("外置仓正转1","D1",1 , 1 )); + add(new Res_PLCADDRESS("外置仓正转2","D2",1 , 1 )); + add(new Res_PLCADDRESS("外置仓正转3","D3",1 , 1 )); + add(new Res_PLCADDRESS("外置仓正转4","D4",1 , 1 )); + add(new Res_PLCADDRESS("外置仓正转5","D5",1 , 1 )); + add(new Res_PLCADDRESS("外置仓正转6","D6",1 , 1 )); + add(new Res_PLCADDRESS("加热仓正转1","D7",1 , 1 )); + add(new Res_PLCADDRESS("加热仓正转2","D8",1 , 1 )); + add(new Res_PLCADDRESS("外置仓反转1","D9",1 , 1 )); + add(new Res_PLCADDRESS("外置仓反转2","D10",1 , 1 )); + add(new Res_PLCADDRESS("外置仓反转3","D11",1, 1)); + add(new Res_PLCADDRESS("外置仓反转4","D12",1, 1)); + add(new Res_PLCADDRESS("外置仓反转5","D13",1, 1)); + add(new Res_PLCADDRESS("外置仓反转6","D14",1, 1)); + add(new Res_PLCADDRESS("加热仓反转1","D15",1, 1)); + add(new Res_PLCADDRESS("加热仓反转2","D16",1, 1)); + add(new Res_PLCADDRESS("粉料仓1","D17",1, 1)); + add(new Res_PLCADDRESS("粉料仓2","D18",1, 1)); + add(new Res_PLCADDRESS("粉料仓3","D19",1, 1)); + add(new Res_PLCADDRESS("粉料仓4","D20",1, 1)); + add(new Res_PLCADDRESS("粉料仓5","D21",1, 1)); + add(new Res_PLCADDRESS("粉料仓6","D22",1, 1)); + add(new Res_PLCADDRESS("普通液体仓1","D23",1, 1)); + add(new Res_PLCADDRESS("普通液体仓2","D23",1, 1)); + add(new Res_PLCADDRESS("进水阀","D40",1, 1)); + add(new Res_PLCADDRESS("排水阀","D41",1, 1)); + add(new Res_PLCADDRESS("加热仓管道1","D42",1, 1)); + add(new Res_PLCADDRESS("加热仓管道2","D43",1, 1)); + add(new Res_PLCADDRESS("三色灯红","D44",1, 1)); + add(new Res_PLCADDRESS("山色灯绿","D45",1, 1)); + add(new Res_PLCADDRESS("山色灯黄","D46",1, 1)); + add(new Res_PLCADDRESS("清洗加热","D47",1, 1)); + add(new Res_PLCADDRESS("清洗温度","D85",1, 1)); + add(new Res_PLCADDRESS("按钮启动","M1",1, 1)); + add(new Res_PLCADDRESS("清洗液位","M2",1, 1)); + }}; + + + /** * Bottom 按钮 */ diff --git a/app/src/main/java/com/bonait/bnframework/common/modbus/ByteLib.java b/app/src/main/java/com/bonait/bnframework/common/modbus/ByteLib.java new file mode 100644 index 00000000..c59e70c8 --- /dev/null +++ b/app/src/main/java/com/bonait/bnframework/common/modbus/ByteLib.java @@ -0,0 +1,81 @@ +package com.bonait.bnframework.common.modbus; + +import com.bonait.bnframework.common.helper.DataFormat; + +public class ByteLib { + + public static byte[] ToBytes(short value,DataFormat df) { + byte[] b = new byte[2]; + b[0]=(byte)((value>>8)&0xff); + b[1]=(byte)((value>>0)&0xff); + return new ByteTransDataFormat().ByteTransDataFormat2(b,df,0); + } + + public static byte[] ToBytes(short[] value,DataFormat df) { + byte[] b = new byte[value.length*2]; + for (int i = 0; i < value.length; i++) + { + b[i*2]=(byte)((value[i]>>8)&0xff); + b[i*2+1]=(byte)((value[i]>>0)&0xff); + } + return new ByteTransDataFormat().ByteTransDataFormat2(b,df,0); + } + + public static byte[] ToBytes(float value,DataFormat df) { + int tempValue = Float.floatToRawIntBits(value); + byte[] b = new byte[4]; + b[0]=(byte)((tempValue>>24)&0xff); + b[1]=(byte)((tempValue>>16)&0xff); + b[2]=(byte)((tempValue>>8)&0xff); + b[3]=(byte)((tempValue>>0)&0xff); + return new ByteTransDataFormat().ByteTransDataFormat4(b,df,0); + } + + public static byte[] ToBytes(float[] value,DataFormat df) { + byte[] b = new byte[value.length*4]; + for (int i=0;i>24)&0xff); + b[i*4+1]=(byte)((tempValue>>16)&0xff); + b[i*4+2]=(byte)((tempValue>>8)&0xff); + b[i*4+3]=(byte)((tempValue>>0)&0xff); + } + return new ByteTransDataFormat().ByteTransDataFormat4(b,df,0); + } + + public static byte[] ToBytes(int value,DataFormat df) { + byte[] b = new byte[4]; + b[0]=(byte)((value>>24)&0xff); + b[1]=(byte)((value>>16)&0xff); + b[2]=(byte)((value>>8)&0xff); + b[3]=(byte)((value>>0)&0xff); + return new ByteTransDataFormat().ByteTransDataFormat4(b,df,0); + } + + public static byte[] ToBytes(int[] value,DataFormat df) { + byte[] b = new byte[value.length*4]; + for (int i=0;i>24)&0xff); + b[i*4+1]=(byte)((value[i]>>16)&0xff); + b[i*4+2]=(byte)((value[i]>>8)&0xff); + b[i*4+3]=(byte)((value[i]>>0)&0xff); + } + return new ByteTransDataFormat().ByteTransDataFormat4(b,df,0); + } + + public static boolean GetBit(byte value,int offset) + { + if (offset > 8 || offset < 1) return false; + return (value & 1 << offset - 1) == 0 ? false : true; + } + + public static byte SetBit(byte value,int offset, boolean val) + { + if (offset > 8 || offset < 1) return value; + int ConvertValue = 1 << offset - 1; + return (byte)(val ? value | ConvertValue : value & ~ConvertValue); + } +} + diff --git a/app/src/main/java/com/bonait/bnframework/common/modbus/ByteTransDataFormat.java b/app/src/main/java/com/bonait/bnframework/common/modbus/ByteTransDataFormat.java new file mode 100644 index 00000000..cc7156fc --- /dev/null +++ b/app/src/main/java/com/bonait/bnframework/common/modbus/ByteTransDataFormat.java @@ -0,0 +1,49 @@ +package com.bonait.bnframework.common.modbus; + +import com.bonait.bnframework.common.helper.DataFormat; + +public class ByteTransDataFormat { + public byte[] ByteTransDataFormat2(byte[] data, DataFormat df,int offset ){ + if (offset+2<2) return new byte[2]; + byte[] numArray = new byte[2]; + if (df==DataFormat.ABCD||df==DataFormat.BADC){ + numArray[0] = data[offset+1]; + numArray[1] = data[offset]; + } + else { + numArray[0] = data[offset]; + numArray[1] = data[offset+1]; + } + return numArray; + } + + public byte[] ByteTransDataFormat4(byte[] data, DataFormat df,int offset ){ + if (offset+4<4) return new byte[4]; + byte[] numArray = new byte[4]; + if (df==DataFormat.ABCD){ + numArray[0] = data[offset+3]; + numArray[1] = data[offset+2]; + numArray[2] = data[offset+1]; + numArray[3] = data[offset]; + } + else if (df==DataFormat.BADC){ + numArray[0] = data[offset+2]; + numArray[1] = data[offset+3]; + numArray[2] = data[offset]; + numArray[3] = data[offset+1]; + } + else if(df==DataFormat.CDAB){ + numArray[0] = data[offset+1]; + numArray[1] = data[offset]; + numArray[2] = data[offset+3]; + numArray[3] = data[offset+2]; + } + else if(df==DataFormat.DCBA){ + numArray[0] = data[offset]; + numArray[1] = data[offset+1]; + numArray[2] = data[offset+2]; + numArray[3] = data[offset+3]; + } + return numArray; + } +} diff --git a/app/src/main/java/com/bonait/bnframework/common/modbus/DataConvertLib.java b/app/src/main/java/com/bonait/bnframework/common/modbus/DataConvertLib.java new file mode 100644 index 00000000..83cdcc57 --- /dev/null +++ b/app/src/main/java/com/bonait/bnframework/common/modbus/DataConvertLib.java @@ -0,0 +1,232 @@ +package com.bonait.bnframework.common.modbus; + +import com.bonait.bnframework.common.helper.ByteHelper; +import com.bonait.bnframework.common.helper.DataFormat; + +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; + +public class DataConvertLib { + + /*** + * 字节数组转换成浮点数 + * @param ,需要转换的字节 + * @param ,转换的数据格式 + * @return + */ + public static 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; + } + + /** + * 字节数组转换成整形 + * @param ,需要转换的字节数组 + * @param ,转换的数据格式 + * @return + */ + public static 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; + } + + /** + * 32位整数转换成字节 + * @param ,number + * @return + */ + public static 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; + } + + /** + * 32位整形转换成16位整数数组 + * @param ,value + * @return + */ + public static 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 short[] ByteToShort(byte[] bytes) { + + int len=bytes.length; + if (bytes.length%2!=0) len++; + byte[] tempBytes=new byte[len]; + short[] result = new short[len/2]; + for (int i=0;i> 8); + } + return byteValue; + } + + public static 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 static 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 ""; + } + +} diff --git a/app/src/main/java/com/bonait/bnframework/common/modbus/ExceptionServer.java b/app/src/main/java/com/bonait/bnframework/common/modbus/ExceptionServer.java new file mode 100644 index 00000000..c9f41879 --- /dev/null +++ b/app/src/main/java/com/bonait/bnframework/common/modbus/ExceptionServer.java @@ -0,0 +1,40 @@ +package com.bonait.bnframework.common.modbus; + +import static com.bonait.bnframework.common.modbus.DataConvertLib.GetAddress; + +import com.bonait.bnframework.common.helper.MessageLog; +import com.licheedev.modbus4android.ModbusRespException; +import com.serotonin.modbus4j.exception.ModbusInitException; +import com.serotonin.modbus4j.exception.ModbusTransportException; +import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse; + +import java.util.concurrent.ExecutionException; + +public class ExceptionServer { + public ExceptionServer(String Address, int length,IExceptionHandling excpet) + { + try { + int add = GetAddress(Address); + if (add < 0) { + MessageLog.ShowError("地址解析失败=" + Address); + return; + } + if (excpet!=null) excpet.onSuccess(add); + } catch (InterruptedException e) { + MessageLog.ShowError("onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); + if (excpet!=null) excpet.onFailure(e.toString()); + } catch (ExecutionException e) { + MessageLog.ShowError("onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); + if (excpet!=null) excpet.onFailure(e.toString()); + } catch (ModbusTransportException e) { + MessageLog.ShowError("onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); + if (excpet!=null) excpet.onFailure(e.toString()); + } catch (ModbusInitException e) { + MessageLog.ShowError("onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); + if (excpet!=null) excpet.onFailure(e.toString()); + } catch (ModbusRespException e) { + MessageLog.ShowError("onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); + if (excpet!=null) excpet.onFailure(e.toString()); + } + } +} diff --git a/app/src/main/java/com/bonait/bnframework/common/modbus/FloatLib.java b/app/src/main/java/com/bonait/bnframework/common/modbus/FloatLib.java new file mode 100644 index 00000000..c456b130 --- /dev/null +++ b/app/src/main/java/com/bonait/bnframework/common/modbus/FloatLib.java @@ -0,0 +1,28 @@ +package com.bonait.bnframework.common.modbus; + +import com.bonait.bnframework.common.helper.DataFormat; + +import java.nio.ByteBuffer; + +public class FloatLib { + public static float ToFloat(byte[] bytes, DataFormat df) { + byte[] res= new ByteTransDataFormat().ByteTransDataFormat4(bytes,df,0); + return ByteBuffer.wrap(res).getFloat(); + } + + public static float[] ToFloats(byte[] bytes, DataFormat df) { + byte[] tempBytes=new byte[bytes.length]; + if (bytes.length%4!=0) + { + int offset=4-bytes.length%4; + tempBytes=new byte[bytes.length+offset]; + } + for (int i=0;i { + void onSuccess(T par); + + void onFailure(String message); + + void onFinally(); +} diff --git a/app/src/main/java/com/bonait/bnframework/common/modbus/IRead.java b/app/src/main/java/com/bonait/bnframework/common/modbus/IRead.java new file mode 100644 index 00000000..7770fa52 --- /dev/null +++ b/app/src/main/java/com/bonait/bnframework/common/modbus/IRead.java @@ -0,0 +1,23 @@ +package com.bonait.bnframework.common.modbus; + +import com.bonait.bnframework.common.helper.DataFormat; +import com.bonait.bnframework.common.helper.I.IReadCallBack; + +import kotlin.UInt; +import kotlin.UShort; + +public interface IRead { + void ReadBool(String address, int length, int slaveId, IReadCallBack callback); + + void ReadShort(String address, int length,int slaveId, IReadCallBack callback); + + void ReadInt(String address, int length, int slaveId,DataFormat df, IReadCallBack callback); + void ReadInt(String address, int length, int slaveId, IReadCallBack callback); + + void ReadByte(String address, int length, int slaveId, IReadCallBack callback); + + void ReadString(String address, int length, int slaveId, IReadCallBack callback); + + void ReadFloat(String address, int length, int slaveId,DataFormat df, IReadCallBack callback); + void ReadFloat(String address, int length, int slaveId, IReadCallBack callback); +} diff --git a/app/src/main/java/com/bonait/bnframework/common/modbus/IWrite.java b/app/src/main/java/com/bonait/bnframework/common/modbus/IWrite.java new file mode 100644 index 00000000..7b05de40 --- /dev/null +++ b/app/src/main/java/com/bonait/bnframework/common/modbus/IWrite.java @@ -0,0 +1,25 @@ +package com.bonait.bnframework.common.modbus; + +import com.bonait.bnframework.common.helper.DataFormat; +import com.bonait.bnframework.common.helper.I.IReadCallBack; +import com.bonait.bnframework.common.helper.I.IWriteCallBack; + +import kotlin.UInt; +import kotlin.UShort; + +public interface IWrite { + void WriteBool(String address, boolean value, int slaveId, IWriteCallBack callback); + void WriteBool(String address, boolean[] value, int slaveId, IWriteCallBack callback); + + void WriteShort(String address, short value, int slaveId, IWriteCallBack callback); + void WriteShort(String address, short[] value, int slaveId, IWriteCallBack callback); + + void WriteInt(String address, int value, int slaveId, IWriteCallBack callback); + void WriteInt(String address, int[] value, int slaveId, IWriteCallBack callback); + + void WriteString(String address, String value, int slaveId, IWriteCallBack callback); + + void WriteFloat(String address, float value, int slaveId, IWriteCallBack callback); + void WriteFloat(String address, float[] value, int slaveId, IWriteCallBack callback); + +} diff --git a/app/src/main/java/com/bonait/bnframework/common/modbus/IntLib.java b/app/src/main/java/com/bonait/bnframework/common/modbus/IntLib.java new file mode 100644 index 00000000..0342e421 --- /dev/null +++ b/app/src/main/java/com/bonait/bnframework/common/modbus/IntLib.java @@ -0,0 +1,48 @@ +package com.bonait.bnframework.common.modbus; + +import com.bonait.bnframework.common.helper.DataFormat; + +import java.nio.ByteBuffer; + +public class IntLib { + public static int ToInt(byte[] bytes, DataFormat df) { + byte[] res= new ByteTransDataFormat().ByteTransDataFormat4(bytes,df,0); + return ByteBuffer.wrap(res).getInt(); + } + + public static int ToInt(short[] shorts, DataFormat df) { + if (shorts.length<2) return 0; + byte[] bytes= ByteLib.ToBytes(shorts,df); + if (bytes.length!=4) return 0; + return ByteBuffer.wrap(bytes).getInt(); + } + + public static int[] ToInts(byte[] bytes, DataFormat df) { + byte[] tempBytes=new byte[bytes.length]; + if (bytes.length%4!=0) + { + int offset=4-bytes.length%4; + tempBytes=new byte[bytes.length+offset]; + } + for (int i=0;i 32 || offset < 1) return false; + return (value & 1 << offset - 1) == 0 ? false : true; + } + + public static int SetBit(int value,int offset, boolean val) + { + if (offset > 32 || offset < 1) return value; + int ConvertValue =1 << offset - 1; + return val ? value | ConvertValue : value & ~ConvertValue; + } +} diff --git a/app/src/main/java/com/bonait/bnframework/common/modbus/ModbusTcpHelper.java b/app/src/main/java/com/bonait/bnframework/common/modbus/ModbusBasis.java similarity index 67% rename from app/src/main/java/com/bonait/bnframework/common/modbus/ModbusTcpHelper.java rename to app/src/main/java/com/bonait/bnframework/common/modbus/ModbusBasis.java index 47e0bea5..95588d2c 100644 --- a/app/src/main/java/com/bonait/bnframework/common/modbus/ModbusTcpHelper.java +++ b/app/src/main/java/com/bonait/bnframework/common/modbus/ModbusBasis.java @@ -4,16 +4,16 @@ import com.licheedev.modbus4android.ModbusWorker; import com.serotonin.modbus4j.ModbusMaster; -public class ModbusTcpHelper extends ModbusWorker { - private static volatile ModbusTcpHelper instance = null; +public class ModbusBasis extends ModbusWorker { + private static volatile ModbusBasis instance = null; - public static ModbusTcpHelper get() { - ModbusTcpHelper manager = instance; + public static ModbusBasis get() { + ModbusBasis manager = instance; if (manager == null) { - synchronized (ModbusTcpHelper.class) { + synchronized (ModbusBasis.class) { manager = instance; if (manager == null) { - manager = new ModbusTcpHelper(); + manager = new ModbusBasis(); instance = manager; } } @@ -21,7 +21,7 @@ public class ModbusTcpHelper extends ModbusWorker { return manager; } - private ModbusTcpHelper() { + private ModbusBasis() { } /** diff --git a/app/src/main/java/com/bonait/bnframework/common/modbus/ModbusClient.java b/app/src/main/java/com/bonait/bnframework/common/modbus/ModbusClient.java new file mode 100644 index 00000000..bbd5f11e --- /dev/null +++ b/app/src/main/java/com/bonait/bnframework/common/modbus/ModbusClient.java @@ -0,0 +1,593 @@ +package com.bonait.bnframework.common.modbus; + + +import static com.bonait.bnframework.common.modbus.DataConvertLib.BytesToFloat; +import static com.bonait.bnframework.common.modbus.DataConvertLib.BytesToInt; +import static com.bonait.bnframework.common.modbus.DataConvertLib.GetAddress; +import static com.bonait.bnframework.common.modbus.DataConvertLib.IntToShorts; + +import com.bonait.bnframework.business.ConfigData; +import com.bonait.bnframework.common.constant.ConfigName; +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 ModbusClient { + private static volatile ModbusClient instance = null; + public static ModbusClient get() { + ModbusClient manager = instance; + if (manager == null) { + synchronized (ModbusClient.class) { + manager = instance; + if (manager == null) { + manager = new ModbusClient(); + instance = manager; + } + } + } + return manager; + } + private ModbusClient() { + } + + static ModbusParam param; + + + + + + /** + * 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; +// +// } +// +// +// /** +// * 连接 +// */ +// public void Connect() throws InterruptedException { +// boolean status = false; +// while (!status) { +// try { +// //status为0则代表通,为1则代表不通。 +// status =ping2(ConfigName.getInstance().Address,1,1); +// Thread.sleep(1000); +// } catch (InterruptedException e) { +// MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " 网络验证失败"); +// } catch (Exception e) { +// MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " 网络验证失败"); +// } +// } +// MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " PLC通讯正常,准备连接!"); +// +// while (ConfigName.getInstance().PlcIsConnect==false) +// { +// ConnectPLC(); +// Thread.sleep(5000); +// } +// } +// +// /** +// * 连接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); +// ModbusBasis.get().init(param, new ModbusCallback() { +// @Override +// public void onSuccess(ModbusMaster modbusMaster) { +// ToastUtils.info("设备 " + ConfigName.getInstance().Address + " 连接成功"); +// +// MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " 连接成功"); +// ConfigName.getInstance().PlcIsConnect = true; +// ConfigData.getInstance().PLC_Init(); +// } +// +// @Override +// public void onFailure(Throwable tr) { +// ConfigName.getInstance().PlcIsConnect = false; +// ToastUtils.info("设备 " + ConfigName.getInstance().Address + " 连接失败:" + tr.getMessage()); +// MessageLog.ShowError("设备 " + ConfigName.getInstance().Address + " 连接失败:" + tr.getMessage()); +// } +// @Override +// public void onFinally() { +// +// } +// }); +// } +// +// /*** +// *读取实时状态 +// * @param Address the address +// * @param length 读取的长度 3 +// * @param callback 读取成功的回调 +// */ +// public void ReadStatus(String Address, int length, IReadCallBack callback) { +// int add = GetAddress(Address); +// if (add < 0) return; +// try { +// ReadHoldingRegistersResponse res = ModbusBasis.get().syncReadHoldingRegisters(1, add, length); +// byte[] data = res.getData(); +// byte[] tempData = new byte[8]; +// tempData[0] = data[1]; +// tempData[1] = data[0]; +// tempData[2] = data[3]; +// tempData[3] = data[2]; +// tempData[4] = data[5]; +// tempData[5] = data[4]; +// tempData[6] = data[7]; +// tempData[7] = data[6]; +// 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 +// * @param length +// * @param callback +// */ +// public void ReadbcStatus(String Address, int length, IReadCallBack callback) { +// int add = GetAddress(Address); +// if (add < 0) return; +// new ExceptionServer(Address, length, new IExceptionHandling() { +// @Override +// public void HandleException() throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { +// ReadHoldingRegistersResponse res = ModbusBasis.get().syncReadHoldingRegisters(1, add, length); +// byte[] data = res.getData(); +// byte[] tempData = new byte[1]; +// tempData[0] = data[1]; +// if (callback != null) callback.onSuccess(tempData); +// } +// }); +// } +// +// +// /*** +// *读取扫码数据 +// * @param Address the address +// * @param length 读取的长度 +// * @param callback 读取成功的回调 +// */ +// public void ReadString(String Address, int length, IReadCallBack callback) { +// int add = GetAddress(Address); +// if (add < 0) return; +// try { +// ReadHoldingRegistersResponse res = ModbusBasis.get().syncReadHoldingRegisters(1, add, length); +// byte[] data = res.getData(); +// byte[] data1 = Arrays.copyOfRange(data, 0, data.length); +// //36 GUID 18 Number +// String id = ""; +// try { +// byte[] tempdata = new byte[data.length]; +// int index=0; +// for (int i = 0; i < data1.length; i++) { +// if (i % 2 == 0) { +// +// tempdata[i + 1] = data1[i]; +// } else { +// tempdata[i - 1] = data1[i]; +// } +// +// if (data1[i]==0 && index==0) +// { +// index=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 { +// ModbusBasis.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 callback) { +// int add = GetAddress(Address); +// if (add < 0) return; +// try { +// ReadHoldingRegistersResponse res = ModbusBasis.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 callback) { +// int add = GetAddress(Address); +// if (add < 0) return; +// try { +// ReadCoilsResponse res = ModbusBasis.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 callback) { +// int add = GetAddress(Address); +// if (add < 0) return; +// try { +// ReadHoldingRegistersResponse res = ModbusBasis.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 callback) { +// int add = GetAddress(Address); +// if (add < 0) return; +// try { +// ReadHoldingRegistersResponse res = ModbusBasis.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 { +// ModbusBasis.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 { +// ModbusBasis.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); +// try { +// ModbusBasis.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 { +// ModbusBasis.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 { +// ModbusBasis.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 { +// ModbusBasis.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 { +// ModbusBasis.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 { +// ModbusBasis.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()); +// } +// } + +} diff --git a/app/src/main/java/com/bonait/bnframework/common/modbus/ModbusMaster.java b/app/src/main/java/com/bonait/bnframework/common/modbus/ModbusMaster.java new file mode 100644 index 00000000..d7089010 --- /dev/null +++ b/app/src/main/java/com/bonait/bnframework/common/modbus/ModbusMaster.java @@ -0,0 +1,584 @@ +package com.bonait.bnframework.common.modbus; + +import static com.bonait.bnframework.common.modbus.DataConvertLib.ByteToShort; +import static com.bonait.bnframework.common.modbus.DataConvertLib.BytesToFloat; +import static com.bonait.bnframework.common.modbus.DataConvertLib.BytesToInt; +import static com.bonait.bnframework.common.modbus.DataConvertLib.GetAddress; +import static com.bonait.bnframework.common.modbus.DataConvertLib.IntToShorts; + +import android.util.Log; + +import com.bonait.bnframework.business.ConfigData; +import com.bonait.bnframework.common.constant.ConfigName; +import com.bonait.bnframework.common.helper.DataFormat; +import com.bonait.bnframework.common.helper.I.IReadCallBack; +import com.bonait.bnframework.common.helper.I.IRun; +import com.bonait.bnframework.common.helper.I.IThread; +import com.bonait.bnframework.common.helper.I.IWriteCallBack; +import com.bonait.bnframework.common.helper.MessageLog; +import com.bonait.bnframework.common.helper.ThreadManager; +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.SerialParam; +import com.licheedev.modbus4android.param.TcpParam; +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.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.ExecutionException; + +import kotlin.UInt; +import kotlin.UShort; + +public class ModbusMaster implements IRead,IWrite,IModbusMaster { + + private static volatile ModbusMaster instance = null; + public static ModbusMaster get() { + ModbusMaster manager = instance; + if (manager == null) { + synchronized (ModbusMaster.class) { + manager = instance; + if (manager == null) { + manager = new ModbusMaster(); + instance = manager; + } + } + } + return manager; + } + private ModbusMaster() { + } + + /** + * Ping PLC地址是否通畅 + * @param address + * @param pingTimes ping的次数 + * @param timeOut 超时时间 10 + * @return + */ + private 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; + + } + + public boolean IsConnected=false; + + /** + * TCP 连接,连接时请用多线程的方式,否者有可能无法连接 + * @param ip + * @param port + * @param result + * @throws InterruptedException + */ + @Override + public void TcpConnect(String ip, int port, IOperateResult result)throws InterruptedException { + MessageLog.ShowInfo("开始验证网络:"+ip ); + boolean status = false; + while (!status) { + try { + //status为0则代表通,为1则代表不通。 + status =ping2(ip,1,1); + Thread.sleep(1000); + } catch (InterruptedException e) { + MessageLog.ShowInfo("设备 " + ip + " 网络验证失败"); + } catch (Exception e) { + MessageLog.ShowInfo("设备 " + ip + " 网络验证失败"); + } + } + MessageLog.ShowInfo("设备 " + ip + " 网络验证成功"); + ModbusParam param= TcpParam.create(ip, port) + .setTimeout(1000) + .setRetries(0) + .setEncapsulated(false) + .setKeepAlive(true); + while (IsConnected==false) + { + MessageLog.ShowInfo("Modbus TCP 1111" ); + ModbusBasis.get().init(param, new ModbusCallback() { + @Override + public void onSuccess(com.serotonin.modbus4j.ModbusMaster modbusMaster) { + IsConnected=true; + if(result!=null) result.onSuccess(); + MessageLog.ShowInfo("Modbus TCP 连接成功" ); + } + @Override + public void onFailure(Throwable tr) { + IsConnected = false; + if(result!=null) result.onFailure(tr.getMessage()); + MessageLog.ShowInfo("Modbus TCP 连接失败" ); + } + @Override + public void onFinally() { + if(result!=null) result.onFinally(); + } + }); + if(IsConnected==false) Thread.sleep(5000); + } + } + + /** + * RTU 串口连接,建议连接时用多线程的方式,否者有可能无法连接 + * @param com + * @param baudRate + * @param result + * @throws InterruptedException + */ + @Override + public void RtuConnect(String com, int baudRate, IOperateResult result)throws InterruptedException { + MessageLog.ShowInfo("开始连接Modbus RTU" ); + ModbusParam param=SerialParam.create(com, baudRate) // 串口地址和波特率 + .setDataBits(8) // 数据位 + .setParity(0) // 校验位 + .setStopBits(1) // 停止位 + .setTimeout(500).setRetries(0); // 不重试 + while (IsConnected==false) + { + ModbusBasis.get().init(param, new ModbusCallback() { + @Override + public void onSuccess(com.serotonin.modbus4j.ModbusMaster modbusMaster) { + IsConnected=true; + if(result!=null) result.onSuccess(); + MessageLog.ShowInfo("Modbus RTU 连接成功" ); + } + @Override + public void onFailure(Throwable tr) { + IsConnected = false; + if(result!=null) result.onFailure(tr.getMessage()); + MessageLog.ShowInfo("Modbus RTU 连接失败" ); + } + @Override + public void onFinally() { + if(result!=null) result.onFinally(); + } + }); + if(IsConnected==false) Thread.sleep(5000); + } + } + + @Override + public void ReadBool(String address, int length, int slaveId, IReadCallBack callback) { + if (!IsConnected) { + return; + } + new ExceptionServer(address, length, new IExceptionHandling() { + @Override + public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { + ReadCoilsResponse res = ModbusBasis.get().syncReadCoil(slaveId, add, length); + boolean[] data = res.getBooleanData(); + boolean[] result = Arrays.copyOfRange(data, 0, length); + if (callback != null) callback.onSuccess(result); + } + + @Override + public void onFailure(String error){ + } + }); + } + + @Override + public void ReadShort(String address, int length,int slaveId, IReadCallBack callback) { + if (!IsConnected) { + return; + } + new ExceptionServer(address, length, new IExceptionHandling() { + @Override + public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { + ReadHoldingRegistersResponse res = ModbusBasis.get().syncReadHoldingRegisters(slaveId, add, length); + short[] data = res.getShortData(); + if (data.length == length) { + if (callback != null) callback.onSuccess(data); + } + } + + @Override + public void onFailure(String error){ + + } + }); + } + + @Override + public void ReadInt(String address, int length, int slaveId, DataFormat df, IReadCallBack callback) { + if (!IsConnected) { + return; + } + new ExceptionServer(address, length, new IExceptionHandling() { + @Override + public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { + ReadHoldingRegistersResponse res = ModbusBasis.get().syncReadHoldingRegisters(slaveId, add, length * 2); + byte[] data = res.getData(); + int[] tempValues = new int[length]; + if(data.length==4*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] = BytesToInt(tempData, df); + } + if (callback != null) callback.onSuccess(tempValues); + }else{ + MessageLog.ShowError("ReadInt onFailure,数据长度不匹配,读取长度:"+length+"返回长度:"+data.length ); + } + } + + @Override + public void onFailure(String error){ + + } + }); + } + + @Override + public void ReadInt(String address, int length, int slaveId, IReadCallBack callback) { + if (!IsConnected) { + return; + } + ReadInt(address, length, slaveId,DataFormat.BADC, callback); + } + + @Override + public void ReadByte(String address, int length, int slaveId, IReadCallBack callback) { + if (!IsConnected) { + return; + } + new ExceptionServer(address, length, new IExceptionHandling() { + @Override + public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { + int tempLength=length; + if (length%2!=0){ + tempLength++; + } + ReadHoldingRegistersResponse res = ModbusBasis.get().syncReadHoldingRegisters(slaveId, add, tempLength ); + byte[] data = res.getData(); + if(data.length==tempLength) + { + byte[] result = Arrays.copyOfRange(data, 0, length); + if (callback != null) callback.onSuccess(result); + }else + { + MessageLog.ShowError("ReadInt onFailure,数据长度不匹配,读取长度:"+length+"返回长度:"+data.length ); + } + } + + @Override + public void onFailure(String error){ + + } + }); + } + + @Override + public void ReadString(String address, int length, int slaveId, IReadCallBack callback) { + if (!IsConnected) { + return; + } + new ExceptionServer(address, length, new IExceptionHandling() { + @Override + public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { + ReadHoldingRegistersResponse res = ModbusBasis.get().syncReadHoldingRegisters(slaveId, add, length); + byte[] data = res.getData(); + try { + if (data.length ==length*2) { + if (callback != null) callback.onSuccess(new String(data, "UTF-8").trim()); + } + } catch (UnsupportedEncodingException ex) { + } + } + + @Override + public void onFailure(String error){ + + } + }); + } + + @Override + public void ReadFloat(String address, int length, int slaveId, DataFormat df, IReadCallBack callback) { + if (!IsConnected) { + return; + } + new ExceptionServer(address, length, new IExceptionHandling() { + @Override + public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { + ReadHoldingRegistersResponse res = ModbusBasis.get().syncReadHoldingRegisters(slaveId, 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, df); + } + if (tempValues.length == length) { + if (callback != null) callback.onSuccess(tempValues); + } + } + + @Override + public void onFailure(String error){ + + } + }); + } + + @Override + public void ReadFloat(String address, int length, int slaveId, IReadCallBack callback) { + if (!IsConnected) { + return; + } + ReadFloat(address,length,slaveId,DataFormat.BADC,callback); + } + + + + + @Override + public void WriteBool(String address, boolean value, int slaveId, IWriteCallBack callback) { + if (!IsConnected) { + if (callback != null) callback.onFailure("设备未连接"); + return; + } + new ExceptionServer(address, 1, new IExceptionHandling() { + @Override + public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { + ModbusBasis.get().syncWriteCoil(slaveId, add, value); + if (callback != null)callback.onSuccess(); + } + + @Override + public void onFailure(String error){ + if (callback != null)callback.onFailure(error); + } + }); + } + + @Override + public void WriteBool(String address, boolean[] value, int slaveId, IWriteCallBack callback) { + if (!IsConnected) { + if (callback != null) callback.onFailure("设备未连接"); + return; + } + new ExceptionServer(address, 1, new IExceptionHandling() { + @Override + public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { + ModbusBasis.get().syncWriteCoils(slaveId, add, value); + if (callback != null)callback.onSuccess(); + } + + @Override + public void onFailure(String error){ + if (callback != null)callback.onFailure(error); + } + }); + } + + @Override + public void WriteShort(String address, short value, int slaveId, IWriteCallBack callback) { + if (!IsConnected) { + if (callback != null) callback.onFailure("设备未连接"); + return; + } + new ExceptionServer(address, 1, new IExceptionHandling() { + @Override + public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { + short[] send = new short[1]; + send[0] = value; + ModbusBasis.get().syncWriteRegisters(slaveId, add, send); + if (callback != null)callback.onSuccess(); + } + + @Override + public void onFailure(String error){ + if (callback != null)callback.onFailure(error); + } + }); + } + + @Override + public void WriteShort(String address, short[] value, int slaveId, IWriteCallBack callback) { + if (!IsConnected) { + if (callback != null) callback.onFailure("设备未连接"); + return; + } + new ExceptionServer(address, 1, new IExceptionHandling() { + @Override + public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { + ModbusBasis.get().syncWriteRegisters(slaveId, add, value); + if (callback != null)callback.onSuccess(); + } + + @Override + public void onFailure(String error){ + if (callback != null)callback.onFailure(error); + } + }); + } + + @Override + public void WriteInt(String address, int value, int slaveId, IWriteCallBack callback) { + if (!IsConnected) { + if (callback != null) callback.onFailure("设备未连接"); + return; + } + new ExceptionServer(address, 1, new IExceptionHandling() { + @Override + public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { + short[] send = IntToShorts(value); + ModbusBasis.get().syncWriteRegisters(slaveId, add, send); + if (callback != null) callback.onSuccess(); + } + + @Override + public void onFailure(String error){ + if (callback != null)callback.onFailure(error); + } + }); + } + + @Override + public void WriteInt(String address, int[] value, int slaveId, IWriteCallBack callback) { + if (!IsConnected) { + if (callback != null) callback.onFailure("设备未连接"); + return; + } + new ExceptionServer(address, 1, new IExceptionHandling() { + @Override + public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { + short[] send=new short[value.length*2]; + for(int i=0;i 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; - - } - - - /** - * 连接 - */ - public void Connect() throws InterruptedException { - boolean status = false; - while (!status) { - try { - //status为0则代表通,为1则代表不通。 - status =ping2(ConfigName.getInstance().Address,1,1); - Thread.sleep(1000); - } catch (InterruptedException e) { - MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " 网络验证失败"); - } catch (Exception e) { - MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " 网络验证失败"); - } - } - MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " PLC通讯正常,准备连接!"); - - while (ConfigName.getInstance().PlcIsConnect==false) - { - ConnectPLC(); - Thread.sleep(5000); - } - } - - /** - * 连接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() { - @Override - public void onSuccess(ModbusMaster modbusMaster) { - ToastUtils.info("设备 " + ConfigName.getInstance().Address + " 连接成功"); - - MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " 连接成功"); - ConfigName.getInstance().PlcIsConnect = true; - ConfigData.getInstance().PLC_Init(); - } - - @Override - public void onFailure(Throwable tr) { - ConfigName.getInstance().PlcIsConnect = false; - ToastUtils.info("设备 " + ConfigName.getInstance().Address + " 连接失败:" + tr.getMessage()); - MessageLog.ShowError("设备 " + ConfigName.getInstance().Address + " 连接失败:" + tr.getMessage()); - } - @Override - public void onFinally() { - - } - }); - } - -// /** -// * 重新连接Modbus -// */ -// public void ReconnectModbus() -// { -// try { -// -// ThreadManager.Get().StartLong("PLC断线重连线程", true, new IThread() { -// @Override -// public void Run() throws InterruptedException { -// try { -// boolean status =ping2(ConfigName.getInstance().Address,1,1); -// if(status) -// { -// ModbusMaster master= ModbusTcpHelper.get().getModbusMaster(); -// if (master==null || master.isConnected() == false) { -// ConnectPLC(); -// } -// Thread.sleep(20000); -// } -// } catch (Exception e) { -// Log.i("PLC", "PLC重连接失败!"+e.getMessage()); -// } -// } -// @Override -// public void RunComplete() throws InterruptedException { -// } -// }); -// }catch (Exception e) { -// MessageLog.ShowInfo("重新连接Modbus异常," +e.getMessage()); -// } -// } - - 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 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[8]; - tempData[0] = data[1]; - tempData[1] = data[0]; - tempData[2] = data[3]; - tempData[3] = data[2]; - tempData[4] = data[5]; - tempData[5] = data[4]; - tempData[6] = data[7]; - tempData[7] = data[6]; - 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 - * @param length - * @param callback - */ - public void ReadbcStatus(String Address, int length, IReadCallBack 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[1]; - tempData[0] = data[1]; - 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 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, data.length); - //36 GUID 18 Number - String id = ""; - try { - byte[] tempdata = new byte[data.length]; - int index=0; - for (int i = 0; i < data1.length; i++) { - if (i % 2 == 0) { - - tempdata[i + 1] = data1[i]; - } else { - tempdata[i - 1] = data1[i]; - } - - if (data1[i]==0 && index==0) - { - index=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 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 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 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 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); - 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()); - } - } - -} diff --git a/app/src/main/java/com/bonait/bnframework/common/modbus/ShortLib.java b/app/src/main/java/com/bonait/bnframework/common/modbus/ShortLib.java new file mode 100644 index 00000000..f04d57bf --- /dev/null +++ b/app/src/main/java/com/bonait/bnframework/common/modbus/ShortLib.java @@ -0,0 +1,38 @@ +package com.bonait.bnframework.common.modbus; + +import com.bonait.bnframework.common.helper.DataFormat; + +import java.nio.ByteBuffer; + +public class ShortLib { + public static short ToShort(byte[] bytes, DataFormat df) { + byte[] res= new ByteTransDataFormat().ByteTransDataFormat2(bytes,df,0); + short result= ByteBuffer.wrap(res).getShort(); + return result; + } + + public static short[] ToShorts(byte[] bytes, DataFormat df) { + byte[] tempBytes=new byte[bytes.length]; + if (bytes.length%2!=0){ tempBytes=new byte[bytes.length+1]; } + for (int i=0; i 16 || offset < 1) return false; + return (value & 1 << offset - 1) == 0 ? false : true; + } + + public static short SetBit(short value,int offset, boolean val) + { + if (offset > 16 || offset < 1) return value; + short ConvertValue = (short)(1 << offset - 1); + return (short)(val ? value | ConvertValue : value & ~ConvertValue); + } +} diff --git a/app/src/main/java/com/bonait/bnframework/common/serialport/SerialPortHelper.java b/app/src/main/java/com/bonait/bnframework/common/serialport/SerialPortHelper.java new file mode 100644 index 00000000..df31bcdc --- /dev/null +++ b/app/src/main/java/com/bonait/bnframework/common/serialport/SerialPortHelper.java @@ -0,0 +1,25 @@ +package com.bonait.bnframework.common.serialport; + + +public class SerialPortHelper { + private SerialPortManager serialPortManager; + public void Open(){ + serialPortManager = new SerialPortManager("/dev/ttyS0", 9600); + serialPortManager.setOnSerialPortDataListener(new SerialPortManager.OnSerialPortDataListener() { + @Override + public void onDataReceived(byte[] buffer, int size) { + + //接收数据处理 +// for (int i = 0; i < size; i += 3) { +// if ((int) (buffer[i] & 0xff) == 0xAA && (int) (buffer[i + 2] & 0xff) == 0xCC) { +// int ChannelNum = (int) buffer[i + 1]; +// if (!CompleteStatus.containsKey(ChannelNum)) +// CompleteStatus.put(ChannelNum, new CompleteStatusModel()); +// CompleteStatus.get(ChannelNum).Status = true; +// ShowLog("通道:" + ChannelNum + " 配料完成"); +// } +// } + } + }); + } +} diff --git a/app/src/main/java/com/bonait/bnframework/common/serialport/SerialPortManager.java b/app/src/main/java/com/bonait/bnframework/common/serialport/SerialPortManager.java new file mode 100644 index 00000000..53ba25fd --- /dev/null +++ b/app/src/main/java/com/bonait/bnframework/common/serialport/SerialPortManager.java @@ -0,0 +1,149 @@ +package com.bonait.bnframework.common.serialport; + +import android.serialport.SerialPort; +import android.util.Log; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +public class SerialPortManager { + private static final String TAG = SerialPortManager.class.getSimpleName(); + + /** + * 串口,默认的8n1 + * + * @param devicePath 串口设备文件 + * @param baudrate 波特率 + * @throws SecurityException + * @throws IOException + */ + public SerialPortManager(String devicePath, int baudrate) { + this(devicePath, baudrate, 8, 0, 1, 0); + } + + /** + * 串口 + * + * @param devicePath 串口设备文件 + * @param baudrate 波特率 + * @param dataBits 数据位;默认8,可选值为5~8 + * @param parity 奇偶校验;0:无校验位(NONE,默认);1:奇校验位(ODD);2:偶校验位(EVEN) + * @param stopBits 停止位;默认1;1:1位停止位;2:2位停止位 + * @throws SecurityException + * @throws IOException + */ + public SerialPortManager(String devicePath, int baudrate, int dataBits, int parity, int stopBits) { + this(devicePath, baudrate, dataBits, parity, stopBits, 0); + } + + /** + * 串口 + * + * @param devicePath 串口设备文件 + * @param baudrate 波特率 + * @param dataBits 数据位;默认8,可选值为5~8 + * @param parity 奇偶校验;0:无校验位(NONE,默认);1:奇校验位(ODD);2:偶校验位(EVEN) + * @param stopBits 停止位;默认1;1:1位停止位;2:2位停止位 + * @param flags 默认0 + * @throws SecurityException + * @throws IOException + */ + public SerialPortManager(String devicePath, int baudrate, int dataBits, int parity, int stopBits, int flags) { + try { + android.serialport.SerialPort serialPort = android.serialport.SerialPort // + .newBuilder(devicePath, baudrate) // 串口地址地址,波特率 + .parity(parity) // 校验位;0:无校验位(NONE,默认);1:奇校验位(ODD);2:偶校验位(EVEN) + .dataBits(dataBits) // 数据位,默认8;可选值为5~8 + .stopBits(stopBits) // 停止位,默认1;1:1位停止位;2:2位停止位 + .flags(flags) //标志位 + .build(); + mSerialPort = serialPort; + mOutputStream = mSerialPort.getOutputStream(); + mInputStream = mSerialPort.getInputStream(); + + /* Create a receiving thread */ + mReadThread = new ReadThread(); + mReadThread.start(); + } catch (Exception e) { + Log.e(TAG, "SerialPortManager初始化出错:" + e.toString()); + e.printStackTrace(); + } + + } + + private SerialPort mSerialPort = null; + protected OutputStream mOutputStream; + private InputStream mInputStream; + private ReadThread mReadThread; + + + /** + * 关闭串口 + */ + public void closeSerialPort() { + if (mReadThread != null) mReadThread.interrupt(); + if (mSerialPort != null) { + mSerialPort.close(); + mSerialPort = null; + } + } + + + /** + * 发送二进制数组 + * + * @param data + * @return + */ + public boolean send(byte[] data) { + try { + if (mOutputStream != null) { + mOutputStream.write(data); + return true; + } + } catch (IOException e) { + e.printStackTrace(); + } + return false; + } + + + OnSerialPortDataListener mOnSerialPortDataListener; + + public SerialPortManager setOnSerialPortDataListener(OnSerialPortDataListener onSerialPortDataListener) { + this.mOnSerialPortDataListener = onSerialPortDataListener; + return this; + } + + /** + * 数据监听 + */ + public interface OnSerialPortDataListener { + void onDataReceived(final byte[] buffer, final int size); + } + + /** + * 数据读取线程 + */ + private class ReadThread extends Thread { + @Override + public void run() { + super.run(); + while (!isInterrupted()) { + int size; + try { + byte[] buffer = new byte[1024 * 2]; + if (mInputStream == null) return; + size = mInputStream.read(buffer); + if (size > 0 && mOnSerialPortDataListener != null) { + mOnSerialPortDataListener.onDataReceived(buffer, size); + } + } catch (IOException e) { + e.printStackTrace(); + return; + } + } + } + } +} diff --git a/app/src/main/java/com/bonait/bnframework/deviceBusiness/DeviceAddManager.java b/app/src/main/java/com/bonait/bnframework/deviceBusiness/DeviceAddManager.java new file mode 100644 index 00000000..817c7856 --- /dev/null +++ b/app/src/main/java/com/bonait/bnframework/deviceBusiness/DeviceAddManager.java @@ -0,0 +1,117 @@ +package com.bonait.bnframework.deviceBusiness; + +public class DeviceAddManager { + + /** + * 心跳地址 + */ + public static String Heartbeat="D0"; + + /** + * 获取外置仓正转地址 + * @param ,外置仓编号 1-6 + * @return + */ + public static String GetExternalForward(int num){ + //D1--D6 + if (num<=0||num>6) return ""; + return "D"+num; + } + + /** + * 获取外置仓反转地址 + * @param ,外置仓编号,1-6 + * @return + */ + public static String GetExternalReversal(int num){ + //D9--D14 + if (num<=0||num>6) return ""; + return "D"+num+8; + } + + /** + * 获取加热仓正转地址 + * @param ,加热仓编号,1-2 + * @return + */ + public static String GetHeatForward(int num){ + //D7--D8 + if (num<=0||num>2) return ""; + return "D"+num+6; + } + + /** + * 获取加热仓反转地址 + * @param ,加热仓编号,1-2 + * @return + */ + public static String GetHeatReversal(int num){ + //D15--D16 + if (num<=0||num>2) return ""; + return "D"+num+14; + } + + /** + * 获取粉料仓地址 + * @param ,粉料仓编号,1-6 + * @return + */ + public static String GetPowder(int num){ + //D17--D22 + if (num<=0||num>6) return ""; + return "D"+num+16; + } + + /** + * 获取液体仓地址 + * @param ,液体仓编号,1-2 + * @return + */ + public static String GetLiquid(int num){ + //D23--D24 + if (num<=0||num>2) return ""; + return "D"+num+22; + } + + /** + * 获取加热仓管道地址 + * @param ,加热仓管道编号,1-2 + * @return + */ + public static String GetHeatPiping(int num){ + //D42--D43 + if (num<=0||num>2) return ""; + return "D"+num+41; + } + + /** + * 进水阀地址 + */ + public static String InletValve="D40"; + + /** + * 排水阀地址 + */ + public static String DrainValve="D41"; + + /** + * 三色红灯 + */ + public static String RedLight="D44"; + + /** + * 三色绿灯 + */ + public static String GreenLight="D45"; + + /** + * 三色黄灯 + */ + public static String YellowLight="D46"; + + /** + * 清洗加热 + */ + public static String CleanHeat="D47"; + +} diff --git a/app/src/main/java/com/bonait/bnframework/modules/home/activity/BottomNavigationMainActivity.java b/app/src/main/java/com/bonait/bnframework/modules/home/activity/BottomNavigationMainActivity.java index fe3686c0..6609e53e 100644 --- a/app/src/main/java/com/bonait/bnframework/modules/home/activity/BottomNavigationMainActivity.java +++ b/app/src/main/java/com/bonait/bnframework/modules/home/activity/BottomNavigationMainActivity.java @@ -1,33 +1,35 @@ package com.bonait.bnframework.modules.home.activity; -import androidx.annotation.NonNull; -import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.viewpager.widget.ViewPager; import android.os.Bundle; import android.util.Log; -import android.view.MenuItem; -import android.widget.RelativeLayout; import com.bonait.bnframework.R; import com.bonait.bnframework.business.ConfigData; import com.bonait.bnframework.business.OrderServer; import com.bonait.bnframework.common.base.BaseActivity; import com.bonait.bnframework.common.constant.ConfigName; +import com.bonait.bnframework.common.helper.DataFormat; import com.bonait.bnframework.common.helper.I.IThread; +import com.bonait.bnframework.common.helper.I.IWriteCallBack; import com.bonait.bnframework.common.helper.MQTT; import com.bonait.bnframework.common.helper.MediaPlayerHelper; 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.ByteLib; +import com.bonait.bnframework.common.modbus.FloatLib; +import com.bonait.bnframework.common.modbus.IOperateResult; +import com.bonait.bnframework.common.modbus.ModbusClient; +import com.bonait.bnframework.common.modbus.ModbusMaster; +import com.bonait.bnframework.common.modbus.ShortLib; import com.bonait.bnframework.common.tabbar.MainNavigateTabBar; import com.bonait.bnframework.common.utils.NetworkUtils; +import com.bonait.bnframework.common.utils.ToastUtils; import com.bonait.bnframework.modules.home.adapter.FragmentAdapter; import com.bonait.bnframework.modules.home.fragment.DingDanfragment; import com.bonait.bnframework.modules.home.fragment.GongnengFragment; -import com.bonait.bnframework.modules.home.fragment.GuanLifragment; -import com.bonait.bnframework.modules.home.fragment.JiaoYanFragment; import com.bonait.bnframework.modules.home.fragment.MakeGoodFragment; import com.bonait.bnframework.modules.home.fragment.SheZhifragment; import com.bonait.bnframework.modules.mine.fragment.MyFragment; @@ -120,43 +122,73 @@ public class BottomNavigationMainActivity extends BaseActivity { * 重新连接plc */ public void ReconnectModbus() { - try { - - ThreadManager.Get().StartLong("PLC断线重连线程", true, new IThread() { - @Override - public void Run() throws InterruptedException { - try { - if (ConfigName.getInstance().PlcIsConnect) { - //ping 不通 - boolean status = ModbusTcpServer.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); - if (status) { - MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " PLC通讯正常,准备连接!"); - ModbusTcpServer.ConnectPLC(); - } else { - MessageLog.ShowInfo("PLC状态断开,尝试连接..."); - ConfigName.getInstance().PlcIsConnect = false; - } - } - Thread.sleep(10000); - } catch (Exception e) { - Log.i("PLC", "PLC重连接失败!" + e.getMessage()); - } - } - - @Override - public void RunComplete() throws InterruptedException { - } - }); - } catch (Exception e) { - MessageLog.ShowInfo("重新连接Modbus异常," + e.getMessage()); - } + new Thread(()->{ + try { + ModbusMaster.get().RtuConnect(ConfigName.getInstance().SerialPortName, 9600, new IOperateResult() { + @Override + public void onSuccess() { + ConfigName.getInstance().PlcIsConnect = true; + ConfigData.getInstance().PLC_Init(); + } + + @Override + public void onFailure(String message) { + ConfigName.getInstance().PlcIsConnect = false; + ToastUtils.info("设备 " + ConfigName.getInstance().Address + " 连接失败:" + message); + } + + @Override + public void onFinally() { + + } + }); + }catch (Exception e ) + { + MessageLog.ShowInfo("重新连接Modbus异常," + e.getMessage()); + } + }).start(); + + + + + +// try { +// +// ThreadManager.Get().StartLong("PLC断线重连线程", true, new IThread() { +// @Override +// public void Run() throws InterruptedException { +// try { +// if (ConfigName.getInstance().PlcIsConnect) { +// //ping 不通 +// boolean status = ModbusClient.ping2(ConfigName.getInstance().Address, 1, 1); +// if (!status) //ping 不通 连接 +// { +// MessageLog.ShowInfo("PLC状态断开,尝试连接..."); +// ConfigName.getInstance().PlcIsConnect = false; +// } +// } else { +// boolean status = ModbusClient.ping2(ConfigName.getInstance().Address, 1, 1); +// if (status) { +// MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " PLC通讯正常,准备连接!"); +// ModbusClient.ConnectPLC(); +// } else { +// MessageLog.ShowInfo("PLC状态断开,尝试连接..."); +// ConfigName.getInstance().PlcIsConnect = false; +// } +// } +// Thread.sleep(10000); +// } catch (Exception e) { +// Log.i("PLC", "PLC重连接失败!" + e.getMessage()); +// } +// } +// +// @Override +// public void RunComplete() throws InterruptedException { +// } +// }); +// } catch (Exception e) { +// MessageLog.ShowInfo("重新连接Modbus异常," + e.getMessage()); +// } } diff --git a/app/src/main/java/com/bonait/bnframework/modules/home/fragment/MakeGoodFragment.java b/app/src/main/java/com/bonait/bnframework/modules/home/fragment/MakeGoodFragment.java index 675a643b..b91f9e71 100644 --- a/app/src/main/java/com/bonait/bnframework/modules/home/fragment/MakeGoodFragment.java +++ b/app/src/main/java/com/bonait/bnframework/modules/home/fragment/MakeGoodFragment.java @@ -245,37 +245,37 @@ public class MakeGoodFragment extends BaseFragment { @Override public void clickListener(View v, Object data) { ResGoodsMake makegood = (ResGoodsMake) data; - if (!ConfigName.getInstance().PlcIsConnect) { - ToastUtils.warning("设备已离线,请检查设备..."); - return; - } - - if (DataBus.getInstance().ZDQX_IsStart) { - ToastUtils.warning("自动清洗中,请等待清洗完成!"); - return; - } - - if (ExecuteTheRecipe.IsMakeGood) { - ToastUtils.warning("请耐心等待上一商品制作完成..."); - return; - } - - if (makegood.subOrder.status == 1) { - ToastUtils.warning("商品:" + makegood.good.name + ",已在制作中..."); - return; - } - - if (makegood.subOrder.status == 2) { - ToastUtils.warning("商品:" + makegood.good.name + ",已制作完成..."); - return; - } - - if (ConfigName.getInstance().versionSelectionEnum.equals("奶茶机")) { - if (!ExecuteTheRecipe.IsCup) { - ToastUtils.warning("出料口没有检测到器皿!"); - return; - } - } +// if (!ConfigName.getInstance().PlcIsConnect) { +// ToastUtils.warning("设备已离线,请检查设备..."); +// return; +// } +// +// if (DataBus.getInstance().ZDQX_IsStart) { +// ToastUtils.warning("自动清洗中,请等待清洗完成!"); +// return; +// } +// +// if (ExecuteTheRecipe.IsMakeGood) { +// ToastUtils.warning("请耐心等待上一商品制作完成..."); +// return; +// } +// +// if (makegood.subOrder.status == 1) { +// ToastUtils.warning("商品:" + makegood.good.name + ",已在制作中..."); +// return; +// } +// +// if (makegood.subOrder.status == 2) { +// ToastUtils.warning("商品:" + makegood.good.name + ",已制作完成..."); +// return; +// } +// +// if (ConfigName.getInstance().versionSelectionEnum.equals("奶茶机")) { +// if (!ExecuteTheRecipe.IsCup) { +// ToastUtils.warning("出料口没有检测到器皿!"); +// return; +// } +// } String title = "温馨提示!"; String message = "客官确定要开始制作【" + makegood.good.name + "】吗?";