Commit b554710c authored by pengguangpu's avatar pengguangpu

扩散jar包代码,完善weighing moudle

parent 8f22acbe
package com.miya.weighing;
package com.miya.utils;
import com.miya.weighing.BuildConfig;
public class D {
private static final String Tag = "HHVerify";
......
package pupu.chuangjieweighing;
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class MoneyUtil {
public static DecimalFormat fnum = new DecimalFormat("##0.000");
/**
* 格式化金额
* @param value
* @return
*/
public static String formatMoney(BigDecimal value){
if (value==null){
return null;
}
return fnum.format(value);
}
/**
* 金额相加
* @param valueStr 基础值
* @param addStr 被加数
* @return
*/
public static String moneyAdd(String valueStr,String addStr){
BigDecimal value = new BigDecimal(valueStr);
BigDecimal augend = new BigDecimal(addStr);
return fnum.format(value.add(augend));
}
/**
* 金额相加
* @param value 基础值
* @param augend 被加数
* @return
*/
public static BigDecimal moneyAdd(BigDecimal value,BigDecimal augend){
return value.add(augend);
}
/**
* 金额相减
* @param valueStr 基础值
* @param minusStr 减数
* @return
*/
public static String moneySub(String valueStr,String minusStr){
BigDecimal value= new BigDecimal(valueStr);
BigDecimal subtrahend = new BigDecimal(minusStr);
return fnum.format(value.subtract(subtrahend));
}
/**
* 金额相减
* @param value 基础值
* @param subtrahend 减数
* @return
*/
public static BigDecimal moneySub(BigDecimal value,BigDecimal subtrahend){
return value.subtract(subtrahend);
}
/**
* 金额相乘
* @param valueStr 基础值
* @param mulStr 被乘数
* @return
*/
public static String moneyMul(String valueStr,String mulStr){
BigDecimal value = new BigDecimal(valueStr);
BigDecimal mulValue = new BigDecimal(mulStr);
return fnum.format(value.multiply(mulValue));
}
/**
* 金额相乘
* @param value 基础值
* @param mulValue 被乘数
* @return
*/
public static BigDecimal moneyMul(BigDecimal value,BigDecimal... mulValue){
BigDecimal temp = null;
for (int i = 0; i <mulValue.length ; i++) {
temp=value.multiply(mulValue[i]);
value=temp;
}
return temp;
}
/**
* 金额相除 <br/>
* 精确小位小数
* @param valueStr 基础值
* @param divideStr 被乘数
* @return
*/
public static String moneydiv(String valueStr,String divideStr){
BigDecimal value = new BigDecimal(valueStr);
BigDecimal divideValue = new BigDecimal(divideStr);
return fnum.format(value.divide(divideValue, 2, BigDecimal.ROUND_HALF_UP));
}
/**
* 金额相除 <br/>
* 精确小位小数
* @param value 基础值
* @param divideValue 被乘数
* @return
*/
public static BigDecimal moneydiv(BigDecimal value,BigDecimal divideValue){
return value.divide(divideValue, 2, BigDecimal.ROUND_HALF_UP);
}
/**
* 值比较大小
* <br/>如果valueStr大于等于compValueStr,则返回true,否则返回false
* true 代表可用余额不足
* @param valueStr (需要消费金额)
* @param compValueStr (可使用金额)
* @return
*/
public static boolean moneyComp(String valueStr,String compValueStr){
BigDecimal value = new BigDecimal(valueStr);
BigDecimal compValue = new BigDecimal(compValueStr);
//0:等于 >0:大于 <0:小于
int result = value.compareTo(compValue);
if(result >= 0){
return true;
}else{
return false;
}
}
/**
* 值比较大小
* <br/>如果valueStr大于等于compValueStr,则返回true,否则返回false
* true 代表可用余额不足
* @param valueStr (需要消费金额)
* @param compValueStr (可使用金额)
* @return
*/
public static int moneyComp(BigDecimal valueStr,BigDecimal compValueStr){
//0:等于 >0:大于 <0:小于
return valueStr.compareTo(compValueStr);
}
/**
* 金额乘以,省去小数点
* @param valueStr 基础值
* @return
*/
public static String moneyMulOfNotPoint (String valueStr, String divideStr){
BigDecimal value = new BigDecimal(valueStr);
BigDecimal mulValue = new BigDecimal(divideStr);
valueStr = fnum.format(value.multiply(mulValue));
return fnum.format(value.multiply(mulValue)).substring(0, valueStr.length()-3);
}
/**
* 给金额加逗号切割
* @param str
* @return
*/
public static String addComma(String str) {
try {
String banNum = "";
if (str.contains(".")) {
String[] arr = str.split("\\.");
if (arr.length == 2) {
str = arr[0];
banNum = "." + arr[1];
}
}
// 将传进数字反转
String reverseStr = new StringBuilder(str).reverse().toString();
String strTemp = "";
for (int i = 0; i < reverseStr.length(); i++) {
if (i * 3 + 3 > reverseStr.length()) {
strTemp += reverseStr.substring(i * 3, reverseStr.length());
break;
}
strTemp += reverseStr.substring(i * 3, i * 3 + 3) + ",";
}
// 将[789,456,] 中最后一个[,]去除
if (strTemp.endsWith(",")) {
strTemp = strTemp.substring(0, strTemp.length() - 1);
}
// 将数字重新反转
String resultStr = new StringBuilder(strTemp).reverse().toString();
resultStr += banNum;
return resultStr;
}catch(Exception e){
return str;
}
}
}
package pupu.chuangjieweighing;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import android_serialport_api.SerialPort1;
public class ReadSerialPort implements Runnable {
public void setDataWeight(DataWeight dataWeight) {
this.dataWeight = dataWeight;
}
//接口回调 用于发送数据
private DataWeight dataWeight;
private InputStream inputStream;
// private Optional<BufferedInputStream> optionalBufferedInputStream;
BufferedInputStream bufferedInputStream;
volatile boolean isEixt = false;//决定是否推出线程
// private Optional<SerialPort1> optionalSerialPort;
SerialPort1 serialPort1;
private static ReadSerialPort readSerialPort;
private byte[] bytes;
private int amend = 18;//用于修正在读取输入流时候,数组的内容没有正确的排序
private int count = 18; //字节数组的大小
private int quInt = 5;//分度值取整,因为机子默认是5 ,所以下方未做解析
private BigDecimal sign;//重量正负
private boolean isNetWeight;//是否是净重
private boolean isTare = false;//有无皮重。默认没有
private boolean outScale = false;//是否显示重量超出量程范围 默认没有超出
private boolean isStabilize = true;//重量是否稳定,默认稳定
private BigDecimal dvalue = new BigDecimal(0); //分度值
private int weightMaxCount = 3;//重量判断三次,如果稳定输出
private BigDecimal nowWeight = new BigDecimal(0);//实时重量
private BigDecimal tempWeight = new BigDecimal(0);//缓存的重量,用于和实时重量进行比较
// //单例模式
// public static ReadSerialPort getSingleton(@NonNull SerialPort1 serialPort1){
// if (readSerialPort==null){
// synchronized (ReadSerialPort.class){
// if (readSerialPort==null){
// readSerialPort=new ReadSerialPort();
// }
// }
// }
// return readSerialPort;
// }
public ReadSerialPort(SerialPort1 serialPort1) {
// this.optionalSerialPort = Optional.ofNullable(serialPort1);
this.serialPort1 = serialPort1;
bytes = new byte[count];
}
@Override
public void run() {
try {
// inputStream = optionalSerialPort.orElseThrow(() -> new NullPointerException("SerialPort元素不存在")).getInputStream();
inputStream = serialPort1.getInputStream();
// optionalBufferedInputStream = Optional.of(new BufferedInputStream(inputStream));
bufferedInputStream = new BufferedInputStream(inputStream);
} catch (Throwable throwable) {
Log.i("pupu", "读取异常了!!!" + throwable.getMessage());
throwable.printStackTrace();
isEixt = true;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
int len = 0;
int temp;
int tempTare;
// BufferedInputStream bufferedInputStream = optionalBufferedInputStream.orElseGet(() -> new BufferedInputStream(inputStream));
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
while (!isEixt) {
try {
if (bufferedInputStream.available() > count - 1) {
len = bufferedInputStream.read(bytes, 0, amend);
System.out.println(Util.bytesToHexString(bytes) + ";len==>" + len);
amend = 18;
if (len == -1)
break;
if (len == count && bytes[count - 1] == 10 && bytes[0] == 2) {
String SWA = Util.zeroize(bytes[1]);
switch (SWA.substring(SWA.length() - 3, 8)) {
case "001":
dvalue = new BigDecimal(10);
break;
case "010":
dvalue = new BigDecimal(1);
break;
case "011":
dvalue = new BigDecimal(0.1);
break;
case "100":
dvalue = new BigDecimal(0.01);
break;
case "101":
dvalue = new BigDecimal(0.001);
break;
default:
dvalue = new BigDecimal(0.001);
break;
}
String SWB = Util.zeroize(bytes[2]);
char[] chars = SWB.toCharArray();
//皮重
if (chars[7] == '0') {
isTare = false;
} else {
isTare = true;
}
//重量正负
if (chars[6] == '0') {
sign = new BigDecimal(1);
} else {
sign = new BigDecimal(-1);
}
//是否在超出量程范围内
if (chars[5] == '0') {
outScale = false;
} else {
outScale = true;
}
//重量是否稳定
if (chars[4] == '0') {
isStabilize = true;
} else {
isStabilize = false;
}
System.out.println("isStabilize" + isStabilize);
temp = (bytes[4] - 48) * 100000 + (bytes[5] - 48) * 10000 + (bytes[6] - 48) * 1000 + (bytes[7] - 48) * 100 + (bytes[8] - 48) * 10 + (bytes[9] - 48);
tempTare = (bytes[10] - 48) * 100000 + (bytes[11] - 48) * 10000 + (bytes[12] - 48) * 1000 + (bytes[13] - 48) * 100 + (bytes[14] - 48) * 10 + (bytes[15] - 48);
if (isTare) {
tempWeight = MoneyUtil.moneyMul(new BigDecimal(temp - tempTare), dvalue, sign);
} else {
tempWeight = MoneyUtil.moneyMul(new BigDecimal(temp), dvalue, sign);
}
// System.out.println("tempWeight"+tempWeight.doubleValue());
//用于表示误差范围
BigDecimal upper = MoneyUtil.moneySub(tempWeight, new BigDecimal(0.005));
BigDecimal lower = MoneyUtil.moneyAdd(tempWeight, new BigDecimal(0.005));
if ((MoneyUtil.moneyComp(nowWeight, upper)) >= 0 && MoneyUtil.moneyComp(nowWeight, lower) <= 0) {
System.out.println("在误差范围内" + weightMaxCount);
weightMaxCount--;
if (weightMaxCount <= 0 && isStabilize) {
nowWeight = tempWeight;
weightMaxCount = 3;
if (dataWeight == null) {
throw new NullPointerException();
}
System.out.println("要发送的重量 " + MoneyUtil.formatMoney(nowWeight));
dataWeight.weight(MoneyUtil.formatMoney(nowWeight));
}
} else {
System.out.println("超出误差范围 次数归3");
nowWeight = tempWeight;
tempWeight = new BigDecimal(0);
weightMaxCount = 3;
}
} else {
System.out.println("重量读取有问题");
for (int i = 0; i < bytes.length - 1; i++) {
if ((bytes[i] == 10 & bytes[i + 1] == 2) || (i == bytes.length & bytes[i] == 10)) {
amend = 18 - (len - i - 1);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
Log.i("pupu", "异常:" + e.getMessage());
}
}
try {
// optionalSerialPort.orElseThrow(() -> new NullPointerException("SerialPort元素不存在")).close();
serialPort1.close();
System.out.println("关闭");
} catch (Exception ex) {
ex.printStackTrace();
Log.i("pupu", "异常:" + ex.getMessage());
}
}
public interface DataWeight {
void weight(String weight);
}
}
package pupu.chuangjieweighing;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import java.io.File;
import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android_serialport_api.SerialPort1;
import static android.content.Context.MODE_PRIVATE;
public class SerialPortFunction {
private volatile static SerialPortFunction serialPortFunction;
private ReadSerialPort readSerialPort;
private ExecutorService executorService;
private Context context;
private SerialPort1 eleSerial;
private SerialPort1 lightSerial;
//双重锁定 避免多线程情况下发生错误
public static SerialPortFunction getInstance() {
if (serialPortFunction == null) {
synchronized (SerialPortFunction.class) {
if (serialPortFunction == null) {
serialPortFunction = new SerialPortFunction();
}
}
}
return serialPortFunction;
}
private SerialPortFunction() {
executorService = Executors.newFixedThreadPool(3);
}
public void setContext(Context context) {
this.context = context;
}
/**
* 开始读取重量信息
*
* @param dataWeight
*/
public void startReadWeight(ReadSerialPort.DataWeight dataWeight) {
if (eleSerial == null) {
return;
}
readSerialPort = new ReadSerialPort(eleSerial);
readSerialPort.setDataWeight(dataWeight);
executorService.submit(readSerialPort);
}
//开始电子秤读取
public void startSerialReadEle(ReadSerialPort.DataWeight dataWeight) {
if (eleSerial == null) {
try {
eleSerial = getSerialPort("ele");
} catch (Exception e) {
e.printStackTrace();
}
}
readSerialPort = new ReadSerialPort(eleSerial);
readSerialPort.setDataWeight(dataWeight);
executorService.submit(readSerialPort);
}
//发送电子秤指令
public void sendEle(final String command) {
Runnable ele = new Runnable() {
@Override
public void run() {
if (eleSerial == null) {
try {
eleSerial = getSerialPort("ele");
} catch (Exception e) {
e.printStackTrace();
}
}
try {
eleSerial.getOutputStream().write(Util.toBytes(command));
eleSerial.getOutputStream().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
};
// Runnable ele = () -> {
// if (eleSerial == null) {
// try {
// eleSerial = getSerialPort("ele");
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// try {
// eleSerial.getOutputStream().write(Util.toBytes(command));
// eleSerial.getOutputStream().flush();
// } catch (IOException e) {
// e.printStackTrace();
// }
// };
executorService.submit(ele);
}
public void sendEle(final byte[] data) {
Runnable ele = new Runnable() {
@Override
public void run() {
if (eleSerial == null) {
try {
eleSerial = getSerialPort("ele");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
try {
eleSerial.getOutputStream().write(data);
eleSerial.getOutputStream().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
};
// Runnable ele = () -> {
// if (eleSerial == null) {
// try {
// eleSerial = getSerialPort("ele");
// } catch (IOException | InterruptedException e) {
// e.printStackTrace();
// }
// }
// try {
// eleSerial.getOutputStream().write(data);
// eleSerial.getOutputStream().flush();
// } catch (IOException e) {
// e.printStackTrace();
// }
// };
executorService.submit(ele);
}
//发送灯指令
public void sendLight(final String conmand) {
Runnable runnable = new Runnable() {
@Override
public void run() {
if (lightSerial == null) {
try {
lightSerial = getSerialPort("light");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
try {
lightSerial.getOutputStream().write(Util.toBytes(conmand));
lightSerial.getOutputStream().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
};
// Runnable runnable = () -> {
// if (lightSerial == null) {
// try {
// lightSerial = getSerialPort("light");
// } catch (IOException | InterruptedException e) {
// e.printStackTrace();
// }
// }
// try {
// lightSerial.getOutputStream().write(Util.toBytes(conmand));
// lightSerial.getOutputStream().flush();
// } catch (IOException e) {
// e.printStackTrace();
// }
// };
executorService.submit(runnable);
}
//关闭电子秤
public void closeEle() {
if (readSerialPort != null) {
readSerialPort.isEixt = true;
readSerialPort = null;
}
if (eleSerial != null) {
eleSerial = null;
}
}
//关闭灯
public void closeLight() {
if (lightSerial != null) {
lightSerial.close();
lightSerial = null;
}
}
/**
* 获取称重台串口对象
*
* @param path 设备串口号
* @param baudrate 波特率
* @return 称重台串口对象
* @author pupu
*/
public SerialPort1 getWeighingSerialPort(String path, int baudrate) throws IOException {
if (TextUtils.isEmpty(path)) {
return null;
}
eleSerial = new SerialPort1(new File(path), baudrate, 0);
return eleSerial;
}
private SerialPort1 getSerialPort(String devicesName) throws SecurityException, IOException, InvalidParameterException, InterruptedException {
/* Read serial port parameters */
String path;
int baudrate;
if (devicesName.equals("ele")) {
//电子称的
SharedPreferences sp = context.getSharedPreferences("com.example.administrator.jni_preferences", MODE_PRIVATE);
path = sp.getString("electronic_port", "");
baudrate = Integer.decode(sp.getString("electronic_baudrates", "-1"));
} else {
//灯的
SharedPreferences sp = context.getSharedPreferences("com.example.administrator.jni_preferences", MODE_PRIVATE);
path = sp.getString("light_port", "");
baudrate = Integer.decode(sp.getString("light_baudrates", "-1"));
}
System.out.println("SerialPortFunction 串口 " + path + "波特率 :" + baudrate);
/* Check parameters */
if ((path.length() == 0) || (baudrate == -1)) {
throw new InvalidParameterException();
}
// /* Open the serial port */
// Process su;
// su = Runtime.getRuntime().exec("/system/xbin/su");
// String cmd = "chmod 777 " + path + "\n"
// + "exit\n";
// /*String cmd = "chmod 777 /dev/s3c_serial0" + "\n"
// + "exit\n";*/
// su.getOutputStream().write(cmd.getBytes());
// if ((su.waitFor() != 0)) {
// throw new SecurityException();
// }
// System.out.println(">>>>>>>>>"+path+" "+baudrate);
return new SerialPort1(new File(path), baudrate, 0);
}
}
package pupu.chuangjieweighing;
import java.lang.reflect.Array;
import java.util.Arrays;
public class Util {
/**
* @param hex 十六进制字符串
* @return 二进制字符串
*/
public static String hexStringToBinary(String hex) {
hex = hex.toUpperCase();
String result = "";
int max = hex.length();
for (int i = 0; i < max; i++) {
char c = hex.charAt(i);
switch (c) {
case '0':
result += "0000";
break;
case '1':
result += "0001";
break;
case '2':
result += "0010";
break;
case '3':
result += "0011";
break;
case '4':
result += "0100";
break;
case '5':
result += "0101";
break;
case '6':
result += "0110";
break;
case '7':
result += "0111";
break;
case '8':
result += "1000";
break;
case '9':
result += "1001";
break;
case 'A':
result += "1010";
break;
case 'B':
result += "1011";
break;
case 'C':
result += "1100";
break;
case 'D':
result += "1101";
break;
case 'E':
result += "1110";
break;
case 'F':
result += "1111";
break;
}
}
return result;
}
/**
* 将16进制字符串转换为byte[]
*
* @param str
* @return
*/
public static byte[] toBytes(String str) {
if (str == null || str.trim().equals("")) {
return new byte[0];
}
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length() / 2; i++) {
String subStr = str.substring(i * 2, i * 2 + 2);
bytes[i] = (byte) Integer.parseInt(subStr, 16);
}
return bytes;
}
public static String bytesToHexFun3(byte[] bytes) {
StringBuilder buf = new StringBuilder(bytes.length * 2);
for (byte b : bytes) { // 使用String的format方法进行转换
buf.append(String.format("%02x", b & 0xff));
}
return buf.toString();
}
public static String bytesToHexString(byte[] bArray) {
StringBuilder sb = new StringBuilder(bArray.length);
String sTemp;
for (byte aBArray : bArray) {
sTemp = Integer.toHexString(0xFF & aBArray);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
/**
* 字节数组转为普通字符串(ASCII对应的字符)
*
* @param bytearray byte[]
* @return String
*/
public static String bytetoString(byte[] bytearray) {
String result = "";
char temp;
int length = bytearray.length;
for (int i = 0; i < length; i++) {
temp = (char) bytearray[i];
result += temp;
}
return result;
}
/**
* @param b 字节
* @return 8位型的二进制字符串
*/
public static String zeroize(byte b) {
String binaryString = Integer.toBinaryString(b);
String str = "00000000";
return str.substring(binaryString.length()) + binaryString;
}
/**
* @param src 源数组
* @param specific 动态参数
* @return 返回源数组同等类型的数组
*/
@SuppressWarnings("unchecked")
public static <T> T[] arrayAdd(T[] src, T... specific) {
//返回类的组件类型的数组。如果这个类并不代表一个数组类,此方法返回null。
Class<?> type = src.getClass().getComponentType();
T[] temp = (T[]) Array.newInstance(type, src.length + specific.length);
System.arraycopy(src, 0, temp, 0, src.length);
System.arraycopy(specific, 0, temp, src.length, specific.length);
return temp;
}
/**
* @param content 要删除内容的数组
* @param specific 删除的内容
* @return 删除指定内容后的数组
*/
public static <T> T[] arraySpeDel(T[] content, T specific) {
int len = content.length;
for (int i = 0; i < content.length; i++) {
if (content[i].equals(specific)) {
System.arraycopy(content, i + 1, content, i, len - 1 - i);
break;
}
}
return Arrays.copyOf(content, len - 1);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment