Author | SHA1 | Message | Date |
---|---|---|---|
pry | 325f387716 | 串口通讯 | 7 months ago |
pry | 4cb3b95b3b | 压力锅界面开发 | 7 months ago |
pry | f25c81c363 | 压力锅界面开发 | 8 months ago |
pry | c5a3ea6351 | 压力锅界面开发 | 8 months ago |
applelon | 1ba9e799f4 | 压力锅测试 | 8 months ago |
fyf | e1b6a5ee7e | 内存清理 | 9 months ago |
fyf | d8011d8182 | 测试 | 9 months ago |
@@ -34,6 +34,8 @@ android { | |||
} | |||
compileOptions { | |||
//启用对新语言API的支持的标志 | |||
coreLibraryDesugaringEnabled true | |||
sourceCompatibility JavaVersion.VERSION_1_8 | |||
targetCompatibility JavaVersion.VERSION_1_8 | |||
} | |||
@@ -112,13 +114,7 @@ dependencies { | |||
implementation 'com.orhanobut:logger:2.2.0' | |||
// leak 内存泄漏检测 | |||
// debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.3' | |||
// releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.3' | |||
// // Optional, if you use support library fragments: | |||
// debugImplementation 'com.squareup.leakcanary:leakcanary-support-fragment:1.6.3' | |||
// implementation files('libs/commons-codec-1.6.jar') | |||
// debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0-alpha-3' | |||
//Modbus | |||
implementation 'com.github.licheedev:Modbus4Android:2.0.2' | |||
@@ -157,4 +153,8 @@ dependencies { | |||
implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:3.0.4' | |||
implementation 'com.contrarywind:Android-PickerView:3.2.6' | |||
implementation 'com.github.xingshuangs:iot-communication:1.5.0' | |||
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.6' | |||
} |
@@ -33,6 +33,7 @@ | |||
tools:ignore="GoogleAppIndexingWarning" | |||
tools:node="merge" | |||
tools:replace="android:icon"> | |||
<activity | |||
android:name=".modules.home.fragment.mode.Silos_item_fragment" | |||
android:exported="false" | |||
@@ -43,7 +44,6 @@ | |||
<activity | |||
android:name=".modules.mine.fragment.from.UserActivity" | |||
android:exported="false" /> | |||
<activity | |||
android:name=".modules.home.fragment.from.fragment.JiaoYan_sdkz_fragment" | |||
android:exported="false" | |||
@@ -56,7 +56,6 @@ | |||
android:name=".modules.home.fragment.from.WdszActivity" | |||
android:exported="false" | |||
tools:ignore="Instantiatable" /> | |||
<activity | |||
android:name=".modules.home.fragment.from.DzcjyActivity" | |||
android:exported="false" | |||
@@ -165,17 +164,17 @@ | |||
</provider> | |||
<activity | |||
android:name=".modules.welcome.activity.WelcomeActivity" | |||
android:name=".MainActivity" | |||
android:exported="true" | |||
android:theme="@style/AppTheme.Launcher"> | |||
android:theme="@style/AppTheme.Launcher" | |||
tools:ignore="DuplicateActivity"> | |||
<intent-filter> | |||
<action android:name="android.intent.action.MAIN" /> | |||
<category android:name="android.intent.category.LAUNCHER" /> | |||
</intent-filter> | |||
</activity> | |||
<activity android:name=".modules.welcome.activity.LoginActivity"> | |||
</activity> | |||
<activity android:name=".modules.welcome.activity.LoginActivity"></activity> | |||
<receiver | |||
android:name=".common.base.BootReceiver" | |||
@@ -0,0 +1,535 @@ | |||
package com.bonait.bnframework.HBL.API; | |||
import com.bonait.bnframework.HBL.Interface.IRunT; | |||
import com.bonait.bnframework.HBL.Logs.MessageLog; | |||
import com.google.gson.Gson; | |||
import com.google.gson.GsonBuilder; | |||
import java.io.BufferedReader; | |||
import java.io.ByteArrayOutputStream; | |||
import java.io.DataOutputStream; | |||
import java.io.IOException; | |||
import java.io.InputStream; | |||
import java.io.InputStreamReader; | |||
import java.lang.reflect.Field; | |||
import java.lang.reflect.Type; | |||
import java.net.HttpURLConnection; | |||
import java.net.URL; | |||
import java.net.URLEncoder; | |||
import java.nio.charset.StandardCharsets; | |||
import java.security.MessageDigest; | |||
import java.util.Arrays; | |||
import java.util.Collections; | |||
import java.util.Comparator; | |||
import java.util.List; | |||
import java.util.Map; | |||
import java.util.concurrent.atomic.AtomicReference; | |||
public class APIHelper { | |||
private static String key="64059261-1599-472c-b418-3c18b4e3883e"; | |||
/** | |||
* 获取加密后的签名 | |||
* @param t | |||
* @return | |||
*/ | |||
public static String GetSign(Object t,String key){ | |||
AtomicReference<String> retstr = new AtomicReference<>(""); | |||
List<Field> fields = Arrays.asList(t.getClass().getFields()); | |||
Collections.sort(fields, Comparator.comparing(Field::getName)); | |||
fields.forEach(item->{ | |||
if( item.getName().toUpperCase()!="sign".toUpperCase()){ | |||
try { | |||
if(item.get(t)!=null&&!item.get(t).toString().isEmpty()){ | |||
Type type = item.getGenericType(); | |||
String typeName = type.toString(); | |||
switch(typeName){ | |||
case "class java.util.Date": | |||
case "class java.lang.String": | |||
case "byte": | |||
case "int": | |||
case "float": | |||
case "double": | |||
case "long": | |||
case "short": | |||
case "boolean": | |||
retstr.set(retstr.get() + item.getName() + "=" + item.get(t) + "&"); | |||
break; | |||
default: | |||
// String a= new GsonBuilder().serializeNulls().create().toJson(item.get(t));//保留为空的属性 | |||
String a= new Gson().toJson(item.get(t)); | |||
retstr.set(retstr.get() + item.getName() + "=" + a + "&"); | |||
break; | |||
} | |||
} | |||
} catch (Exception e) { | |||
} | |||
} | |||
}); | |||
String tempSign="&key="+key; | |||
if(retstr.get().length()>0){ | |||
tempSign=retstr.get().substring(0, retstr.get().length()-1)+"&key="+key; | |||
} | |||
// String tempSign=retstr.get().substring(0, retstr.get().length()-1)+"&key="+key; | |||
StringBuilder sb = new StringBuilder(); | |||
try{ | |||
MessageDigest md = MessageDigest.getInstance("MD5"); | |||
byte[] digest = md.digest(tempSign.toUpperCase().getBytes()); | |||
for (byte b : digest) { | |||
sb.append(Integer.toHexString((b & 0xFF) | 0x100).substring(1,3)); | |||
} | |||
}catch (Exception e){ | |||
} | |||
return sb.toString().toUpperCase(); | |||
} | |||
public static String Post(String url, Map<String, String> parameters, Map<String, String> headers) throws IOException { | |||
HttpURLConnection connection = null; | |||
InputStream inputStream = null; | |||
BufferedReader reader = null; | |||
StringBuffer buffer = new StringBuffer(); | |||
try { | |||
URL requestUrl = new URL(url); | |||
connection = (HttpURLConnection) requestUrl.openConnection(); | |||
connection.setRequestMethod("POST"); | |||
connection.setConnectTimeout(5000); | |||
connection.setReadTimeout(5000); | |||
connection.setDoOutput(true); | |||
connection.setDoInput(true); | |||
// 设置header | |||
if (headers != null) { | |||
for (Map.Entry<String, String> entry : headers.entrySet()) { | |||
connection.setRequestProperty(entry.getKey(), entry.getValue()); | |||
} | |||
} | |||
// 设置参数 | |||
if (parameters != null) { | |||
StringBuilder stringBuilder = new StringBuilder(); | |||
for (Map.Entry<String, String> entry : parameters.entrySet()) { | |||
stringBuilder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&"); | |||
} | |||
String params = stringBuilder.toString(); | |||
byte[] postData = params.getBytes("UTF-8"); | |||
connection.setRequestProperty("Content-Length", Integer.toString(postData.length)); | |||
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { | |||
outputStream.write(postData); | |||
} | |||
} | |||
// 获取响应结果 | |||
int statusCode = connection.getResponseCode(); | |||
if (statusCode == HttpURLConnection.HTTP_OK) { | |||
inputStream = connection.getInputStream(); | |||
reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); | |||
String line; | |||
while ((line = reader.readLine()) != null) { | |||
buffer.append(line); | |||
} | |||
} else { | |||
throw new IOException("服务器返回错误,状态码:" + statusCode); | |||
} | |||
}catch (Exception e){ | |||
MessageLog.ShowError("POST 请求异常:"+e.toString()); | |||
}finally { | |||
// 关闭连接和流 | |||
if (reader != null) { | |||
reader.close(); | |||
} | |||
if (inputStream != null) { | |||
inputStream.close(); | |||
} | |||
if (connection != null) { | |||
connection.disconnect(); | |||
} | |||
} | |||
return buffer.toString(); | |||
} | |||
public static String Post(String url, String body, Map<String, String> headers) throws IOException { | |||
HttpURLConnection connection = null; | |||
InputStream inputStream = null; | |||
BufferedReader reader = null; | |||
StringBuffer buffer = new StringBuffer(); | |||
try { | |||
URL requestUrl = new URL(url); | |||
connection = (HttpURLConnection) requestUrl.openConnection(); | |||
connection.setRequestMethod("POST"); | |||
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");// "Fiddler" | |||
connection.setRequestProperty("Content-Type", "application/json"); | |||
connection.setRequestProperty("Charset", "UTF-8"); | |||
connection.setConnectTimeout(5000); | |||
connection.setReadTimeout(5000); | |||
connection.setDoOutput(true); | |||
connection.setDoInput(true); | |||
// 设置header | |||
if (headers != null) { | |||
for (Map.Entry<String, String> entry : headers.entrySet()) { | |||
connection.setRequestProperty(entry.getKey(), entry.getValue()); | |||
} | |||
} | |||
// 设置参数 | |||
if (!body .isEmpty()) { | |||
connection.setRequestProperty("Content-Length", Integer.toString(body.getBytes().length)); | |||
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { | |||
outputStream.write(body.getBytes()); | |||
} | |||
} | |||
// 获取响应结果 | |||
int statusCode = connection.getResponseCode(); | |||
if (statusCode == HttpURLConnection.HTTP_OK) { | |||
inputStream = connection.getInputStream(); | |||
reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); | |||
String line; | |||
while ((line = reader.readLine()) != null) { | |||
buffer.append(line); | |||
} | |||
} else { | |||
throw new IOException("服务器返回错误,状态码:" + statusCode); | |||
} | |||
}catch (Exception e){ | |||
MessageLog.ShowError("POST 请求异常:"+e.toString()); | |||
}finally { | |||
// 关闭连接和流 | |||
if (reader != null) { | |||
reader.close(); | |||
} | |||
if (inputStream != null) { | |||
inputStream.close(); | |||
} | |||
if (connection != null) { | |||
connection.disconnect(); | |||
} | |||
} | |||
return buffer.toString(); | |||
} | |||
public static String Post(String url, Object body, Map<String, String> headers) throws IOException { | |||
HttpURLConnection connection = null; | |||
InputStream inputStream = null; | |||
BufferedReader reader = null; | |||
StringBuffer buffer = new StringBuffer(); | |||
try { | |||
URL requestUrl = new URL(url); | |||
connection = (HttpURLConnection) requestUrl.openConnection(); | |||
connection.setRequestMethod("POST"); | |||
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");// "Fiddler" | |||
connection.setRequestProperty("Content-Type", "application/json"); | |||
connection.setRequestProperty("Charset", "UTF-8"); | |||
connection.setConnectTimeout(5000); | |||
connection.setReadTimeout(5000); | |||
connection.setDoOutput(true); | |||
connection.setDoInput(true); | |||
// 设置header | |||
if (headers != null) { | |||
for (Map.Entry<String, String> entry : headers.entrySet()) { | |||
connection.setRequestProperty(entry.getKey(), entry.getValue()); | |||
} | |||
} | |||
// 设置参数 | |||
if (body !=null) { | |||
byte[] bytes = new Gson().toJson(body).getBytes(); | |||
connection.setRequestProperty("Content-Length", Integer.toString(bytes.length)); | |||
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { | |||
outputStream.write(bytes); | |||
} | |||
} | |||
// 获取响应结果 | |||
int statusCode = connection.getResponseCode(); | |||
if (statusCode == HttpURLConnection.HTTP_OK) { | |||
inputStream = connection.getInputStream(); | |||
reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); | |||
String line; | |||
while ((line = reader.readLine()) != null) { | |||
buffer.append(line); | |||
} | |||
} else { | |||
throw new IOException("服务器返回错误,状态码:" + statusCode); | |||
} | |||
}catch (Exception e){ | |||
MessageLog.ShowError("POST 请求异常:"+e.toString()); | |||
}finally { | |||
// 关闭连接和流 | |||
if (reader != null) { | |||
reader.close(); | |||
} | |||
if (inputStream != null) { | |||
inputStream.close(); | |||
} | |||
if (connection != null) { | |||
connection.disconnect(); | |||
} | |||
} | |||
return buffer.toString(); | |||
} | |||
public static void Post(String url, Object body, IRunT<APIResult> callback) { | |||
new Thread(()->{ | |||
HttpURLConnection connection = null; | |||
InputStream inputStream = null; | |||
BufferedReader reader = null; | |||
StringBuffer buffer = new StringBuffer(); | |||
try { | |||
URL requestUrl = new URL(url); | |||
connection = (HttpURLConnection) requestUrl.openConnection(); | |||
connection.setRequestMethod("POST"); | |||
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");// "Fiddler" | |||
connection.setRequestProperty("Content-Type", "application/json"); | |||
connection.setRequestProperty("Charset", "UTF-8"); | |||
connection.setConnectTimeout(5000); | |||
connection.setReadTimeout(5000); | |||
connection.setDoOutput(true); | |||
connection.setDoInput(true); | |||
if(body!=null){ | |||
//获取签名信息 | |||
String sign = GetSign(body,key); | |||
//设置请求头 | |||
connection.setRequestProperty("key", key); | |||
connection.setRequestProperty("sign", sign); | |||
//设置请求 body | |||
byte[] bytes = new Gson().toJson(body).getBytes(); | |||
connection.setRequestProperty("Content-Length", Integer.toString(bytes.length)); | |||
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { | |||
outputStream.write(bytes); | |||
} | |||
} | |||
// 获取响应结果 | |||
int statusCode = connection.getResponseCode(); | |||
if (statusCode == HttpURLConnection.HTTP_OK) { | |||
inputStream = connection.getInputStream(); | |||
reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); | |||
String line; | |||
while ((line = reader.readLine()) != null) { | |||
buffer.append(line); | |||
} | |||
} else { | |||
throw new IOException("服务器返回错误,状态码:" + statusCode); | |||
} | |||
}catch (Exception e){ | |||
MessageLog.ShowError("POST 请求异常:"+e.toString()); | |||
return; | |||
}finally { | |||
try{ | |||
// 关闭连接和流 | |||
if (reader != null) reader.close(); | |||
if (inputStream != null) inputStream.close(); | |||
if (connection != null) connection.disconnect(); | |||
}catch(Exception e){ | |||
MessageLog.ShowError("POST 请求异常:"+e.toString()); | |||
return; | |||
} | |||
} | |||
try{ | |||
APIResult res = new GsonBuilder().serializeNulls().create().fromJson(buffer.toString(), APIResult.class); | |||
if(res!=null)if(callback!=null) callback.Run(res); | |||
}catch(Exception e){ | |||
} | |||
}).start(); | |||
} | |||
public static void Post(String url, Object body,String signkey, IRunT<APIResult> callback) { | |||
new Thread(()->{ | |||
HttpURLConnection connection = null; | |||
InputStream inputStream = null; | |||
BufferedReader reader = null; | |||
StringBuffer buffer = new StringBuffer(); | |||
try { | |||
URL requestUrl = new URL(url); | |||
connection = (HttpURLConnection) requestUrl.openConnection(); | |||
connection.setRequestMethod("POST"); | |||
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");// "Fiddler" | |||
connection.setRequestProperty("Content-Type", "application/json"); | |||
connection.setRequestProperty("Charset", "UTF-8"); | |||
connection.setConnectTimeout(5000); | |||
connection.setReadTimeout(5000); | |||
connection.setDoOutput(true); | |||
connection.setDoInput(true); | |||
if(body!=null){ | |||
//获取签名信息 | |||
String sign = GetSign(body,signkey); | |||
MessageLog.ShowInfo("签名信息:"+sign); | |||
//设置请求头 | |||
connection.setRequestProperty("key", signkey); | |||
// connection.setRequestProperty("sign", sign); | |||
//设置请求 body | |||
byte[] bytes = new Gson().toJson(body).getBytes(); | |||
connection.setRequestProperty("Content-Length", Integer.toString(bytes.length)); | |||
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { | |||
outputStream.write(bytes); | |||
} | |||
} | |||
// 获取响应结果 | |||
int statusCode = connection.getResponseCode(); | |||
if (statusCode == HttpURLConnection.HTTP_OK) { | |||
inputStream = connection.getInputStream(); | |||
reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); | |||
String line; | |||
while ((line = reader.readLine()) != null) { | |||
buffer.append(line); | |||
} | |||
} else { | |||
throw new IOException("服务器返回错误,状态码:" + statusCode); | |||
} | |||
}catch (Exception e){ | |||
MessageLog.ShowError("POST 请求异常:"+e.toString()); | |||
return; | |||
}finally { | |||
try{ | |||
// 关闭连接和流 | |||
if (reader != null) reader.close(); | |||
if (inputStream != null) inputStream.close(); | |||
if (connection != null) connection.disconnect(); | |||
}catch(Exception e){ | |||
MessageLog.ShowError("POST 请求异常:"+e.toString()); | |||
return; | |||
} | |||
} | |||
try{ | |||
APIResult res = new GsonBuilder().serializeNulls().create().fromJson(buffer.toString(), APIResult.class); | |||
if(res!=null)if(callback!=null) callback.Run(res); | |||
}catch(Exception e){ | |||
MessageLog.ShowError("POST 请求异常:"+e.toString()); | |||
} | |||
}).start(); | |||
} | |||
public static <T> void PostT(String url, Object body,String signkey ,IRunT<APIResultT<T>> callback) { | |||
new Thread(()->{ | |||
HttpURLConnection connection = null; | |||
InputStream inputStream = null; | |||
BufferedReader reader = null; | |||
StringBuffer buffer = new StringBuffer(); | |||
try { | |||
URL requestUrl = new URL(url); | |||
connection = (HttpURLConnection) requestUrl.openConnection(); | |||
connection.setRequestMethod("POST"); | |||
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");// "Fiddler" | |||
connection.setRequestProperty("Content-Type", "application/json"); | |||
connection.setRequestProperty("Charset", "UTF-8"); | |||
connection.setConnectTimeout(5000); | |||
connection.setReadTimeout(5000); | |||
connection.setDoOutput(true); | |||
connection.setDoInput(true); | |||
if(body!=null){ | |||
//获取签名信息 | |||
String sign = GetSign(body,signkey); | |||
//设置请求头 | |||
connection.setRequestProperty("key", signkey); | |||
connection.setRequestProperty("sign", sign); | |||
//设置请求 body | |||
byte[] bytes = new Gson().toJson(body).getBytes(); | |||
connection.setRequestProperty("Content-Length", Integer.toString(bytes.length)); | |||
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { | |||
outputStream.write(bytes); | |||
} | |||
} | |||
// 获取响应结果 | |||
int statusCode = connection.getResponseCode(); | |||
if (statusCode == HttpURLConnection.HTTP_OK) { | |||
inputStream = connection.getInputStream(); | |||
reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); | |||
String line; | |||
while ((line = reader.readLine()) != null) { | |||
buffer.append(line); | |||
} | |||
} else { | |||
throw new IOException("服务器返回错误,状态码:" + statusCode); | |||
} | |||
}catch (Exception e){ | |||
MessageLog.ShowError("POST 请求异常:"+e.toString()); | |||
return; | |||
}finally { | |||
try{ | |||
// 关闭连接和流 | |||
if (reader != null) reader.close(); | |||
if (inputStream != null) inputStream.close(); | |||
if (connection != null) connection.disconnect(); | |||
}catch(Exception e){ | |||
MessageLog.ShowError("POST 请求异常:"+e.toString()); | |||
return; | |||
} | |||
} | |||
try{ | |||
APIResultT<T> res = new GsonBuilder().serializeNulls().create().fromJson(buffer.toString(), APIResultT.class); | |||
if(res!=null)if(callback!=null) callback.Run(res); | |||
}catch(Exception e){ | |||
MessageLog.ShowError("POST请求返回值解析异常,"+e.toString()); | |||
} | |||
}).start(); | |||
} | |||
public static void get(String urlAdd,Map<String,String> params,IRunT<String> callback) { | |||
new Thread(()->{ | |||
try { | |||
String ResponseAdd = BuildUrlWithParams(urlAdd,params);//请求地址和参数 | |||
URL url = new URL(ResponseAdd); | |||
HttpURLConnection Connection = (HttpURLConnection) url.openConnection(); | |||
Connection.setRequestMethod("GET"); | |||
Connection.setConnectTimeout(3000); | |||
Connection.setReadTimeout(3000); | |||
int responseCode = Connection.getResponseCode(); | |||
if (responseCode == Connection.HTTP_OK) { | |||
InputStream inputStream = Connection.getInputStream(); | |||
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); | |||
byte[] bytes = new byte[1024]; | |||
int length = 0; | |||
while ((length = inputStream.read(bytes)) != -1) { | |||
arrayOutputStream.write(bytes, 0, length); | |||
arrayOutputStream.flush();//强制释放缓冲区 | |||
} | |||
String s = arrayOutputStream.toString(); | |||
if(callback!=null)callback.Run(s); | |||
} else { | |||
MessageLog.ShowError("get 请求失败"); | |||
} | |||
} catch (Exception e) { | |||
MessageLog.ShowError(e); | |||
} | |||
}).start(); | |||
} | |||
/** | |||
* 请求参数拼接 | |||
* @param Url 请求地址 | |||
* @param params 请求参数 | |||
* @return | |||
*/ | |||
public static String BuildUrlWithParams(String Url,Map<String,String> params){ | |||
StringBuilder sb = new StringBuilder(Url); | |||
if(params!=null&&!params.isEmpty()){ | |||
sb.append("?"); | |||
params.forEach((key,value)->{ | |||
sb.append(key).append("=").append(value).append("&"); | |||
}); | |||
sb.deleteCharAt(sb.length()-1); | |||
} | |||
return sb.toString(); | |||
} | |||
} |
@@ -0,0 +1,21 @@ | |||
package com.bonait.bnframework.HBL.API; | |||
import com.google.gson.GsonBuilder; | |||
public class APIResult { | |||
public int statusCode ; | |||
public Object data ; | |||
public String succeeded ; | |||
public String errors ; | |||
public String extras ; | |||
public int timestamp ; | |||
public String toString(){ | |||
return new GsonBuilder().serializeNulls().create().toJson(this);//保留为空的属性 | |||
} | |||
} |
@@ -0,0 +1,21 @@ | |||
package com.bonait.bnframework.HBL.API; | |||
import com.google.gson.GsonBuilder; | |||
public class APIResultT<T> { | |||
public int statusCode ; | |||
public T data ; | |||
public String succeeded ; | |||
public String errors ; | |||
public String extras ; | |||
public int timestamp ; | |||
public String toString(){ | |||
return new GsonBuilder().serializeNulls().create().toJson(this);//保留为空的属性 | |||
} | |||
} |
@@ -0,0 +1,57 @@ | |||
package com.bonait.bnframework.HBL.API; | |||
import java.security.KeyManagementException; | |||
import java.security.NoSuchAlgorithmException; | |||
import java.security.SecureRandom; | |||
import java.security.cert.X509Certificate; | |||
import javax.net.ssl.HostnameVerifier; | |||
import javax.net.ssl.HttpsURLConnection; | |||
import javax.net.ssl.SSLContext; | |||
import javax.net.ssl.SSLSession; | |||
import javax.net.ssl.TrustManager; | |||
import javax.net.ssl.X509TrustManager; | |||
public class Utils { | |||
/** | |||
* 禁用SSL验证 | |||
*/ | |||
public static void disableSSLCertChecking() { | |||
try { | |||
TrustManager[] trustAllCerts = new TrustManager[]{ | |||
new X509TrustManager() { | |||
public X509Certificate[] getAcceptedIssuers() { | |||
return new X509Certificate[0]; | |||
} | |||
@Override | |||
public void checkClientTrusted(X509Certificate[] certs, String authType) { | |||
} | |||
@Override | |||
public void checkServerTrusted(X509Certificate[] certs, String authType) { | |||
} | |||
} | |||
}; | |||
SSLContext sc = SSLContext.getInstance("SSL"); | |||
sc.init(null, trustAllCerts, new SecureRandom()); | |||
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); | |||
// Create all-trusting host name verifier | |||
HostnameVerifier allHostsValid = new HostnameVerifier() { | |||
public boolean verify(String hostname, SSLSession session) { | |||
return true; | |||
} | |||
}; | |||
// Install the all-trusting host verifier | |||
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); | |||
} catch (NoSuchAlgorithmException e) { | |||
e.printStackTrace(); | |||
} catch (KeyManagementException e) { | |||
e.printStackTrace(); | |||
} | |||
} | |||
} |
@@ -0,0 +1,44 @@ | |||
package com.bonait.bnframework.HBL.Communication; | |||
import java.io.IOException; | |||
import java.io.InputStreamReader; | |||
import java.io.LineNumberReader; | |||
public class CommBase { | |||
/** | |||
* Ping PLC地址是否通畅 | |||
* @param address | |||
* @param pingTimes ping的次数 | |||
* @param timeOut 超时时间 10 | |||
* @return | |||
*/ | |||
public boolean NetPing(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; | |||
} | |||
} |
@@ -0,0 +1,89 @@ | |||
package com.bonait.bnframework.HBL.Communication.Modbus; | |||
import com.bonait.bnframework.HBL.Logs.MessageLog; | |||
import com.bonait.bnframework.HBL.Result.OperateResultT; | |||
import com.licheedev.modbus4android.ModbusRespException; | |||
import com.serotonin.modbus4j.exception.ModbusInitException; | |||
import com.serotonin.modbus4j.exception.ModbusTransportException; | |||
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()); | |||
} | |||
} | |||
public int GetAddress(String address) { | |||
if (address == null) return -1; | |||
if (address.length() > 0) { | |||
address = address.trim(); | |||
try{ | |||
if (address.toUpperCase().contains("M") &&address.toUpperCase().contains(".")&& address.length() >= 4) { | |||
String[] res = address.substring(1).split("[.]"); | |||
if (res != null && res.length == 2) { | |||
int firstAdd = Integer.parseInt(res[0]); | |||
int endAdd = Integer.parseInt(res[1]); | |||
if (endAdd >= 0 && endAdd <= 7) { | |||
return (firstAdd * 8) + 320 + endAdd; | |||
} | |||
} | |||
} else if (address.toUpperCase().contains("I") && address.length() >= 4) { | |||
String[] res = address.substring(1).split("[.]"); | |||
if (res != null && res.length == 2) { | |||
int firstAdd = Integer.parseInt(res[0]); | |||
int endAdd = Integer.parseInt(res[1]); | |||
if (endAdd >= 0 && endAdd <= 7) { | |||
return (firstAdd * 8) + endAdd; | |||
} | |||
} | |||
} else if ((address.toUpperCase().contains("VW") || address.toUpperCase().contains("VD")) && address.length() >= 3) { | |||
String res = address.substring(2); | |||
if (res != null) { | |||
int tempAdd = Integer.parseInt(res); | |||
return (tempAdd / 2) + 100; | |||
} | |||
}else if (address.toUpperCase().contains("M")&&address.length() >=2){ | |||
return Integer.parseInt(address.substring(1))+4000; | |||
}else if (address.toUpperCase().contains("X")&&address.length() >=2){ | |||
int xadd = Integer.parseInt( address.substring(1)); | |||
return (xadd / 10 * 8) + xadd % 10; | |||
}else if (address.toUpperCase().contains("Y")&&address.length() >=2){ | |||
int yadd = Integer.parseInt( address.substring(1)); | |||
return ((yadd / 10 * 8) + yadd % 10) + 300; | |||
}else if (address.toUpperCase().contains("D")&&address.length() >=2){ | |||
return Integer.parseInt( address.substring(1)); | |||
} | |||
else { | |||
return Integer.parseInt(address); | |||
} | |||
}catch (Exception e){ | |||
MessageLog.ShowError(e); | |||
} | |||
} | |||
return -1; | |||
} | |||
} |
@@ -0,0 +1,15 @@ | |||
package com.bonait.bnframework.HBL.Communication.Modbus; | |||
import com.licheedev.modbus4android.ModbusRespException; | |||
import com.serotonin.modbus4j.exception.ModbusInitException; | |||
import com.serotonin.modbus4j.exception.ModbusTransportException; | |||
import java.util.concurrent.ExecutionException; | |||
public interface IExceptionHandling { | |||
void onSuccess(int add)throws InterruptedException, ExecutionException, ModbusTransportException, | |||
ModbusInitException, ModbusRespException; | |||
void onFailure(String error); | |||
} |
@@ -0,0 +1,10 @@ | |||
package com.bonait.bnframework.HBL.Communication.Modbus; | |||
import com.bonait.bnframework.HBL.Result.OperateResult; | |||
public interface IModbusMaster { | |||
OperateResult TcpConnect(String ip, int port); | |||
OperateResult RtuConnect(String com, int baudRate); | |||
boolean getConnected(); | |||
} |
@@ -0,0 +1,23 @@ | |||
package com.bonait.bnframework.HBL.Communication.Modbus; | |||
import com.bonait.bnframework.HBL.Enum.DataFormat; | |||
import com.bonait.bnframework.HBL.Result.OperateResultT; | |||
public interface IRead { | |||
OperateResultT<boolean[]> ReadBool(String address, int length); | |||
OperateResultT<Boolean> ReadBool(String address); | |||
OperateResultT<short[]> ReadShort(String address, int length); | |||
OperateResultT<Short> ReadShort(String address); | |||
OperateResultT<int[]> ReadInt(String address, int length); | |||
OperateResultT<Integer> ReadInt(String address); | |||
OperateResultT<byte[]> ReadByte(String address, int length); | |||
OperateResultT<String> ReadString(String address, int length); | |||
OperateResultT<float[]> ReadFloat(String address, int length); | |||
OperateResultT<Float> ReadFloat(String address); | |||
} |
@@ -0,0 +1,24 @@ | |||
package com.bonait.bnframework.HBL.Communication.Modbus; | |||
import com.bonait.bnframework.HBL.Result.OperateResult; | |||
import com.bonait.bnframework.common.helper.I.IWriteCallBack; | |||
public interface IWrite { | |||
OperateResult WriteBool(String address, boolean value); | |||
OperateResult WriteBool(String address, boolean[] value); | |||
OperateResult WriteBool(String address, boolean[] value, int slaveId); | |||
OperateResult WriteShort(String address, short value); | |||
OperateResult WriteShort(String address, short[] value); | |||
OperateResult WriteShort(String address, short[] value, int slaveId); | |||
OperateResult WriteInt(String address, int value); | |||
OperateResult WriteInt(String address, int[] value); | |||
OperateResult WriteInt(String address, int[] value, int slaveId); | |||
OperateResult WriteString(String address, String value, int slaveId); | |||
OperateResult WriteFloat(String address, float value); | |||
OperateResult WriteFloat(String address, float[] value); | |||
OperateResult WriteFloat(String address, float[] value, int slaveId); | |||
} |
@@ -0,0 +1,622 @@ | |||
package com.bonait.bnframework.HBL.Communication.Modbus; | |||
import static com.bonait.bnframework.HBL.DataUtil.DataConvertLib.ByteToShort; | |||
import com.bonait.bnframework.HBL.Communication.CommBase; | |||
import com.bonait.bnframework.HBL.DataUtil.FloatLib; | |||
import com.bonait.bnframework.HBL.DataUtil.IntLib; | |||
import com.bonait.bnframework.HBL.DataUtil.ShortLib; | |||
import com.bonait.bnframework.HBL.Enum.DataFormat; | |||
import com.bonait.bnframework.HBL.Interface.IRunT; | |||
import com.bonait.bnframework.HBL.Logs.MessageLog; | |||
import com.bonait.bnframework.HBL.Result.OperateResult; | |||
import com.bonait.bnframework.HBL.Result.OperateResultT; | |||
import com.licheedev.modbus4android.ModbusCallback; | |||
import com.licheedev.modbus4android.ModbusParam; | |||
import com.licheedev.modbus4android.ModbusRespException; | |||
import com.licheedev.modbus4android.ModbusWorker; | |||
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.UnsupportedEncodingException; | |||
import java.util.Arrays; | |||
import java.util.concurrent.ExecutionException; | |||
import java.util.concurrent.atomic.AtomicReference; | |||
public class ModbusMaster implements IRead,IWrite ,IModbusMaster{ | |||
private boolean IsConnected=false; | |||
private ModbusWorker mw = new ModbusWorker(); | |||
public boolean IsReconnection=true; | |||
public DataFormat WriteDataFormat= DataFormat.ABCD; | |||
public DataFormat ReadDataFormat= DataFormat.BADC; | |||
public int SlaveId=1; | |||
@Override | |||
public OperateResult TcpConnect(String ip, int port) { | |||
try{ | |||
MessageLog.ShowInfo("开始验证网络:"+ip ); | |||
boolean status = false; | |||
while (!status&&IsReconnection) { | |||
try { | |||
status =new CommBase().NetPing(ip,1,1);//status为0则代表通,为1则代表不通。 | |||
Thread.sleep(1000); | |||
} catch (Exception e) { | |||
MessageLog.ShowInfo("设备 " + ip + " 网络验证失败"); | |||
} | |||
} | |||
MessageLog.ShowInfo("开始连接Modbus TCP" ); | |||
ModbusParam param= TcpParam.create(ip, port).setTimeout(1000).setRetries(0).setEncapsulated(false).setKeepAlive(true); | |||
AtomicReference<String> errorInfo=new AtomicReference<>(""); | |||
while (IsConnected==false) | |||
{ | |||
errorInfo.set(""); | |||
mw.init(param, new ModbusCallback<com.serotonin.modbus4j.ModbusMaster>() { | |||
@Override | |||
public void onSuccess(com.serotonin.modbus4j.ModbusMaster modbusMaster) { | |||
IsConnected=true; | |||
MessageLog.ShowInfo("Modbus TCP 连接成功" ); | |||
} | |||
@Override | |||
public void onFailure(Throwable tr) { | |||
IsConnected = false; | |||
errorInfo.set(tr.getMessage()); | |||
MessageLog.ShowInfo("Modbus TCP 连接失败" ); | |||
} | |||
@Override | |||
public void onFinally() { | |||
} | |||
}); | |||
if(!IsReconnection)break; | |||
if(IsConnected==false) Thread.sleep(5000); | |||
} | |||
if(IsConnected)return OperateResult.CreateSuccess(); | |||
else return OperateResult.CreateFailed(errorInfo.get()); | |||
}catch(Exception ex){ | |||
return OperateResult.CreateFailed(ex); | |||
} | |||
} | |||
@Override | |||
public OperateResult RtuConnect(String com, int baudRate) { | |||
try{ | |||
MessageLog.ShowInfo("开始连接Modbus RTU" ); | |||
ModbusParam param= SerialParam.create(com, baudRate) // 串口地址和波特率 | |||
.setDataBits(8) // 数据位 | |||
.setParity(0) // 校验位 | |||
.setStopBits(1) // 停止位 | |||
.setTimeout(500).setRetries(0); // 不重试 | |||
AtomicReference<String> errorInfo=new AtomicReference<>(""); | |||
while (IsConnected==false) | |||
{ | |||
mw.init(param, new ModbusCallback<com.serotonin.modbus4j.ModbusMaster>() { | |||
@Override | |||
public void onSuccess(com.serotonin.modbus4j.ModbusMaster modbusMaster) { | |||
IsConnected=true; | |||
MessageLog.ShowInfo("Modbus RTU 连接成功" ); | |||
} | |||
@Override | |||
public void onFailure(Throwable tr) { | |||
IsConnected = false; | |||
errorInfo.set(tr.getMessage()); | |||
MessageLog.ShowInfo("Modbus RTU 连接失败" ); | |||
} | |||
@Override | |||
public void onFinally() { | |||
} | |||
}); | |||
if(!IsReconnection)break; | |||
if(IsConnected==false) Thread.sleep(5000); | |||
} | |||
if(IsConnected)return OperateResult.CreateSuccess(); | |||
else return OperateResult.CreateFailed(errorInfo.get()); | |||
}catch(Exception ex){ | |||
return OperateResult.CreateFailed(ex); | |||
} | |||
} | |||
@Override | |||
public boolean getConnected() { | |||
return IsConnected; | |||
} | |||
public <T> OperateResultT<T> Read(String address, int length){ | |||
// if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");} | |||
AtomicReference<OperateResultT<T>>resultValue=new AtomicReference<OperateResultT<T>>(); | |||
try{ | |||
String typeName= resultValue.get().Content.getClass().getCanonicalName(); | |||
switch(typeName){ | |||
case "java.lang.String": | |||
resultValue.set((OperateResultT<T>)ReadString(address,length)); | |||
break; | |||
case "java.lang.Byte": | |||
resultValue.set((OperateResultT<T>)ReadByte(address,1)); | |||
break; | |||
case "java.lang.Integer": | |||
resultValue.set((OperateResultT<T>)ReadInt(address)); | |||
break; | |||
case "java.lang.Float": | |||
resultValue.set((OperateResultT<T>)ReadFloat(address)); | |||
break; | |||
case "java.lang.Short": | |||
resultValue.set((OperateResultT<T>)ReadShort(address)); | |||
break; | |||
case "java.lang.Boolean": | |||
resultValue.set((OperateResultT<T>)ReadBool(address)); | |||
break; | |||
case "int[]": | |||
resultValue.set((OperateResultT<T>)ReadInt(address,length)); | |||
break; | |||
case "float[]": | |||
resultValue.set((OperateResultT<T>)ReadFloat(address,length)); | |||
break; | |||
case "short[]": | |||
resultValue.set((OperateResultT<T>)ReadShort(address,length)); | |||
break; | |||
case "boolean[]": | |||
resultValue.set((OperateResultT<T>)ReadBool(address,length)); | |||
break; | |||
default: | |||
resultValue.set(OperateResultT.CreateFailedT("不匹配的数据类型:"+typeName)); | |||
break; | |||
} | |||
}catch(Exception ex){ | |||
resultValue.set(OperateResultT.CreateFailedT(ex)); | |||
} | |||
// if(result!=null)result.Run(resultValue.get()); | |||
return resultValue.get(); | |||
} | |||
public <T> OperateResultT<T> Read(String address){ | |||
// if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");} | |||
AtomicReference<OperateResultT<T>>resultValue=new AtomicReference<>(); | |||
resultValue.set(Read(address,1)); | |||
return resultValue.get(); | |||
} | |||
public <T> OperateResult Write(String address,T value) { | |||
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");} | |||
AtomicReference<OperateResult>resultValue=new AtomicReference<>(); | |||
try{ | |||
String typeName= value.getClass().getCanonicalName(); | |||
switch(typeName){ | |||
case "java.lang.String": | |||
resultValue.set(WriteString(address,value.toString(),SlaveId)); | |||
break; | |||
case "java.lang.Integer": | |||
resultValue.set(WriteInt(address,Integer.parseInt(value.toString()))); | |||
break; | |||
case "java.lang.Float": | |||
resultValue.set(WriteFloat(address,Float.parseFloat(value.toString()))); | |||
break; | |||
case "java.lang.Short": | |||
resultValue.set(WriteShort(address,Short.parseShort(value.toString()))); | |||
break; | |||
case "java.lang.Boolean": | |||
resultValue.set(WriteBool(address,Boolean.parseBoolean(value.toString()))); | |||
break; | |||
case "int[]": | |||
resultValue.set(WriteInt(address,(int[])value)); | |||
break; | |||
case "float[]": | |||
resultValue.set(WriteFloat(address,(float[])value)); | |||
break; | |||
case "short[]": | |||
resultValue.set(WriteShort(address,(short[])value)); | |||
break; | |||
case "boolean[]": | |||
resultValue.set(WriteBool(address,(boolean[])value)); | |||
break; | |||
default: | |||
resultValue.set(OperateResult.CreateFailed("不匹配的数据类型:"+typeName)); | |||
break; | |||
} | |||
}catch(Exception ex){ | |||
resultValue.set(OperateResult.CreateFailed(ex)); | |||
} | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResultT<boolean[]> ReadBool(String address, int length) { | |||
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");} | |||
AtomicReference<OperateResultT<boolean[]>>resultValue=new AtomicReference<>(); | |||
new ExceptionServer(address, length, new IExceptionHandling() { | |||
@Override | |||
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { | |||
ReadCoilsResponse res = mw.syncReadCoil(SlaveId, add, length); | |||
boolean[] data = res.getBooleanData(); | |||
boolean[] result = Arrays.copyOfRange(data, 0, length); | |||
resultValue.set(OperateResultT.CreateSuccess(result)); | |||
} | |||
@Override | |||
public void onFailure(String error){ | |||
resultValue.set(OperateResultT.CreateFailedT(address+",读取异常:"+error)); | |||
} | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResultT<Boolean> ReadBool(String address) { | |||
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");} | |||
AtomicReference<OperateResultT<Boolean>>resultValue=new AtomicReference<>(); | |||
ReadBool(address,1).OnSource((s)->{ | |||
resultValue.set(OperateResultT.CreateSuccess(s.Content[0])); | |||
}).OnFailed(s->{ | |||
resultValue.set(OperateResultT.CreateFailedT(s.message)); | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResultT<short[]> ReadShort(String address, int length) { | |||
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");} | |||
AtomicReference<OperateResultT<short[]>>resultValue=new AtomicReference<>(); | |||
new ExceptionServer(address, length, new IExceptionHandling() { | |||
@Override | |||
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { | |||
ReadHoldingRegistersResponse res = mw.syncReadHoldingRegisters(SlaveId, add, length); | |||
short[] data = res.getShortData(); | |||
if (data.length == length) { | |||
resultValue.set(OperateResultT.CreateSuccess(data)); | |||
} | |||
} | |||
@Override | |||
public void onFailure(String error){ | |||
resultValue.set(OperateResultT.CreateFailedT(address+",读取异常:"+error)); | |||
} | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResultT<Short> ReadShort(String address) { | |||
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");} | |||
AtomicReference<OperateResultT<Short>>resultValue=new AtomicReference<>(); | |||
ReadShort(address,1).OnSource((s)->{ | |||
resultValue.set(OperateResultT.CreateSuccess(s.Content[0])); | |||
}).OnFailed(s->{ | |||
resultValue.set(OperateResultT.CreateFailedT(s.message)); | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResultT<int[]> ReadInt(String address, int length) { | |||
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");} | |||
AtomicReference<OperateResultT<int[]>>resultValue=new AtomicReference<>(); | |||
new ExceptionServer(address, length, new IExceptionHandling() { | |||
@Override | |||
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { | |||
ReadHoldingRegistersResponse res = mw.syncReadHoldingRegisters(SlaveId, add, length * 2); | |||
int[] tempValues= IntLib.ToInts(res.getData(),ReadDataFormat); | |||
if(tempValues.length==length){ | |||
resultValue.set(OperateResultT.CreateSuccess(tempValues)); | |||
}else{ | |||
resultValue.set(OperateResultT.CreateFailedT(address+",读取失败,返回长度和实际读取长度不匹配")); | |||
} | |||
} | |||
@Override | |||
public void onFailure(String error){ | |||
resultValue.set(OperateResultT.CreateFailedT(address+",读取异常:"+error)); | |||
} | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResultT<Integer> ReadInt(String address) { | |||
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");} | |||
AtomicReference<OperateResultT<Integer>>resultValue=new AtomicReference<>(); | |||
ReadInt(address,1).OnSource((s)->{ | |||
resultValue.set(OperateResultT.CreateSuccess(s.Content[0])); | |||
}).OnFailed(s->{ | |||
resultValue.set(OperateResultT.CreateFailedT(s.message)); | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResultT<byte[]> ReadByte(String address, int length) { | |||
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");} | |||
AtomicReference<OperateResultT<byte[]>>resultValue=new AtomicReference<>(); | |||
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 = mw.syncReadHoldingRegisters(SlaveId, add, tempLength ); | |||
byte[] data = res.getData(); | |||
if(data.length==tempLength){ | |||
byte[] result = Arrays.copyOfRange(data, 0, length); | |||
resultValue.set(OperateResultT.CreateSuccess(result)); | |||
}else{ | |||
resultValue.set(OperateResultT.CreateFailedT(address+",读取失败,返回长度和实际读取长度不匹配")); | |||
} | |||
} | |||
@Override | |||
public void onFailure(String error){ | |||
resultValue.set(OperateResultT.CreateFailedT(address+",读取异常:"+error)); | |||
} | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResultT<String> ReadString(String address, int length) { | |||
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");} | |||
AtomicReference<OperateResultT<String>>resultValue=new AtomicReference<>(); | |||
new ExceptionServer(address, length, new IExceptionHandling() { | |||
@Override | |||
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { | |||
ReadHoldingRegistersResponse res = mw.syncReadHoldingRegisters(SlaveId, add, length); | |||
byte[] data = res.getData(); | |||
try { | |||
if (data.length ==length*2) { | |||
resultValue.set(OperateResultT.CreateSuccess(new String(data, "UTF-8").trim())); | |||
} | |||
} catch (UnsupportedEncodingException ex) { | |||
resultValue.set(OperateResultT.CreateFailedT(address+",读取失败,字符串解析失败:"+ex.toString())); | |||
} | |||
} | |||
@Override | |||
public void onFailure(String error){ | |||
resultValue.set(OperateResultT.CreateFailedT(address+",读取异常:"+error)); | |||
} | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResultT<float[]> ReadFloat(String address, int length) { | |||
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");} | |||
AtomicReference<OperateResultT<float[]>>resultValue=new AtomicReference<>(); | |||
new ExceptionServer(address, length, new IExceptionHandling() { | |||
@Override | |||
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { | |||
ReadHoldingRegistersResponse res = mw.syncReadHoldingRegisters(SlaveId, add, length*2); | |||
float[] tempValues = FloatLib.ToFloats(res.getData(),ReadDataFormat); | |||
if (tempValues.length == length) { | |||
resultValue.set(OperateResultT.CreateSuccess(tempValues)); | |||
}else{ | |||
resultValue.set(OperateResultT.CreateFailedT(address+",读取失败,返回长度和实际读取长度不匹配")); | |||
} | |||
} | |||
@Override | |||
public void onFailure(String error){ | |||
resultValue.set(OperateResultT.CreateFailedT(address+",读取异常:"+error)); | |||
} | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResultT<Float> ReadFloat(String address) { | |||
if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");} | |||
AtomicReference<OperateResultT<Float>>resultValue=new AtomicReference<>(); | |||
ReadFloat(address,1).OnSource((s)->{ | |||
resultValue.set(OperateResultT.CreateSuccess(s.Content[0])); | |||
}).OnFailed(s->{ | |||
resultValue.set(OperateResultT.CreateFailedT(s.message)); | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResult WriteBool(String address, boolean value) { | |||
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");} | |||
return WriteBool(address,new boolean[]{value}); | |||
} | |||
@Override | |||
public OperateResult WriteBool(String address, boolean[] value) { | |||
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");} | |||
AtomicReference<OperateResult>resultValue=new AtomicReference<>(); | |||
new ExceptionServer(address, 1, new IExceptionHandling() { | |||
@Override | |||
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { | |||
mw.syncWriteCoils(SlaveId, add, value); | |||
resultValue.set(OperateResult.CreateSuccess()); | |||
} | |||
@Override | |||
public void onFailure(String error){ | |||
resultValue.set(OperateResult.CreateFailed(address+",读取异常:"+error)); | |||
} | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResult WriteBool(String address, boolean[] value, int slaveId) { | |||
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");} | |||
AtomicReference<OperateResult>resultValue=new AtomicReference<>(); | |||
new ExceptionServer(address, 1, new IExceptionHandling() { | |||
@Override | |||
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { | |||
mw.syncWriteCoils(slaveId, add, value); | |||
resultValue.set(OperateResult.CreateSuccess()); | |||
} | |||
@Override | |||
public void onFailure(String error){ | |||
resultValue.set(OperateResult.CreateFailed(address+",读取异常:"+error)); | |||
} | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResult WriteShort(String address, short value) { | |||
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");} | |||
return WriteShort(address, new short[]{value}); | |||
} | |||
@Override | |||
public OperateResult WriteShort(String address, short[] value) { | |||
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");} | |||
AtomicReference<OperateResult>resultValue=new AtomicReference<>(); | |||
new ExceptionServer(address, 1, new IExceptionHandling() { | |||
@Override | |||
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { | |||
mw.syncWriteRegisters(SlaveId, add, value); | |||
resultValue.set(OperateResult.CreateSuccess()); | |||
} | |||
@Override | |||
public void onFailure(String error){ | |||
resultValue.set(OperateResult.CreateFailed(address+",读取异常:"+error)); | |||
} | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResult WriteShort(String address, short[] value, int slaveId) { | |||
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");} | |||
AtomicReference<OperateResult>resultValue=new AtomicReference<>(); | |||
new ExceptionServer(address, 1, new IExceptionHandling() { | |||
@Override | |||
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { | |||
mw.syncWriteRegisters(slaveId, add, value); | |||
resultValue.set(OperateResult.CreateSuccess()); | |||
} | |||
@Override | |||
public void onFailure(String error){ | |||
resultValue.set(OperateResult.CreateFailed(address+",读取异常:"+error)); | |||
} | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResult WriteInt(String address, int value) { | |||
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");} | |||
return WriteInt(address, new int[]{value}); | |||
} | |||
@Override | |||
public OperateResult WriteInt(String address, int[] value) { | |||
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");} | |||
AtomicReference<OperateResult>resultValue=new AtomicReference<>(); | |||
new ExceptionServer(address, 1, new IExceptionHandling() { | |||
@Override | |||
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { | |||
short[] send=ShortLib.ToShorts(value,WriteDataFormat); | |||
mw.syncWriteRegisters(SlaveId, add,send); | |||
resultValue.set(OperateResult.CreateSuccess()); | |||
} | |||
@Override | |||
public void onFailure(String error){ | |||
resultValue.set(OperateResult.CreateFailed(address+",读取异常:"+error)); | |||
} | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResult WriteInt(String address, int[] value, int slaveId) { | |||
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");} | |||
AtomicReference<OperateResult>resultValue=new AtomicReference<>(); | |||
new ExceptionServer(address, 1, new IExceptionHandling() { | |||
@Override | |||
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { | |||
short[] send=ShortLib.ToShorts(value,WriteDataFormat); | |||
mw. syncWriteRegisters(slaveId, add,send); | |||
resultValue.set(OperateResult.CreateSuccess()); | |||
} | |||
@Override | |||
public void onFailure(String error){ | |||
resultValue.set(OperateResult.CreateFailed(address+",读取异常:"+error)); | |||
} | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResult WriteString(String address, String value, int slaveId) { | |||
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");} | |||
AtomicReference<OperateResult>resultValue=new AtomicReference<>(); | |||
new ExceptionServer(address, 1, new IExceptionHandling() { | |||
@Override | |||
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { | |||
byte[] bytes= value.getBytes(); | |||
short[] send =ByteToShort(bytes); | |||
mw.syncWriteRegisters(slaveId, add, send); | |||
resultValue.set(OperateResult.CreateSuccess()); | |||
} | |||
@Override | |||
public void onFailure(String error){ | |||
resultValue.set(OperateResult.CreateFailed(address+",读取异常:"+error)); | |||
} | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResult WriteFloat(String address, float value) { | |||
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");} | |||
return WriteFloat(address, new float[]{value}); | |||
} | |||
@Override | |||
public OperateResult WriteFloat(String address, float[] value) { | |||
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");} | |||
AtomicReference<OperateResult>resultValue=new AtomicReference<>(); | |||
new ExceptionServer(address, 1, new IExceptionHandling() { | |||
@Override | |||
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { | |||
short[] send=ShortLib.ToShorts(value,WriteDataFormat); | |||
mw.syncWriteRegisters(SlaveId, add, send); | |||
resultValue.set(OperateResult.CreateSuccess()); | |||
} | |||
@Override | |||
public void onFailure(String error){ | |||
resultValue.set(OperateResult.CreateFailed(address+",读取异常:"+error)); | |||
} | |||
}); | |||
return resultValue.get(); | |||
} | |||
@Override | |||
public OperateResult WriteFloat(String address, float[] value, int slaveId) { | |||
if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");} | |||
AtomicReference<OperateResult>resultValue=new AtomicReference<>(); | |||
new ExceptionServer(address, 1, new IExceptionHandling() { | |||
@Override | |||
public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException { | |||
short[] send=ShortLib.ToShorts(value,WriteDataFormat); | |||
mw.syncWriteRegisters(slaveId, add, send); | |||
resultValue.set(OperateResult.CreateSuccess()); | |||
} | |||
@Override | |||
public void onFailure(String error){ | |||
resultValue.set(OperateResult.CreateFailed(address+",读取异常:"+error)); | |||
} | |||
}); | |||
return resultValue.get(); | |||
} | |||
} |
@@ -0,0 +1,157 @@ | |||
package com.bonait.bnframework.HBL.Communication.Siemens; | |||
import com.bonait.bnframework.HBL.DataUtil.Convert; | |||
import com.bonait.bnframework.HBL.Interface.IRun; | |||
import com.bonait.bnframework.HBL.Logs.MessageLog; | |||
import com.bonait.bnframework.HBL.Result.OperateResult; | |||
import com.bonait.bnframework.HBL.Result.OperateResultT; | |||
import com.github.xingshuangs.iot.protocol.s7.enums.EPlcType; | |||
public class CommHelper { | |||
private static CommHelper mInstance; //实例变量设置私有,防止直接通过类名访问 | |||
private CommHelper() { //默认构造函数私有,防止类外直接new创建对象 | |||
} | |||
public static synchronized CommHelper get() { //静态同步方法作为唯一的实例对象获取方式 | |||
if (mInstance == null) { | |||
mInstance = new CommHelper(); | |||
} | |||
return mInstance; | |||
} | |||
private String IPAddress="127.0.0.1"; | |||
public boolean IsConnected(){ | |||
return siemens.IsConnected; | |||
} | |||
public IRun ConnectOk; | |||
public SiemensHelper siemens=new SiemensHelper(EPlcType.S200_SMART, IPAddress); | |||
public void Connect(){ | |||
new Thread(new Runnable() { | |||
@Override | |||
public void run() { | |||
MessageLog.ShowInfo("开始连接PLC"); | |||
int tempFlag=0; | |||
while (!siemens.checkConnected()){ | |||
try{ | |||
tempFlag++; | |||
siemens=new SiemensHelper(EPlcType.S200_SMART, IPAddress); | |||
siemens.connect(); | |||
siemens.Delay(1000); | |||
}catch (Exception e){ | |||
if(tempFlag==1)MessageLog.ShowInfo("PLC连接失败:"+e.getMessage()); | |||
siemens.Delay(1000); | |||
} | |||
} | |||
if(ConnectOk!=null)ConnectOk.Run(); | |||
siemens.IsConnected=true; | |||
MessageLog.ShowInfo("PLC连接成功"); | |||
} | |||
}).start(); | |||
} | |||
public void writePLC(String add,Object value){ | |||
if(!IsConnected()) { | |||
MessageLog.ShowInfo(add+":写入数据失败,连接已断开"); | |||
return; | |||
} | |||
if(value==null) { | |||
MessageLog.ShowInfo("writePLC:写入值为空"); | |||
return; | |||
} | |||
try{ | |||
if(add.toUpperCase().contains("VD")){ | |||
Float tempVD= Float.parseFloat(value.toString()); | |||
siemens.WriteFloat32(add,tempVD); | |||
} | |||
else if (add.toUpperCase().contains("VW")){ | |||
Integer tempVW= Integer.parseInt(value.toString()); | |||
siemens.WriteUInt16(add,tempVW); | |||
} | |||
else if (add.toUpperCase().contains("V")){ | |||
Boolean tempV= Boolean.parseBoolean(value.toString()); | |||
siemens.WriteBoolean(add,tempV); | |||
} | |||
}catch (Exception e){ | |||
MessageLog.ShowInfo("writePLC:写入失败,"+e.getMessage()); | |||
} | |||
} | |||
public Object readPLC(String add){ | |||
try{ | |||
if(add.toUpperCase().contains("VD")){ | |||
return siemens.ReadFloat32(add); | |||
} | |||
else if (add.toUpperCase().contains("VW")||add.toUpperCase().contains("IW")||add.toUpperCase().contains("QW")){ | |||
return siemens.ReadUInt16(add); | |||
} | |||
else if (add.toUpperCase().contains("V")){ | |||
return siemens.ReadBoolean(add); | |||
} | |||
}catch (Exception e){ | |||
MessageLog.ShowInfo("readPLC:读取失败,"+e.getMessage()); | |||
} | |||
return new Object(); | |||
} | |||
public <T> OperateResultT<T> Read(String add){ | |||
if(!IsConnected()) return OperateResultT.CreateFailedT(add+":读取数据失败,连接已断开"); | |||
OperateResultT<T> result = new OperateResultT<>(); | |||
String typeName=result.Content.getClass() .getName(); | |||
try{ | |||
if(typeName.contains("Boolean")){ | |||
return Convert.TryToGenericity(siemens.ReadBoolean(add)); | |||
}else if(typeName.contains("Integer")){ | |||
if(add.toUpperCase().contains("VD")){ | |||
return Convert.TryToGenericity(siemens.ReadInt32(add)); | |||
} | |||
else if (add.toUpperCase().contains("VW")||add.toUpperCase().contains("IW")||add.toUpperCase().contains("QW")){ | |||
return Convert.TryToGenericity(siemens.ReadUInt16(add)); | |||
} | |||
}else if(typeName.contains("Short")){ | |||
return Convert.TryToGenericity(siemens.ReadInt16(add)); | |||
}else if(typeName.contains("Float")){ | |||
return Convert.TryToGenericity(siemens.ReadFloat32(add)); | |||
}else{ | |||
return OperateResultT.CreateFailedT(typeName+" 暂不支持的数据类型"); | |||
} | |||
}catch (Exception e){ | |||
return OperateResultT.CreateFailedT(e); | |||
} | |||
return result; | |||
} | |||
public <T> OperateResult Write(String add, T value){ | |||
if(!IsConnected()) return OperateResult.CreateFailed(add+":读取数据失败,连接已断开"); | |||
if(value ==null) return OperateResult.CreateFailed(add+":写入值无效"); | |||
String typeName=value.getClass() .getName(); | |||
try{ | |||
if(typeName.contains("Boolean")){ | |||
Convert.<Boolean>TryToGenericity(value).OnSource(s->{ siemens.WriteBoolean(add,s.Content);}); | |||
}else if(typeName.contains("Integer")){ | |||
if(add.toUpperCase().contains("VD")){ | |||
Convert.<Integer>TryToGenericity(value).OnSource(s->{ siemens.WriteInt32(add,s.Content);}); | |||
} | |||
else if (add.toUpperCase().contains("VW")){ | |||
Convert.<Integer>TryToGenericity(value).OnSource(s->{ siemens.WriteUInt16(add,s.Content);}); | |||
} | |||
}else if(typeName.contains("Short")){ | |||
Convert.<Short>TryToGenericity(value).OnSource(s->{ siemens.WriteInt16(add,s.Content);}); | |||
}else if(typeName.contains("Float")){ | |||
Convert.<Float>TryToGenericity(value).OnSource(s->{ siemens.WriteFloat32(add,s.Content);}); | |||
}else{ | |||
return OperateResult.CreateFailed(typeName+" 暂不支持的数据类型"); | |||
} | |||
return OperateResult.CreateSuccess(); | |||
}catch (Exception e){ | |||
return OperateResult.CreateFailed(e); | |||
} | |||
} | |||
} |
@@ -0,0 +1,360 @@ | |||
package com.bonait.bnframework.HBL.Communication.Siemens; | |||
import android.util.Log; | |||
import com.bonait.bnframework.HBL.Logs.MessageLog; | |||
import com.github.xingshuangs.iot.exceptions.SocketRuntimeException; | |||
import com.github.xingshuangs.iot.protocol.s7.enums.EPlcType; | |||
import com.github.xingshuangs.iot.protocol.s7.model.DataItem; | |||
import com.github.xingshuangs.iot.protocol.s7.service.S7PLC; | |||
import com.github.xingshuangs.iot.protocol.s7.utils.AddressUtil; | |||
import com.github.xingshuangs.iot.utils.FloatUtil; | |||
import com.github.xingshuangs.iot.utils.IntegerUtil; | |||
import com.github.xingshuangs.iot.utils.ShortUtil; | |||
import java.util.ArrayList; | |||
import java.util.Arrays; | |||
import java.util.List; | |||
public class SiemensHelper extends S7PLC { | |||
public Boolean IsConnected=false; | |||
public boolean CancelWrite=false; | |||
public void Delay(long millis){ | |||
try{ | |||
Thread.sleep(millis); | |||
}catch(InterruptedException e){ | |||
} | |||
} | |||
public boolean ReadBoolean(String address){ | |||
boolean result=false; | |||
while(true){ | |||
try { | |||
result=this.readBoolean(address); | |||
IsConnected=true; | |||
break; | |||
} | |||
catch(SocketRuntimeException ex){ | |||
this.close(); | |||
IsConnected=false; | |||
Delay(1000); | |||
} | |||
} | |||
return result; | |||
} | |||
public List<Boolean> ReadBoolean(String... address) { | |||
List<Boolean> result=new ArrayList<>(); | |||
while(true){ | |||
try { | |||
result=this.readBoolean(Arrays.asList(address)); | |||
IsConnected=true; | |||
break; | |||
} | |||
catch(SocketRuntimeException ex){ | |||
this.close(); | |||
IsConnected=false; | |||
Delay(1000); | |||
} | |||
} | |||
return result; | |||
} | |||
public short ReadInt16(String address) { | |||
short result=0; | |||
while(true){ | |||
try { | |||
DataItem dataItem = this.readS7Data(AddressUtil.parseByte(address, 2)); | |||
result= ShortUtil.toInt16(dataItem.getData()); | |||
IsConnected=true; | |||
break; | |||
} | |||
catch(SocketRuntimeException ex){ | |||
this.close(); | |||
IsConnected=false; | |||
Delay(1000); | |||
} | |||
} | |||
return result; | |||
} | |||
public List<Short> ReadInt16(String... address) { | |||
List<Short> result=new ArrayList<>(); | |||
while(true){ | |||
try { | |||
result=this.readInt16(Arrays.asList(address)); | |||
IsConnected=true; | |||
break; | |||
} | |||
catch(SocketRuntimeException ex){ | |||
this.close(); | |||
IsConnected=false; | |||
Delay(1000); | |||
} | |||
} | |||
return result; | |||
} | |||
public int ReadUInt16(String address) { | |||
int result=0; | |||
while(true){ | |||
try { | |||
DataItem dataItem = this.readS7Data(AddressUtil.parseByte(address, 2)); | |||
result= ShortUtil.toUInt16(dataItem.getData()); | |||
IsConnected=true; | |||
break; | |||
} | |||
catch(SocketRuntimeException ex){ | |||
this.close(); | |||
IsConnected=false; | |||
Delay(1000); | |||
} | |||
} | |||
return result; | |||
} | |||
public List<Integer> ReadUInt16(String... address) { | |||
List<Integer> result=new ArrayList<>(); | |||
while(true){ | |||
try { | |||
result=this.readUInt16(Arrays.asList(address)); | |||
IsConnected=true; | |||
break; | |||
} | |||
catch(SocketRuntimeException ex){ | |||
this.close(); | |||
IsConnected=false; | |||
Delay(1000); | |||
} | |||
} | |||
return result; | |||
} | |||
public int ReadInt32(String address) { | |||
int result=0; | |||
while(true){ | |||
try { | |||
DataItem dataItem = this.readS7Data(AddressUtil.parseByte(address, 4)); | |||
result= IntegerUtil.toInt32(dataItem.getData()); | |||
IsConnected=true; | |||
break; | |||
} | |||
catch(SocketRuntimeException ex){ | |||
this.close(); | |||
IsConnected=false; | |||
Delay(1000); | |||
} | |||
} | |||
return result; | |||
} | |||
public List<Integer> ReadInt32(String... address) { | |||
List<Integer> result=new ArrayList<>(); | |||
while(true){ | |||
try { | |||
result=this.readInt32(Arrays.asList(address)); | |||
IsConnected=true; | |||
break; | |||
} | |||
catch(SocketRuntimeException ex){ | |||
this.close(); | |||
IsConnected=false; | |||
Delay(1000); | |||
} | |||
} | |||
return result; | |||
} | |||
public float ReadFloat32(String address) { | |||
float result=0f; | |||
while(true){ | |||
try { | |||
DataItem dataItem = this.readS7Data(AddressUtil.parseByte(address, 4)); | |||
result= FloatUtil.toFloat32(dataItem.getData()); | |||
IsConnected=true; | |||
break; | |||
} | |||
catch(SocketRuntimeException ex){ | |||
this.close(); | |||
IsConnected=false; | |||
Delay(1000); | |||
} | |||
} | |||
return result; | |||
} | |||
public List<Float> ReadFloat32(String... address) { | |||
List<Float> result=new ArrayList<>(); | |||
while(true){ | |||
try { | |||
result=this.readFloat32(Arrays.asList(address)); | |||
IsConnected=true; | |||
break; | |||
} | |||
catch(SocketRuntimeException ex){ | |||
this.close(); | |||
IsConnected=false; | |||
Delay(1000); | |||
} | |||
} | |||
return result; | |||
} | |||
public void WriteBoolean(String address, boolean data) { | |||
if(!IsConnected){ | |||
MessageLog.ShowInfo(address+":写入数据失败,连接已断开"); | |||
return; | |||
} | |||
while (true) { | |||
try { | |||
this.writeS7Data(AddressUtil.parseBit(address), DataItem.createReqByBoolean(data)); | |||
IsConnected=true; | |||
break; | |||
} | |||
catch(SocketRuntimeException ex){ | |||
this.close(); | |||
IsConnected=false; | |||
Delay(100); | |||
if(CancelWrite)break; | |||
} | |||
catch (Exception e){ | |||
MessageLog.ShowError("WriteBoolean 写入异常:"+e.toString()); | |||
break; | |||
} | |||
} | |||
} | |||
public void WriteUInt16(String address, int data) { | |||
if(!IsConnected){ | |||
MessageLog.ShowInfo(address+":写入数据失败,连接已断开"); | |||
return; | |||
} | |||
while (true) { | |||
try { | |||
this.writeByte(address, ShortUtil.toByteArray(data)); | |||
IsConnected=true; | |||
break; | |||
} | |||
catch(SocketRuntimeException ex){ | |||
this.close(); | |||
IsConnected=false; | |||
Delay(100); | |||
if(CancelWrite)break; | |||
} | |||
catch (Exception e){ | |||
MessageLog.ShowError("WriteUInt16 写入异常:"+e.toString()); | |||
break; | |||
} | |||
} | |||
} | |||
public void WriteInt16(String address, short data) { | |||
if(!IsConnected){ | |||
MessageLog.ShowInfo(address+":写入数据失败,连接已断开"); | |||
return; | |||
} | |||
while (true) { | |||
try { | |||
Log.e("info","准备写入数据:"+data); | |||
this.writeByte(address, ShortUtil.toByteArray(data)); | |||
IsConnected=true; | |||
break; | |||
} | |||
catch(SocketRuntimeException ex){ | |||
Log.e("socketException","写入:"+data+"失败"); | |||
this.close(); | |||
IsConnected=false; | |||
Delay(100); | |||
if(CancelWrite)break; | |||
} | |||
catch (Exception e){ | |||
MessageLog.ShowError("WriteInt16 写入异常:"+e.toString()); | |||
break; | |||
} | |||
} | |||
} | |||
public void WriteUInt32(String address, long data) { | |||
if(!IsConnected){ | |||
MessageLog.ShowInfo(address+":写入数据失败,连接已断开"); | |||
return; | |||
} | |||
while (true) { | |||
try { | |||
this.writeByte(address, IntegerUtil.toByteArray(data)); | |||
IsConnected=true; | |||
break; | |||
} | |||
catch(SocketRuntimeException ex){ | |||
this.close(); | |||
IsConnected=false; | |||
Delay(100); | |||
if(CancelWrite)break; | |||
} | |||
catch (Exception e){ | |||
MessageLog.ShowError("WriteUInt32 写入异常:"+e.toString()); | |||
break; | |||
} | |||
} | |||
} | |||
public void WriteInt32(String address, int data) { | |||
if(!IsConnected){ | |||
MessageLog.ShowInfo(address+":写入数据失败,连接已断开"); | |||
return; | |||
} | |||
while (true) { | |||
try { | |||
this.writeByte(address, IntegerUtil.toByteArray(data)); | |||
IsConnected=true; | |||
break; | |||
} | |||
catch(SocketRuntimeException ex){ | |||
this.close(); | |||
IsConnected=false; | |||
Delay(100); | |||
if(CancelWrite)break; | |||
} | |||
catch (Exception e){ | |||
MessageLog.ShowError("WriteInt32 写入异常:"+e.toString()); | |||
break; | |||
} | |||
} | |||
} | |||
public void WriteFloat32(String address, float data) { | |||
if(!IsConnected){ | |||
MessageLog.ShowInfo(address+":写入数据失败,连接已断开"); | |||
return; | |||
} | |||
while (true) { | |||
try { | |||
this.writeByte(address, FloatUtil.toByteArray(data)); | |||
IsConnected=true; | |||
break; | |||
} | |||
catch(SocketRuntimeException ex){ | |||
this.close(); | |||
IsConnected=false; | |||
Delay(100); | |||
if(CancelWrite)break; | |||
} | |||
catch (Exception e){ | |||
MessageLog.ShowError("WriteFloat32 写入异常:"+e.toString()); | |||
break; | |||
} | |||
} | |||
} | |||
public SiemensHelper(EPlcType PlcType, String ip){ | |||
super(PlcType, ip); | |||
} | |||
} |
@@ -0,0 +1,213 @@ | |||
package com.bonait.bnframework.HBL.CustomView; | |||
import android.content.Context; | |||
import android.content.res.TypedArray; | |||
import android.graphics.Canvas; | |||
import android.graphics.Color; | |||
import android.graphics.Paint; | |||
import android.graphics.Path; | |||
import android.graphics.RectF; | |||
import android.os.Build; | |||
import android.util.AttributeSet; | |||
import android.view.View; | |||
import android.view.ViewGroup; | |||
import com.bonait.bnframework.R; | |||
/** | |||
* 阴影容器 | |||
* 需要在 res->values->attrs.xml中添加以下内容 | |||
* <declare-styleable name="ShadowContainer"> | |||
* <attr name="containerShadowColor" format="color" /><!--阴影颜色--> | |||
* <attr name="containerShadowRadius" format="dimension" /><!--阴影半径--> | |||
* <attr name="containerDeltaLength" format="dimension" /><!--子View到ShadowContainer的距离--> | |||
* <attr name="containerCornerRadius" format="dimension" /><!--子View背景的圆角大小--> | |||
* <attr name="deltaX" format="dimension" /> | |||
* <attr name="deltaY" format="dimension" /> | |||
* <attr name="enable" format="boolean" /> | |||
* </declare-styleable> | |||
* Reference: https://github.com/cjlemon/Shadow | |||
*/ | |||
public class ShadowContainer extends ViewGroup { | |||
private final float deltaLength; | |||
private final float cornerRadius; | |||
private final Paint mShadowPaint; | |||
private boolean drawShadow; | |||
public ShadowContainer(Context context) { | |||
this(context, null); | |||
} | |||
public ShadowContainer(Context context, AttributeSet attrs) { | |||
this(context, attrs, 0); | |||
} | |||
public ShadowContainer(Context context, AttributeSet attrs, int defStyleAttr) { | |||
super(context, attrs, defStyleAttr); | |||
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ShadowContainer); | |||
int shadowColor = a.getColor(R.styleable.ShadowContainer_containerShadowColor, Color.RED); | |||
float shadowRadius = a.getDimension(R.styleable.ShadowContainer_containerShadowRadius, 0); | |||
deltaLength = a.getDimension(R.styleable.ShadowContainer_containerDeltaLength, 0); | |||
cornerRadius = a.getDimension(R.styleable.ShadowContainer_containerCornerRadius, 0); | |||
float dx = a.getDimension(R.styleable.ShadowContainer_deltaX, 0); | |||
float dy = a.getDimension(R.styleable.ShadowContainer_deltaY, 0); | |||
drawShadow = a.getBoolean(R.styleable.ShadowContainer_enable, true); | |||
a.recycle(); | |||
mShadowPaint = new Paint(); | |||
mShadowPaint.setStyle(Paint.Style.FILL); | |||
mShadowPaint.setAntiAlias(true); | |||
mShadowPaint.setColor(shadowColor); | |||
mShadowPaint.setShadowLayer(shadowRadius, dx, dy, shadowColor); | |||
} | |||
@Override | |||
protected void dispatchDraw(Canvas canvas) { | |||
if (drawShadow) { | |||
/* | |||
setShadowLayer()/setMaskFilter is not support hardware acceleration, so using LAYER_TYPE_SOFTWARE, but software layers isn't always good. | |||
LAYER_TYPE_SOFTWARE: software layers should be avoided when the affected view tree updates often. | |||
*/ | |||
if (getLayerType() != LAYER_TYPE_SOFTWARE) { | |||
setLayerType(LAYER_TYPE_SOFTWARE, null); | |||
} | |||
View child = getChildAt(0); | |||
int left = child.getLeft(); | |||
int top = child.getTop(); | |||
int right = child.getRight(); | |||
int bottom = child.getBottom(); | |||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { | |||
canvas.drawRoundRect(left, top, right, bottom, cornerRadius, cornerRadius, mShadowPaint); | |||
} else { | |||
Path drawablePath = new Path(); | |||
drawablePath.moveTo(left + cornerRadius, top); | |||
drawablePath.arcTo(new RectF(left, top, left + 2 * cornerRadius, top + 2 * cornerRadius), -90, -90, false); | |||
drawablePath.lineTo(left, bottom - cornerRadius); | |||
drawablePath.arcTo(new RectF(left, bottom - 2 * cornerRadius, left + 2 * cornerRadius, bottom), 180, -90, false); | |||
drawablePath.lineTo(right - cornerRadius, bottom); | |||
drawablePath.arcTo(new RectF(right - 2 * cornerRadius, bottom - 2 * cornerRadius, right, bottom), 90, -90, false); | |||
drawablePath.lineTo(right, top + cornerRadius); | |||
drawablePath.arcTo(new RectF(right - 2 * cornerRadius, top, right, top + 2 * cornerRadius), 0, -90, false); | |||
drawablePath.close(); | |||
canvas.drawPath(drawablePath, mShadowPaint); | |||
} | |||
} | |||
super.dispatchDraw(canvas); | |||
} | |||
/** | |||
* setMeasuredDimension(): store the modified width and modified height. | |||
* | |||
* @param widthMeasureSpec the original width | |||
* @param heightMeasureSpec the original height | |||
*/ | |||
@Override | |||
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { | |||
super.onMeasure(widthMeasureSpec, heightMeasureSpec); | |||
if (getChildCount() != 1) { | |||
throw new IllegalStateException("Child View can have only one!!!"); | |||
} | |||
int measuredWidth = getMeasuredWidth(); | |||
int measuredHeight = getMeasuredHeight(); | |||
int widthMode = MeasureSpec.getMode(widthMeasureSpec); | |||
int heightMode = MeasureSpec.getMode(heightMeasureSpec); | |||
View child = getChildAt(0); | |||
MarginLayoutParams layoutParams = (MarginLayoutParams) child.getLayoutParams(); | |||
int childBottomMargin = (int) (Math.max(deltaLength, layoutParams.bottomMargin) + 1); | |||
int childLeftMargin = (int) (Math.max(deltaLength, layoutParams.leftMargin) + 1); | |||
int childRightMargin = (int) (Math.max(deltaLength, layoutParams.rightMargin) + 1); | |||
int childTopMargin = (int) (Math.max(deltaLength, layoutParams.topMargin) + 1); | |||
int widthMeasureSpecMode; | |||
int widthMeasureSpecSize; | |||
int heightMeasureSpecMode; | |||
int heightMeasureSpecSize; | |||
if (widthMode == MeasureSpec.UNSPECIFIED) { | |||
widthMeasureSpecMode = MeasureSpec.UNSPECIFIED; | |||
widthMeasureSpecSize = MeasureSpec.getSize(widthMeasureSpec); | |||
} else { | |||
if (layoutParams.width == MarginLayoutParams.MATCH_PARENT) { | |||
widthMeasureSpecMode = MeasureSpec.EXACTLY; | |||
widthMeasureSpecSize = measuredWidth - childLeftMargin - childRightMargin; | |||
} else if (MarginLayoutParams.WRAP_CONTENT == layoutParams.width) { | |||
widthMeasureSpecMode = MeasureSpec.AT_MOST; | |||
widthMeasureSpecSize = measuredWidth - childLeftMargin - childRightMargin; | |||
} else { | |||
widthMeasureSpecMode = MeasureSpec.EXACTLY; | |||
widthMeasureSpecSize = layoutParams.width; | |||
} | |||
} | |||
if (heightMode == MeasureSpec.UNSPECIFIED) { | |||
heightMeasureSpecMode = MeasureSpec.UNSPECIFIED; | |||
heightMeasureSpecSize = MeasureSpec.getSize(heightMeasureSpec); | |||
} else { | |||
if (layoutParams.height == MarginLayoutParams.MATCH_PARENT) { | |||
heightMeasureSpecMode = MeasureSpec.EXACTLY; | |||
heightMeasureSpecSize = measuredHeight - childBottomMargin - childTopMargin; | |||
} else if (MarginLayoutParams.WRAP_CONTENT == layoutParams.height) { | |||
heightMeasureSpecMode = MeasureSpec.AT_MOST; | |||
heightMeasureSpecSize = measuredHeight - childBottomMargin - childTopMargin; | |||
} else { | |||
heightMeasureSpecMode = MeasureSpec.EXACTLY; | |||
heightMeasureSpecSize = layoutParams.height; | |||
} | |||
} | |||
measureChild(child, MeasureSpec.makeMeasureSpec(widthMeasureSpecSize, widthMeasureSpecMode), MeasureSpec.makeMeasureSpec(heightMeasureSpecSize, heightMeasureSpecMode)); | |||
int parentWidthMeasureSpec = MeasureSpec.getMode(widthMeasureSpec); | |||
int parentHeightMeasureSpec = MeasureSpec.getMode(heightMeasureSpec); | |||
int height = measuredHeight; | |||
int width = measuredWidth; | |||
int childHeight = child.getMeasuredHeight(); | |||
int childWidth = child.getMeasuredWidth(); | |||
if (parentHeightMeasureSpec == MeasureSpec.AT_MOST) { | |||
height = childHeight + childTopMargin + childBottomMargin; | |||
} | |||
if (parentWidthMeasureSpec == MeasureSpec.AT_MOST) { | |||
width = childWidth + childRightMargin + childLeftMargin; | |||
} | |||
if (width < childWidth + 2 * deltaLength) { | |||
width = (int) (childWidth + 2 * deltaLength); | |||
} | |||
if (height < childHeight + 2 * deltaLength) { | |||
height = (int) (childHeight + 2 * deltaLength); | |||
} | |||
if (height != measuredHeight || width != measuredWidth) { | |||
setMeasuredDimension(width, height); | |||
} | |||
} | |||
@Override | |||
protected void onLayout(boolean changed, int l, int t, int r, int b) { | |||
View child = getChildAt(0); | |||
int measuredWidth = getMeasuredWidth(); | |||
int measuredHeight = getMeasuredHeight(); | |||
int childMeasureWidth = child.getMeasuredWidth(); | |||
int childMeasureHeight = child.getMeasuredHeight(); | |||
child.layout((measuredWidth - childMeasureWidth) / 2, (measuredHeight - childMeasureHeight) / 2, (measuredWidth + childMeasureWidth) / 2, (measuredHeight + childMeasureHeight) / 2); | |||
} | |||
@Override | |||
protected LayoutParams generateDefaultLayoutParams() { | |||
return new MarginLayoutParams(MarginLayoutParams.WRAP_CONTENT, MarginLayoutParams.WRAP_CONTENT); | |||
} | |||
@Override | |||
protected LayoutParams generateLayoutParams(LayoutParams p) { | |||
return new MarginLayoutParams(p); | |||
} | |||
@Override | |||
public LayoutParams generateLayoutParams(AttributeSet attrs) { | |||
return new MarginLayoutParams(getContext(), attrs); | |||
} | |||
public void setDrawShadow(boolean drawShadow) { | |||
if (this.drawShadow == drawShadow) { | |||
return; | |||
} | |||
this.drawShadow = drawShadow; | |||
postInvalidate(); | |||
} | |||
} | |||
@@ -0,0 +1,81 @@ | |||
package com.bonait.bnframework.HBL.DataUtil; | |||
import com.bonait.bnframework.HBL.Enum.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<value.length;i++) | |||
{ | |||
int tempValue = Float.floatToRawIntBits(value[i]); | |||
b[i*4]=(byte)((tempValue>>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<value.length;i++) | |||
{ | |||
b[i*4]=(byte)((value[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); | |||
} | |||
} |
@@ -0,0 +1,51 @@ | |||
package com.bonait.bnframework.HBL.DataUtil; | |||
import com.bonait.bnframework.HBL.Enum.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; | |||
} | |||
} | |||
@@ -0,0 +1,108 @@ | |||
package com.bonait.bnframework.HBL.DataUtil; | |||
import com.alibaba.fastjson.TypeReference; | |||
import com.bonait.bnframework.HBL.Result.OperateResultT; | |||
import com.google.gson.Gson; | |||
import com.google.gson.GsonBuilder; | |||
public class Convert { | |||
public static OperateResultT<Boolean> TryToBoolean(Object value){ | |||
if(value==null) return OperateResultT.CreateFailedT("TryToBoolean:转换对象为空"); | |||
try{ | |||
return OperateResultT.CreateSuccess(Boolean.parseBoolean(value.toString())); | |||
}catch (Exception e) { | |||
return OperateResultT.CreateFailedT(e); | |||
} | |||
} | |||
public static OperateResultT<Integer> TryToInt(Object value){ | |||
if(value==null) return OperateResultT.CreateFailedT("TryToInt:转换对象为空"); | |||
try{ | |||
return OperateResultT.CreateSuccess(Integer.parseInt(value.toString())); | |||
}catch (Exception e) { | |||
return OperateResultT.CreateFailedT(e); | |||
} | |||
} | |||
public static OperateResultT<Short> TryToShort(Object value){ | |||
if(value==null) return OperateResultT.CreateFailedT("TryToShort:转换对象为空"); | |||
try{ | |||
return OperateResultT.CreateSuccess(Short.parseShort(value.toString())); | |||
}catch (Exception e) { | |||
return OperateResultT.CreateFailedT(e); | |||
} | |||
} | |||
public static OperateResultT<Float> TryToFloat(Object value){ | |||
if(value==null) return OperateResultT.CreateFailedT("TryToFloat:转换对象为空"); | |||
try{ | |||
return OperateResultT.CreateSuccess(Float.parseFloat(value.toString())); | |||
}catch (Exception e) { | |||
return OperateResultT.CreateFailedT(e); | |||
} | |||
} | |||
public static <T> OperateResultT<T> TryToGenericity( Object value){ | |||
if(value==null) return OperateResultT.CreateFailedT("TryToGenericity:转换对象为空"); | |||
try{ | |||
return OperateResultT.CreateSuccess((T)value); | |||
}catch (Exception e) { | |||
return OperateResultT.CreateFailedT(e); | |||
} | |||
} | |||
// public static <T extends Number> OperateResultT<T> TryToNumber(Object value,Class<T> type){ | |||
// if(value==null) return OperateResultT.CreateFailedT("TryToGenericity:转换对象为空"); | |||
// try{ | |||
// String temp = value.toString(); | |||
// if(type==Integer.TYPE){ | |||
// return OperateResultT.CreateSuccess((T)Integer.valueOf(temp)); | |||
// }else if (type==Short.TYPE){ | |||
// return OperateResultT.CreateSuccess((T)Short.valueOf(temp)); | |||
// }else if (type==Byte.TYPE){ | |||
// return OperateResultT.CreateSuccess((T)Byte.valueOf(temp)); | |||
// }else if (type==Float.TYPE){ | |||
// return OperateResultT.CreateSuccess((T)Float.valueOf(temp)); | |||
// }else if (type==Long.TYPE){ | |||
// return OperateResultT.CreateSuccess((T)Long.valueOf(temp)); | |||
// }else if (type==Double.TYPE){ | |||
// return OperateResultT.CreateSuccess((T)Double.valueOf(temp)); | |||
// }else if (type.getName().contains(Boolean.TYPE.getName())){ | |||
// return OperateResultT.CreateSuccess((T)Boolean.valueOf(temp)); | |||
// }else if (type.getName().contains(String.class.getName())){ | |||
// return OperateResultT.CreateSuccess((T)temp); | |||
// } | |||
// return OperateResultT.CreateSuccess((T)value); | |||
// }catch (Exception e) { | |||
// return OperateResultT.CreateFailedT(e); | |||
// } | |||
// } | |||
public static <T> OperateResultT<T> fromJson(Object value, Class<T> clazz) { | |||
if(value==null) return OperateResultT.CreateFailedT("TryToBoolean:转换对象为空"); | |||
try{ | |||
Gson gson = new GsonBuilder().create(); | |||
String temp = gson.toJson(value); | |||
T arr = gson.fromJson(temp, clazz); | |||
if(arr!=null)return OperateResultT.CreateSuccess( arr ); | |||
else return OperateResultT.CreateFailedT("返回对象为空"); | |||
}catch (Exception e) { | |||
return OperateResultT.CreateFailedT(e); | |||
} | |||
} | |||
public static <T> OperateResultT<T> fromJson(String value, Class<T> clazz) { | |||
if(value==null||value.isEmpty()) return OperateResultT.CreateFailedT("TryToBoolean:转换对象为空"); | |||
try{ | |||
Gson gson = new GsonBuilder().create(); | |||
T arr = gson.fromJson(value, clazz); | |||
if(arr!=null)return OperateResultT.CreateSuccess( arr); | |||
else return OperateResultT.CreateFailedT("返回对象为空"); | |||
}catch (Exception e) { | |||
return OperateResultT.CreateFailedT(e); | |||
} | |||
} | |||
} |
@@ -0,0 +1,244 @@ | |||
package com.bonait.bnframework.HBL.DataUtil; | |||
import com.bonait.bnframework.HBL.Enum.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<len;i++){ | |||
if (i<bytes.length)tempBytes[i]=bytes[i]; | |||
} | |||
for(int m=0;m<result.length;m++) { | |||
result[m] = (short) ((tempBytes[m * 2] & 0xff) | ((tempBytes[m * 2 + 1] & 0xff) << 8)); | |||
} | |||
return result; | |||
} | |||
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; | |||
} | |||
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 if (address.toUpperCase().contains("GI") &&address.length() >=3){ | |||
String res = address.substring(2); | |||
if (res != null) { | |||
try { | |||
return Integer.parseInt(res); | |||
} 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 ""; | |||
} | |||
} |
@@ -0,0 +1,31 @@ | |||
package com.bonait.bnframework.HBL.DataUtil; | |||
import com.bonait.bnframework.HBL.Enum.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<bytes.length;i++){tempBytes[i]=bytes[i];} | |||
float[] result = new float[tempBytes.length/4]; | |||
for (int i=0; i<result.length; i++){ | |||
byte[] res= new ByteTransDataFormat().ByteTransDataFormat4(tempBytes,df,i*4); | |||
result[i]=ByteBuffer.wrap(res).getFloat(); | |||
} | |||
return result; | |||
} | |||
} |
@@ -0,0 +1,51 @@ | |||
package com.bonait.bnframework.HBL.DataUtil; | |||
import com.bonait.bnframework.HBL.Enum.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<bytes.length;i++){tempBytes[i]=bytes[i];} | |||
int[] result = new int[tempBytes.length/4]; | |||
for (int i=0; i<result.length; i++){ | |||
byte[] res= new ByteTransDataFormat().ByteTransDataFormat4(tempBytes,df,i*4); | |||
result[i]=ByteBuffer.wrap(res).getInt(); | |||
} | |||
return result; | |||
} | |||
public static boolean GetBit(int value,int offset) | |||
{ | |||
if (offset > 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; | |||
} | |||
} |
@@ -0,0 +1,37 @@ | |||
package com.bonait.bnframework.HBL.DataUtil; | |||
import com.bonait.bnframework.HBL.Interface.IRunT; | |||
import java.io.Serializable; | |||
import java.util.LinkedHashMap; | |||
public class NotifyPropVar<T extends Serializable> { | |||
public NotifyPropVar(T defaultValue){ | |||
_value=defaultValue; | |||
} | |||
public IRunT<T> ChangeNotify; | |||
private boolean IsFirst=false; | |||
private LinkedHashMap<String,IRunT<T>> changedNotifys=new LinkedHashMap<>(); | |||
public void Register(String key,IRunT<T> notify){ | |||
if(changedNotifys.containsKey(key))changedNotifys.remove(key); | |||
changedNotifys.put(key,notify); | |||
} | |||
private T _value; | |||
public T getValue(){ return _value; } | |||
public void setValue(T value){ | |||
if (value != null && !value.equals(_value) || !IsFirst) | |||
{ | |||
_value=value; | |||
if(ChangeNotify!=null) ChangeNotify.Run(value); | |||
changedNotifys.values().forEach(item->{item.Run(value);}); | |||
IsFirst = true; | |||
} | |||
} | |||
} | |||
@@ -0,0 +1,51 @@ | |||
package com.bonait.bnframework.HBL.DataUtil; | |||
import com.bonait.bnframework.HBL.Enum.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<bytes.length; i++){tempBytes[i]=bytes[i];} | |||
short[] result = new short[tempBytes.length/2]; | |||
for (int i=0; i<result.length; i++){ | |||
byte[] res= new ByteTransDataFormat().ByteTransDataFormat2(tempBytes,df,i*2); | |||
result[i]=ByteBuffer.wrap(res).getShort(); | |||
} | |||
return result; | |||
} | |||
public static short[] ToShorts(float[] floats, DataFormat df) { | |||
byte[] bytes = ByteLib.ToBytes(floats,df); | |||
return ShortLib.ToShorts(bytes,df); | |||
} | |||
public static short[] ToShorts(int[] floats, DataFormat df) { | |||
byte[] bytes = ByteLib.ToBytes(floats,df); | |||
return ShortLib.ToShorts(bytes,df); | |||
} | |||
public static boolean GetBit(short value,int offset) | |||
{ | |||
if (offset > 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); | |||
} | |||
} |
@@ -0,0 +1,8 @@ | |||
package com.bonait.bnframework.HBL.Dialog; | |||
public enum AlertDialogButton { | |||
OK , | |||
OKCancel, | |||
YesNoCancel, | |||
YesNo, | |||
} |
@@ -0,0 +1,15 @@ | |||
package com.bonait.bnframework.HBL.Dialog; | |||
import android.os.Bundle; | |||
import androidx.appcompat.app.AppCompatActivity; | |||
import com.bonait.bnframework.R; | |||
public class DialogActivity extends AppCompatActivity { | |||
@Override | |||
protected void onCreate(Bundle savedInstanceState) { | |||
super.onCreate(savedInstanceState); | |||
setContentView(R.layout.activity_dialog); | |||
} | |||
} |
@@ -0,0 +1,309 @@ | |||
package com.bonait.bnframework.HBL.Dialog; | |||
import android.app.Activity; | |||
import android.content.Context; | |||
import android.view.View; | |||
import android.widget.Button; | |||
import android.widget.RelativeLayout; | |||
import android.widget.TextView; | |||
import com.bonait.bnframework.HBL.Logs.MessageLog; | |||
import com.bonait.bnframework.R; | |||
/** | |||
* 自定义弹框 | |||
* 需要在 res->values->styles.xml中添加 custom_dialog2样式 | |||
* 需要在layout中添加dialog布局页面 | |||
*/ | |||
public class DialogManager { | |||
// private static DialogView dview; | |||
private static Context mContext; | |||
private static Activity mActivity; | |||
public static void Init(Context context,Activity activity){ | |||
mContext = context; | |||
mActivity=activity; | |||
} | |||
/** | |||
* 对话框,自定义按钮,非阻塞 | |||
* */ | |||
private static void showDialog(String message, AlertDialogButton btn,DialogType dt, IDialogAction action) { | |||
if(mContext==null) return; | |||
try{ | |||
DialogView dview=new DialogView(mContext, R.layout.activity_dialog, R.style.custom_dialog2); | |||
if (dview != null) { | |||
if (!dview.isShowing()) { | |||
String btnName1="确定"; | |||
String btnName2="取消"; | |||
if(btn==AlertDialogButton.YesNoCancel||btn==AlertDialogButton.YesNo){ | |||
btnName1="是"; | |||
btnName2="否"; | |||
} | |||
dview.setCanceledOnTouchOutside(false);//禁用触摸其它区域关闭弹框 | |||
RelativeLayout rlTitle = (RelativeLayout) dview.findViewById(R.id.rl_title); | |||
if(dt== DialogType.提示)rlTitle.setBackgroundResource(R.drawable.dialog_info_title_back); | |||
if(dt== DialogType.警告)rlTitle.setBackgroundResource(R.drawable.dialog_warn_title_back); | |||
if(dt== DialogType.错误)rlTitle.setBackgroundResource(R.drawable.dialog_error_title_back); | |||
TextView Tv=(TextView)dview.findViewById(R.id.tv_Title); | |||
TextView Info=(TextView)dview.findViewById(R.id.tv_Info); | |||
Button ok = (Button)dview.findViewById(R.id.btn_ok); | |||
Button cancel = (Button)dview.findViewById(R.id.btn_cancel); | |||
Tv.setText(dt.toString()); | |||
Info.setText(message); | |||
ok.setText(btnName1); | |||
cancel.setText(btnName2); | |||
if(btn==AlertDialogButton.OK)cancel.setVisibility(View.GONE); | |||
ok.setOnClickListener(view->{ | |||
if(action!=null)action.ExitDialog(true); | |||
hide(dview); | |||
}); | |||
cancel.setOnClickListener(view->{ | |||
if(action!=null)action.ExitDialog(false); | |||
hide(dview); | |||
}); | |||
dview.show(); | |||
} | |||
} | |||
}catch(Exception e){ | |||
MessageLog.ShowError("打开弹框异常:"+e.toString()); | |||
} | |||
} | |||
/** | |||
* 对话框,自定义按钮,非阻塞 | |||
* */ | |||
private static void showDialog(Context ct,String message, AlertDialogButton btn,DialogType dt, IDialogAction action) { | |||
if(ct==null) return; | |||
try{ | |||
DialogView dview=new DialogView(ct, R.layout.activity_dialog, R.style.custom_dialog2); | |||
if (dview != null) { | |||
if (!dview.isShowing()) { | |||
String btnName1="确定"; | |||
String btnName2="取消"; | |||
if(btn==AlertDialogButton.YesNoCancel||btn==AlertDialogButton.YesNo){ | |||
btnName1="是"; | |||
btnName2="否"; | |||
} | |||
dview.setCanceledOnTouchOutside(false);//禁用触摸其它区域关闭弹框 | |||
RelativeLayout rlTitle = (RelativeLayout) dview.findViewById(R.id.rl_title); | |||
if(dt== DialogType.提示)rlTitle.setBackgroundResource(R.drawable.dialog_info_title_back); | |||
if(dt== DialogType.警告)rlTitle.setBackgroundResource(R.drawable.dialog_warn_title_back); | |||
if(dt== DialogType.错误)rlTitle.setBackgroundResource(R.drawable.dialog_error_title_back); | |||
TextView Tv=(TextView)dview.findViewById(R.id.tv_Title); | |||
TextView Info=(TextView)dview.findViewById(R.id.tv_Info); | |||
Button ok = (Button)dview.findViewById(R.id.btn_ok); | |||
Button cancel = (Button)dview.findViewById(R.id.btn_cancel); | |||
Tv.setText(dt.toString()); | |||
Info.setText(message); | |||
ok.setText(btnName1); | |||
cancel.setText(btnName2); | |||
if(btn==AlertDialogButton.OK)cancel.setVisibility(View.GONE); | |||
ok.setOnClickListener(view->{ | |||
if(action!=null)action.ExitDialog(true); | |||
hide(dview); | |||
}); | |||
cancel.setOnClickListener(view->{ | |||
if(action!=null)action.ExitDialog(false); | |||
hide(dview); | |||
}); | |||
dview.show(); | |||
} | |||
} | |||
}catch(Exception e){ | |||
MessageLog.ShowError("打开弹框异常:"+e.toString()); | |||
} | |||
} | |||
/** | |||
* 对话框,自定义按钮,非阻塞 | |||
* */ | |||
private static void showDialog(Activity activity,String message, AlertDialogButton btn,DialogType dt, IDialogAction action) { | |||
if(activity==null) return; | |||
try{ | |||
DialogView dview1=new DialogView(activity, R.layout.activity_dialog, R.style.custom_dialog2); | |||
if (dview1 != null) { | |||
if (!dview1.isShowing()) { | |||
String btnName1="确定"; | |||
String btnName2="取消"; | |||
if(btn==AlertDialogButton.YesNoCancel||btn==AlertDialogButton.YesNo){ | |||
btnName1="是"; | |||
btnName2="否"; | |||
} | |||
dview1.setCanceledOnTouchOutside(false);//禁用触摸其它区域关闭弹框 | |||
RelativeLayout rlTitle = (RelativeLayout) dview1.findViewById(R.id.rl_title); | |||
if(dt== DialogType.提示)rlTitle.setBackgroundResource(R.drawable.dialog_info_title_back); | |||
if(dt== DialogType.警告)rlTitle.setBackgroundResource(R.drawable.dialog_warn_title_back); | |||
if(dt== DialogType.错误)rlTitle.setBackgroundResource(R.drawable.dialog_error_title_back); | |||
TextView Tv=(TextView)dview1.findViewById(R.id.tv_Title); | |||
TextView Info=(TextView)dview1.findViewById(R.id.tv_Info); | |||
Button ok = (Button)dview1.findViewById(R.id.btn_ok); | |||
Button cancel = (Button)dview1.findViewById(R.id.btn_cancel); | |||
Tv.setText(dt.toString()); | |||
Info.setText(message); | |||
ok.setText(btnName1); | |||
cancel.setText(btnName2); | |||
if(btn==AlertDialogButton.OK)cancel.setVisibility(View.GONE); | |||
ok.setOnClickListener(view->{ | |||
if(action!=null)action.ExitDialog(true); | |||
hide(dview1); | |||
}); | |||
cancel.setOnClickListener(view->{ | |||
if(action!=null)action.ExitDialog(false); | |||
hide(dview1); | |||
}); | |||
dview1.show(); | |||
} | |||
} | |||
}catch(Exception e){ | |||
MessageLog.ShowError("打开弹框异常:"+e.toString()); | |||
} | |||
} | |||
/** | |||
* 隐藏弹框 | |||
* @param view | |||
*/ | |||
private static void hide(DialogView view) { | |||
if (view != null) { | |||
if (view.isShowing()) { | |||
view.dismiss(); | |||
} | |||
} | |||
} | |||
/** | |||
* 信息提示框 | |||
* @param message 提示信息 | |||
* @param btn 显示按钮 | |||
* @param action 执行回调 | |||
*/ | |||
public static void showInfo(String message, AlertDialogButton btn, IDialogAction action) { | |||
if(mActivity!=null) | |||
mActivity.runOnUiThread(()->{showDialog(message,btn,DialogType.提示,action);}); | |||
else showDialog(message,btn,DialogType.提示,action); | |||
} | |||
/** | |||
* 警告提示框 | |||
* @param message 警告信息 | |||
* @param btn 显示按钮 | |||
* @param action 执行回调 | |||
*/ | |||
public static void showWarn(String message, AlertDialogButton btn, IDialogAction action) { | |||
if(mActivity!=null) | |||
mActivity.runOnUiThread(()->{showDialog(message,btn,DialogType.警告,action);}); | |||
else showDialog(message,btn,DialogType.警告,action); | |||
} | |||
/** | |||
* 错误提示框 | |||
* @param message 错误信息 | |||
* @param btn 显示按钮 | |||
* @param action 执行回调 | |||
*/ | |||
public static void showError(String message, AlertDialogButton btn, IDialogAction action) { | |||
if(mActivity!=null) | |||
mActivity.runOnUiThread(()->{showDialog(message,btn,DialogType.错误,action);}); | |||
else showDialog(message,btn,DialogType.错误,action); | |||
} | |||
/** | |||
* 信息提示框 | |||
* @param message 提示信息 | |||
* @param btn 显示按钮 | |||
* @param action 执行回调 | |||
*/ | |||
public static void showInfo( Context ct,String message, AlertDialogButton btn, IDialogAction action) { | |||
if(mActivity!=null) | |||
mActivity.runOnUiThread(()->{showDialog(ct,message,btn,DialogType.提示,action);}); | |||
else showDialog(ct,message,btn,DialogType.提示,action); | |||
} | |||
/** | |||
* 警告提示框 | |||
* @param message 警告信息 | |||
* @param btn 显示按钮 | |||
* @param action 执行回调 | |||
*/ | |||
public static void showWarn( Context ct,String message, AlertDialogButton btn, IDialogAction action) { | |||
if(mActivity!=null) | |||
mActivity.runOnUiThread(()->{showDialog(ct,message,btn,DialogType.警告,action);}); | |||
else showDialog(ct,message,btn,DialogType.警告,action); | |||
} | |||
/** | |||
* 错误提示框 | |||
* @param message 错误信息 | |||
* @param btn 显示按钮 | |||
* @param action 执行回调 | |||
*/ | |||
public static void showError( Context ct,String message, AlertDialogButton btn, IDialogAction action) { | |||
if(mActivity!=null) | |||
mActivity.runOnUiThread(()->{showDialog(ct,message,btn,DialogType.错误,action);}); | |||
else showDialog(ct,message,btn,DialogType.错误,action); | |||
} | |||
/** | |||
* 信息提示框 | |||
* @param message 提示信息 | |||
* @param btn 显示按钮 | |||
* @param action 执行回调 | |||
*/ | |||
public static void showInfo( Activity activity,String message, AlertDialogButton btn, IDialogAction action) { | |||
if(mActivity!=null) | |||
mActivity.runOnUiThread(()->{showDialog(activity,message,btn,DialogType.提示,action);}); | |||
else showDialog(activity,message,btn,DialogType.提示,action); | |||
} | |||
/** | |||
* 警告提示框 | |||
* @param message 警告信息 | |||
* @param btn 显示按钮 | |||
* @param action 执行回调 | |||
*/ | |||
public static void showWarn(Activity activity,String message, AlertDialogButton btn, IDialogAction action) { | |||
if(mActivity!=null) | |||
mActivity.runOnUiThread(()->{showDialog(activity,message,btn,DialogType.警告,action);}); | |||
else showDialog(activity,message,btn,DialogType.警告,action); | |||
} | |||
/** | |||
* 错误提示框 | |||
* @param message 错误信息 | |||
* @param btn 显示按钮 | |||
* @param action 执行回调 | |||
*/ | |||
public static void showError( Activity activity,String message, AlertDialogButton btn, IDialogAction action) { | |||
if(mActivity!=null) | |||
mActivity.runOnUiThread(()->{showDialog(activity,message,btn,DialogType.错误,action);}); | |||
else showDialog(activity,message,btn,DialogType.错误,action); | |||
} | |||
} | |||
@@ -0,0 +1,7 @@ | |||
package com.bonait.bnframework.HBL.Dialog; | |||
public enum DialogType { | |||
警告, | |||
提示, | |||
错误 | |||
} |
@@ -0,0 +1,35 @@ | |||
package com.bonait.bnframework.HBL.Dialog; | |||
import android.app.Activity; | |||
import android.app.Dialog; | |||
import android.content.Context; | |||
import android.view.Window; | |||
import androidx.annotation.NonNull; | |||
public class DialogView extends Dialog { | |||
public DialogView(@NonNull Context context, int layout, int style, int gravity) { | |||
super(context, style); | |||
setContentView(layout); | |||
Window mWindow = getWindow(); | |||
// WindowManager.LayoutParams params = mWindow.getAttributes(); | |||
// params.width = WindowManager.LayoutParams.MATCH_PARENT; | |||
// params.height = WindowManager.LayoutParams.WRAP_CONTENT; | |||
// params.gravity = gravity; | |||
// mWindow.setAttributes(params); | |||
} | |||
public DialogView(@NonNull Context context, int layout, int style) { | |||
super(context, style); | |||
setContentView(layout); | |||
Window mWindow = getWindow(); | |||
} | |||
public DialogView(@NonNull Activity activity, int layout, int style) { | |||
super(activity, style); | |||
setContentView(layout); | |||
Window mWindow = getWindow(); | |||
} | |||
} |
@@ -0,0 +1,6 @@ | |||
package com.bonait.bnframework.HBL.Dialog; | |||
public interface IDialogAction { | |||
void ExitDialog(boolean status); | |||
} |
@@ -1,4 +1,4 @@ | |||
package com.bonait.bnframework.common.helper; | |||
package com.bonait.bnframework.HBL.Enum; | |||
public enum DataFormat { | |||
ABCD, |
@@ -0,0 +1,43 @@ | |||
package com.bonait.bnframework.HBL; | |||
import com.bonait.bnframework.HBL.Interface.IRun; | |||
import com.bonait.bnframework.HBL.Logs.MessageLog; | |||
import java.util.concurrent.ExecutorService; | |||
import java.util.concurrent.Executors; | |||
/** | |||
* 异步方法 | |||
*/ | |||
public class Executor { | |||
private static Executor mInstance; //实例变量设置私有,防止直接通过类名访问 | |||
private Executor() { //默认构造函数私有,防止类外直接new创建对象 | |||
} | |||
public static synchronized Executor get() { //静态同步方法作为唯一的实例对象获取方式 | |||
if (mInstance == null) { | |||
mInstance = new Executor(); | |||
} | |||
return mInstance; | |||
} | |||
private ExecutorService executor= Executors.newCachedThreadPool() ; | |||
public void runThread(IRun run) { | |||
executor.submit(new Runnable(){ | |||
@Override | |||
public void run() { | |||
try { | |||
if(run!=null)run.Run(); | |||
}catch(Exception ex) { | |||
MessageLog.ShowError("runThread 异常:"+ex.getMessage()); | |||
} | |||
} | |||
}); | |||
} | |||
} |
@@ -0,0 +1,5 @@ | |||
package com.bonait.bnframework.HBL.Interface; | |||
public interface IRun { | |||
void Run(); | |||
} |
@@ -1,4 +1,4 @@ | |||
package com.bonait.bnframework.common.helper.I; | |||
package com.bonait.bnframework.HBL.Interface; | |||
public interface IRunT<T> { | |||
void Run(T t); |
@@ -0,0 +1,7 @@ | |||
package com.bonait.bnframework.HBL.Logs; | |||
public interface IMessageLogNotify { | |||
void ErrorMsg(String msg); | |||
void InfoMsg(String msg); | |||
void WarnMsg(String msg); | |||
} |
@@ -0,0 +1,62 @@ | |||
package com.bonait.bnframework.HBL.Logs; | |||
import android.util.Log; | |||
import com.bonait.bnframework.HBL.Thread.ThreadManager; | |||
import com.bonait.bnframework.common.db.QueryDB; | |||
import com.bonait.bnframework.common.db.mode.BPA_ALERTLOG; | |||
import java.util.concurrent.ConcurrentLinkedQueue; | |||
public class MessageLog { | |||
private static IMessageLogNotify MsgNotify; | |||
private static ConcurrentLinkedQueue<String> msgQueue=new ConcurrentLinkedQueue<String>(); | |||
private static void Init(){ | |||
MsgNotify = new IMessageLogNotify() { | |||
@Override | |||
public void ErrorMsg(String msg) { | |||
Log.e("错误日志",msg); | |||
} | |||
@Override | |||
public void InfoMsg(String msg) { | |||
Log.i("信息日志",msg); | |||
} | |||
@Override | |||
public void WarnMsg(String msg) { | |||
Log.w("警告日志",msg); | |||
} | |||
}; | |||
ThreadManager.get().StartLong("日志信息保存",true,()->{ | |||
while(msgQueue.size()>0){ | |||
String msg= msgQueue.poll(); | |||
BPA_ALERTLOG log= new BPA_ALERTLOG(); | |||
log.text=msg; | |||
QueryDB.AddAlertlog(log); | |||
} | |||
Thread.sleep(2000); | |||
}); | |||
} | |||
public static void ShowInfo(String msg) { | |||
if (MsgNotify == null)Init(); | |||
MsgNotify.InfoMsg(msg); | |||
} | |||
public static void ShowWarning(String msg) { | |||
if (MsgNotify == null)Init(); | |||
MsgNotify.WarnMsg(msg); | |||
} | |||
public static void ShowError(String msg) { | |||
if (MsgNotify == null)Init(); | |||
MsgNotify.ErrorMsg(msg); | |||
} | |||
public static void ShowError(Exception e) { | |||
if (MsgNotify == null)Init(); | |||
MsgNotify.ErrorMsg(e.toString()); | |||
} | |||
} |
@@ -0,0 +1,230 @@ | |||
package com.bonait.bnframework.HBL; | |||
import android.content.Context; | |||
import android.net.ConnectivityManager; | |||
import android.net.Network; | |||
import android.net.NetworkCapabilities; | |||
import android.net.NetworkInfo; | |||
import android.net.NetworkRequest; | |||
import android.os.Build; | |||
import android.util.Log; | |||
import java.io.DataOutputStream; | |||
/** | |||
* Created by LY on 2019/1/4. | |||
*/ | |||
public class NetworkUtils { | |||
//判断网络连接是否可用(返回true表示网络可用,false为不可用) | |||
public static boolean checkNetworkAvailable(Context context) { | |||
//获取手机所有链接管理对象(包括对Wi-Fi,net等连接的管理) | |||
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |||
if (manager == null) { | |||
return false; | |||
} else { | |||
//获取NetworkInfo对象 | |||
NetworkInfo[] info = manager.getAllNetworkInfo(); | |||
if (info != null && info.length > 0) { | |||
for (int i = 0; i < info.length; i++) { | |||
System.out.println(i + "状态" + info[i].getState()); | |||
System.out.println(i + "类型" + info[i].getTypeName()); | |||
// 判断当前网络状态是否为连接状态 | |||
if (info[i].getState() == NetworkInfo.State.CONNECTED) { | |||
return true; | |||
} | |||
} | |||
} | |||
} | |||
return false; | |||
} | |||
/** | |||
* 检测当的网络(WLAN、4G/3G/2G)状态,兼容Android 6.0以下 | |||
* @param context Context | |||
* @return true 表示网络可用 | |||
*/ | |||
public static boolean isNetworkConnected(Context context) { | |||
boolean result = false; | |||
try { | |||
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { | |||
if (cm != null) { | |||
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork()); | |||
if (capabilities != null) { | |||
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { | |||
result = true; | |||
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) { | |||
result = true; | |||
} | |||
} | |||
} | |||
} else { | |||
if (cm != null) { | |||
NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); | |||
if (activeNetwork != null) { | |||
// connected to the internet | |||
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { | |||
result = true; | |||
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { | |||
result = true; | |||
} | |||
} | |||
} | |||
} | |||
} catch (Exception e) { | |||
return false; | |||
} | |||
return result; | |||
} | |||
/** | |||
* 判断是否是移动网络连接 | |||
* */ | |||
public static boolean isActiveNetworkMobile(Context context) { | |||
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |||
if (connectivityManager != null) { | |||
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); | |||
return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE; | |||
} | |||
return false; | |||
} | |||
/** | |||
* 判断是否是wifi | |||
* */ | |||
public static boolean isActiveNetworkWifi(Context context) { | |||
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |||
if (connectivityManager != null) { | |||
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); | |||
return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI; | |||
} | |||
return false; | |||
} | |||
/** | |||
* @deprecated 请先使用 {@link NetworkUtils#isNetworkConnected(Context)} 方法 | |||
* | |||
* 检测当的网络(WLAN、4G/3G/2G)状态 | |||
* | |||
* @param context Context | |||
* @return true 表示网络可用 | |||
*/ | |||
@Deprecated | |||
public static boolean checkNet(Context context) { | |||
try { | |||
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |||
if (connectivity != null) { | |||
NetworkInfo info = connectivity.getActiveNetworkInfo(); | |||
if (info != null && info.isConnected()) { | |||
/*if (info.getState() == NetworkInfo.State.CONNECTED) { | |||
return true; | |||
}*/ | |||
NetworkCapabilities networkCapabilities = connectivity.getNetworkCapabilities(connectivity.getActiveNetwork()); | |||
return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED); | |||
} | |||
} | |||
} catch (Exception e) { | |||
return false; | |||
} | |||
return false; | |||
} | |||
/** | |||
* 绑定有线网络 | |||
* @param context | |||
*/ | |||
public static void connetEnternet(Context context) | |||
{ | |||
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |||
NetworkRequest.Builder builder = new NetworkRequest.Builder(); | |||
builder.addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET); | |||
//builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI); | |||
NetworkRequest networkRequest = builder.build(); | |||
connManager.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() { | |||
@Override | |||
public void onAvailable(Network network) { | |||
super.onAvailable(network); | |||
connManager.bindProcessToNetwork(network); // 绑定应用程序到有线网络 | |||
} | |||
}); | |||
} | |||
/** | |||
* 绑定有线网络 | |||
* @param context | |||
*/ | |||
public static void connetWifi(Context context) | |||
{ | |||
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |||
NetworkRequest.Builder builder = new NetworkRequest.Builder(); | |||
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI); | |||
NetworkRequest networkRequest = builder.build(); | |||
connManager.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() { | |||
@Override | |||
public void onAvailable(Network network) { | |||
super.onAvailable(network); | |||
connManager.bindProcessToNetwork(network); // 绑定应用程序到有线网络 | |||
} | |||
}); | |||
} | |||
/** | |||
* 同步时间 | |||
*/ | |||
public static void SynchronizationTime() | |||
{ | |||
new Thread(new Runnable() { | |||
@Override | |||
public void run() { | |||
try { | |||
exec3("settings put global auto_time 0"); | |||
Thread.sleep(500); | |||
exec3("settings put global auto_time 1"); | |||
} catch (InterruptedException e) { | |||
} | |||
} | |||
}).start(); | |||
} | |||
/** | |||
* 发送 | |||
* @param cmds | |||
*/ | |||
public static void exec3(String... cmds) { | |||
StringBuffer command = new StringBuffer(); | |||
if (cmds.length <= 0) { | |||
return; | |||
} | |||
for (String cmd : cmds) { | |||
command.append(cmd).append("\n"); | |||
} | |||
Process process = null; | |||
DataOutputStream os = null; | |||
try { | |||
process = Runtime.getRuntime().exec("su"); | |||
// process = Runtime.getRuntime().exec("system/bin/su"); | |||
os = new DataOutputStream(process.getOutputStream()); | |||
os.write(command.toString().getBytes()); | |||
os.writeBytes("exit\n"); | |||
os.flush(); | |||
process.waitFor(); | |||
} catch (Exception e) { | |||
e.printStackTrace(); | |||
Log.e("eeee",""+e.toString()); | |||
} finally { | |||
try { | |||
os.close(); | |||
} catch (Exception e) { | |||
e.printStackTrace(); | |||
} | |||
if(process!=null){ | |||
process.destroy(); | |||
} | |||
} | |||
} | |||
} |
@@ -0,0 +1,30 @@ | |||
package com.bonait.bnframework.HBL.Result; | |||
public abstract class IResult { | |||
/** | |||
* 是否成功 | |||
*/ | |||
public boolean isSuccess ; | |||
/** | |||
* 返回消息 | |||
*/ | |||
public String message; | |||
/** | |||
* 操作代码 | |||
*/ | |||
public ResultCode resultCode = ResultCode.Default ; | |||
abstract void setErrorMsg(String msg); | |||
public boolean getIsSuccess(){ | |||
return resultCode==ResultCode.Success; | |||
} | |||
public void setIsSuccess(boolean tempSuccess){ | |||
isSuccess= tempSuccess; | |||
resultCode = tempSuccess ? ResultCode.Success : ResultCode.Fail; | |||
} | |||
} |
@@ -0,0 +1,78 @@ | |||
package com.bonait.bnframework.HBL.Result; | |||
import com.bonait.bnframework.HBL.Interface.IRun; | |||
import com.bonait.bnframework.HBL.Logs.MessageLog; | |||
public class OperateResult extends IResult { | |||
public OperateResult(){ | |||
} | |||
public OperateResult(Exception ex){ | |||
message = ex.getMessage()+"\rException:"+ex.toString(); | |||
resultCode = ResultCode.Exception; | |||
isSuccess=false; | |||
} | |||
public OperateResult(String msg, ResultCode rc) | |||
{ | |||
message = msg; | |||
resultCode = rc; | |||
isSuccess=false; | |||
} | |||
public OperateResult(ResultCode rc) | |||
{ | |||
resultCode = rc; | |||
isSuccess=true; | |||
} | |||
@Override | |||
public void setErrorMsg(String msg) { | |||
message =message+ msg; | |||
isSuccess=false; | |||
resultCode = ResultCode.Fail; | |||
} | |||
public OperateResult OnSource(IRun action){ | |||
if(action!=null&&getIsSuccess())action.Run(); | |||
return this; | |||
} | |||
public OperateResult OnFailed(IRun action){ | |||
try{ | |||
if(action!=null&&!getIsSuccess())action.Run(); | |||
}catch(Exception e){ | |||
MessageLog.ShowError(e); | |||
} | |||
return this; | |||
} | |||
public OperateResult OnFinally(IRun action){ | |||
try{ | |||
if(action!=null)action.Run(); | |||
}catch(Exception e){ | |||
MessageLog.ShowError(e); | |||
} | |||
return this; | |||
} | |||
public static OperateResult CreateSuccess() | |||
{ | |||
return new OperateResult(ResultCode.Success); | |||
} | |||
public static OperateResult CreateFailed(String msg) | |||
{ | |||
MessageLog.ShowError(msg); | |||
return new OperateResult(msg, ResultCode.Fail); | |||
} | |||
public static OperateResult CreateFailed(Exception ex) | |||
{ | |||
MessageLog.ShowError(ex.toString()); | |||
return new OperateResult(ex); | |||
} | |||
} |
@@ -0,0 +1,88 @@ | |||
package com.bonait.bnframework.HBL.Result; | |||
import com.bonait.bnframework.HBL.Interface.IRunT; | |||
import com.bonait.bnframework.HBL.Logs.MessageLog; | |||
public class OperateResultT<T> extends IResult | |||
{ | |||
public OperateResultT(){} | |||
public OperateResultT(Exception ex) { | |||
message = ex.getMessage()+"\rException:"+ex.toString(); | |||
resultCode = ResultCode.Exception; | |||
isSuccess=false; | |||
} | |||
public OperateResultT(String msg, ResultCode rc ){ | |||
message = msg; | |||
resultCode = rc; | |||
isSuccess=false; | |||
} | |||
public OperateResultT(ResultCode rc){ | |||
resultCode = rc; | |||
isSuccess=true; | |||
} | |||
@Override | |||
public void setErrorMsg(String msg) { | |||
message =message+ msg; | |||
isSuccess=false; | |||
resultCode = ResultCode.Fail; | |||
} | |||
public OperateResultT(T content, String msg, ResultCode rc){ | |||
Content = content; | |||
message = msg; | |||
resultCode = rc; | |||
isSuccess=getIsSuccess(); | |||
} | |||
public T Content ; | |||
public void setContent(T value){ | |||
Content = value; | |||
resultCode = ResultCode.Success; | |||
isSuccess=true; | |||
} | |||
public OperateResultT<T> OnSource(IRunT<OperateResultT<T>> action){ | |||
try{ | |||
if(action!=null&&getIsSuccess())action.Run(this); | |||
}catch(Exception e){ | |||
MessageLog.ShowError(e); | |||
} | |||
return this; | |||
} | |||
public OperateResultT<T> OnFailed(IRunT<OperateResultT<T>> action){ | |||
try{ | |||
if(action!=null&&!getIsSuccess())action.Run(this); | |||
}catch(Exception e){ | |||
MessageLog.ShowError(e); | |||
} | |||
return this; | |||
} | |||
public OperateResultT<T> OnFinally(IRunT<OperateResultT<T>> action){ | |||
if(action!=null)action.Run(this); | |||
return this; | |||
} | |||
public static <T> OperateResultT<T> CreateSuccess(T value) | |||
{ | |||
return new OperateResultT<T>(value,"", ResultCode.Success); | |||
} | |||
public static <T> OperateResultT<T> CreateFailedT(String msg) | |||
{ | |||
MessageLog.ShowError(msg); | |||
return new OperateResultT<T>( msg, ResultCode.Fail); | |||
} | |||
public static <T> OperateResultT<T> CreateFailedT(Exception ex) | |||
{ | |||
MessageLog.ShowError(ex.toString()); | |||
return new OperateResultT<T>(ex); | |||
} | |||
} |
@@ -0,0 +1,38 @@ | |||
package com.bonait.bnframework.HBL.Result; | |||
public enum ResultCode { | |||
/** | |||
* 默认 | |||
*/ | |||
Default, | |||
/** | |||
* 错误 | |||
*/ | |||
Error, | |||
/** | |||
* 异常 | |||
*/ | |||
Exception, | |||
/** | |||
* 成功 | |||
*/ | |||
Success, | |||
/** | |||
* 失败 | |||
*/ | |||
Fail, | |||
/** | |||
* 操作超时 | |||
*/ | |||
Overtime, | |||
/** | |||
* 操作取消 | |||
*/ | |||
Canceled | |||
} |
@@ -0,0 +1,5 @@ | |||
package com.bonait.bnframework.HBL.Thread; | |||
public interface IThread { | |||
void Run() throws Exception; | |||
} |
@@ -0,0 +1,7 @@ | |||
package com.bonait.bnframework.HBL.Thread; | |||
public interface IThreadComplete { | |||
void Run() throws Exception; | |||
void RunComplete() throws Exception; | |||
} |
@@ -0,0 +1,110 @@ | |||
package com.bonait.bnframework.HBL.Thread; | |||
import com.bonait.bnframework.HBL.Logs.MessageLog; | |||
import java.util.concurrent.ConcurrentHashMap; | |||
public class ThreadManager { | |||
private static volatile ThreadManager _Instance; | |||
public static ThreadManager get() { | |||
if (_Instance == null) | |||
_Instance = new ThreadManager(); | |||
return _Instance; | |||
} | |||
private ThreadManager() { | |||
} | |||
public long RestartInterval = 2000; | |||
ConcurrentHashMap<String, ThreadModel> tm = new ConcurrentHashMap<>(); | |||
private void Sleep(long millis) { | |||
try { | |||
Thread.sleep(millis); | |||
} catch (InterruptedException e) { | |||
throw new RuntimeException(e); | |||
} | |||
} | |||
public void StartLong(String Key, boolean IsRestart, IThreadComplete _thread) { | |||
if (!tm.containsKey(Key)) { | |||
tm.put(Key, new ThreadModel()); | |||
tm.get(Key).RunThread = _thread; | |||
tm.get(Key).ThreadObj = new Thread(() -> { | |||
MessageLog.ShowInfo("启动线程:" + Key); | |||
while (!tm.get(Key).IsCancel) { | |||
if (IsRestart) { | |||
try { | |||
tm.get(Key).RunThread.Run(); | |||
} catch (Exception ex) { | |||
MessageLog.ShowError("多线程:" + Key + "运行发生异常,已重启,errorMsg:" + ex.toString()); | |||
Sleep(RestartInterval); | |||
} | |||
} else { | |||
try { | |||
tm.get(Key).RunThread.Run(); | |||
} catch (Exception e) { | |||
MessageLog.ShowError("多线程:" + Key + "运行发生异常,已退出,errorMsg:" + e.toString()); | |||
} | |||
} | |||
} | |||
try { | |||
tm.get(Key).RunThread.RunComplete(); | |||
MessageLog.ShowInfo("线程:[" + Key + "]--执行完成"); | |||
} catch (Exception e) { | |||
MessageLog.ShowError("多线程:" + Key + "执行完成任务发生异常,已退出,errorMsg:" + e.toString()); | |||
} | |||
tm.remove(Key); | |||
}); | |||
tm.get(Key).ThreadObj.setName(Key); | |||
tm.get(Key).ThreadObj.start(); | |||
} else { | |||
MessageLog.ShowWarning("任务-[" + Key + "]-已存在"); | |||
} | |||
} | |||
public void StartLong(String Key, boolean IsRestart, IThread _thread) { | |||
if (!tm.containsKey(Key)) { | |||
tm.put(Key, new ThreadModel()); | |||
tm.get(Key).Task = _thread; | |||
tm.get(Key).ThreadObj = new Thread(() -> { | |||
MessageLog.ShowInfo("启动线程:" + Key); | |||
while (!tm.get(Key).IsCancel) { | |||
if (IsRestart) { | |||
try { | |||
tm.get(Key).RunThread.Run(); | |||
} catch (Exception ex) { | |||
MessageLog.ShowError("多线程:" + Key + "运行发生异常,已重启,errorMsg:" + ex.toString()); | |||
Sleep(RestartInterval); | |||
} | |||
} else { | |||
try { | |||
tm.get(Key).RunThread.Run(); | |||
} catch (Exception e) { | |||
MessageLog.ShowError("多线程:" + Key + "运行发生异常,已退出,errorMsg:" + e.toString()); | |||
} | |||
} | |||
} | |||
try { | |||
tm.get(Key).RunThread.RunComplete(); | |||
MessageLog.ShowInfo("线程:[" + Key + "]--执行完成"); | |||
} catch (Exception e) { | |||
MessageLog.ShowError("多线程:" + Key + "执行完成任务发生异常,已退出,errorMsg:" + e.toString()); | |||
} | |||
tm.remove(Key); | |||
}); | |||
tm.get(Key).ThreadObj.setName(Key); | |||
tm.get(Key).ThreadObj.start(); | |||
} else { | |||
MessageLog.ShowWarning("任务-[" + Key + "]-已存在"); | |||
} | |||
} | |||
public void Stop(String Key) { | |||
if (tm.containsKey(Key)) { | |||
tm.get(Key).IsCancel = true; | |||
} | |||
} | |||
} |
@@ -0,0 +1,8 @@ | |||
package com.bonait.bnframework.HBL.Thread; | |||
public class ThreadModel { | |||
public IThreadComplete RunThread; | |||
public IThread Task; | |||
public boolean IsCancel; | |||
public Thread ThreadObj; | |||
} |
@@ -0,0 +1,44 @@ | |||
package com.bonait.bnframework.HBL.Trig; | |||
import com.bonait.bnframework.HBL.Interface.IRun; | |||
import java.util.concurrent.ConcurrentHashMap; | |||
/** | |||
* 上升沿操作 | |||
*/ | |||
public class RTrig { | |||
private static volatile ConcurrentHashMap<String, RTrig> _Instance; | |||
public static RTrig get(String name) { | |||
if (_Instance == null) | |||
_Instance = new ConcurrentHashMap<String, RTrig>(); | |||
if (!_Instance.containsKey(name)) | |||
_Instance.put(name, new RTrig()); | |||
return _Instance.get(name); | |||
} | |||
private RTrig() { | |||
} | |||
private boolean flag=false; | |||
private boolean Q=false; | |||
public boolean getQ() { | |||
return Q; | |||
} | |||
private void setIN(boolean falag) { | |||
Q = falag && !flag; | |||
flag = falag; | |||
} | |||
public void Start(boolean IN, IRun callback) { | |||
setIN(IN); | |||
if (Q) | |||
callback.Run(); | |||
} | |||
} |
@@ -0,0 +1,39 @@ | |||
package com.bonait.bnframework; | |||
//import androidx.appcompat.app.AppCompatActivity; | |||
import android.graphics.Color; | |||
import android.os.Bundle; | |||
import android.util.Log; | |||
import com.bonait.bnframework.HBL.DataUtil.Convert; | |||
import com.bonait.bnframework.HBL.Interface.IRunT; | |||
import com.bonait.bnframework.HBL.Result.OperateResultT; | |||
import com.bonait.bnframework.common.DashboardView; | |||
import com.bonait.bnframework.common.base.BaseActivity; | |||
import com.bonait.bnframework.common.helper.ModbusHelper; | |||
import java.util.ArrayList; | |||
import java.util.List; | |||
public class MainActivity extends BaseActivity { | |||
@Override | |||
protected void onCreate(Bundle savedInstanceState) { | |||
super.onCreate(savedInstanceState); | |||
setContentView(R.layout.activity_main); | |||
test(); | |||
} | |||
private void test(){ | |||
String a = "123"; | |||
// Convert.TryToNumber(a,ArrayList<Integer>.class.getClass()).OnSource(s->{ | |||
// Log.i("test",s.Content.toString()); | |||
// }).OnFailed(s->{ | |||
// | |||
// }); | |||
} | |||
} |
@@ -29,8 +29,6 @@ import com.bonait.bnframework.common.db.mode.BPA_USER; | |||
import com.bonait.bnframework.common.db.res.AlertLogEnum; | |||
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.utils.NetworkUtils; | |||
import com.bonait.bnframework.common.utils.ToastUtils; | |||
@@ -8,6 +8,7 @@ import android.os.Message; | |||
import androidx.annotation.NonNull; | |||
import com.bonait.bnframework.HBL.Interface.IRunT; | |||
import com.bonait.bnframework.R; | |||
import com.bonait.bnframework.common.constant.ConfigName; | |||
import com.bonait.bnframework.common.constant.DataBus; | |||
@@ -25,14 +26,10 @@ 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.model.ResAPI; | |||
import com.bonait.bnframework.common.model.mode.ActionJsonMode; | |||
import com.bonait.bnframework.common.model.mode.BomTechnologyActionInfo; | |||
@@ -880,16 +877,16 @@ public class ConfigData { | |||
*/ | |||
public void AddImage(Context context) { | |||
BitmapFactory.Options options = new BitmapFactory.Options(); | |||
options.inSampleSize = 2;//宽高压缩为原来的1/2 | |||
//options.inSampleSize = 2;//宽高压缩为原来的1/2 | |||
//options.inPreferredConfig=Bitmap.Config.ARGB_4444; | |||
Bitmap bitmap1 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image1, options); | |||
Bitmap bitmap2 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image2, options); | |||
Bitmap bitmap3 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image3, options); | |||
Bitmap bitmap4 = BitmapFactory.decodeResource(context.getResources(), R.mipmap.image4, options); | |||
LocalCacheUtils localCacheUtils = new LocalCacheUtils(); | |||
localCacheUtils.setBitmapToLocal("image1.png", bitmap1); | |||
localCacheUtils.setBitmapToLocal("image2.png", bitmap2); | |||
localCacheUtils.setBitmapToLocal("image3.png", bitmap3); | |||
localCacheUtils.setBitmapToLocal("image4.png", bitmap4); | |||
LocalCacheUtils.Get().setBitmapToLocal("image1.png", bitmap1); | |||
LocalCacheUtils.Get().setBitmapToLocal("image2.png", bitmap2); | |||
LocalCacheUtils.Get().setBitmapToLocal("image3.png", bitmap3); | |||
LocalCacheUtils.Get().setBitmapToLocal("image4.png", bitmap4); | |||
} | |||
/** | |||
@@ -974,7 +971,7 @@ public class ConfigData { | |||
@Override | |||
public void run() { | |||
try { | |||
ModbusTcpServer.get().Connect(); | |||
// ModbusTcpServer.get().Connect(); | |||
} catch (Exception e) { | |||
} | |||
@@ -985,7 +982,7 @@ public class ConfigData { | |||
* 关闭PLC | |||
*/ | |||
public void ColsePLC() { | |||
ModbusTcpHelper.get().release();//释放modbus | |||
// ModbusTcpHelper.get().release();//释放modbus | |||
ConfigName.getInstance().PlcIsConnect=false; | |||
} | |||
/** | |||
@@ -10,6 +10,12 @@ import android.util.Log; | |||
import androidx.annotation.NonNull; | |||
import com.bonait.bnframework.HBL.DataUtil.ShortLib; | |||
import com.bonait.bnframework.HBL.Interface.IRun; | |||
import com.bonait.bnframework.HBL.Interface.IRunT; | |||
import com.bonait.bnframework.HBL.Logs.MessageLog; | |||
import com.bonait.bnframework.HBL.Thread.IThread; | |||
import com.bonait.bnframework.HBL.Thread.ThreadManager; | |||
import com.bonait.bnframework.R; | |||
import com.bonait.bnframework.common.constant.ConfigName; | |||
import com.bonait.bnframework.common.constant.DataBus; | |||
@@ -24,17 +30,11 @@ 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.ModbusHelper; | |||
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.utils.ToastUtils; | |||
import com.qmuiteam.qmui.widget.dialog.QMUIDialog; | |||
@@ -243,7 +243,7 @@ public class ExecuteTheRecipe { | |||
} | |||
}).start(); | |||
ThreadManager.Get().StartLong("PLC设备数据监听", true, new IThread() { | |||
ThreadManager.get().StartLong("PLC设备数据监听", true, new IThread() { | |||
@Override | |||
public void Run() throws InterruptedException { | |||
try { | |||
@@ -271,13 +271,10 @@ public class ExecuteTheRecipe { | |||
Thread.sleep(500); | |||
} | |||
@Override | |||
public void RunComplete() throws InterruptedException { | |||
} | |||
}); | |||
ThreadManager.Get().StartLong("PLC设备-温度重量", true, new IThread() { | |||
ThreadManager.get().StartLong("PLC设备-温度重量", true, new IThread() { | |||
@Override | |||
public void Run() throws InterruptedException { | |||
try { | |||
@@ -317,13 +314,9 @@ public class ExecuteTheRecipe { | |||
} | |||
Thread.sleep(200); | |||
} | |||
@Override | |||
public void RunComplete() throws InterruptedException { | |||
} | |||
}); | |||
ThreadManager.Get().StartLong("PLC设备-自动加热补水", true, new IThread() { | |||
ThreadManager.get().StartLong("PLC设备-自动加热补水", true, new IThread() { | |||
@Override | |||
public void Run() throws InterruptedException { | |||
try { | |||
@@ -336,14 +329,9 @@ public class ExecuteTheRecipe { | |||
} | |||
Thread.sleep(5000); | |||
} | |||
@Override | |||
public void RunComplete() throws InterruptedException { | |||
} | |||
}); | |||
ThreadManager.Get().StartLong("PLC设备数据监听-信号检测", true, new IThread() { | |||
ThreadManager.get().StartLong("PLC设备数据监听-信号检测", true, new IThread() { | |||
@Override | |||
public void Run() throws InterruptedException { | |||
try { | |||
@@ -353,13 +341,9 @@ public class ExecuteTheRecipe { | |||
} | |||
Thread.sleep(100); | |||
} | |||
@Override | |||
public void RunComplete() throws InterruptedException { | |||
} | |||
}); | |||
ThreadManager.Get().StartLong("商品制作线程", true, new IThread() { | |||
ThreadManager.get().StartLong("商品制作线程", true, new IThread() { | |||
@Override | |||
public void Run() throws InterruptedException { | |||
try { | |||
@@ -405,7 +389,7 @@ public class ExecuteTheRecipe { | |||
silos = item; | |||
} | |||
if (silos == null) { | |||
MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, message + "下发失败!物料没有管理料仓!"); | |||
MessageLog.ShowInfo(message + "下发失败!物料没有管理料仓!"); | |||
} else { | |||
//MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, message + "准备下发【" + silos.num + "】号料仓PLC控制命令,需求量:=" + recipe.value); | |||
int _val = (int)Math.round((Double.parseDouble(recipe.value) * 10)); | |||
@@ -425,7 +409,7 @@ public class ExecuteTheRecipe { | |||
@Override | |||
public void Run() { | |||
IsComplete[0] = true; | |||
MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, "[" + GoodMake.good.name + "]步骤【" + key + "】配料完成!"); | |||
MessageLog.ShowInfo( "[" + GoodMake.good.name + "]步骤【" + key + "】配料完成!"); | |||
} | |||
}; | |||
@@ -439,7 +423,7 @@ public class ExecuteTheRecipe { | |||
@Override | |||
public void onFailure(String ErrorMsg) { | |||
MessageLog.ShowInfo("[" + GoodMake.good.name + "]步骤【" + key + "】启动配料失败!"); | |||
MessageLog.ShowAlertMessage(AlertLogEnum.异常订单未制作日志, "[" + GoodMake.good.name + "]步骤【" + key + "】启动配料失败!"); | |||
// MessageLog.ShowAlertMessage(AlertLogEnum.异常订单未制作日志, "[" + GoodMake.good.name + "]步骤【" + key + "】启动配料失败!"); | |||
} | |||
}); | |||
@@ -453,11 +437,11 @@ public class ExecuteTheRecipe { | |||
//更新缓存商品制作列表状态 | |||
count += goodsRecipes.size(); | |||
DataBus.getInstance().UpdateGoodsMake(GoodMake.subOrder.id, "步骤【" + key + "】:" + RecipesNames + "-配料完成!", count, key, true); | |||
MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, "[" + GoodMake.good.name + "]步骤【" + key + "】下发" + RecipesNames + "执行完成!"); | |||
MessageLog.ShowInfo( "[" + GoodMake.good.name + "]步骤【" + key + "】下发" + RecipesNames + "执行完成!"); | |||
} | |||
DataBus.getInstance().DeleteGoodsMake(GoodMake.subOrder.id); | |||
MessageLog.ShowUserMessage(UserLogEnum.订单处理日志, "[" + GoodMake.good.name + "]-订单执行完成,请取餐!"); | |||
MessageLog.ShowInfo( "[" + GoodMake.good.name + "]-订单执行完成,请取餐!"); | |||
GoodMake=null; | |||
IsMakeGood=false; | |||
@@ -468,10 +452,6 @@ public class ExecuteTheRecipe { | |||
} | |||
Thread.sleep(500); | |||
} | |||
@Override | |||
public void RunComplete() throws InterruptedException { | |||
} | |||
}); | |||
} | |||
//endregion | |||
@@ -491,10 +471,10 @@ public class ExecuteTheRecipe { | |||
if (!plcaddress.address.isEmpty() && ConfigName.getInstance().PlcIsConnect) { | |||
if (plcaddress.address.toUpperCase().startsWith("VD"))//int | |||
{ | |||
ModbusTcpServer.get().WriteInt(plcaddress.address, (int) value, callback); | |||
ModbusHelper.get().WriteInt(plcaddress.address, (int) value); | |||
} else if (plcaddress.address.toUpperCase().startsWith("M"))//bool | |||
{ | |||
ModbusTcpServer.get().WriteBool(plcaddress.address, (boolean) value, callback); | |||
ModbusHelper.get().WriteBool(plcaddress.address, (boolean) value); | |||
} else if (plcaddress.address.toUpperCase().startsWith("VW"))//short | |||
{ | |||
if(plcaddress.address.contains(".")) | |||
@@ -502,21 +482,17 @@ 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<short[]>() { | |||
@Override | |||
public void onSuccess(short[] shorts) { | |||
Short val=shorts[0]; | |||
Short valk= ByteHelper.setBit(val,endAdd,(boolean) value); | |||
ModbusTcpServer.get().WriteShort(firstAdd, valk, null); | |||
} | |||
ModbusHelper.get().ReadShort(firstAdd).OnSource(s->{ | |||
Short valk= ShortLib.SetBit(s.Content,endAdd,(boolean)value) ; | |||
ModbusHelper.get().WriteShort(firstAdd, valk); | |||
}); | |||
}else | |||
{ | |||
ModbusTcpServer.get().WriteShort(plcaddress.address, Short.parseShort(value.toString()), callback); | |||
ModbusHelper.get().WriteShort(plcaddress.address, Short.parseShort(value.toString())); | |||
} | |||
}else if (plcaddress.address.toUpperCase().startsWith("VR"))//float | |||
{ | |||
ModbusTcpServer.get().WriteFloat(plcaddress.address, Float.parseFloat(value.toString()), callback); | |||
ModbusHelper.get().WriteFloat(plcaddress.address, Float.parseFloat(value.toString())); | |||
} | |||
} | |||
} | |||
@@ -541,13 +517,13 @@ 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]; | |||
ModbusHelper.get().ReadInt(plcaddress.address).OnSource(s->{ | |||
ReturnsVariable[0] = s.Content; | |||
}); | |||
} else if (plcaddress.address.toUpperCase().startsWith("M"))//bool | |||
{ | |||
ModbusTcpServer.get().ReadBool(plcaddress.address, 1, val -> { | |||
ReturnsVariable[0] = val[0]; | |||
ModbusHelper.get().ReadBool(plcaddress.address).OnSource(s->{ | |||
ReturnsVariable[0] = s.Content; | |||
}); | |||
} else if (plcaddress.address.toUpperCase().startsWith("VW"))//short | |||
{ | |||
@@ -556,21 +532,21 @@ public class ExecuteTheRecipe { | |||
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; | |||
}); | |||
// ModbusHelper.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]; | |||
}); | |||
// ModbusHelper.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]; | |||
}); | |||
// ModbusHelper.get().ReadFloat(plcaddress.address, 1, val -> { | |||
// ReturnsVariable[0] = val[0]; | |||
// }); | |||
} | |||
} | |||
} | |||
@@ -595,32 +571,32 @@ public class ExecuteTheRecipe { | |||
if (!plcaddress.address.isEmpty() && ConfigName.getInstance().PlcIsConnect) { | |||
if (plcaddress.address.toUpperCase().startsWith("VD"))//int | |||
{ | |||
ModbusTcpServer.get().ReadInt(plcaddress.address, length, val -> { | |||
for (int i = 0; i < length; i++) { | |||
ReturnsVariable[i] = val[i]; | |||
} | |||
}); | |||
// ModbusHelper.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 -> { | |||
for (int i = 0; i < length; i++) { | |||
ReturnsVariable[i] = val[i]; | |||
} | |||
}); | |||
// ModbusHelper.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 -> { | |||
for (int i = 0; i < length; i++) { | |||
ReturnsVariable[i] = val[i]; | |||
} | |||
}); | |||
// ModbusHelper.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 -> { | |||
for (int i = 0; i < length; i++) { | |||
ReturnsVariable[i] = val[i]; | |||
} | |||
}); | |||
// ModbusHelper.get().ReadFloat(plcaddress.address, length, val -> { | |||
// for (int i = 0; i < length; i++) { | |||
// ReturnsVariable[i] = val[i]; | |||
// } | |||
// }); | |||
} | |||
} | |||
} | |||
@@ -639,7 +615,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); | |||
// ModbusHelper.get().WriteBool(address, (boolean) value, callback); | |||
} | |||
} catch (Exception ex) { | |||
ToastUtils.error("异常信息:" + ex.getMessage()); | |||
@@ -681,19 +657,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); | |||
} | |||
}); | |||
// ModbusHelper.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,25 +686,25 @@ 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; | |||
}); | |||
// ModbusHelper.get().ReadString(plcaddress.address, 40, (data) -> { | |||
// | |||
// if(!data.isEmpty() && !Code.equals(data) && OnScanTheCodeInformationT != null) | |||
// { | |||
// Log.d("信息", "扫码数据: "+data); | |||
// OnScanTheCodeInformationT.Run(data); | |||
// ModbusHelper.get().WriteString(plcaddress.address, 40, null); | |||
// } | |||
// | |||
// //记录上一次读取PLC 扫码数据 | |||
// Code = data; | |||
// }); | |||
} | |||
} | |||
// if (ConfigName.getInstance().PLC_Address.containsKey("配料次数")) { | |||
// BPA_PLCADDRESS plcaddress = ConfigName.getInstance().PLC_Address.get("配料次数"); | |||
// if (!plcaddress.address.isEmpty() && ConfigName.getInstance().PlcIsConnect) { | |||
// ModbusTcpServer.get().ReadInt(plcaddress.address, 1, (data) -> { | |||
// ModbusHelper.get().ReadInt(plcaddress.address, 1, (data) -> { | |||
// MakeGoodCount=data[0] ; | |||
// }); | |||
// } | |||
@@ -851,12 +827,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(); | |||
}); | |||
}); | |||
// ModbusHelper.get().ReadBool(plcaddress.address, 1, booleans -> { | |||
// RTrig.get(name).Start(booleans[0], () -> { | |||
// if (callback != null) | |||
// callback.Run(); | |||
// }); | |||
// }); | |||
} | |||
} | |||
} | |||
@@ -2,6 +2,7 @@ package com.bonait.bnframework.business; | |||
import android.app.Activity; | |||
import android.app.Application; | |||
import android.content.Context; | |||
import android.util.Log; | |||
import com.bonait.bnframework.BuildConfig; | |||
@@ -23,10 +24,7 @@ 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.notification.MainNotification; | |||
import com.bonait.bnframework.common.utils.AppUtils; | |||
import com.bonait.bnframework.common.utils.NetworkUtils; | |||
@@ -49,7 +47,6 @@ import org.litepal.LitePal; | |||
import java.util.ArrayList; | |||
import java.util.concurrent.TimeUnit; | |||
import java.util.logging.Level; | |||
import okhttp3.OkHttpClient; | |||
public class MainInit { | |||
@@ -90,7 +87,7 @@ public class MainInit { | |||
MainNotification.initNotificationChannel(app); | |||
// 内存泄漏检测 | |||
initLeakCanary(false); | |||
initLeakCanary(true,app); | |||
// Log日志打印框架 | |||
initLogCat(); | |||
@@ -210,83 +207,85 @@ public class MainInit { | |||
* 初始化消息日志接收打印 | |||
*/ | |||
public static void InitMsgLog(){ | |||
MessageLog.MsgNotify = new IMessageLogNotify() { | |||
@Override | |||
public void ErrorMsg(String msg) { | |||
if(msg.contains("msg:com.serotonin.modbus4j.exception")) | |||
{ | |||
ModbusTcpHelper.get().release();//释放modbus | |||
ConfigName.getInstance().PlcIsConnect=false; | |||
BPA_ALERTLOG log = new BPA_ALERTLOG(); | |||
log.userID = ConfigName.getInstance().user.userID; | |||
log.type=4; | |||
log.text = msg+"程序断开PLC,准备重连机制..."; | |||
QueryDB.AddAlertlog(log); | |||
} | |||
} | |||
@Override | |||
public void InfoMsg(String msg) { | |||
Log.i("Info", msg); | |||
} | |||
@Override | |||
public void WarnMsg(String msg) { | |||
Log.w("Warn", msg); | |||
} | |||
@Override | |||
public void UserMsg(UserLogEnum type, String msg) { | |||
BPA_LOG log = new BPA_LOG(); | |||
log.userID = ConfigName.getInstance().user.userID; | |||
ToastUtils.info(msg); | |||
switch (type.toString()) | |||
{ | |||
case "登录日志":log.type=1; | |||
break; | |||
case "角色操作日志":log.type=2; | |||
break; | |||
case "数据接收":log.type=3; | |||
break; | |||
case "上传日志":log.type=4; | |||
break; | |||
case "订单处理日志":log.type=5; | |||
break; | |||
} | |||
log.text = msg; | |||
QueryDB.Addlog(log); | |||
} | |||
@Override | |||
public void AlertMsg(AlertLogEnum type, String msg) { | |||
BPA_ALERTLOG log = new BPA_ALERTLOG(); | |||
log.userID = ConfigName.getInstance().user.userID; | |||
switch (type.toString()) | |||
{ | |||
case "异常订单未制作日志":log.type=1; | |||
break; | |||
case "料仓缺料日志":log.type=2; | |||
break; | |||
case "传感器异常日志":log.type=3; | |||
break; | |||
case "其他":log.type=4; | |||
break; | |||
} | |||
log.text = msg; | |||
QueryDB.AddAlertlog(log); | |||
} | |||
}; | |||
// MessageLog.MsgNotify = new IMessageLogNotify() { | |||
// @Override | |||
// public void ErrorMsg(String msg) { | |||
// if(msg.contains("msg:com.serotonin.modbus4j.exception")) | |||
// { | |||
// ModbusTcpHelper.get().release();//释放modbus | |||
// ConfigName.getInstance().PlcIsConnect=false; | |||
// | |||
// BPA_ALERTLOG log = new BPA_ALERTLOG(); | |||
// log.userID = ConfigName.getInstance().user.userID; | |||
// log.type=4; | |||
// log.text = msg+"程序断开PLC,准备重连机制..."; | |||
// QueryDB.AddAlertlog(log); | |||
// } | |||
// } | |||
// @Override | |||
// public void InfoMsg(String msg) { | |||
// Log.i("Info", msg); | |||
// | |||
// } | |||
// @Override | |||
// public void WarnMsg(String msg) { | |||
// Log.w("Warn", msg); | |||
// } | |||
// @Override | |||
// public void UserMsg(UserLogEnum type, String msg) { | |||
// BPA_LOG log = new BPA_LOG(); | |||
// log.userID = ConfigName.getInstance().user.userID; | |||
// ToastUtils.info(msg); | |||
// switch (type.toString()) | |||
// { | |||
// case "登录日志":log.type=1; | |||
// break; | |||
// case "角色操作日志":log.type=2; | |||
// break; | |||
// case "数据接收":log.type=3; | |||
// break; | |||
// case "上传日志":log.type=4; | |||
// break; | |||
// case "订单处理日志":log.type=5; | |||
// break; | |||
// } | |||
// log.text = msg; | |||
// QueryDB.Addlog(log); | |||
// } | |||
// | |||
// @Override | |||
// public void AlertMsg(AlertLogEnum type, String msg) { | |||
// BPA_ALERTLOG log = new BPA_ALERTLOG(); | |||
// log.userID = ConfigName.getInstance().user.userID; | |||
// switch (type.toString()) | |||
// { | |||
// case "异常订单未制作日志":log.type=1; | |||
// break; | |||
// case "料仓缺料日志":log.type=2; | |||
// break; | |||
// case "传感器异常日志":log.type=3; | |||
// break; | |||
// case "其他":log.type=4; | |||
// break; | |||
// } | |||
// log.text = msg; | |||
// | |||
// QueryDB.AddAlertlog(log); | |||
// } | |||
// }; | |||
} | |||
/** | |||
* 内存泄漏检测,根据flag来判断要不要初始化 | |||
*/ | |||
private static void initLeakCanary(boolean flag) { | |||
private static void initLeakCanary(boolean flag, Application context) { | |||
if (flag) { | |||
// leak 内存检测注册 | |||
// if (LeakCanary.isInAnalyzerProcess(this)) { | |||
// if (LeakCanary.isInAnalyzerProcess(context)) { | |||
// // This process is dedicated to LeakCanary for heap analysis. | |||
// // You should not init your app in this process. | |||
// return; | |||
// } | |||
// LeakCanary.install(this); | |||
// LeakCanary.install(context); | |||
} | |||
} | |||
@@ -2,6 +2,9 @@ package com.bonait.bnframework.business; | |||
import android.util.Log; | |||
import com.bonait.bnframework.HBL.Interface.IRun; | |||
import com.bonait.bnframework.HBL.Logs.MessageLog; | |||
import com.bonait.bnframework.HBL.Thread.ThreadManager; | |||
import com.bonait.bnframework.common.constant.ConfigName; | |||
import com.bonait.bnframework.common.db.QueryDB; | |||
import com.bonait.bnframework.common.db.mode.BPA_GOODPROPERTY; | |||
@@ -14,12 +17,8 @@ import com.bonait.bnframework.common.db.mode.BPA_MENU; | |||
import com.bonait.bnframework.common.db.mode.BPA_SILOSANDMATERIAL; | |||
import com.bonait.bnframework.common.helper.AES; | |||
import com.bonait.bnframework.common.helper.I.IMessage; | |||
import com.bonait.bnframework.common.helper.I.IRun; | |||
import com.bonait.bnframework.common.helper.I.IThread; | |||
import com.bonait.bnframework.common.helper.Json; | |||
import com.bonait.bnframework.common.helper.MQTT; | |||
import com.bonait.bnframework.common.helper.MessageLog; | |||
import com.bonait.bnframework.common.helper.ThreadManager; | |||
import com.bonait.bnframework.common.helper.mode.BPAPackage; | |||
import com.bonait.bnframework.common.helper.mode.BPA_GoodsInfo; | |||
import com.bonait.bnframework.common.helper.mode.BPA_HeartPackage; | |||
@@ -119,23 +118,11 @@ public class OrderServer { | |||
ConfigName.getInstance().mqtt_ip, | |||
ConfigName.getInstance().mqtt_post); | |||
ThreadManager.Get().StartLong("心跳服务", true, new IThread() { | |||
@Override | |||
public void Run() throws InterruptedException { | |||
if(MQTT.get().IsConnect) | |||
{ | |||
try { | |||
PushHeart(); | |||
} catch (Exception e) { | |||
} | |||
} | |||
Thread.sleep(1000); | |||
} | |||
@Override | |||
public void RunComplete() throws InterruptedException { | |||
ThreadManager.get().StartLong("心跳服务",true,()->{ | |||
if(MQTT.get().IsConnect){ | |||
PushHeart(); | |||
} | |||
Thread.sleep(1000); | |||
}); | |||
} | |||
@@ -0,0 +1,492 @@ | |||
package com.bonait.bnframework.common; | |||
import android.animation.Animator; | |||
import android.animation.AnimatorListenerAdapter; | |||
import android.animation.ObjectAnimator; | |||
import android.animation.ValueAnimator; | |||
import android.content.Context; | |||
import android.content.res.Resources; | |||
import android.graphics.Canvas; | |||
import android.graphics.Color; | |||
import android.graphics.Matrix; | |||
import android.graphics.Paint; | |||
import android.graphics.Path; | |||
import android.graphics.Rect; | |||
import android.graphics.RectF; | |||
import android.graphics.SweepGradient; | |||
//import android.support.v4.content.ContextCompat; | |||
import android.text.TextUtils; | |||
import android.util.AttributeSet; | |||
import android.util.Log; | |||
import android.util.TypedValue; | |||
import android.view.View; | |||
import android.view.animation.LinearInterpolator; | |||
import com.bonait.bnframework.business.ExecuteTheRecipe; | |||
import java.util.Random; | |||
/** | |||
* DashboardView style 4,仿汽车速度仪表盘 | |||
* Created by woxingxiao on 2016-12-19. | |||
*/ | |||
public class DashboardView extends View { | |||
private int mRadius; // 扇形半径 | |||
private int mStartAngle = 150; // 起始角度 | |||
private int mSweepAngle = 240; // 绘制角度 | |||
private int mMin = 0; // 最小值 | |||
private int mMax = 180; // 最大值 | |||
private int mSection = 10; // 值域(mMax-mMin)等分份数 | |||
private int mPortion = 5; // 一个mSection等分份数 | |||
private String mHeaderText = "km/h"; // 表头 | |||
private float mVelocity = mMin; // 实时速度 | |||
private int mStrokeWidth; // 画笔宽度 | |||
private int mLength1; // 长刻度的相对圆弧的长度 | |||
private int mLength2; // 刻度读数顶部的相对圆弧的长度 | |||
private int mPLRadius; // 指针长半径 | |||
private int mPSRadius; // 指针短半径 | |||
private int mPadding; | |||
private float mCenterX, mCenterY; // 圆心坐标 | |||
private Paint mPaint; | |||
private Path pointerPath=new Path(); | |||
private Paint pointerPaint=new Paint(); | |||
private boolean IsInit=false; | |||
private RectF mRectFArc; | |||
private RectF mRectFInnerArc; | |||
private Rect mRectText; | |||
private String[] mTexts; | |||
private int[] mColors; | |||
private Paint mTextPaint=new Paint(); | |||
private int textSize=40; | |||
private String unity="℃"; | |||
private int textColor=Color.parseColor("#03A9F4"); | |||
private int backgroundColor=Color.parseColor("#292a30"); | |||
public void setMaxValue(int maxValue){ | |||
mMax=maxValue; | |||
init(); | |||
} | |||
public void setHeaderText(String header){ | |||
mHeaderText=header; | |||
init(); | |||
} | |||
public void setBackgroundColor(int color){ | |||
backgroundColor=color; | |||
} | |||
public void setTextSize(int size){ | |||
textSize=size; | |||
} | |||
public void setTextColor(int color){ | |||
textColor=color; | |||
} | |||
public void setUnity(String mUnity){ | |||
unity=mUnity; | |||
} | |||
public DashboardView(Context context) { | |||
this(context, null); | |||
} | |||
public DashboardView(Context context, AttributeSet attrs) { | |||
this(context, attrs, 0); | |||
} | |||
public DashboardView(Context context, AttributeSet attrs, int defStyleAttr) { | |||
super(context, attrs, defStyleAttr); | |||
init(); | |||
} | |||
private void init() { | |||
mStrokeWidth = dp2px(3); | |||
mLength1 = dp2px(8) + mStrokeWidth; | |||
mLength2 = mLength1 + dp2px(4); | |||
mPaint = new Paint(); | |||
mPaint.setAntiAlias(true); | |||
mPaint.setStrokeCap(Paint.Cap.ROUND); | |||
mRectFArc = new RectF(); | |||
mRectFInnerArc = new RectF(); | |||
mRectText = new Rect(); | |||
mTexts = new String[mSection + 1]; // 需要显示mSection + 1个刻度读数 | |||
for (int i = 0; i < mTexts.length; i++) { | |||
int n = (mMax - mMin) / mSection; | |||
mTexts[i] = String.valueOf(mMin + i * n); | |||
} | |||
mColors = new int[]{Color.GREEN, Color.YELLOW, Color.RED};//内圆渐变设置 | |||
} | |||
@Override | |||
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { | |||
super.onMeasure(widthMeasureSpec, heightMeasureSpec); | |||
mPadding = Math.max( | |||
Math.max(getPaddingLeft(), getPaddingTop()), | |||
Math.max(getPaddingRight(), getPaddingBottom()) | |||
); | |||
setPadding(mPadding, mPadding, mPadding, mPadding); | |||
int width = resolveSize(dp2px(260), widthMeasureSpec); | |||
mRadius = (width - mPadding * 2 - mStrokeWidth * 2) / 2; | |||
// 由起始角度确定的高度 | |||
float[] point1 = getCoordinatePoint(mRadius, mStartAngle); | |||
// 由结束角度确定的高度 | |||
float[] point2 = getCoordinatePoint(mRadius, mStartAngle + mSweepAngle); | |||
int height = (int) Math.max(point1[1] + mRadius + mStrokeWidth * 2, | |||
point2[1] + mRadius + mStrokeWidth * 2); | |||
setMeasuredDimension(width, height + getPaddingTop() + getPaddingBottom()); | |||
mCenterX = mCenterY = getMeasuredWidth() / 2f; | |||
mRectFArc.set( | |||
getPaddingLeft() + mStrokeWidth, | |||
getPaddingTop() + mStrokeWidth, | |||
getMeasuredWidth() - getPaddingRight() - mStrokeWidth, | |||
getMeasuredWidth() - getPaddingBottom() - mStrokeWidth | |||
); | |||
mPaint.setTextSize(sp2px(16)); | |||
mPaint.getTextBounds("0", 0, "0".length(), mRectText); | |||
mRectFInnerArc.set( | |||
getPaddingLeft() + mLength2 + mRectText.height() + dp2px(30), | |||
getPaddingTop() + mLength2 + mRectText.height() + dp2px(30), | |||
getMeasuredWidth() - getPaddingRight() - mLength2 - mRectText.height() - dp2px(30), | |||
getMeasuredWidth() - getPaddingBottom() - mLength2 - mRectText.height() - dp2px(30) | |||
); | |||
mPLRadius = mRadius - dp2px(10); | |||
mPSRadius = dp2px(25); | |||
} | |||
private float Scale(float InputValue, float InputMax, float InputMin, float OutMax, float OutMin) | |||
{ | |||
float value = ((OutMax - OutMin) * (InputValue - InputMin)) / (InputMax - InputMin) + OutMin; | |||
if (value > OutMax) return OutMax; | |||
if (value < OutMin) return OutMin; | |||
return value; | |||
} | |||
private void CanvasInit(Canvas canvas){ | |||
mPaint.reset(); | |||
pointerPaint.reset(); | |||
pointerPath.reset(); | |||
mTextPaint.reset(); | |||
canvas.drawColor(backgroundColor);//背景色 | |||
this.setPadding(10,30,10,10); | |||
/** | |||
* 画圆弧 | |||
*/ | |||
mPaint.setStyle(Paint.Style.STROKE); | |||
mPaint.setStrokeWidth(mStrokeWidth); | |||
mPaint.setColor(Color.parseColor("#03A9F4")); | |||
canvas.drawArc(mRectFArc, mStartAngle, mSweepAngle, false, mPaint); | |||
/** | |||
* 画长刻度 | |||
* 画好起始角度的一条刻度后通过canvas绕着原点旋转来画剩下的长刻度 | |||
*/ | |||
double cos = Math.cos(Math.toRadians(mStartAngle - 180)); | |||
double sin = Math.sin(Math.toRadians(mStartAngle - 180)); | |||
float x0 = (float) (mPadding + mStrokeWidth + mRadius * (1 - cos)); | |||
float y0 = (float) (mPadding + mStrokeWidth + mRadius * (1 - sin)); | |||
float x1 = (float) (mPadding + mStrokeWidth + mRadius - (mRadius - mLength1) * cos); | |||
float y1 = (float) (mPadding + mStrokeWidth + mRadius - (mRadius - mLength1) * sin); | |||
canvas.save(); | |||
canvas.drawLine(x0, y0, x1, y1, mPaint); | |||
float angle = mSweepAngle * 1f / mSection; | |||
for (int i = 0; i < mSection; i++) { | |||
canvas.rotate(angle, mCenterX, mCenterY); | |||
canvas.drawLine(x0, y0, x1, y1, mPaint); | |||
} | |||
canvas.restore(); | |||
/** | |||
* 画短刻度 | |||
* 同样采用canvas的旋转原理 | |||
*/ | |||
canvas.save(); | |||
mPaint.setStrokeWidth(mStrokeWidth / 2f); | |||
float x2 = (float) (mPadding + mStrokeWidth + mRadius - (mRadius - 2 * mLength1 / 3f) * cos); | |||
float y2 = (float) (mPadding + mStrokeWidth + mRadius - (mRadius - 2 * mLength1 / 3f) * sin); | |||
canvas.drawLine(x0, y0, x2, y2, mPaint); | |||
angle = mSweepAngle * 1f / (mSection * mPortion); | |||
for (int i = 1; i < mSection * mPortion; i++) { | |||
canvas.rotate(angle, mCenterX, mCenterY); | |||
if (i % mPortion == 0) { // 避免与长刻度画重合 | |||
continue; | |||
} | |||
canvas.drawLine(x0, y0, x2, y2, mPaint); | |||
} | |||
canvas.restore(); | |||
/** | |||
* 画长刻度读数 | |||
*/ | |||
mPaint.setTextSize(sp2px(16)); | |||
mPaint.setStyle(Paint.Style.FILL); | |||
float α; | |||
float[] p; | |||
angle = mSweepAngle * 1f / mSection; | |||
for (int i = 0; i <= mSection; i++) { | |||
α = mStartAngle + angle * i; | |||
p = getCoordinatePoint(mRadius - mLength2, α); | |||
if (α % 360 > 135 && α % 360 < 225) { | |||
mPaint.setTextAlign(Paint.Align.LEFT); | |||
} else if ((α % 360 >= 0 && α % 360 < 45) || (α % 360 > 315 && α % 360 <= 360)) { | |||
mPaint.setTextAlign(Paint.Align.RIGHT); | |||
} else { | |||
mPaint.setTextAlign(Paint.Align.CENTER); | |||
} | |||
try { | |||
mPaint.getTextBounds(mHeaderText, 0, mTexts[i].length(), mRectText); | |||
}catch(Exception e){} | |||
int txtH = mRectText.height(); | |||
if (i <= 1 || i >= mSection - 1) { | |||
canvas.drawText(mTexts[i], p[0], p[1] + txtH / 2, mPaint); | |||
} else if (i == 3) { | |||
canvas.drawText(mTexts[i], p[0] + txtH / 2, p[1] + txtH, mPaint); | |||
} else if (i == mSection - 3) { | |||
canvas.drawText(mTexts[i], p[0] - txtH / 2, p[1] + txtH, mPaint); | |||
} else { | |||
canvas.drawText(mTexts[i], p[0], p[1] + txtH, mPaint); | |||
} | |||
} | |||
mPaint.setStrokeCap(Paint.Cap.SQUARE); | |||
mPaint.setStyle(Paint.Style.STROKE); | |||
mPaint.setStrokeWidth(dp2px(10)); | |||
mPaint.setShader(generateSweepGradient()); | |||
canvas.drawArc(mRectFInnerArc, mStartAngle + 1, mSweepAngle - 2, false, mPaint); | |||
mPaint.setStrokeCap(Paint.Cap.ROUND); | |||
mPaint.setStyle(Paint.Style.FILL); | |||
mPaint.setShader(null); | |||
/** | |||
* 画表头 | |||
* 没有表头就不画 | |||
*/ | |||
if (!TextUtils.isEmpty(mHeaderText)) { | |||
mPaint.setTextSize(textSize); | |||
mPaint.setColor(textColor); | |||
mPaint.setTextAlign(Paint.Align.CENTER); | |||
mPaint.getTextBounds(mHeaderText, 0, mHeaderText.length(), mRectText); | |||
canvas.drawText(mHeaderText, mCenterX, mCenterY + dp2px(100), mPaint); | |||
// canvas.drawText(mHeaderText, mCenterX, mCenterY - mRectText.height() * 3, mPaint); | |||
} | |||
/** | |||
* 画指针 | |||
*/ | |||
float θ = mStartAngle + mSweepAngle * (mVelocity - mMin) / (mMax - mMin); // 指针与水平线夹角 | |||
int r = mRadius / 8; | |||
int tempWidth = 10; | |||
canvas.save(); | |||
canvas.translate(getMeasuredWidth() / 2, mCenterY); | |||
canvas.rotate(θ); | |||
pointerPaint.setColor(Color.parseColor("#03A9F4")); | |||
pointerPaint.setAntiAlias(true);//抗锯齿 | |||
pointerPath.moveTo(mRadius-this.getPaddingLeft()-30, 0); | |||
pointerPath.lineTo(0, 0 - tempWidth); | |||
pointerPath.lineTo(0, 0 + tempWidth); | |||
pointerPath.close(); | |||
canvas.drawPath(pointerPath, pointerPaint); | |||
canvas.restore(); | |||
/** | |||
* 中心圆 | |||
*/ | |||
mPaint.setColor(Color.parseColor("#CCCCCC")); | |||
canvas.drawCircle(mCenterX, mCenterY, r, mPaint); | |||
/** | |||
* 画实时度数值 | |||
*/ | |||
mPaint.setColor(Color.parseColor("#6200EE")); | |||
mPaint.setStrokeWidth(dp2px(2)); | |||
int xOffset = dp2px(22); | |||
mTextPaint.reset(); | |||
mTextPaint.setColor(Color.WHITE); | |||
mTextPaint.setTextAlign(Paint.Align.CENTER); | |||
mTextPaint.setTextSize(textSize); | |||
mTextPaint.setColor(textColor); | |||
mTextPaint.setAntiAlias(true); | |||
canvas.drawText( String.format("%.2f", mVelocity)+unity,mCenterX, mCenterY + dp2px(60),mTextPaint); | |||
} | |||
@Override | |||
protected void onDraw(Canvas canvas) { | |||
super.onDraw(canvas); | |||
CanvasInit(canvas); | |||
} | |||
/** | |||
* 数码管样式 | |||
*/ | |||
// 1 | |||
// —— | |||
// 2 | | 3 | |||
// —— 4 | |||
// 5 | | 6 | |||
// —— | |||
// 7 | |||
private void drawDigitalTube(Canvas canvas, float num, int xOffset) { | |||
float x = mCenterX + xOffset; | |||
float y = mCenterY + dp2px(40); | |||
int lx = dp2px(5); | |||
int ly = dp2px(10); | |||
int gap = dp2px(2); | |||
// 1 | |||
mPaint.setAlpha(num == -1 || num == 1 || num == 4 ? 25 : 255); | |||
canvas.drawLine(x - lx, y, x + lx, y, mPaint); | |||
// 2 | |||
mPaint.setAlpha(num == -1 || num == 1 || num == 2 || num == 3 || num == 7 ? 25 : 255); | |||
canvas.drawLine(x - lx - gap, y + gap, x - lx - gap, y + gap + ly, mPaint); | |||
// 3 | |||
mPaint.setAlpha(num == -1 || num == 5 || num == 6 ? 25 : 255); | |||
canvas.drawLine(x + lx + gap, y + gap, x + lx + gap, y + gap + ly, mPaint); | |||
// 4 | |||
mPaint.setAlpha(num == -1 || num == 0 || num == 1 || num == 7 ? 25 : 255); | |||
canvas.drawLine(x - lx, y + gap * 2 + ly, x + lx, y + gap * 2 + ly, mPaint); | |||
// 5 | |||
mPaint.setAlpha(num == -1 || num == 1 || num == 3 || num == 4 || num == 5 || num == 7 | |||
|| num == 9 ? 25 : 255); | |||
canvas.drawLine(x - lx - gap, y + gap * 3 + ly, | |||
x - lx - gap, y + gap * 3 + ly * 2, mPaint); | |||
// 6 | |||
mPaint.setAlpha(num == -1 || num == 2 ? 25 : 255); | |||
canvas.drawLine(x + lx + gap, y + gap * 3 + ly, | |||
x + lx + gap, y + gap * 3 + ly * 2, mPaint); | |||
// 7 | |||
mPaint.setAlpha(num == -1 || num == 1 || num == 4 || num == 7 ? 25 : 255); | |||
canvas.drawLine(x - lx, y + gap * 4 + ly * 2, x + lx, y + gap * 4 + ly * 2, mPaint); | |||
} | |||
private int dp2px(int dp) { | |||
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, | |||
Resources.getSystem().getDisplayMetrics()); | |||
} | |||
private int sp2px(int sp) { | |||
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, | |||
Resources.getSystem().getDisplayMetrics()); | |||
} | |||
public float[] getCoordinatePoint(int radius, float angle) { | |||
float[] point = new float[2]; | |||
double arcAngle = Math.toRadians(angle); //将角度转换为弧度 | |||
if (angle < 90) { | |||
point[0] = (float) (mCenterX + Math.cos(arcAngle) * radius); | |||
point[1] = (float) (mCenterY + Math.sin(arcAngle) * radius); | |||
} else if (angle == 90) { | |||
point[0] = mCenterX; | |||
point[1] = mCenterY + radius; | |||
} else if (angle > 90 && angle < 180) { | |||
arcAngle = Math.PI * (180 - angle) / 180.0; | |||
point[0] = (float) (mCenterX - Math.cos(arcAngle) * radius); | |||
point[1] = (float) (mCenterY + Math.sin(arcAngle) * radius); | |||
} else if (angle == 180) { | |||
point[0] = mCenterX - radius; | |||
point[1] = mCenterY; | |||
} else if (angle > 180 && angle < 270) { | |||
arcAngle = Math.PI * (angle - 180) / 180.0; | |||
point[0] = (float) (mCenterX - Math.cos(arcAngle) * radius); | |||
point[1] = (float) (mCenterY - Math.sin(arcAngle) * radius); | |||
} else if (angle == 270) { | |||
point[0] = mCenterX; | |||
point[1] = mCenterY - radius; | |||
} else { | |||
arcAngle = Math.PI * (360 - angle) / 180.0; | |||
point[0] = (float) (mCenterX + Math.cos(arcAngle) * radius); | |||
point[1] = (float) (mCenterY - Math.sin(arcAngle) * radius); | |||
} | |||
return point; | |||
} | |||
private SweepGradient generateSweepGradient() { | |||
SweepGradient sweepGradient = new SweepGradient(mCenterX, mCenterY, | |||
mColors, | |||
new float[]{0, 140 / 360f, mSweepAngle / 360f} | |||
); | |||
Matrix matrix = new Matrix(); | |||
matrix.setRotate(mStartAngle - 3, mCenterX, mCenterY); | |||
sweepGradient.setLocalMatrix(matrix); | |||
return sweepGradient; | |||
} | |||
public float getVelocity() { | |||
return mVelocity; | |||
} | |||
public void setVelocity(float velocity) { | |||
if (mVelocity == velocity || velocity < mMin || velocity > mMax) { | |||
return; | |||
} | |||
mVelocity = velocity; | |||
postInvalidate(); | |||
} | |||
private boolean isAnimFinished = true; | |||
public void setValue(float value){ | |||
if (isAnimFinished) { | |||
ObjectAnimator animator = ObjectAnimator.ofFloat(this, "setVelocity", getVelocity(), value); | |||
animator.setDuration(100).setInterpolator(new LinearInterpolator()); | |||
animator.addListener(new AnimatorListenerAdapter() { | |||
@Override | |||
public void onAnimationStart(Animator animation) { | |||
isAnimFinished = false; | |||
} | |||
@Override | |||
public void onAnimationEnd(Animator animation) { | |||
isAnimFinished = true; | |||
} | |||
@Override | |||
public void onAnimationCancel(Animator animation) { | |||
isAnimFinished = true; | |||
} | |||
}); | |||
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { | |||
@Override | |||
public void onAnimationUpdate(ValueAnimator animation) { | |||
float value = (float)animation.getAnimatedValue(); | |||
setVelocity(value); | |||
} | |||
}); | |||
animator.start(); | |||
} | |||
} | |||
} | |||
@@ -16,6 +16,7 @@ import com.bonait.bnframework.common.constant.ConfigName; | |||
import com.bonait.bnframework.common.constant.Constants; | |||
import com.bonait.bnframework.common.helper.ActiveMax; | |||
import com.bonait.bnframework.common.helper.MediaPlayerHelper; | |||
import com.bonait.bnframework.common.image.utils.LocalCacheUtils; | |||
import com.bonait.bnframework.common.utils.AlertDialogUtils; | |||
import com.bonait.bnframework.common.utils.ToastUtils; | |||
import com.qmuiteam.qmui.arch.QMUIActivity; | |||
@@ -48,6 +49,11 @@ public class BaseActivity extends QMUIActivity implements EasyPermissions.Permis | |||
return QMUIDisplayHelper.dp2px(MainApplication.getContext(), 100); | |||
} | |||
@Override | |||
protected void onDestroy() { | |||
super.onDestroy(); | |||
LocalCacheUtils.Get().releaseMemory(); | |||
} | |||
/** | |||
* 跳转界面 | |||
@@ -4,6 +4,7 @@ import android.app.Activity; | |||
import android.content.Intent; | |||
import android.widget.LinearLayout; | |||
import com.bonait.bnframework.HBL.Logs.MessageLog; | |||
import com.bonait.bnframework.R; | |||
import com.bonait.bnframework.business.ExecuteTheRecipe; | |||
import com.bonait.bnframework.common.db.QueryDB; | |||
@@ -26,7 +27,6 @@ import com.bonait.bnframework.common.db.res.UserLogEnum; | |||
import com.bonait.bnframework.common.db.res.lcMode; | |||
import com.bonait.bnframework.common.db.res.wdszMode; | |||
import com.bonait.bnframework.common.helper.I.MyClickListener; | |||
import com.bonait.bnframework.common.helper.MessageLog; | |||
import com.bonait.bnframework.common.helper.mode.OrderA; | |||
import com.bonait.bnframework.common.helper.mode.ResultA; | |||
import com.bonait.bnframework.common.linktab.LinkMode; | |||
@@ -173,7 +173,10 @@ public class DataBus { | |||
ArrayList<BPA_SUBORDER> suborders= QueryDB.GetSubOrdersTodayNoMake(); | |||
for (BPA_SUBORDER item:suborders) | |||
{ | |||
AddGoodsMake(item); | |||
if(QueryDB.GetGoodsId(item.goodsID)!=null) // ---> // ---> | |||
{ | |||
AddGoodsMake(item); | |||
} | |||
} | |||
ExecuteTheRecipe.MakeGoodCount= QueryDB.GetSuOrderTodanCount(); | |||
@@ -0,0 +1,269 @@ | |||
package com.bonait.bnframework.common.cookie; | |||
import android.content.Context; | |||
import android.graphics.Color; | |||
import android.text.TextUtils; | |||
import android.util.AttributeSet; | |||
import android.view.Gravity; | |||
import android.view.View; | |||
import android.view.ViewGroup; | |||
import android.view.ViewParent; | |||
import android.view.animation.Animation; | |||
import android.view.animation.AnimationUtils; | |||
import android.widget.ImageView; | |||
import android.widget.LinearLayout; | |||
import android.widget.TextView; | |||
import androidx.annotation.NonNull; | |||
import androidx.annotation.Nullable; | |||
import androidx.core.content.ContextCompat; | |||
import com.bonait.bnframework.R; | |||
/** | |||
* Created by Eric on 2017/3/2. | |||
*/ | |||
final class Cookie extends LinearLayout { | |||
private Animation slideInAnimation; | |||
private Animation slideOutAnimation; | |||
private LinearLayout layoutCookie; | |||
private TextView tvTitle; | |||
private TextView tvMessage; | |||
private ImageView ivIcon; | |||
private TextView btnAction; | |||
private ImageView btnActionWithIcon; | |||
private long duration = 2000; | |||
private int layoutGravity = Gravity.BOTTOM; | |||
public Cookie(@NonNull final Context context) { | |||
this(context, null); | |||
} | |||
public Cookie(@NonNull final Context context, @Nullable final AttributeSet attrs) { | |||
this(context, attrs, 0); | |||
} | |||
public Cookie(@NonNull final Context context, @Nullable final AttributeSet attrs, | |||
final int defStyleAttr) { | |||
super(context, attrs, defStyleAttr); | |||
initViews(context); | |||
} | |||
public int getLayoutGravity() { | |||
return layoutGravity; | |||
} | |||
private void initViews(Context context) { | |||
inflate(getContext(), R.layout.layout_cookie, this); | |||
layoutCookie = (LinearLayout) findViewById(R.id.cookie); | |||
tvTitle = (TextView) findViewById(R.id.tv_title); | |||
tvMessage = (TextView) findViewById(R.id.tv_message); | |||
ivIcon = (ImageView) findViewById(R.id.iv_icon); | |||
btnAction = (TextView) findViewById(R.id.btn_action); | |||
btnActionWithIcon = (ImageView) findViewById(R.id.btn_action_with_icon); | |||
initDefaultStyle(context); | |||
} | |||
/** | |||
* Init the default text color or background color. You can change the default style by set the | |||
* Theme's attributes. | |||
* | |||
* <pre> | |||
* <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> | |||
* <item name="cookieTitleColor">@color/default_title_color</item> | |||
* <item name="cookieMessageColor">@color/default_message_color</item> | |||
* <item name="cookieActionColor">@color/default_action_color</item> | |||
* <item name="cookieBackgroundColor">@color/default_bg_color</item> | |||
* </style> | |||
* </pre> | |||
*/ | |||
private void initDefaultStyle(Context context) { | |||
//Custom the default style of a cookie | |||
int titleColor = ThemeResolver.getColor(context, R.attr.cookieTitleColor, Color.WHITE); | |||
int messageColor = ThemeResolver.getColor(context, R.attr.cookieMessageColor, Color.WHITE); | |||
int actionColor = ThemeResolver.getColor(context, R.attr.cookieActionColor, Color.WHITE); | |||
int backgroundColor = ThemeResolver.getColor(context, R.attr.cookieBackgroundColor, | |||
ContextCompat.getColor(context, R.color.default_bg_color)); | |||
tvTitle.setTextColor(titleColor); | |||
tvMessage.setTextColor(messageColor); | |||
btnAction.setTextColor(actionColor); | |||
layoutCookie.setBackgroundColor(backgroundColor); | |||
} | |||
public void setParams(final CookieBar.Params params) { | |||
if (params != null) { | |||
duration = params.duration; | |||
layoutGravity = params.layoutGravity; | |||
//Icon | |||
if (params.iconResId != 0) { | |||
ivIcon.setVisibility(VISIBLE); | |||
ivIcon.setBackgroundResource(params.iconResId); | |||
} | |||
//Title | |||
if (!TextUtils.isEmpty(params.title)) { | |||
tvTitle.setVisibility(VISIBLE); | |||
tvTitle.setText(params.title); | |||
if (params.titleColor != 0) { | |||
tvTitle.setTextColor(ContextCompat.getColor(getContext(), params.titleColor)); | |||
} | |||
} | |||
//Message | |||
if (!TextUtils.isEmpty(params.message)) { | |||
tvMessage.setVisibility(VISIBLE); | |||
tvMessage.setText(params.message); | |||
if (params.messageColor != 0) { | |||
tvMessage.setTextColor(ContextCompat.getColor(getContext(), params.messageColor)); | |||
} | |||
if (TextUtils.isEmpty(params.title)) { | |||
LayoutParams layoutParams = (LayoutParams) tvMessage | |||
.getLayoutParams(); | |||
layoutParams.topMargin = 0; | |||
} | |||
} | |||
//Action | |||
if ((!TextUtils.isEmpty(params.action) || params.actionIcon != 0) | |||
&& params.onActionClickListener != null) { | |||
btnAction.setVisibility(VISIBLE); | |||
btnAction.setText(params.action); | |||
btnAction.setOnClickListener(new OnClickListener() { | |||
@Override | |||
public void onClick(View view) { | |||
params.onActionClickListener.onClick(); | |||
dismiss(); | |||
} | |||
}); | |||
//Action Color | |||
if (params.actionColor != 0) { | |||
btnAction.setTextColor(ContextCompat.getColor(getContext(), params.actionColor)); | |||
} | |||
} | |||
if (params.actionIcon != 0 && params.onActionClickListener != null) { | |||
btnAction.setVisibility(GONE); | |||
btnActionWithIcon.setVisibility(VISIBLE); | |||
btnActionWithIcon.setBackgroundResource(params.actionIcon); | |||
btnActionWithIcon.setOnClickListener(new OnClickListener() { | |||
@Override | |||
public void onClick(View view) { | |||
params.onActionClickListener.onClick(); | |||
dismiss(); | |||
} | |||
}); | |||
} | |||
//Background | |||
if (params.backgroundColor != 0) { | |||
layoutCookie | |||
.setBackgroundColor(ContextCompat.getColor(getContext(), params.backgroundColor)); | |||
} | |||
int padding = getContext().getResources().getDimensionPixelSize(R.dimen.default_padding); | |||
if (layoutGravity == Gravity.BOTTOM) { | |||
layoutCookie.setPadding(padding, padding, padding, padding); | |||
} | |||
createInAnim(); | |||
createOutAnim(); | |||
} | |||
} | |||
@Override | |||
protected void onLayout(boolean changed, int l, int t, int r, int b) { | |||
if (layoutGravity == Gravity.TOP) { | |||
super.onLayout(changed, l, 0, r, layoutCookie.getMeasuredHeight()); | |||
} else { | |||
super.onLayout(changed, l, t, r, b); | |||
} | |||
} | |||
private void createInAnim() { | |||
slideInAnimation = AnimationUtils.loadAnimation(getContext(), | |||
layoutGravity == Gravity.BOTTOM ? R.anim.slide_in_from_bottom : R.anim.slide_in_from_top); | |||
slideInAnimation.setAnimationListener(new Animation.AnimationListener() { | |||
@Override | |||
public void onAnimationStart(Animation animation) { | |||
} | |||
@Override | |||
public void onAnimationEnd(Animation animation) { | |||
postDelayed(new Runnable() { | |||
@Override | |||
public void run() { | |||
dismiss(); | |||
} | |||
}, duration); | |||
} | |||
@Override | |||
public void onAnimationRepeat(Animation animation) { | |||
} | |||
}); | |||
setAnimation(slideInAnimation); | |||
} | |||
private void createOutAnim() { | |||
slideOutAnimation = AnimationUtils.loadAnimation(getContext(), | |||
layoutGravity == Gravity.BOTTOM ? R.anim.slide_out_to_bottom : R.anim.slide_out_to_top); | |||
slideOutAnimation.setAnimationListener(new Animation.AnimationListener() { | |||
@Override | |||
public void onAnimationStart(Animation animation) { | |||
} | |||
@Override | |||
public void onAnimationEnd(Animation animation) { | |||
} | |||
@Override | |||
public void onAnimationRepeat(Animation animation) { | |||
} | |||
}); | |||
} | |||
private void dismiss() { | |||
slideOutAnimation.setAnimationListener(new Animation.AnimationListener() { | |||
@Override | |||
public void onAnimationStart(final Animation animation) { | |||
} | |||
@Override | |||
public void onAnimationEnd(final Animation animation) { | |||
destroy(); | |||
} | |||
@Override | |||
public void onAnimationRepeat(final Animation animation) { | |||
} | |||
}); | |||
startAnimation(slideOutAnimation); | |||
} | |||
private void destroy() { | |||
postDelayed(new Runnable() { | |||
@Override | |||
public void run() { | |||
ViewParent parent = getParent(); | |||
if (parent != null) { | |||
Cookie.this.clearAnimation(); | |||
((ViewGroup) parent).removeView(Cookie.this); | |||
} | |||
} | |||
}, 200); | |||
} | |||
} |
@@ -0,0 +1,180 @@ | |||
package com.bonait.bnframework.common.cookie; | |||
import android.app.Activity; | |||
import android.view.Gravity; | |||
import android.view.ViewGroup; | |||
import androidx.annotation.ColorRes; | |||
import androidx.annotation.DrawableRes; | |||
import androidx.annotation.StringRes; | |||
/** | |||
* CookieBar is a lightweight library for showing a brief message at the top or bottom of the | |||
* screen. <p> | |||
* <pre> | |||
* new CookieBar | |||
* .Builder(MainActivity.this) | |||
* .setTitle("TITLE") | |||
* .setMessage("MESSAGE") | |||
* .setAction("ACTION", new OnActionClickListener() {}) | |||
* .show(); | |||
* </pre> | |||
* <p> Created by Eric on 2017/3/2. | |||
*/ | |||
public class CookieBar { | |||
private static final String TAG = "cookie"; | |||
private Cookie cookieView; | |||
private Activity context; | |||
private CookieBar() { | |||
} | |||
private CookieBar(Activity context, Params params) { | |||
this.context = context; | |||
cookieView = new Cookie(context); | |||
cookieView.setParams(params); | |||
} | |||
public void show() { | |||
if (cookieView != null) { | |||
final ViewGroup decorView = (ViewGroup) context.getWindow().getDecorView(); | |||
final ViewGroup content = (ViewGroup) decorView.findViewById(android.R.id.content); | |||
if (cookieView.getParent() == null) { | |||
if (cookieView.getLayoutGravity() == Gravity.BOTTOM) { | |||
content.addView(cookieView); | |||
} else { | |||
decorView.addView(cookieView); | |||
} | |||
} | |||
} | |||
} | |||
public static class Builder { | |||
private Params params = new Params(); | |||
public Activity context; | |||
/** | |||
* Create a builder for an cookie. | |||
*/ | |||
public Builder(Activity activity) { | |||
this.context = activity; | |||
} | |||
public Builder setIcon(@DrawableRes int iconResId) { | |||
params.iconResId = iconResId; | |||
return this; | |||
} | |||
public Builder setTitle(String title) { | |||
params.title = title; | |||
return this; | |||
} | |||
public Builder setTitle(@StringRes int resId) { | |||
params.title = context.getString(resId); | |||
return this; | |||
} | |||
public Builder setMessage(String message) { | |||
params.message = message; | |||
return this; | |||
} | |||
public Builder setMessage(@StringRes int resId) { | |||
params.message = context.getString(resId); | |||
return this; | |||
} | |||
public Builder setDuration(long duration) { | |||
params.duration = duration; | |||
return this; | |||
} | |||
public Builder setTitleColor(@ColorRes int titleColor) { | |||
params.titleColor = titleColor; | |||
return this; | |||
} | |||
public Builder setMessageColor(@ColorRes int messageColor) { | |||
params.messageColor = messageColor; | |||
return this; | |||
} | |||
public Builder setBackgroundColor(@ColorRes int backgroundColor) { | |||
params.backgroundColor = backgroundColor; | |||
return this; | |||
} | |||
public Builder setActionColor(@ColorRes int actionColor) { | |||
params.actionColor = actionColor; | |||
return this; | |||
} | |||
public Builder setAction(String action, OnActionClickListener onActionClickListener) { | |||
params.action = action; | |||
params.onActionClickListener = onActionClickListener; | |||
return this; | |||
} | |||
public Builder setAction(@StringRes int resId, OnActionClickListener onActionClickListener) { | |||
params.action = context.getString(resId); | |||
params.onActionClickListener = onActionClickListener; | |||
return this; | |||
} | |||
public Builder setActionWithIcon(@DrawableRes int resId, | |||
OnActionClickListener onActionClickListener) { | |||
params.actionIcon = resId; | |||
params.onActionClickListener = onActionClickListener; | |||
return this; | |||
} | |||
public Builder setLayoutGravity(int layoutGravity) { | |||
params.layoutGravity = layoutGravity; | |||
return this; | |||
} | |||
public CookieBar create() { | |||
CookieBar cookie = new CookieBar(context, params); | |||
return cookie; | |||
} | |||
public CookieBar show() { | |||
final CookieBar cookie = create(); | |||
cookie.show(); | |||
return cookie; | |||
} | |||
} | |||
final static class Params { | |||
public String title; | |||
public String message; | |||
public String action; | |||
public OnActionClickListener onActionClickListener; | |||
public int iconResId; | |||
public int backgroundColor; | |||
public int titleColor; | |||
public int messageColor; | |||
public int actionColor; | |||
public long duration = 2000; | |||
public int layoutGravity = Gravity.TOP; | |||
public int actionIcon; | |||
} | |||
} |
@@ -0,0 +1,50 @@ | |||
package com.bonait.bnframework.common.cookie; | |||
import android.app.Activity; | |||
import android.widget.Toast; | |||
import com.bonait.bnframework.R; | |||
public class CookieHelper { | |||
public static int Mode = 0; | |||
public static int ShowTime = 10000; | |||
/** | |||
* 显示消息 | |||
* @param title | |||
* @param message | |||
*/ | |||
public static void Show(Activity activity, String title, String message) { | |||
if (Mode == 1) { | |||
new CookieBar.Builder(activity) | |||
.setBackgroundColor(R.color.app_color_blue) | |||
.setActionColor(android.R.color.white) | |||
.setTitleColor(R.color.white) | |||
.setTitle(title) | |||
.setMessage(message) | |||
.setDuration(ShowTime) | |||
.setActionWithIcon(R.mipmap.ic_action_close, new OnActionClickListener() { | |||
@Override | |||
public void onClick() { | |||
} | |||
}) | |||
.show(); | |||
} else { | |||
new CookieBar.Builder(activity) | |||
.setTitle(title) | |||
.setMessage(message) | |||
.setDuration(ShowTime) | |||
.setBackgroundColor(R.color.app_color_blue) | |||
.setActionColor(android.R.color.white) | |||
.setTitleColor(R.color.white) | |||
.setAction("已读确认关闭", new OnActionClickListener() { | |||
@Override | |||
public void onClick() { | |||
} | |||
}) | |||
.show(); | |||
} | |||
} | |||
} |
@@ -0,0 +1,10 @@ | |||
package com.bonait.bnframework.common.cookie; | |||
/** | |||
* Created by Eric on 2017/3/3. | |||
*/ | |||
public interface OnActionClickListener { | |||
void onClick(); | |||
} |
@@ -0,0 +1,26 @@ | |||
package com.bonait.bnframework.common.cookie; | |||
import android.content.Context; | |||
import android.content.res.TypedArray; | |||
import androidx.annotation.AttrRes; | |||
/** | |||
* Created by Eric on 2017/3/21. | |||
*/ | |||
public class ThemeResolver { | |||
public static int getColor(Context context, @AttrRes int attr) { | |||
return getColor(context, attr, 0); | |||
} | |||
public static int getColor(Context context, @AttrRes int attr, int defaultColor) { | |||
TypedArray a = context.getTheme().obtainStyledAttributes(new int[]{attr}); | |||
try { | |||
return a.getColor(0, defaultColor); | |||
} finally { | |||
a.recycle(); | |||
} | |||
} | |||
} |
@@ -1,13 +0,0 @@ | |||
package com.bonait.bnframework.common.helper.I; | |||
import com.bonait.bnframework.common.db.res.AlertLogEnum; | |||
import com.bonait.bnframework.common.db.res.UserLogEnum; | |||
public interface IMessageLogNotify { | |||
void ErrorMsg(String msg); | |||
void InfoMsg(String msg); | |||
void WarnMsg(String msg); | |||
void UserMsg(UserLogEnum type, String msg); | |||
void AlertMsg(AlertLogEnum type, String msg); | |||
} |
@@ -1,5 +0,0 @@ | |||
package com.bonait.bnframework.common.helper.I; | |||
public interface IRun { | |||
void Run(); | |||
} |
@@ -1,7 +0,0 @@ | |||
package com.bonait.bnframework.common.helper.I; | |||
public interface IThread { | |||
void Run() throws InterruptedException; | |||
void RunComplete() throws InterruptedException; | |||
} |
@@ -5,9 +5,10 @@ import android.net.ConnectivityManager; | |||
import android.net.NetworkInfo; | |||
import android.util.Log; | |||
import com.bonait.bnframework.HBL.Interface.IRun; | |||
import com.bonait.bnframework.HBL.Logs.MessageLog; | |||
import com.bonait.bnframework.common.constant.ConfigName; | |||
import com.bonait.bnframework.common.helper.I.IMessage; | |||
import com.bonait.bnframework.common.helper.I.IRun; | |||
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; | |||
import org.eclipse.paho.client.mqttv3.MqttCallback; | |||
@@ -1,89 +0,0 @@ | |||
package com.bonait.bnframework.common.helper; | |||
import com.bonait.bnframework.common.db.res.AlertLogEnum; | |||
import com.bonait.bnframework.common.db.res.UserLogEnum; | |||
import com.bonait.bnframework.common.helper.I.IMessageLogNotify; | |||
import com.bonait.bnframework.common.helper.I.IRun; | |||
import java.text.SimpleDateFormat; | |||
import java.util.Date; | |||
public class MessageLog { | |||
public static IMessageLogNotify MsgNotify; | |||
/** | |||
* 日志触发通知 | |||
*/ | |||
public static IRun AddNotify; | |||
public static String MsgInfo = ""; | |||
public static void ShowInfo(String msg) { | |||
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); | |||
Date date = new Date(); | |||
String tempMsg = formatter.format(date) + ":" + msg; | |||
if(MsgInfo.length()>=8000)MsgInfo=""; | |||
MsgInfo = tempMsg + "\r\n" + MsgInfo; | |||
if (MsgNotify != null) | |||
MsgNotify.InfoMsg(tempMsg); | |||
if (AddNotify != null) AddNotify.Run(); | |||
} | |||
public static void ShowWarning(String msg) { | |||
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); | |||
Date date = new Date(); | |||
String tempMsg = formatter.format(date) + ":" + msg; | |||
if(MsgInfo.length()>=8000)MsgInfo=""; | |||
MsgInfo = tempMsg + "\r\n" + MsgInfo; | |||
if (MsgNotify != null) | |||
MsgNotify.WarnMsg(tempMsg); | |||
if (AddNotify != null) AddNotify.Run(); | |||
} | |||
public static void ShowError(String msg) { | |||
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); | |||
Date date = new Date(); | |||
String tempMsg = formatter.format(date) + ":" + msg; | |||
if(MsgInfo.length()>=8000)MsgInfo=""; | |||
MsgInfo = tempMsg + "\r\n" + MsgInfo; | |||
if (MsgNotify != null) | |||
MsgNotify.ErrorMsg(tempMsg); | |||
if (AddNotify != null) AddNotify.Run(); | |||
} | |||
/** | |||
* 用户操作日志 | |||
* @param type | |||
* @param msg | |||
*/ | |||
public static void ShowUserMessage(UserLogEnum type, String msg) | |||
{ | |||
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); | |||
Date date = new Date(); | |||
String tempMsg = formatter.format(date) + ":" + msg; | |||
if(MsgInfo.length()>=8000)MsgInfo=""; | |||
MsgInfo = tempMsg + "\r\n" + MsgInfo; | |||
if (MsgNotify != null) | |||
MsgNotify.UserMsg(type,tempMsg); | |||
if (AddNotify != null) AddNotify.Run(); | |||
} | |||
/** | |||
* 预警日志 | |||
* @param type | |||
* @param msg | |||
*/ | |||
public static void ShowAlertMessage(AlertLogEnum type, String msg) | |||
{ | |||
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); | |||
Date date = new Date(); | |||
String tempMsg = formatter.format(date) + ":" + msg; | |||
if(MsgInfo.length()>=8000)MsgInfo=""; | |||
MsgInfo = tempMsg + "\r\n" + MsgInfo; | |||
if (MsgNotify != null) | |||
MsgNotify.AlertMsg(type,tempMsg); | |||
if (AddNotify != null) AddNotify.Run(); | |||
} | |||
} |
@@ -0,0 +1,20 @@ | |||
package com.bonait.bnframework.common.helper; | |||
import com.bonait.bnframework.HBL.Communication.Modbus.ModbusMaster; | |||
public class ModbusHelper extends ModbusMaster { | |||
private static volatile ModbusHelper instance = null; | |||
public synchronized static ModbusHelper get(){ | |||
if(instance==null)instance=new ModbusHelper(); | |||
return instance; | |||
} | |||
private ModbusHelper(){} | |||
public void RtuInit(String comName,int baudRate){ | |||
new Thread(()->{ RtuConnect(comName,baudRate);}).start(); | |||
} | |||
public void TcpInit(String ip,int port){ | |||
new Thread(()->{ TcpConnect(ip,port);}).start(); | |||
} | |||
} |
@@ -1,6 +1,6 @@ | |||
package com.bonait.bnframework.common.helper; | |||
import com.bonait.bnframework.common.helper.I.IRun; | |||
import com.bonait.bnframework.HBL.Interface.IRun; | |||
import java.util.concurrent.ConcurrentHashMap; | |||
@@ -1,75 +0,0 @@ | |||
package com.bonait.bnframework.common.helper; | |||
import com.bonait.bnframework.common.helper.I.IThread; | |||
import com.bonait.bnframework.common.helper.mode.ThreadModel; | |||
import java.util.concurrent.ConcurrentHashMap; | |||
public class ThreadManager { | |||
private static volatile ThreadManager _Instance; | |||
public static ThreadManager Get() { | |||
if (_Instance == null) | |||
_Instance = new ThreadManager(); | |||
return _Instance; | |||
} | |||
private ThreadManager() { | |||
} | |||
public long RestartInterval = 2000; | |||
ConcurrentHashMap<String, ThreadModel> ts = new ConcurrentHashMap<>(); | |||
private void Sleep(long millis) { | |||
try { | |||
Thread.sleep(millis); | |||
} catch (InterruptedException e) { | |||
throw new RuntimeException(e); | |||
} | |||
} | |||
public void StartLong(String Key, boolean IsRestart, IThread _thread) { | |||
if (!ts.containsKey(Key)) { | |||
ts.put(Key, new ThreadModel()); | |||
ts.get(Key).RunThread = _thread; | |||
ts.get(Key).ThreadObj = new Thread(() -> { | |||
MessageLog.ShowInfo("启动线程:" + Key); | |||
while (!ts.get(Key).IsCancel) { | |||
if (IsRestart) { | |||
try { | |||
ts.get(Key).RunThread.Run(); | |||
} catch (Exception ex) { | |||
MessageLog.ShowError("多线程:" + Key + "运行发生异常,已重启,errorMsg:" + ex.toString()); | |||
Sleep(RestartInterval); | |||
} | |||
} else { | |||
try { | |||
ts.get(Key).RunThread.Run(); | |||
} catch (InterruptedException e) { | |||
MessageLog.ShowError("多线程:" + Key + "运行发生异常,已退出,errorMsg:" + e.toString()); | |||
} | |||
} | |||
} | |||
try { | |||
ts.get(Key).RunThread.RunComplete(); | |||
MessageLog.ShowInfo("线程:[" + Key + "]--执行完成"); | |||
} catch (InterruptedException e) { | |||
throw new RuntimeException(e); | |||
} | |||
ts.remove(Key); | |||
}); | |||
ts.get(Key).ThreadObj.setName(Key); | |||
ts.get(Key).ThreadObj.start(); | |||
} else { | |||
MessageLog.ShowWarning("任务-[" + Key + "]-已存在"); | |||
} | |||
} | |||
public void Stop(String Key) { | |||
if (ts.containsKey(Key)) { | |||
ts.get(Key).IsCancel = true; | |||
} | |||
} | |||
} |
@@ -1,9 +0,0 @@ | |||
package com.bonait.bnframework.common.helper.mode; | |||
import com.bonait.bnframework.common.helper.I.IThread; | |||
public class ThreadModel { | |||
public IThread RunThread; | |||
public boolean IsCancel; | |||
public Thread ThreadObj; | |||
} |
@@ -1,6 +1,7 @@ | |||
package com.bonait.bnframework.common.image; | |||
import android.graphics.Bitmap; | |||
import android.graphics.drawable.BitmapDrawable; | |||
import android.widget.ImageView; | |||
import com.bin.david.form.data.form.IForm; | |||
@@ -17,18 +18,15 @@ import java.util.regex.Pattern; | |||
*/ | |||
public class MyBitmapUtils { | |||
private NetCacheUtils mNetCacheUtils; | |||
private LocalCacheUtils mLocalCacheUtils; | |||
private MemoryCacheUtils mMemoryCacheUtils; | |||
public MyBitmapUtils(){ | |||
mMemoryCacheUtils=new MemoryCacheUtils(); | |||
mLocalCacheUtils=new LocalCacheUtils(); | |||
mNetCacheUtils=new NetCacheUtils(mLocalCacheUtils,mMemoryCacheUtils); | |||
mNetCacheUtils=new NetCacheUtils(mMemoryCacheUtils); | |||
} | |||
public void disPlay(ImageView ivPic, String url) { | |||
ivPic.setImageResource(R.mipmap.loading2); | |||
Bitmap bitmap; | |||
//内存缓存 | |||
String name=""; | |||
//https://hbl-1305371387.cos.ap-chengdu.myqcloud.com/Franchisee/jccy@163.com/goods/133381212328681942.jpg | |||
@@ -40,29 +38,20 @@ public class MyBitmapUtils { | |||
name=url; | |||
} | |||
bitmap=mMemoryCacheUtils.getBitmapFromMemory(name); | |||
if (bitmap!=null){ | |||
ivPic.setImageBitmap(bitmap); | |||
System.out.println("从内存获取图片啦....."); | |||
return; | |||
} | |||
//本地缓存 | |||
bitmap = mLocalCacheUtils.getBitmapFromLocal(name); | |||
if(bitmap !=null){ | |||
ivPic.setImageBitmap(bitmap); | |||
System.out.println("从本地获取图片啦....."); | |||
//从本地获取图片后,保存至内存中 | |||
mMemoryCacheUtils.setBitmapToMemory(name,bitmap); | |||
return; | |||
} | |||
//网络缓存 | |||
if(url.contains("http")) | |||
if(url!=null && !url.isEmpty()) | |||
{ | |||
mNetCacheUtils.getBitmapFromNet(ivPic,url); | |||
if(LocalCacheUtils.Get().SetBitmapFile(ivPic,name)){ | |||
return; | |||
} | |||
//网络缓存 | |||
if(url.contains("http")) | |||
{ | |||
mNetCacheUtils.getBitmapFromNet(ivPic,url); | |||
} | |||
} | |||
} | |||
/** | |||
* 判断字符串是否为URL | |||
* | |||
@@ -0,0 +1,49 @@ | |||
package com.bonait.bnframework.common.image.utils; | |||
import android.graphics.BitmapFactory; | |||
public class ImageUtils { | |||
public static int computeSampleSize(BitmapFactory.Options options, | |||
int minSideLength, int maxNumOfPixels) { | |||
int initialSize = computeInitialSampleSize(options, minSideLength, | |||
maxNumOfPixels); | |||
int roundedSize; | |||
if (initialSize <= 8 ) { | |||
roundedSize = 1 ; | |||
while (roundedSize < initialSize) { | |||
roundedSize <<= 1 ; | |||
} | |||
} else { | |||
roundedSize = (initialSize + 7 ) / 8 * 8 ; | |||
} | |||
return roundedSize; | |||
} | |||
public static int computeInitialSampleSize(BitmapFactory.Options options, | |||
int minSideLength, int maxNumOfPixels) { | |||
double w = options.outWidth; | |||
double h = options.outHeight; | |||
int lowerBound = (maxNumOfPixels == - 1 ) ? 1 : | |||
( int ) Math.ceil(Math.sqrt(w * h / maxNumOfPixels)); | |||
int upperBound = (minSideLength == - 1 ) ? 128 : | |||
( int ) Math.min(Math.floor(w / minSideLength), | |||
Math.floor(h / minSideLength)); | |||
if (upperBound < lowerBound) { | |||
// return the larger one when there is no overlapping zone. | |||
return lowerBound; | |||
} | |||
if ((maxNumOfPixels == - 1 ) && | |||
(minSideLength == - 1 )) { | |||
return 1 ; | |||
} else if (minSideLength == - 1 ) { | |||
return lowerBound; | |||
} else { | |||
return upperBound; | |||
} | |||
} | |||
} |
@@ -1,69 +1,217 @@ | |||
package com.bonait.bnframework.common.image.utils; | |||
import android.app.Activity; | |||
import android.app.ActivityManager; | |||
import android.content.Context; | |||
import android.graphics.Bitmap; | |||
import android.graphics.BitmapFactory; | |||
import android.os.Debug; | |||
import android.os.Environment; | |||
import android.util.Log; | |||
import android.view.View; | |||
import android.widget.ImageView; | |||
import android.os.Process; | |||
import com.bonait.bnframework.R; | |||
import com.bonait.bnframework.business.OrderServer; | |||
import com.bonait.bnframework.common.constant.ConfigName; | |||
import com.bonait.bnframework.common.helper.AES; | |||
import com.bumptech.glide.Glide; | |||
import com.bumptech.glide.load.engine.DiskCacheStrategy; | |||
import com.bumptech.glide.request.RequestOptions; | |||
import com.bumptech.glide.request.target.Target; | |||
import java.io.File; | |||
import java.io.FileInputStream; | |||
import java.io.FileOutputStream; | |||
import java.io.IOException; | |||
import java.io.RandomAccessFile; | |||
import java.nio.channels.FileChannel; | |||
import java.util.ArrayList; | |||
import java.util.List; | |||
import java.util.Map; | |||
/** | |||
* 三级缓存之本地缓存 | |||
*/ | |||
public class LocalCacheUtils { | |||
private static final String CACHE_PATH= Environment.getExternalStorageDirectory().getAbsolutePath()+"/hblchayingdb/WebImage"; | |||
private static final String CACHE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/hblchayingdb/WebImage"; | |||
//region 私有单例 | |||
private static volatile LocalCacheUtils _instance; | |||
public static LocalCacheUtils Get() { | |||
if (_instance == null) | |||
_instance = new LocalCacheUtils(); | |||
return _instance; | |||
} | |||
private LocalCacheUtils() { | |||
} | |||
//endregion | |||
/** | |||
* 从本地读取图片 | |||
* 设置Image图片 | |||
* | |||
* @param ivPic | |||
* @param url | |||
* @return | |||
*/ | |||
public Bitmap getBitmapFromLocal(String url){ | |||
String fileName = null;//把图片的url当做文件名,并进行MD5加密 | |||
try { | |||
fileName = url;//MD5Encoder.encode(url);//AES.Encrypt(url);//MD5Encoder.encode(url); | |||
File file=new File(CACHE_PATH,fileName); | |||
Bitmap bitmap=null; | |||
if(file.exists())// | |||
{ | |||
bitmap = BitmapFactory.decodeStream(new FileInputStream(file)); | |||
public boolean SetBitmapFile(ImageView ivPic, String url) { | |||
File file = new File(CACHE_PATH, url); | |||
if (null != file && file.exists()) { | |||
try { | |||
Glide.with(ivPic.getContext()).load(file) | |||
//.override(width, height) | |||
// .thumbnail(0.1f) // 加载原始图片的10%作为缩略图 | |||
//.fitCenter() // 缩放图片以适应ImageView的尺寸 | |||
.override(150, 75) // 设置目标图片的宽度和高度 | |||
.placeholder(R.mipmap.loading2) | |||
// .error(R.mipmap.loadingerror) | |||
.skipMemoryCache(true) // 禁用内存缓存 | |||
.diskCacheStrategy(DiskCacheStrategy.NONE) | |||
//.diskCacheStrategy(DiskCacheStrategy.ALL) // 缓存所有版本的图片 | |||
.into(ivPic); | |||
System.out.println("从本地获取图片啦....."); | |||
return true; | |||
} catch (OutOfMemoryError e) { | |||
e.printStackTrace(); | |||
} catch (IllegalArgumentException ex) { | |||
System.out.println("界面已经销毁....."); | |||
} | |||
return bitmap; | |||
} catch (Exception e) { | |||
e.printStackTrace(); | |||
} | |||
return null; | |||
return false; | |||
} | |||
/** | |||
* 判断活动窗体是否正在显示 | |||
* | |||
* @param context | |||
* @return | |||
*/ | |||
public boolean isActivityVisible(Context context) { | |||
if (context instanceof Activity) { | |||
Activity activity = (Activity) context; | |||
return !activity.isFinishing() && !activity.isDestroyed(); | |||
} | |||
return false; | |||
} | |||
/** | |||
* 从网络获取图片后,保存至本地缓存 | |||
* | |||
* @param url | |||
* @param bitmap | |||
*/ | |||
public void setBitmapToLocal(String url,Bitmap bitmap){ | |||
public String setBitmapToLocal(String url, Bitmap bitmap) { | |||
try { | |||
String fileName = url.substring(url.lastIndexOf('/')+1);;//MD5Encoder.encode(url);;//AES.Encrypt(url);//;MD5Encoder.encode(url);//把图片的url当做文件名,并进行MD5加密 | |||
File file=new File(CACHE_PATH,fileName); | |||
String fileName = url.substring(url.lastIndexOf('/') + 1); | |||
;//MD5Encoder.encode(url);;//AES.Encrypt(url);//;MD5Encoder.encode(url);//把图片的url当做文件名,并进行MD5加密 | |||
File file = new File(CACHE_PATH, fileName); | |||
//通过得到文件的父文件,判断父文件是否存在 | |||
File parentFile = file.getParentFile(); | |||
if (!parentFile.exists()){ | |||
if (!parentFile.exists()) { | |||
parentFile.mkdirs(); | |||
} | |||
if(!file.exists())//文件不存在 | |||
if (!file.exists())//文件不存在 | |||
{ | |||
//把图片保存至本地 | |||
bitmap.compress(Bitmap.CompressFormat.JPEG,100,new FileOutputStream(file)); | |||
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, new FileOutputStream(file)); | |||
} | |||
return fileName; | |||
} catch (Exception e) { | |||
e.printStackTrace(); | |||
} | |||
return ""; | |||
} | |||
private RandomAccessFile procStatFile; | |||
private RandomAccessFile appStatFile; | |||
private Long lastCpuTime; | |||
private Long lastAppCpuTime; | |||
/** | |||
* 运行内存 | |||
*/ | |||
public void RunCPUOrMemory() | |||
{ | |||
// int cpu = (int)sampleCPU(); | |||
// int mem = (int)sampleMemory(); | |||
// Log.e("实时内存消耗", ": CPU: " + cpu + "%" + ", Memory: " + mem + "MB"); | |||
releaseMemory(); | |||
} | |||
/** | |||
* 释放内存 | |||
*/ | |||
public static void releaseMemory() { | |||
System.runFinalization(); | |||
Runtime.getRuntime().gc(); | |||
Runtime.getRuntime().runFinalization(); | |||
System.gc(); | |||
} | |||
/** | |||
* 读取CPU | |||
* @return | |||
*/ | |||
private double sampleCPU() { | |||
long cpuTime; | |||
long appTime; | |||
double sampleValue = 0.0D; | |||
try { | |||
if (procStatFile == null || appStatFile == null) { | |||
procStatFile = new RandomAccessFile("/proc/stat", "r"); | |||
appStatFile = new RandomAccessFile("/proc/" + Process.myPid() + "/stat", "r"); | |||
} else { | |||
procStatFile.seek(0L); | |||
appStatFile.seek(0L); | |||
} | |||
String procStatString = procStatFile.readLine(); | |||
String appStatString = appStatFile.readLine(); | |||
String procStats[] = procStatString.split(" "); | |||
String appStats[] = appStatString.split(" "); | |||
cpuTime = Long.parseLong(procStats[2]) + Long.parseLong(procStats[3]) | |||
+ Long.parseLong(procStats[4]) + Long.parseLong(procStats[5]) | |||
+ Long.parseLong(procStats[6]) + Long.parseLong(procStats[7]) | |||
+ Long.parseLong(procStats[8]); | |||
appTime = Long.parseLong(appStats[13]) + Long.parseLong(appStats[14]); | |||
if (lastCpuTime == null && lastAppCpuTime == null) { | |||
lastCpuTime = cpuTime; | |||
lastAppCpuTime = appTime; | |||
return sampleValue; | |||
} | |||
sampleValue = ((double) (appTime - lastAppCpuTime) / (double) (cpuTime - lastCpuTime)) * 100D; | |||
lastCpuTime = cpuTime; | |||
lastAppCpuTime = appTime; | |||
} catch (Exception e) { | |||
e.printStackTrace(); | |||
} | |||
return sampleValue; | |||
} | |||
/** | |||
* 读取内存消耗 | |||
* @return | |||
*/ | |||
private double sampleMemory() { | |||
double mem = 0.0D; | |||
try { | |||
// 统计进程的内存信息 totalPss | |||
ActivityManager activityManager = (ActivityManager) ConfigName.getInstance().dishesCon.getSystemService(Context.ACTIVITY_SERVICE); | |||
final Debug.MemoryInfo[] memInfo = activityManager.getProcessMemoryInfo(new int[]{Process.myPid()}); | |||
if (memInfo.length > 0) { | |||
// TotalPss = dalvikPss + nativePss + otherPss, in KB | |||
final int totalPss = memInfo[0].getTotalPss(); | |||
if (totalPss >= 0) { | |||
// Mem in MB | |||
mem = totalPss / 1024.0D; | |||
} | |||
} | |||
} catch (Exception e) { | |||
e.printStackTrace(); | |||
} | |||
return mem; | |||
} | |||
} |
@@ -3,6 +3,7 @@ package com.bonait.bnframework.common.image.utils; | |||
import android.graphics.Bitmap; | |||
import android.graphics.BitmapFactory; | |||
import android.graphics.drawable.BitmapDrawable; | |||
import android.os.AsyncTask; | |||
import android.widget.ImageView; | |||
@@ -15,11 +16,9 @@ import java.net.URL; | |||
*/ | |||
public class NetCacheUtils { | |||
private LocalCacheUtils mLocalCacheUtils; | |||
private MemoryCacheUtils mMemoryCacheUtils; | |||
public NetCacheUtils(LocalCacheUtils localCacheUtils, MemoryCacheUtils memoryCacheUtils) { | |||
mLocalCacheUtils = localCacheUtils; | |||
public NetCacheUtils( MemoryCacheUtils memoryCacheUtils) { | |||
mMemoryCacheUtils = memoryCacheUtils; | |||
} | |||
@@ -73,14 +72,14 @@ public class NetCacheUtils { | |||
@Override | |||
protected void onPostExecute(Bitmap result) { | |||
if (result != null) { | |||
ivPic.setImageBitmap(result); | |||
System.out.println("从网络缓存图片啦....."); | |||
//从网络获取图片后,保存至本地缓存 | |||
mLocalCacheUtils.setBitmapToLocal(url, result); | |||
//保存至内存中 | |||
mMemoryCacheUtils.setBitmapToMemory(url, result); | |||
String filename= LocalCacheUtils.Get().setBitmapToLocal(url, result); | |||
//设置图片显示,用新版的获取更小的资源 | |||
LocalCacheUtils.Get().SetBitmapFile(ivPic,filename); | |||
} | |||
} | |||
} | |||
@@ -104,6 +103,10 @@ public class NetCacheUtils { | |||
BitmapFactory.Options options = new BitmapFactory.Options(); | |||
options.inSampleSize=2;//宽高压缩为原来的1/2 | |||
options.inPreferredConfig=Bitmap.Config.ARGB_4444; | |||
// 设置是否深拷贝,与inPurgeable结合使用 | |||
options.inInputShareable = true; | |||
// 设置为True时,表示系统内存不足时可以被回 收,设置为False时,表示不能被回收。 | |||
options.inPurgeable = true; | |||
Bitmap bitmap = BitmapFactory.decodeStream(conn.getInputStream(),null,options); | |||
return bitmap; | |||
} | |||
@@ -3,6 +3,7 @@ package com.bonait.bnframework.common.linktab.good; | |||
import android.content.res.Resources; | |||
import androidx.annotation.LayoutRes; | |||
import androidx.annotation.NonNull; | |||
import androidx.annotation.Nullable; | |||
import androidx.recyclerview.widget.RecyclerView; | |||
@@ -37,4 +38,6 @@ public class GoodRightAdapter extends BaseQuickAdapter<LinkMode, BaseViewHolder> | |||
newgood_adapter adapter = new newgood_adapter(getContext(), item.content); | |||
view.setAdapter(adapter); | |||
} | |||
} |
@@ -3,6 +3,7 @@ package com.bonait.bnframework.common.linktab.makegood; | |||
import android.content.res.Resources; | |||
import androidx.annotation.LayoutRes; | |||
import androidx.annotation.NonNull; | |||
import androidx.annotation.Nullable; | |||
import androidx.recyclerview.widget.RecyclerView; | |||
@@ -26,6 +27,7 @@ public class MakeGoodRightAdapter extends BaseQuickAdapter<LinkMode, BaseViewHol | |||
Fdata=data; | |||
} | |||
public newmakegood_adapter adapter=null; | |||
@Override | |||
protected void convert(BaseViewHolder holder, LinkMode item) { | |||
RecyclerView view= holder.getView(R.id.recycler_view); | |||
@@ -33,7 +35,7 @@ public class MakeGoodRightAdapter extends BaseQuickAdapter<LinkMode, BaseViewHol | |||
MyLayoutManager layout = new MyLayoutManager(); | |||
layout.setAutoMeasureEnabled(true); | |||
view.setLayoutManager(layout); | |||
newmakegood_adapter adapter = new newmakegood_adapter(getContext(), item.content); | |||
adapter = new newmakegood_adapter(getContext(), item.content); | |||
view.setAdapter(adapter); | |||
} | |||
} |
@@ -1,44 +0,0 @@ | |||
package com.bonait.bnframework.common.modbus; | |||
import com.licheedev.modbus4android.ModbusWorker; | |||
import com.serotonin.modbus4j.ModbusMaster; | |||
public class ModbusTcpHelper extends ModbusWorker { | |||
private static volatile ModbusTcpHelper instance = null; | |||
public static ModbusTcpHelper get() { | |||
ModbusTcpHelper manager = instance; | |||
if (manager == null) { | |||
synchronized (ModbusTcpHelper.class) { | |||
manager = instance; | |||
if (manager == null) { | |||
manager = new ModbusTcpHelper(); | |||
instance = manager; | |||
} | |||
} | |||
} | |||
return manager; | |||
} | |||
private ModbusTcpHelper() { | |||
} | |||
/** | |||
* 释放整个ModbusManager,单例会被置null | |||
*/ | |||
public synchronized void release() { | |||
super.release(); | |||
instance = null; | |||
} | |||
/** | |||
* 获取 | |||
* @return | |||
*/ | |||
public synchronized ModbusMaster getModbusMaster() | |||
{ | |||
return super.getModbusMaster(); | |||
} | |||
} |
@@ -1,812 +0,0 @@ | |||
package com.bonait.bnframework.common.modbus; | |||
import android.os.Looper; | |||
import com.bonait.bnframework.MainApplication; | |||
import com.bonait.bnframework.business.ConfigData; | |||
import com.bonait.bnframework.common.constant.ConfigName; | |||
import com.bonait.bnframework.common.constant.DataBus; | |||
import com.bonait.bnframework.common.helper.DataFormat; | |||
import com.bonait.bnframework.common.helper.I.IReadCallBack; | |||
import com.bonait.bnframework.common.helper.I.IWriteCallBack; | |||
import com.bonait.bnframework.common.helper.MessageLog; | |||
import com.bonait.bnframework.common.utils.ToastUtils; | |||
import com.licheedev.modbus4android.ModbusCallback; | |||
import com.licheedev.modbus4android.ModbusParam; | |||
import com.licheedev.modbus4android.ModbusRespException; | |||
import com.licheedev.modbus4android.param.TcpParam; | |||
import com.serotonin.modbus4j.ModbusMaster; | |||
import com.serotonin.modbus4j.exception.ModbusInitException; | |||
import com.serotonin.modbus4j.exception.ModbusTransportException; | |||
import com.serotonin.modbus4j.msg.ReadCoilsResponse; | |||
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse; | |||
import java.io.IOException; | |||
import java.io.InputStreamReader; | |||
import java.io.LineNumberReader; | |||
import java.io.UnsupportedEncodingException; | |||
import java.nio.ByteBuffer; | |||
import java.util.Arrays; | |||
import java.util.concurrent.ExecutionException; | |||
public class ModbusTcpServer { | |||
private static volatile ModbusTcpServer instance = null; | |||
public static ModbusTcpServer get() { | |||
ModbusTcpServer manager = instance; | |||
if (manager == null) { | |||
synchronized (ModbusTcpServer.class) { | |||
manager = instance; | |||
if (manager == null) { | |||
manager = new ModbusTcpServer(); | |||
instance = manager; | |||
} | |||
} | |||
} | |||
return manager; | |||
} | |||
private ModbusTcpServer() { | |||
} | |||
static ModbusParam param; | |||
private int GetAddress(String address) { | |||
if (address == null) return -1; | |||
if (address.length() > 0) { | |||
address = address.trim(); | |||
if (address.toUpperCase().contains("M") && address.length() >= 4) { | |||
String[] res = address.substring(1).split("[.]"); | |||
if (res != null && res.length == 2) { | |||
try { | |||
int firstAdd = Integer.parseInt(res[0]); | |||
int endAdd = Integer.parseInt(res[1]); | |||
if (endAdd >= 0 && endAdd <= 7) { | |||
return (firstAdd * 8) + 320 + endAdd; | |||
} | |||
} catch (NumberFormatException e) { | |||
return -1; | |||
} | |||
} | |||
} else if (address.toUpperCase().contains("I") && address.length() >= 4) { | |||
String[] res = address.substring(1).split("[.]"); | |||
if (res != null && res.length == 2) { | |||
try { | |||
int firstAdd = Integer.parseInt(res[0]); | |||
int endAdd = Integer.parseInt(res[1]); | |||
if (endAdd >= 0 && endAdd <= 7) { | |||
return (firstAdd * 8) + endAdd; | |||
} | |||
} catch (NumberFormatException e) { | |||
return -1; | |||
} | |||
} | |||
} else if ((address.toUpperCase().contains("VW") || address.toUpperCase().contains("VD")) && address.length() >= 3) { | |||
String res = address.substring(2); | |||
if (res != null) { | |||
try { | |||
int tempAdd = Integer.parseInt(res); | |||
return (tempAdd / 2) + 100; | |||
} catch (NumberFormatException e) { | |||
return -1; | |||
} | |||
} | |||
} else { | |||
try { | |||
return Integer.parseInt(address); | |||
} catch (NumberFormatException e) { | |||
return -1; | |||
} | |||
} | |||
} | |||
return -1; | |||
} | |||
/** | |||
* 获取布尔位地址信息 | |||
* 列:M2.5 = getBitSingleAdd("M",2,5); | |||
* | |||
* @param Prefix 地址标头 | |||
* @param startAdd 起始地址编号 | |||
* @param num 要获取的第几位数量 | |||
* @return | |||
*/ | |||
public String getBitSingleAdd(String Prefix, int startAdd, int num) { | |||
if (num > 0) { | |||
int FirstAdd = num / 8; | |||
int EndAdd = num % 8; | |||
if (EndAdd == 0) { | |||
FirstAdd--; | |||
EndAdd = 7; | |||
} else { | |||
EndAdd--; | |||
} | |||
return Prefix + FirstAdd + startAdd + "." + EndAdd; | |||
} | |||
return ""; | |||
} | |||
/** | |||
* Ping PLC地址是否通畅 | |||
* @param address | |||
* @param pingTimes ping的次数 | |||
* @param timeOut 超时时间 10 | |||
* @return | |||
*/ | |||
public static boolean ping2(String address, int pingTimes, int timeOut) { | |||
Process process = null; | |||
try { | |||
process = Runtime.getRuntime().exec( "ping " + "-c " + pingTimes + " -w " + timeOut+ " "+address); | |||
InputStreamReader r = new InputStreamReader(process.getInputStream()); | |||
LineNumberReader returnData = new LineNumberReader(r); | |||
String returnMsg=""; | |||
String line = ""; | |||
while ((line = returnData.readLine()) != null) { | |||
System.out.println(line); | |||
returnMsg += line; | |||
} | |||
if(returnMsg.indexOf("100% packet loss")!=-1){ | |||
System.out.println("与 " +address +" 连接不畅通."); | |||
//ToastUtils.info("与 " +address +" 连接不畅通."); | |||
return false; | |||
} else{ | |||
System.out.println("与 " +address +" 连接畅通."); | |||
//ToastUtils.info("与 " +address +" 连接不畅通."); | |||
return true; | |||
} | |||
} catch (IOException e) { | |||
// e.printStackTrace(); | |||
} | |||
return false; | |||
} | |||
/** | |||
* 连接 | |||
*/ | |||
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<ModbusMaster>() { | |||
@Override | |||
public void onSuccess(ModbusMaster modbusMaster) { | |||
ToastUtils.info("设备 " + ConfigName.getInstance().Address + " 连接成功"); | |||
MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " 连接成功"); | |||
ConfigName.getInstance().PlcIsConnect = true; | |||
ConfigData.getInstance().PLC_Init(); | |||
} | |||
@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<byte[]> callback) { | |||
int add = GetAddress(Address); | |||
if (add < 0) return; | |||
try { | |||
ReadHoldingRegistersResponse res = ModbusTcpHelper.get().syncReadHoldingRegisters(1, add, length); | |||
byte[] data = res.getData(); | |||
byte[] tempData = new byte[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<byte[]> callback) { | |||
int add = GetAddress(Address); | |||
if (add < 0) return; | |||
try { | |||
ReadHoldingRegistersResponse res = ModbusTcpHelper.get().syncReadHoldingRegisters(1, add, length); | |||
byte[] data = res.getData(); | |||
byte[] tempData = new byte[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<String> callback) { | |||
int add = GetAddress(Address); | |||
if (add < 0) return; | |||
try { | |||
ReadHoldingRegistersResponse res = ModbusTcpHelper.get().syncReadHoldingRegisters(1, add, length); | |||
byte[] data = res.getData(); | |||
byte[] data1 = Arrays.copyOfRange(data, 0, 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<short[]> callback) { | |||
int add = GetAddress(Address); | |||
if (add < 0) return; | |||
try { | |||
ReadHoldingRegistersResponse res = ModbusTcpHelper.get().syncReadHoldingRegisters(1, add, length); | |||
short[] data = res.getShortData(); | |||
if (data.length == length) { | |||
if (callback != null) callback.onSuccess(data); | |||
} | |||
} catch (InterruptedException e) { | |||
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} catch (ExecutionException e) { | |||
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} catch (ModbusTransportException e) { | |||
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} catch (ModbusInitException e) { | |||
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} catch (ModbusRespException e) { | |||
MessageLog.ShowError("ReadShort onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} | |||
} | |||
public void ReadBool(String Address, int length, IReadCallBack<boolean[]> callback) { | |||
int add = GetAddress(Address); | |||
if (add < 0) return; | |||
try { | |||
ReadCoilsResponse res = ModbusTcpHelper.get().syncReadCoil(1, add, length); | |||
boolean[] data = res.getBooleanData(); | |||
boolean[] result = Arrays.copyOfRange(data, 0, length); | |||
if (result.length == length) { | |||
if (callback != null) callback.onSuccess(result); | |||
} | |||
} catch (InterruptedException e) { | |||
MessageLog.ShowError("ReadBool onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} catch (ExecutionException e) { | |||
MessageLog.ShowError("ReadBool onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} catch (ModbusTransportException e) { | |||
MessageLog.ShowError("ReadBool onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} catch (ModbusInitException e) { | |||
MessageLog.ShowError("ReadBool onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} catch (ModbusRespException e) { | |||
MessageLog.ShowError("ReadBool onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} | |||
} | |||
public void ReadFloat(String Address, int length, IReadCallBack<float[]> callback) { | |||
int add = GetAddress(Address); | |||
if (add < 0) return; | |||
try { | |||
ReadHoldingRegistersResponse res = ModbusTcpHelper.get().syncReadHoldingRegisters(1, add, length*2); | |||
byte[] data = res.getData(); | |||
float[] tempValues = new float[length]; | |||
for (int i = 0; i < length; i++) { | |||
byte[] tempData = new byte[4]; | |||
for (int m = 0; m < 4; m++) { | |||
tempData[m] = data[i * 4 + m]; | |||
} | |||
tempValues[i] = BytesToFloat(tempData, DataFormat.BADC); | |||
} | |||
if (tempValues.length == length) { | |||
if (callback != null) callback.onSuccess(tempValues); | |||
} | |||
} catch (InterruptedException e) { | |||
MessageLog.ShowError("ReadFloat onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} catch (ExecutionException e) { | |||
MessageLog.ShowError("ReadFloat onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} catch (ModbusTransportException e) { | |||
MessageLog.ShowError("ReadFloat onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} catch (ModbusInitException e) { | |||
MessageLog.ShowError("ReadFloat onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} catch (ModbusRespException e) { | |||
MessageLog.ShowError("ReadFloat onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} | |||
} | |||
public void ReadInt(String Address, int length, IReadCallBack<int[]> callback) { | |||
int add = GetAddress(Address); | |||
if (add < 0) return; | |||
try { | |||
ReadHoldingRegistersResponse res = ModbusTcpHelper.get().syncReadHoldingRegisters(1, add, length * 2); | |||
byte[] data = res.getData(); | |||
int[] tempValues = new int[length]; | |||
if(data.length>=4) | |||
{ | |||
for (int i = 0; i < length; i++) { | |||
byte[] tempData = new byte[4]; | |||
for (int m = 0; m < 4; m++) { | |||
tempData[m] = data[i * 4 + m]; | |||
} | |||
// Integer a1 = tempValues[i] = BytesToInt(tempData, DataFormat.ABCD); | |||
// Integer a2 = tempValues[i] = BytesToInt(tempData, DataFormat.BADC); | |||
// Integer a3 = tempValues[i] = BytesToInt(tempData, DataFormat.CDAB); | |||
// Integer a4 = tempValues[i] = BytesToInt(tempData, DataFormat.DCBA); | |||
tempValues[i] = BytesToInt(tempData, DataFormat.BADC); | |||
} | |||
}else | |||
{ | |||
MessageLog.ShowError("ReadInt onFailure,Address=" ); | |||
} | |||
if (callback != null) callback.onSuccess(tempValues); | |||
} catch (InterruptedException e) { | |||
MessageLog.ShowError("ReadInt onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} catch (ExecutionException e) { | |||
MessageLog.ShowError("ReadInt onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} catch (ModbusTransportException e) { | |||
MessageLog.ShowError("ReadInt onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} catch (ModbusInitException e) { | |||
MessageLog.ShowError("ReadInt onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} catch (ModbusRespException e) { | |||
MessageLog.ShowError("ReadInt onFailure,Address=" + Address + ",length=" + length + ",msg:" + e.toString()); | |||
} | |||
} | |||
public void WriteShort(String Address, short Value, IWriteCallBack callback) { | |||
int add = GetAddress(Address); | |||
if (add < 0) return; | |||
short[] send = new short[1]; | |||
send[0] = Value; | |||
try { | |||
ModbusTcpHelper.get().syncWriteRegisters(1, add, send); | |||
if (callback != null) | |||
callback.onSuccess(); | |||
} catch (InterruptedException e) { | |||
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString()); | |||
if (callback != null) callback.onFailure(e.toString()); | |||
} catch (ExecutionException e) { | |||
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString()); | |||
if (callback != null) callback.onFailure(e.toString()); | |||
} catch (ModbusTransportException e) { | |||
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString()); | |||
if (callback != null) callback.onFailure(e.toString()); | |||
} catch (ModbusInitException e) { | |||
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString()); | |||
if (callback != null) callback.onFailure(e.toString()); | |||
} catch (ModbusRespException e) { | |||
MessageLog.ShowError("WriteShort onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString()); | |||
if (callback != null) callback.onFailure(e.toString()); | |||
} | |||
} | |||
public void WriteBool(String Address, boolean Value, IWriteCallBack callback) { | |||
int add = GetAddress(Address); | |||
if (add < 0) return; | |||
try { | |||
ModbusTcpHelper.get().syncWriteCoil(1, add, Value); | |||
if (callback != null) | |||
callback.onSuccess(); | |||
} catch (InterruptedException e) { | |||
MessageLog.ShowError("WriteBool onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString()); | |||
if (callback != null) callback.onFailure(e.toString()); | |||
} catch (ExecutionException e) { | |||
MessageLog.ShowError("WriteBool onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString()); | |||
if (callback != null) callback.onFailure(e.toString()); | |||
} catch (ModbusTransportException e) { | |||
MessageLog.ShowError("WriteBool onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString()); | |||
if (callback != null) callback.onFailure(e.toString()); | |||
} catch (ModbusInitException e) { | |||
MessageLog.ShowError("WriteBool onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString()); | |||
if (callback != null) callback.onFailure(e.toString()); | |||
} catch (ModbusRespException e) { | |||
MessageLog.ShowError("WriteBool onFailure,Address=" + Address + ",length=" + Value + ",msg:" + e.toString()); | |||
if (callback != null) callback.onFailure(e.toString()); | |||
} | |||
} | |||
public void WriteFloat(String Address, float Value, IWriteCallBack callback) { | |||
int add = GetAddress(Address); | |||
if (add < 0) return; | |||
int intBits = Float.floatToRawIntBits(Value); | |||
short[] send = IntToShorts(intBits); | |||
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()); | |||
} | |||
} | |||
} |
@@ -17,10 +17,9 @@ import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvide | |||
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask; | |||
import com.alibaba.sdk.android.oss.model.PutObjectRequest; | |||
import com.alibaba.sdk.android.oss.model.PutObjectResult; | |||
import com.bonait.bnframework.HBL.Interface.IRunT; | |||
import com.bonait.bnframework.business.ConfigData; | |||
import com.bonait.bnframework.common.constant.ConfigName; | |||
import com.bonait.bnframework.common.helper.I.IRun; | |||
import com.bonait.bnframework.common.helper.I.IRunT; | |||
import com.bonait.bnframework.common.image.utils.LocalCacheUtils; | |||
import com.bonait.bnframework.common.model.ResAPI; | |||
@@ -18,38 +18,41 @@ public class MyLayoutManager extends RecyclerView.LayoutManager { | |||
@Override | |||
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { | |||
detachAndScrapAttachedViews(recycler); | |||
int sumWidth = getWidth(); | |||
int curLineWidth = 0, curLineTop = 0; | |||
int lastLineMaxHeight = 0; | |||
for (int i = 0; i < getItemCount(); i++) { | |||
View view = recycler.getViewForPosition(i); | |||
addView(view); | |||
measureChildWithMargins(view, 0, 0); | |||
int width = getDecoratedMeasuredWidth(view); | |||
int height = getDecoratedMeasuredHeight(view); | |||
curLineWidth += width; | |||
if (curLineWidth <= sumWidth) {//不需要换行 | |||
layoutDecorated(view, curLineWidth - width, curLineTop, curLineWidth, curLineTop + height); | |||
//比较当前行多有item的最大高度 | |||
lastLineMaxHeight = Math.max(lastLineMaxHeight, height); | |||
} else {//换行 | |||
curLineWidth = width; | |||
if (lastLineMaxHeight == 0) { | |||
try { | |||
detachAndScrapAttachedViews(recycler); | |||
int sumWidth = getWidth(); | |||
int curLineWidth = 0, curLineTop = 0; | |||
int lastLineMaxHeight = 0; | |||
for (int i = 0; i < getItemCount(); i++) { | |||
View view = recycler.getViewForPosition(i); | |||
addView(view); | |||
measureChildWithMargins(view, 0, 0); | |||
int width = getDecoratedMeasuredWidth(view); | |||
int height = getDecoratedMeasuredHeight(view); | |||
curLineWidth += width; | |||
if (curLineWidth <= sumWidth) {//不需要换行 | |||
layoutDecorated(view, curLineWidth - width, curLineTop, curLineWidth, curLineTop + height); | |||
//比较当前行多有item的最大高度 | |||
lastLineMaxHeight = Math.max(lastLineMaxHeight, height); | |||
} else {//换行 | |||
curLineWidth = width; | |||
if (lastLineMaxHeight == 0) { | |||
lastLineMaxHeight = height; | |||
} | |||
//记录当前行top | |||
curLineTop += lastLineMaxHeight; | |||
layoutDecorated(view, 0, curLineTop, width, curLineTop + height); | |||
lastLineMaxHeight = height; | |||
} | |||
//记录当前行top | |||
curLineTop += lastLineMaxHeight; | |||
layoutDecorated(view, 0, curLineTop, width, curLineTop + height); | |||
lastLineMaxHeight = height; | |||
} | |||
} catch (IndexOutOfBoundsException e) { | |||
e.printStackTrace(); | |||
} | |||
} | |||
} |
@@ -10,17 +10,18 @@ import android.util.Log; | |||
import android.view.MenuItem; | |||
import android.widget.RelativeLayout; | |||
import com.bonait.bnframework.HBL.Logs.MessageLog; | |||
import com.bonait.bnframework.HBL.Thread.IThread; | |||
import com.bonait.bnframework.HBL.Thread.ThreadManager; | |||
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.I.IThread; | |||
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.helper.ModbusHelper; | |||
import com.bonait.bnframework.common.image.utils.LocalCacheUtils; | |||
import com.bonait.bnframework.common.tabbar.MainNavigateTabBar; | |||
import com.bonait.bnframework.common.utils.NetworkUtils; | |||
import com.bonait.bnframework.modules.home.adapter.FragmentAdapter; | |||
@@ -111,49 +112,55 @@ public class BottomNavigationMainActivity extends BaseActivity { | |||
//判断连接环境 | |||
ConfigData.getInstance().ToggleEnvironment(); | |||
//2.初始化PLC | |||
ReconnectModbus(); | |||
ModbusHelper.get().RtuInit("/dev/ttyCOM0",9600); | |||
// ReconnectModbus(); | |||
//MQTT数据监听 | |||
OrderServer.Get().MqttInit(); | |||
} | |||
/** | |||
* 重新连接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 { | |||
} | |||
}); | |||
// 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; | |||
//// } | |||
//// } | |||
// | |||
// LocalCacheUtils.Get().RunCPUOrMemory(); | |||
// | |||
// Thread.sleep(5000); | |||
// } catch (Exception e) { | |||
// Log.i("PLC", "PLC重连接失败!" + e.getMessage()); | |||
// } | |||
// } | |||
// | |||
// | |||
// }); | |||
} catch (Exception e) { | |||
MessageLog.ShowInfo("重新连接Modbus异常," + e.getMessage()); | |||
} | |||
@@ -53,6 +53,16 @@ public class image_sp_adapter extends RecyclerView.Adapter<RecyclerView.ViewHold | |||
} | |||
/** | |||
* 当列表不在使用时候 | |||
* @param holder The ViewHolder for the view being recycled | |||
*/ | |||
@Override | |||
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) { | |||
super.onViewRecycled(holder); | |||
// 回收不可见的图片资源 | |||
((MyLCViewHolder1)holder).img.setImageDrawable(null); | |||
} | |||
@Override | |||
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { | |||
try { | |||
@@ -50,6 +50,13 @@ public class newgood_adapter extends RecyclerView.Adapter<RecyclerView.ViewHolde | |||
Data = data; | |||
} | |||
@Override | |||
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) { | |||
super.onViewRecycled(holder); | |||
// 回收不可见的图片资源 | |||
((MyLCViewHolder1)holder).ImageUrl.setImageDrawable(null); | |||
} | |||
@NonNull | |||
@Override | |||
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { | |||
@@ -50,6 +50,13 @@ public class newmakegood_adapter extends RecyclerView.Adapter<RecyclerView.View | |||
return new newgood_adapter.MyLCViewHolder1(inflate); | |||
} | |||
@Override | |||
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) { | |||
super.onViewRecycled(holder); | |||
// 回收不可见的图片资源 | |||
((MyLCViewHolder1)holder).ImageUrl.setImageDrawable(null); | |||
} | |||
@Override | |||
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { | |||
try { | |||
@@ -25,7 +25,6 @@ import com.bonait.bnframework.common.constant.ConfigName; | |||
import com.bonait.bnframework.common.constant.DataBus; | |||
import com.bonait.bnframework.common.db.res.SilosLsjyMode; | |||
import com.bonait.bnframework.common.db.res.wdszMode; | |||
import com.bonait.bnframework.common.helper.I.IRun; | |||
import com.bonait.bnframework.common.helper.I.IWriteCallBack; | |||
import com.bonait.bnframework.common.helper.InputFilterMinMax; | |||
import com.bonait.bnframework.common.utils.ToastUtils; | |||
@@ -1,5 +1,7 @@ | |||
package com.bonait.bnframework.modules.home.fragment; | |||
import static com.bonait.bnframework.MainApplication.getContext; | |||
import androidx.annotation.NonNull; | |||
import androidx.annotation.Nullable; | |||
import androidx.appcompat.app.AppCompatActivity; | |||
@@ -15,13 +17,17 @@ import android.os.Bundle; | |||
import android.os.Handler; | |||
import android.os.Message; | |||
import android.util.Log; | |||
import android.view.Gravity; | |||
import android.view.LayoutInflater; | |||
import android.view.View; | |||
import android.widget.Button; | |||
import android.widget.ListView; | |||
import android.widget.RelativeLayout; | |||
import android.widget.TextView; | |||
import android.widget.Toast; | |||
import com.bonait.bnframework.HBL.Interface.IRun; | |||
import com.bonait.bnframework.HBL.Interface.IRunT; | |||
import com.bonait.bnframework.R; | |||
import com.bonait.bnframework.business.ConfigData; | |||
import com.bonait.bnframework.business.ExecuteTheRecipe; | |||
@@ -29,24 +35,27 @@ import com.bonait.bnframework.common.base.BaseFragment; | |||
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.cookie.CookieBar; | |||
import com.bonait.bnframework.common.cookie.CookieHelper; | |||
import com.bonait.bnframework.common.cookie.OnActionClickListener; | |||
import com.bonait.bnframework.common.db.QueryDB; | |||
import com.bonait.bnframework.common.db.mode.BPA_GOODPROPERTY; | |||
import com.bonait.bnframework.common.db.mode.BPA_GOODS; | |||
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPENAME; | |||
import com.bonait.bnframework.common.db.mode.BPA_GOODSTYPE; | |||
import com.bonait.bnframework.common.db.mode.BPA_ORDER; | |||
import com.bonait.bnframework.common.db.mode.BPA_SILOS; | |||
import com.bonait.bnframework.common.db.mode.BPA_SUBORDER; | |||
import com.bonait.bnframework.common.db.res.AlertLogEnum; | |||
import com.bonait.bnframework.common.db.res.ResGoodProperty; | |||
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.I.IRun; | |||
import com.bonait.bnframework.common.helper.I.IRunT; | |||
import com.bonait.bnframework.common.helper.I.IThread; | |||
import com.bonait.bnframework.common.db.res.lcMode; | |||
import com.bonait.bnframework.common.helper.I.IWriteCallBack; | |||
import com.bonait.bnframework.common.helper.I.MyClickListener; | |||
import com.bonait.bnframework.common.helper.MessageLog; | |||
import com.bonait.bnframework.common.helper.ThreadManager; | |||
import com.bonait.bnframework.common.helper.WrapContentLinearLayoutManager; | |||
import com.bonait.bnframework.common.linktab.LinkMode; | |||
import com.bonait.bnframework.common.linktab.TopItemDecoration; | |||
import com.bonait.bnframework.common.linktab.good.GoodLeftAdapter; | |||
@@ -62,6 +71,7 @@ import com.bonait.bnframework.modules.home.adapter.wl_adapter; | |||
import com.bonait.bnframework.modules.home.fragment.mode.add_makegood_control; | |||
import com.bonait.bnframework.modules.home.fragment.mode.add_manguan_control; | |||
import com.bonait.bnframework.modules.home.fragment.mode.add_pf_control; | |||
import com.bumptech.glide.Glide; | |||
import com.litao.slider.NiftySlider; | |||
import com.orhanobut.logger.Logger; | |||
import com.qmuiteam.qmui.widget.QMUITopBarLayout; | |||
@@ -229,9 +239,10 @@ public class MakeGoodFragment extends BaseFragment { | |||
* 加载商品 | |||
*/ | |||
public void LoadingGood() { | |||
LinearLayoutManager layoutManager = new LinearLayoutManager(context); | |||
layoutManager.setOrientation(LinearLayoutManager.VERTICAL); | |||
datatab_paiduishangping.setLayoutManager(layoutManager); | |||
// LinearLayoutManager layoutManager = new LinearLayoutManager(context); | |||
// layoutManager.setOrientation(LinearLayoutManager.VERTICAL); | |||
// datatab_paiduishangping.setLayoutManager(layoutManager); | |||
datatab_paiduishangping.setLayoutManager(new WrapContentLinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL,false)); | |||
DataBus.getInstance().loadinggoodAdapter = new loadinggood_adapter(context, myClickListener, getActivity()); | |||
datatab_paiduishangping.setAdapter(DataBus.getInstance().loadinggoodAdapter); | |||
@@ -279,7 +290,7 @@ public class MakeGoodFragment extends BaseFragment { | |||
String title = "温馨提示!"; | |||
String message = "客官确定要开始制作【" + makegood.good.name + "】吗?"; | |||
QMUIDialog dialog= AlertDialogUtils.showDialog111(context, title, message, new QMUIDialogAction.ActionListener() { | |||
QMUIDialog dialog = AlertDialogUtils.showDialog111(context, title, message, new QMUIDialogAction.ActionListener() { | |||
@Override | |||
public void onClick(QMUIDialog dialog, int index) { | |||
make(makegood); | |||
@@ -287,8 +298,7 @@ public class MakeGoodFragment extends BaseFragment { | |||
} | |||
}); | |||
if (ConfigName.getInstance().versionSelectionEnum.equals("配料吧台")) | |||
{ | |||
if (ConfigName.getInstance().versionSelectionEnum.equals("配料吧台")) { | |||
ExecuteTheRecipe.OnIngredientButtonPressedNotify = new IRun() { | |||
@Override | |||
public void Run() { | |||
@@ -306,8 +316,7 @@ public class MakeGoodFragment extends BaseFragment { | |||
} | |||
}; | |||
public void make(ResGoodsMake makegood) | |||
{ | |||
public void make(ResGoodsMake makegood) { | |||
//判断温度是否到达 | |||
if (!ConfigName.getInstance().versionSelectionEnum.equals("配料吧台")) { | |||
if (makegood.Gt1) { | |||
@@ -341,9 +350,9 @@ public class MakeGoodFragment extends BaseFragment { | |||
*/ | |||
private void initTopBar() { | |||
mTopBar.setTitle("智慧菠萝点餐系统"+ConfigName.getInstance().Version); | |||
mTopBar.setTitle("智慧菠萝点餐系统" + ConfigName.getInstance().Version); | |||
mTopBar.addLeftImageButton(R.mipmap.silos1,1).setOnClickListener(new View.OnClickListener() { | |||
mTopBar.addLeftImageButton(R.mipmap.silos1, 1).setOnClickListener(new View.OnClickListener() { | |||
@Override | |||
public void onClick(View v) { | |||
add_manguan.SetData(); | |||
@@ -390,7 +399,7 @@ public class MakeGoodFragment extends BaseFragment { | |||
}; | |||
} | |||
@OnClick({R.id.good_gengxin, R.id.cheng_clear,R.id.loadgood}) | |||
@OnClick({R.id.good_gengxin, R.id.cheng_clear, R.id.loadgood}) | |||
public void onViewClicked(View view) { | |||
switch (view.getId()) { | |||
case R.id.good_gengxin://刷新 | |||
@@ -410,11 +419,9 @@ public class MakeGoodFragment extends BaseFragment { | |||
}); | |||
break; | |||
case R.id.loadgood://加载数据 | |||
if(loadgoodliebiao.getVisibility()==View.VISIBLE) | |||
{ | |||
if (loadgoodliebiao.getVisibility() == View.VISIBLE) { | |||
loadgoodliebiao.setVisibility(View.GONE); | |||
}else | |||
{ | |||
} else { | |||
loadgoodliebiao.setVisibility(View.VISIBLE); | |||
} | |||
break; | |||
@@ -444,17 +451,48 @@ public class MakeGoodFragment extends BaseFragment { | |||
} | |||
}; | |||
int time=0; | |||
/** | |||
* 实时显示线程 | |||
*/ | |||
public void Run() { | |||
new Thread(new Runnable() { | |||
@Override | |||
public void run() { | |||
while (true) { | |||
try { | |||
mHandler.sendEmptyMessage(0); | |||
if(time>=60) //12秒执行一次 | |||
{ | |||
ArrayList<lcMode> lcModes = DataBus.getInstance().ResGetLc(); | |||
String title=""; | |||
for (lcMode item:lcModes) | |||
{ | |||
//lcMode.warningValue >= lcMode.silosmargin | |||
//总量大于0 绑定了物料 告警值设置了 告警大于余量 告警 | |||
if(item.siloszl>0 && !item.materialId.isEmpty() && item.warningValue>0 && item.warningValue >= item.silosmargin) | |||
{ | |||
title+="料仓"+item.num+"-"+item.materialName+"|"; | |||
} | |||
} | |||
if(!title.isEmpty()) | |||
{ | |||
String finalTitle = title; | |||
activity.runOnUiThread(new Runnable() { | |||
@Override | |||
public void run() { | |||
//0.6 --- 0.9 | |||
CookieHelper.Show(activity, finalTitle +"-余量提示","料仓余量不足,请及时补料!若程序预警错误,请及时手动补充原料后,在料仓界面点击《补充原料》"); | |||
} | |||
}); | |||
} | |||
time=0; | |||
} | |||
Thread.sleep(200); | |||
time++; | |||
} catch (Exception ex) { | |||
ToastUtils.error("异常信息:" + ex.getMessage()); | |||
} | |||
@@ -560,12 +598,61 @@ public class MakeGoodFragment extends BaseFragment { | |||
} | |||
}; | |||
// ThreadManager.Get().StartLong("商品制作线程1111111", true, new IThread() { | |||
// @Override | |||
// public void Run() throws InterruptedException { | |||
// try { | |||
// if(DataBus.getInstance().GoodsMake.size()>0) | |||
// { | |||
// ResGoodsMake mmmmm= DataBus.getInstance().GoodsMake.get(0); | |||
// ArrayList<ResGoodsRecipe> recipes= mmmmm.recipes; | |||
// | |||
// //region 根据物料配方排序Sort步骤分组 | |||
// LinkedHashMap<Integer, List<ResGoodsRecipe>> rgrs = new LinkedHashMap<>(); | |||
// for (int i = 0; i < recipes.size(); i++) { | |||
// if (!rgrs.containsKey(recipes.get(i).sort)) | |||
// rgrs.put(recipes.get(i).sort, new ArrayList<>()); | |||
// rgrs.get(recipes.get(i).sort).add(recipes.get(i)); | |||
// } | |||
// //endregion | |||
// int count = 0; | |||
// for (LinkedHashMap.Entry<Integer, List<ResGoodsRecipe>> entry : rgrs.entrySet()) { | |||
// final Integer key = entry.getKey(); | |||
// List<ResGoodsRecipe> goodsRecipes = entry.getValue(); | |||
// //region 当前一次性下发物料集合 | |||
// String RecipesNames = ""; | |||
// for (ResGoodsRecipe item : goodsRecipes) { | |||
// RecipesNames += item.materialName + ","; | |||
// } | |||
// count = 2; | |||
// DataBus.getInstance().UpdateGoodsMake(mmmmm.subOrder.id, "步骤【" + key + "】准备下发物料:" + RecipesNames, count, key, false); | |||
// Thread.sleep(1000); | |||
// } | |||
// | |||
// DataBus.getInstance().DeleteGoodsMake(mmmmm.subOrder.id); | |||
// } | |||
// } catch (Exception ex) { | |||
// ToastUtils.error("异常信息:" + ex.getMessage()); | |||
// } | |||
// Thread.sleep(500); | |||
// } | |||
// @Override | |||
// public void RunComplete() throws InterruptedException { | |||
// | |||
// } | |||
// }); | |||
} | |||
@Override | |||
public void onDestroy() { | |||
super.onDestroy(); | |||
Logger.d("第一页销毁"); | |||
rv_right.setAdapter(null); | |||
Glide.get(getContext()).clearMemory(); | |||
} | |||
/** | |||
@@ -33,10 +33,10 @@ import com.bonait.bnframework.common.db.mode.BPA_MATERIAL; | |||
import com.bonait.bnframework.common.db.res.ResGoodProperty; | |||
import com.bonait.bnframework.common.db.res.ResGoodsRecipe; | |||
import com.bonait.bnframework.common.db.res.lcMode; | |||
import com.bonait.bnframework.common.helper.I.IRunT; | |||
import com.bonait.bnframework.common.helper.I.MyClickListener; | |||
import com.bonait.bnframework.common.http.callback.json.JsonDialogCallback; | |||
import com.bonait.bnframework.common.image.MyBitmapUtils; | |||
import com.bonait.bnframework.common.image.utils.LocalCacheUtils; | |||
import com.bonait.bnframework.common.linktab.LeftAdapter; | |||
import com.bonait.bnframework.common.linktab.LinkMode; | |||
import com.bonait.bnframework.common.linktab.RightAdapter; | |||
@@ -63,6 +63,7 @@ import com.bonait.bnframework.modules.home.fragment.GongnengFragment; | |||
import com.bonait.bnframework.modules.home.fragment.mode.add_good_control; | |||
import com.bonait.bnframework.modules.home.fragment.mode.add_pf_control; | |||
import com.bonait.bnframework.modules.home.fragment.mode.add_pf_home_control; | |||
import com.bumptech.glide.Glide; | |||
import com.google.gson.Gson; | |||
import com.lzy.okgo.OkGo; | |||
import com.lzy.okgo.model.HttpHeaders; | |||
@@ -419,6 +420,8 @@ public class GoodPeiFangActivity extends BaseActivity { | |||
@Override | |||
public void onDestroy() { | |||
super.onDestroy(); | |||
rv_right.setAdapter(null); | |||
Glide.get(this).clearMemory(); | |||
} | |||
@Override | |||
@@ -7,6 +7,7 @@ import androidx.recyclerview.widget.RecyclerView; | |||
import android.os.Bundle; | |||
import android.os.Environment; | |||
import android.view.View; | |||
import android.widget.ImageView; | |||
import com.bonait.bnframework.R; | |||
import com.bonait.bnframework.common.base.BaseActivity; | |||
@@ -15,11 +16,13 @@ import com.bonait.bnframework.common.constant.MessageName; | |||
import com.bonait.bnframework.common.db.mode.BPA_GOODS; | |||
import com.bonait.bnframework.common.helper.AES; | |||
import com.bonait.bnframework.common.helper.I.MyClickListener; | |||
import com.bonait.bnframework.common.image.utils.LocalCacheUtils; | |||
import com.bonait.bnframework.common.message.MessageManager; | |||
import com.bonait.bnframework.common.utils.ToastUtils; | |||
import com.bonait.bnframework.common.view.MyLayoutManager; | |||
import com.bonait.bnframework.modules.home.adapter.image_sp_adapter; | |||
import com.bonait.bnframework.modules.home.fragment.mode.image_sp; | |||
import com.bumptech.glide.Glide; | |||
import com.qmuiteam.qmui.widget.QMUITopBar; | |||
import com.qmuiteam.qmui.widget.QMUITopBarLayout; | |||
@@ -73,7 +76,6 @@ public class ImageChooseActivity extends BaseActivity { | |||
recyclerView.setLayoutManager(layout); | |||
image_sp_adapter spadapter = new image_sp_adapter(this,data); | |||
recyclerView.setAdapter(spadapter); | |||
spadapter.mListener=new MyClickListener() { | |||
@Override | |||
public void clickListener(View v, Object data) { | |||
@@ -93,10 +95,13 @@ public class ImageChooseActivity extends BaseActivity { | |||
@Override | |||
public void onDestroy() { | |||
super.onDestroy(); | |||
recyclerView.setAdapter(null); | |||
Glide.get(this).clearMemory(); | |||
} | |||
@Override | |||
protected boolean canDragBack() { | |||
return false; | |||
} | |||
} | |||
} | |||
@@ -87,17 +87,16 @@ public class ImageSourceActivity extends BaseActivity { | |||
startActivityForResult(intent, Constants.REQ_CODE); | |||
break; | |||
case R.id.baocunbendi://保存按钮 | |||
BitmapFactory.Options options = new BitmapFactory.Options(); | |||
options.inSampleSize = 2;//宽高压缩为原来的1/2 | |||
for (FileEntity item : PickerManager.getInstance().files) { | |||
File file = item.getFile(); | |||
try { | |||
Bitmap bitmap1 = BitmapFactory.decodeStream(new FileInputStream(file)); | |||
new LocalCacheUtils().setBitmapToLocal(file.getName(), bitmap1); | |||
LocalCacheUtils.Get().setBitmapToLocal(file.getName(), bitmap1); | |||
} catch (Exception e) { | |||
} | |||
} | |||
ToastUtils.info("添加成功!"); | |||
FlushedImage(); | |||
break; | |||
} | |||
} | |||
@@ -11,13 +11,13 @@ import android.os.Bundle; | |||
import android.view.View; | |||
import android.widget.Button; | |||
import com.bonait.bnframework.HBL.Interface.IRun; | |||
import com.bonait.bnframework.R; | |||
import com.bonait.bnframework.business.ExecuteTheRecipe; | |||
import com.bonait.bnframework.common.base.BaseActivity; | |||
import com.bonait.bnframework.common.constant.DataBus; | |||
import com.bonait.bnframework.common.db.QueryDB; | |||
import com.bonait.bnframework.common.db.mode.BPA_SUGAR; | |||
import com.bonait.bnframework.common.helper.I.IRun; | |||
import com.bonait.bnframework.common.helper.I.IWriteCallBack; | |||
import com.bonait.bnframework.common.helper.WrapContentLinearLayoutManager; | |||
import com.bonait.bnframework.common.utils.AlertDialogUtils; | |||
@@ -18,6 +18,7 @@ import android.widget.TextView; | |||
import androidx.annotation.NonNull; | |||
import androidx.annotation.Nullable; | |||
import com.bonait.bnframework.HBL.Interface.IRun; | |||
import com.bonait.bnframework.R; | |||
import com.bonait.bnframework.business.ExecuteTheRecipe; | |||
import com.bonait.bnframework.common.base.BaseFragment; | |||
@@ -26,7 +27,6 @@ import com.bonait.bnframework.common.constant.DataBus; | |||
import com.bonait.bnframework.common.db.QueryDB; | |||
import com.bonait.bnframework.common.db.res.SilosLsjyMode; | |||
import com.bonait.bnframework.common.db.res.lcMode; | |||
import com.bonait.bnframework.common.helper.I.IRun; | |||
import com.bonait.bnframework.common.helper.I.IWriteCallBack; | |||
import com.bonait.bnframework.common.utils.ToastUtils; | |||
import com.bonait.bnframework.modules.home.fragment.from.LogActivity; | |||
@@ -29,6 +29,7 @@ import com.bonait.bnframework.common.db.mode.BPA_SUBORDER; | |||
import com.bonait.bnframework.common.db.res.ResGoodProperty; | |||
import com.bonait.bnframework.common.db.res.ResGoodsRecipe; | |||
import com.bonait.bnframework.common.helper.I.MyClickListener; | |||
import com.bonait.bnframework.common.helper.WrapContentLinearLayoutManager; | |||
import com.bonait.bnframework.common.utils.ToastUtils; | |||
import com.bonait.bnframework.common.view.MyLayoutManager; | |||
import com.bonait.bnframework.modules.home.adapter.newneatril_adapter; | |||
@@ -86,9 +87,9 @@ public class add_makegood_control extends LinearLayout{ | |||
private void initData() { | |||
//2.填充规则数据,查询所有属性大类 | |||
LinearLayoutManager layoutManager=new LinearLayoutManager(getContext()); | |||
layoutManager.setOrientation(LinearLayoutManager.VERTICAL); | |||
datatab_makesx.setLayoutManager(layoutManager); | |||
// LinearLayoutManager layoutManager=new LinearLayoutManager(getContext()); | |||
// layoutManager.setOrientation(LinearLayoutManager.VERTICAL); | |||
datatab_makesx.setLayoutManager(new WrapContentLinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL,false)); | |||
//if(DataBus.getInstance().sxadapter==null) | |||
{ | |||
@@ -106,6 +107,20 @@ public class add_makegood_control extends LinearLayout{ | |||
bpa_goodproperties.add(pro); | |||
} | |||
} | |||
for (ResGoodProperty item:bpa_goodproperties) | |||
{ | |||
int i = 0; | |||
for (ResGoodProperty c : item.child) { | |||
if (i == 0) { | |||
c.isSelect = true; | |||
}else | |||
{ | |||
c.isSelect =false; | |||
} | |||
i++; | |||
} | |||
} | |||
DataBus.getInstance().sxadapter = new pfsx_adapter(contextMian,bpa_goodproperties); | |||
} | |||
@@ -26,6 +26,7 @@ import androidx.annotation.NonNull; | |||
import androidx.annotation.Nullable; | |||
import androidx.fragment.app.FragmentManager; | |||
import com.bonait.bnframework.HBL.Interface.IRun; | |||
import com.bonait.bnframework.R; | |||
import com.bonait.bnframework.business.ExecuteTheRecipe; | |||
import com.bonait.bnframework.common.constant.ConfigName; | |||
@@ -34,7 +35,6 @@ import com.bonait.bnframework.common.db.mode.BPA_MATERIAL; | |||
import com.bonait.bnframework.common.db.mode.BPA_SILOS; | |||
import com.bonait.bnframework.common.db.mode.BPA_SILOSANDMATERIAL; | |||
import com.bonait.bnframework.common.db.res.lcMode; | |||
import com.bonait.bnframework.common.helper.I.IRun; | |||
import com.bonait.bnframework.common.helper.I.IWriteCallBack; | |||
import com.bonait.bnframework.common.helper.I.MyClickListener; | |||
import com.bonait.bnframework.common.model.mode.ResMenuLeft; | |||
@@ -22,6 +22,7 @@ import android.widget.ImageView; | |||
import android.widget.LinearLayout; | |||
import android.widget.RelativeLayout; | |||
import com.bonait.bnframework.HBL.Logs.MessageLog; | |||
import com.bonait.bnframework.R; | |||
import com.bonait.bnframework.business.ConfigData; | |||
import com.bonait.bnframework.common.base.BaseActivity; | |||
@@ -32,7 +33,6 @@ import com.bonait.bnframework.common.db.QueryDB; | |||
import com.bonait.bnframework.common.db.mode.BPA_USER; | |||
import com.bonait.bnframework.common.db.res.UserLogEnum; | |||
import com.bonait.bnframework.common.helper.ActiveMax; | |||
import com.bonait.bnframework.common.helper.MessageLog; | |||
import com.bonait.bnframework.common.utils.AlertDialogUtils; | |||
import com.bonait.bnframework.common.utils.AnimationToolUtils; | |||
import com.bonait.bnframework.common.utils.AppUtils; | |||
@@ -212,7 +212,7 @@ public class LoginActivity extends BaseActivity implements Validator.ValidationL | |||
BPA_USER user= QueryDB.UserLogin(userAccount,password); | |||
if(user!=null) | |||
{ | |||
MessageLog.ShowUserMessage(UserLogEnum.登录日志,user.name+"-登录成功"); | |||
MessageLog.ShowInfo(user.name+"-登录成功"); | |||
ConfigName.getInstance().user=user; | |||
ConfigData.getInstance().SavePZ(); | |||
//跳转到主页 | |||
@@ -0,0 +1,3 @@ | |||
<?xml version="1.0" encoding="utf-8"?> | |||
<anticipateInterpolator xmlns:android="http://schemas.android.com/apk/res/android" | |||
android:tension="0.8"/> |
@@ -0,0 +1,3 @@ | |||
<?xml version="1.0" encoding="utf-8"?> | |||
<overshootInterpolator xmlns:android="http://schemas.android.com/apk/res/android" | |||
android:tension="0.8"/> |
@@ -0,0 +1,10 @@ | |||
<?xml version="1.0" encoding="utf-8"?> | |||
<set xmlns:android="http://schemas.android.com/apk/res/android" | |||
android:duration="700" | |||
android:interpolator="@anim/interpolator_slight_overshoot"> | |||
<translate | |||
android:fromYDelta="100%" | |||
android:toYDelta="0%" /> | |||
</set> |
@@ -0,0 +1,10 @@ | |||
<?xml version="1.0" encoding="utf-8"?> | |||
<set xmlns:android="http://schemas.android.com/apk/res/android" | |||
android:duration="700" | |||
android:interpolator="@anim/interpolator_slight_overshoot"> | |||
<translate | |||
android:fromYDelta="-100%" | |||
android:toYDelta="0%" /> | |||
</set> |
@@ -0,0 +1,11 @@ | |||
<?xml version="1.0" encoding="utf-8"?> | |||
<set xmlns:android="http://schemas.android.com/apk/res/android" | |||
android:duration="500" | |||
android:fillAfter="true" | |||
android:interpolator="@anim/interpolator_slight_anticipate"> | |||
<translate | |||
android:fromYDelta="0%" | |||
android:toYDelta="100%" /> | |||
</set> |
@@ -0,0 +1,11 @@ | |||
<?xml version="1.0" encoding="utf-8"?> | |||
<set xmlns:android="http://schemas.android.com/apk/res/android" | |||
android:duration="500" | |||
android:fillAfter="true" | |||
android:interpolator="@anim/interpolator_slight_anticipate"> | |||
<translate | |||
android:fromYDelta="0%" | |||
android:toYDelta="-100%" /> | |||
</set> |