android对接大华条码秤方案
- 大华对外并没有提供相关客户端代码,因此翻遍了网络找了找资料,同时也咨询了大华官方的技术人员,在经历了将近一周的时间,终于搞出来满足需求的一个demo
需求
- 1、批量写入商品到大华条码秤;
- 2、单条更新条码秤内部商品;
- 3、清除条码秤内部所有商品;
- 4、条码头部更改为自定义内容,尾部根据设置动态打印价格或者重量;
- 5、封装提供jar包,供外部使用;
android大华秤demo下载
需求增加
1、调整打印文字头,要求打印内容为固定门店名
2、调整标签打印效果,要求根据采购固定的标签尺寸打印产品设计标签内容
代码内部注释还算完整,正常copy就可以使用,有歧义的地方欢迎留言,看到会回复的,
创建一个对象写入数据使用
package com.example.bighua.dahuautil;
/**
* @ClassName: BarCodeScaleGoods
* @Description: 大华条码秤写入对象
* @Author: 有时有晌
* @Date: 2021/11/15 21:57
*/
public class BarCodeScaleGoods {
public String pluCode;//大华自己索引 不可跨越设置 例如 内部有商品数据 1,2,3 不可直接跳过4设置后边,否则失败
public String code;//商品编码7位
public Double price;//价格
public String goodsName;//商品名
public String unit;//单位
public String barCodeHeader;//条码前缀
@Override
public String toString() {
return "BarCodeScaleGoods{" +
"pluCode='" + pluCode + '\'' +
", code='" + code + '\'' +
", price=" + price +
", goodsName='" + goodsName + '\'' +
", unit='" + unit + '\'' +
", barCodeHeader='" + barCodeHeader + '\'' +
'}';
}
}
准备自己的socketUtils
package com.example.bighua.dahuautil;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
/**
* @ClassName: SocketUtils
* @Description:
* try
* {
* int port = 4001;
* IPAddress ip = IPAddress.Parse(textBox1.Text.Trim());
* IPEndPoint ipe = new IPEndPoint(ip, port);
* Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
* socket.Connect(ipe);
* var name = "毛豆";//商品名称
* var barCodd = "123456";//商品条码
* var shelfLife = 2;//商品有效期
* var nameConvert = GetChineseWord(name);
* var plu = "1";
* var price = 10.1;//单价分
* StringBuilder qwm = new StringBuilder();
* foreach (var c in nameConvert)
* {
* qwm.Append(getCode(c.ToString()));
* }
* //$"!0V{4位PLU}A{7位商品编码}{6位数价格(单位分)}{模式(0:称重,1:计件,2:定重)}000000{3位有效期}{2位店号(01-99)}000000000000000{2位皮重(00-15)}0000000000000000000000000000000B{商品名称区位码}CDE" + "\r\n";
* string sendStr = $"!0V{plu.PadLeft(4, '0')}A{barCodd.PadLeft(7, '0')}{(price * 100).ToString().PadLeft(6, '0')}0000000{shelfLife.ToString().PadLeft(3, '0')}01000000000000000000000000000000000000000000000000B{qwm}CDE" + "\r\n";
* byte[] bs = Encoding.ASCII.GetBytes(sendStr);
* socket.Send(bs, bs.Length, 0);
* string recvStr = "";
* byte[] recvBytes = new byte[1024];
* int bytes;
* bytes = socket.Receive(recvBytes, recvBytes.Length, 0);
* recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
* socket.Close();
*
* MessageBox.Show("下发成功");
* }
* catch (Exception ex)
* {
*
* MessageBox.Show("异常:" + ex.Message);
* }
* @Author: 有时有晌
* @Date: 2021/11/15 21:54
*/
public class SocketUtils {
private Socket socket;
private BufferedReader bufferedReader;
private SocketUtils socketUtils;
public SocketUtils getSocketUtils(){
if (socketUtils==null){
socketUtils = new SocketUtils();
}
return socketUtils;
}
/**
* socket连接大华条码秤 端口固定是4001(大华秤自己的端口,不要修改)修改后无法连接
* @param ip
*/
public boolean connect(String ip){
try {
socket = new Socket();
InetSocketAddress socketAddress = new InetSocketAddress(TextUtils.isEmpty(ip)?"192.168.108.200":ip, 4001);
socket.connect(socketAddress, 10 * 1000);
socket.setSoTimeout(5 * 1000);
if (socket.isConnected()) {
// 向 socket 服务器写入数据
// byte[] bytes = {0x21, 0x30, 0x49, 0x41, 0x0d, 0x0a, 0x03};
// socket.getOutputStream().write(bytes);
// socket.getOutputStream();
//上边38 39行 是每次写入前都执行清理
// 接收 socket 服务器返回的数据
InputStreamReader ipr = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(ipr);
// try {
// String str = bufferedReader.readLine();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
return socket.isConnected();
} catch (IOException error) {
error.printStackTrace();
System.out.println("==-->socket连接异常");
}
return false;
}
/**
* 发送指令
* @param bytes
* @return
*/
private String sendCommand(byte[] bytes) {
byte[] suffix = {0x0d, 0x0a, 0x03};
try {
if (socket != null && socket.isConnected() && socket.getOutputStream() != null) {
byte[] command = Utils.byteMerger(bytes, suffix);
socket.getOutputStream().write(command);
Log.e("TAG","==-->指令发送成功");
return "SEND_SUCCESS";
} else {
return "NOT_CONNECT";
}
} catch (IOException e) {
e.printStackTrace();
return "SEND_FAIL";
}
}
/**
* 清除大华秤内部商品
* @return
*/
public boolean clearData() {
if (socket != null && socket.isConnected()) {
byte[] bytes = {0x21, 0x30, 0x49, 0x41};
sendCommand(bytes);
byte[] bytes2 = {0x21, 0x30, 0x48, 0x41};
sendCommand(bytes2);
return true;
} else {
return false;
}
}
/**
* 修改条码打印后缀为价格
* @return
*/
public boolean changePrice() {
if (socket != null && socket.isConnected()) {
String priceType = modelPrice();
byte[] bytes = priceType.getBytes();
String result = sendCommand(bytes);
Log.e("TAG","==-->发送改为价格指令"+result);
if (result.equals("SEND_SUCCESS")) {
try {
InputStreamReader ipr = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(ipr);
String str = bufferedReader.readLine();
if (str.length() > 0) {
Log.e("TAG","==-->发送改为价格指令成功");
return true;
} else {
Log.e("TAG","==-->发送改为价格指令失败");
return false;
}
} catch (IOException e) {
e.printStackTrace();
Log.e("TAG","==-->发送改为价格指令失败发生异常"+e.getMessage()+" "+e.getCause());
return false;
}
} else {
Log.e("TAG","==-->发送改为价格指令 !SEND_SUCCESS");
return false;
}
} else {
return false;
}
}
/**
* 修改条码打印后缀为重量
* @return
*/
public boolean changeWeight() {
if (socket != null && socket.isConnected()) {
String modelWeight = modelWeight();
byte[] bytes = modelWeight.getBytes();
String result = sendCommand(bytes);
Log.e("TAG","==-->发送改为重量指令"+result);
if (result.equals("SEND_SUCCESS")) {
try {
InputStreamReader ipr = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(ipr);
String str = bufferedReader.readLine();
if (str.length() > 0) {
Log.e("TAG","==-->发送改为重量指令成功");
return true;
} else {
Log.e("TAG","==-->发送改为重量指令失败");
return false;
}
} catch (IOException e) {
e.printStackTrace();
Log.e("TAG","==-->发送改为重量指令失败发生异常"+e.getMessage()+" "+e.getCause());
return false;
}
} else {
Log.e("TAG","==-->发送改为重量指令失败 !SEND_SUCCESS");
return false;
}
} else {
return false;
}
}
/**
* 更新条码后缀为价格值
* !0O[协议头]
* 01[秤号]
* 05[打印浓度]
* 00[是否打折]
* 01[抹零允许]
* 02[条码格式]
* 01[条码类型]
* 01[分位圆整]
* 01[日期格式]
* 00[净重单位]
* 00[单价单位]
* 01[钱箱驱动开关]
* 00[量程选折]
* 01[打印是否清零]
* 00[连续纸条码设置]
* 00[金额厘位设置]
* 00[表头1字体]
* 00[表头2字体]
* 00[表头3字体]
* 00[表头4字体]
* 00[表尾1字体]
* 00[表尾2字体]
* 00[表尾3字体]
* 00[表尾4字体]
* 01[正文字体]
* @return
*/
private static String modelPrice() {
String modePrice = "!0O010503000501000100010100010001000000000000000001";
return modePrice;
}
/**
* 更新条码后缀为重量值
* !0O[协议头]
* 01[秤号]
* 05[打印浓度]
* 00[是否打折]
* 01[抹零允许]
* 02[条码格式]
* 01[条码类型]
* 01[分位圆整]
* 01[日期格式]
* 00[净重单位]
* 00[单价单位]
* 01[钱箱驱动开关]
* 00[量程选折]
* 01[打印是否清零]
* 00[连续纸条码设置]
* 00[金额厘位设置]
* 00[表头1字体]
* 00[表头2字体]
* 00[表头3字体]
* 00[表头4字体]
* 00[表尾1字体]
* 00[表尾2字体]
* 00[表尾3字体]
* 00[表尾4字体]
* 01[正文字体]
* @return
*/
private String modelWeight() {
// String modelWeight = "!0O010503010202000100010100010001000000000000000001";//这个能正常打印重量 但是barCode不对 -- 留作备份
String modelWeight = "!0O010503010502000100010100010001000000000000000001";//这个能正常打印重量 barCode打印头正确 保持与price条码格式都为05
return modelWeight;
}
/**
* 设置写入商品
* @param goods
* @return
*/
public boolean setGoods(BarCodeScaleGoods goods) {
if (!socket.isConnected()){
Log.e("TAG","==-->socket没有连接");
return false;
}
String plu = goods.pluCode;
String code = goods.code;
String price = String.valueOf(new Double(goods.price * 100).intValue());
String goodsName = Utils.StringToAreaByteCode(goods.goodsName);
String unit = goods.unit;
String barHeader = goods.barCodeHeader;
//需满足大华秤内部自身长度,不够追加
while (plu.length() < 4) {
plu = '0' + plu;
}
while (price.length() < 6) {
price = '0' + price;
}
// %s 为占位符 依次用后边 plu code price unit barHeader goodsName 替换 具体长度请参考大华秤自己demo 内部有固定长度要求
// 如 plu 固定长度为4位,长度不够自行拼接0
String goodsInfo = String.format("!0V%sA%s%s%s000000999%s010000000000000000000000000000000000000000000000B%sCDE", plu, code, price, unit,barHeader,goodsName);//这个条形码前缀以动态输入
// String goodsInfo = String.format("!0V%sA%s%s%s00000099901010000000000000000000000000000000000000000000000B%sCDE", plu, code, price, unit, goodsName);//这个条形码按大华机器走
Log.e("TAG","==-->大华电子秤 最终 str:= "+goodsInfo);
byte[] bytes = goodsInfo.getBytes();
String result = sendCommand(bytes);
//根据sendCommand返回结果判断
if (result.equals("SEND_SUCCESS")) {
try {
InputStreamReader ipr = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(ipr);
String str = bufferedReader.readLine();
if (str.length() > 0) {
Log.e("TAG","==-->商品下发成功");
return true;
} else {
Log.e("TAG","==-->商品下发失败");
return false;
}
} catch (IOException e) {
e.printStackTrace();
Log.e("TAG","==-->商品下发失败发生异常"+e.getMessage()+" "+e.getCause());
return false;
}
} else {
Log.e("TAG","==-->商品下发失败 !SEND_SUCCESS");
return false;
}
}
/**
* 执行完成关闭socket
*/
public void closeConnect(){
try{
if (socket!=null||socket.isConnected()){
Log.e("TAG","==-->socket关闭连接");
try {
if(socket.getOutputStream()!=null){
socket.getOutputStream().close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (socket.getInputStream()!=null){
socket.getInputStream().close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(socket!=null){
socket.close();
socket=null;
}
} catch (IOException e) {
e.printStackTrace();
}
try {
bufferedReader = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
相关工具类
package com.example.bighua.dahuautil;
import java.io.UnsupportedEncodingException;
/**
* @ClassName: Utils
* @Description: 大华条码秤
* @Author: 有时有晌
* @Date: 2021/11/15 18:03
*/
public class Utils {
public static byte[] byteMerger(byte[] bt1, byte[] bt2){
byte[] bt3 = new byte[bt1.length + bt2.length];
System.arraycopy(bt1, 0, bt3, 0, bt1.length);
System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
return bt3;
}
public static String bytes2HexString(byte b) {
return bytes2HexString(new byte[] { b });
}
private static String bytes2HexString(byte[] b) {
String ret = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex.toUpperCase();
}
return ret;
}
public static String StringToAreaByteCode(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
result += charToAreaByteCode(str.charAt(i));
}
return result;
}
private static String charToAreaByteCode(char str) {
byte[] bs = new byte[0];
try {
bs = String.valueOf(str).getBytes("GB2312");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String s = "";
String t = "";
for (int i = 0; i < bs.length; i++) {
int a = Integer.parseInt(Utils.bytes2HexString(bs[i]), 16);
t = (a - 0x80 - 0x20) + "";
if(t.length() == 1){
t = 0 + t;
}
s += t;
}
return s;
}
// public static String bytes2HexString(byte b) {
// return bytes2HexString(new byte[]{b});
// }
//
// public static String bytes2HexString(byte[] b) {
// String ret = "";
// for (int i = 0; i < b.length; i++) {
// String hex = Integer.toHexString(b[i] & 0xFF);
// if (hex.length() == 1) {
// hex = '0' + hex;
// }
// ret += hex.toUpperCase();
// }
// return ret;
// }
//
// public static String StringToAreaByteCode(String str) {
// String result = "";
// for (int i = 0; i < str.length(); i++) {
// result += charToAreaByteCode(str.charAt(i));
// }
//
// return result;
// }
//
// public static String charToAreaByteCode(char str) {
// byte[] bs = new byte[0];
// try {
// bs = String.valueOf(str).getBytes("GB2312");
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// String s = "";
// String t = "";
// for (int i = 0; i < bs.length; i++) {
// int a = Integer.parseInt(bytes2HexString(bs[i]), 16);
// t = (a - 0x80 - 0x20) + "";
// if (t.length() == 1) {
// t = 0 + t;
// }
// s += t;
// }
//
// return s;
// }
//
// public static byte[] hexStringToByteArray(String hexString) {
// hexString = hexString.replaceAll(" ", "");
// int len = hexString.length();
// byte[] bytes = new byte[len / 2];
// for (int i = 0; i < len; i += 2) {
// // 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个字节
// bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
// .digit(hexString.charAt(i + 1), 16));
// }
// return bytes;
// }
//
// public static String stringToHexString(String string) {
// char[] c = new char[string.length()];
// c = string.toCharArray();
// String hesStr = "";
// for (int i = 0; i < c.length; i++) {
// hesStr = hesStr + Integer.toHexString(c[i]);
// }
// return hesStr;
// }
//
// public static String toAreaCode(String word, boolean isChina) {
// StringBuilder areaCode = new StringBuilder();
// byte[] bs;
// try {
// bs = word.getBytes("GB2312");
// for (byte b : bs) {
// int code = Integer.parseInt(Integer.toHexString(b & 0xFF), 16);
// if (isChina) {
// int temp = code - 0x80 - 0x20;
// if (temp < 10) {
// areaCode.append("0").append(temp);
// } else {
// areaCode.append(temp);
// }
// } else {
// int temp = code - 32;
// if (temp < 10) {
// areaCode.append("030").append(temp);
// } else {
// areaCode.append("03").append(temp);
// }
// }
// }
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// Log.e("liluo", "区位码转码异常,可能导致乱码或者空白字符");
// }
// return areaCode.toString();
// }
//
// /**
// * 根据Unicode编码判断中文汉字和符号
// */
// public static boolean isChinese(char c) {
// Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
// return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
// || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
// || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
// || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION;
// }
//
// /**
// * 获取完整的区位码
// *
// * @param name 原始字符串
// * @return 区位码
// */
// public static String getTotalAreaCode(String name) {
// StringBuilder stringBuilder = new StringBuilder();
// char[] nameChar = name.toCharArray();
// for (char c : nameChar) {
// if (isChinese(c))
// stringBuilder.append(toAreaCode(String.valueOf(c), true));
// else
// stringBuilder.append(toAreaCode(String.valueOf(c), false));
// }
// String code = stringBuilder.toString();
// if (code.contains("-")) {
// Log.e("liluo", name + "的区位码存在非法字符:" + code);
// return "";
// } else {
// Log.d("liluo", name + "的区位码:" + code);
// return code;
// }
// }
//
// public static String str2HexStr(String str) {
// char[] chars = "0123456789ABCDEF".toCharArray();
// StringBuilder stringBuilder = new StringBuilder("");
// byte[] bs = str.getBytes();
// int bit;
// for (int i = 0; i < bs.length; i++) {
// bit = (bs[i] & 0x0f0) >> 4;
// stringBuilder.append(chars[bit]);
// bit = bs[i] & 0x0f;
// stringBuilder.append(chars[bit]);
// stringBuilder.append(' ');
// }
// return stringBuilder.toString().trim();
// }
}
最终调用
package com.example.bighua
import android.annotation.SuppressLint
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.*
import com.example.bighua.dahuautil.BarCodeScaleGoods
import com.example.bighua.dahuautil.SocketUtils
import com.example.bighua.dahuautil.Utils
class MainActivity : AppCompatActivity() , View.OnClickListener{
var tv_dahua:TextView?=null
var tv_dahua_only:TextView?=null
var tv_clean:TextView?=null
var ed_plu:EditText?=null //plu
var ed_goods_name:EditText?=null //商品名
var edit_code_header:EditText?=null //条形码前缀
var rl_progress:RelativeLayout?=null //progressBar 布局
var progress_bar:ProgressBar?=null //progressBar
var tv_progress:TextView?=null //progressBar text
var tv_model:TextView?=null
var tv_model2:TextView?=null
var layout_data:LinearLayout?=null //layout data
var scaleProtocol:ScaleProtocol?=null
var pluInfor:ScaleProtocol.PLUInfor?=null
// var ip = "36.110.14.51"
var ip = "192.168.108.200"
val goods:MutableList = mutableListOf()
var barHeader:String?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
ed_plu = findViewById(R.id.ed_plu)
ed_goods_name = findViewById(R.id.ed_goods_name)
edit_code_header = findViewById(R.id.edit_code_header)
rl_progress = findViewById(R.id.rl_progress)
tv_progress = findViewById(R.id.tv_progress)
progress_bar = findViewById(R.id.progress_bar)
layout_data = findViewById(R.id.layout_data)
tv_dahua = findViewById(R.id.tv_dahua)
tv_dahua_only = findViewById(R.id.tv_dahua_only)
tv_clean = findViewById(R.id.tv_clean)
tv_model = findViewById(R.id.tv_model)
tv_model2 = findViewById(R.id.tv_model2)
tv_dahua?.setOnClickListener(this)
tv_dahua_only?.setOnClickListener(this)
tv_clean?.setOnClickListener(this)
tv_model?.setOnClickListener(this)
tv_model2?.setOnClickListener(this)
edit_code_header?.addTextChangedListener(object :TextWatcher{
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(s: Editable?) {
if (!TextUtils.isEmpty(s)){
if (s?.length!! <2){
Toast.makeText(this@MainActivity,"长度需为2",Toast.LENGTH_SHORT).show()
return
}
barHeader = s.toString()
initData()
}
}
})
initData()
// tv_clean?.setOnClickListener {
// Thread{
// var socketUtils = SocketUtils().socketUtils
// socketUtils.connect("192.168.108.200")
// var isClean = socketUtils.clearData()
//
// runOnUiThread {
// Toast.makeText(this,if (isClean) "清除成功" else "清除失败", Toast.LENGTH_SHORT).show()
// }
// socketUtils.closeConnect()
// }.start()
// }
//
// tv_dahua?.setOnClickListener {
// var str = Utils.str2HexStr("土豆")
//// var str = "土豆"
// Log.e("TAG","==-->土豆:=${str}")
// Thread {
// var socketUtils = SocketUtils().socketUtils
// socketUtils.connect("192.168.108.200")
//
// goods.forEach {
// var isSendSuccess = socketUtils.setGoods(it)
// var beanIndex = goods.indexOf(it)
// if (beanIndex==goods.size-1){
// socketUtils.closeConnect()
// }
// }
//// when{
//// isSendSuccess->{
//// runOnUiThread {
//// Toast.makeText(this,"success",Toast.LENGTH_SHORT).show()
//// }
//// }
//// }
// }.start()
//
// }
}
private fun initData() {
var barCodeScaleGoods1 = BarCodeScaleGoods()
barCodeScaleGoods1.pluCode = "1"
barCodeScaleGoods1.code = "1200001"
barCodeScaleGoods1.price = 5.0
barCodeScaleGoods1.goodsName = "冬瓜"
barCodeScaleGoods1.unit = "0"
barCodeScaleGoods1.barCodeHeader = if (TextUtils.isEmpty(barHeader)) "24" else barHeader
var barCodeScaleGoods2 = BarCodeScaleGoods()
barCodeScaleGoods2.pluCode = "2"
barCodeScaleGoods2.code = "1200002"
barCodeScaleGoods2.price = 5.0
barCodeScaleGoods2.goodsName = "朝天椒"
barCodeScaleGoods2.unit = "0"
barCodeScaleGoods2.barCodeHeader = if (TextUtils.isEmpty(barHeader)) "24" else barHeader
var barCodeScaleGoods3 = BarCodeScaleGoods()
barCodeScaleGoods3.pluCode = "3"
barCodeScaleGoods3.code = "1200003"
barCodeScaleGoods3.price = 5.0
barCodeScaleGoods3.goodsName = "牛奶"
barCodeScaleGoods3.unit = "0"
barCodeScaleGoods3.barCodeHeader = if (TextUtils.isEmpty(barHeader)) "24" else barHeader
var barCodeScaleGoods4 = BarCodeScaleGoods()
barCodeScaleGoods4.pluCode = "4"
barCodeScaleGoods4.code = "1200004"
barCodeScaleGoods4.price = 5.0
barCodeScaleGoods4.goodsName = "番茄"
barCodeScaleGoods4.unit = "0"
barCodeScaleGoods4.barCodeHeader = if (TextUtils.isEmpty(barHeader)) "24" else barHeader
var barCodeScaleGoods5 = BarCodeScaleGoods()
barCodeScaleGoods5.pluCode = "5"
barCodeScaleGoods5.code = "1200005"
barCodeScaleGoods5.price = 5.0
barCodeScaleGoods5.goodsName = "土豆"
barCodeScaleGoods5.unit = "0"
barCodeScaleGoods5.barCodeHeader = if (TextUtils.isEmpty(barHeader)) "24" else barHeader
var barCodeScaleGoods100 = BarCodeScaleGoods()
barCodeScaleGoods100.pluCode = "100"
barCodeScaleGoods100.code = "1200100"
barCodeScaleGoods100.price = 101.0
barCodeScaleGoods100.goodsName = "注意pluCode不能跨越设置,否则失败,哪怕提示成功,一般发生异常"
barCodeScaleGoods100.unit = "0"
barCodeScaleGoods100.barCodeHeader = if (TextUtils.isEmpty(barHeader)) "24" else barHeader
goods.clear()
goods.add(barCodeScaleGoods1)
goods.add(barCodeScaleGoods2)
goods.add(barCodeScaleGoods3)
goods.add(barCodeScaleGoods4)
goods.add(barCodeScaleGoods5)
// goods.add(barCodeScaleGoods100)
var stringBuffer = StringBuffer()
var textView = TextView(this)
var textView2 = TextView(this)
goods.forEach {
stringBuffer.append(it.toString()+"\r\n")
}
textView.text = stringBuffer
textView2.text = "注意pluCode不能跨越设置,否则失败,哪怕提示成功,一版情况会显示异常例如上边pluCode==100的时候,仅作为参考"
textView2.setTextColor(Color.parseColor("#BB996C"))
layout_data?.addView(textView)
layout_data?.addView(textView2)
}
@SuppressLint("SetTextI18n")
override fun onClick(v: View?) {
v?.let {v->
when(v.id){
R.id.tv_clean->{
Thread {
var socketUtils = SocketUtils().socketUtils
socketUtils.connect(ip)
var isClean = socketUtils.clearData()
runOnUiThread {
Toast.makeText(this, if (isClean) "清除成功" else "清除失败", Toast.LENGTH_SHORT).show()
}
socketUtils.closeConnect()
}.start()
}
R.id.tv_dahua->{//批量更新
rl_progress?.visibility = View.VISIBLE
Log.e("TAG","==-->批量更新开始执行")
Thread {
var socketUtils = SocketUtils().socketUtils
var isConnect = socketUtils.connect(ip)
if (!isConnect){
runOnUiThread {
Toast.makeText(this,"socket连接失败",Toast.LENGTH_SHORT).show()
rl_progress?.visibility = View.GONE
}
return@Thread
}
goods.forEach {
Log.e("TAG","==-->商品信息:= $it")
var isSendSuccess = socketUtils.setGoods(it)
var beanIndex = goods.indexOf(it)
runOnUiThread {
progress_bar?.max = goods.size
progress_bar?.progress = beanIndex+1
Log.e("TAG","==-->进度0:="+progress_bar?.progress+" "+progress_bar?.max)
Log.e("TAG","==-->进度1:="+beanIndex+" "+goods.size)
tv_progress?.text ="${beanIndex+1}/${goods.size}"
if (beanIndex==goods.size-1){
rl_progress?.visibility = View.GONE
Toast.makeText(this,"写入完成",Toast.LENGTH_SHORT).show()
}
}
if (beanIndex==goods.size-1){
socketUtils.closeConnect()
}
Thread.sleep(1000)
}
}.start()
}
R.id.tv_dahua_only->{//单条更新
var barCodeScaleGoods1 = BarCodeScaleGoods()
barCodeScaleGoods1.pluCode = if (TextUtils.isEmpty(ed_plu?.text)) "1" else ed_plu?.text.toString()
barCodeScaleGoods1.code = "1200001"
barCodeScaleGoods1.price = 5.0
barCodeScaleGoods1.goodsName = if (TextUtils.isEmpty(ed_goods_name?.text)) "暂无" else ed_goods_name?.text.toString()
barCodeScaleGoods1.unit = "0"
barCodeScaleGoods1.barCodeHeader = if (TextUtils.isEmpty(barHeader)) "24" else barHeader
Thread{
var socketUtils = SocketUtils().socketUtils
socketUtils.connect(ip)
var isSendSuccess = socketUtils.setGoods(barCodeScaleGoods1)
runOnUiThread {
if (isSendSuccess){
Toast.makeText(this,"写入完成",Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(this,"写入失败",Toast.LENGTH_SHORT).show()
}
}
socketUtils.closeConnect()
}.start()
}
R.id.tv_model->{
Thread {
var socketUtils = SocketUtils().socketUtils
socketUtils.connect(ip)
var isClean = socketUtils.changePrice()
runOnUiThread {
Toast.makeText(this, if (isClean) "设置成功" else "设置失败", Toast.LENGTH_SHORT).show()
}
socketUtils.closeConnect()
}.start()
}
R.id.tv_model2->{
Thread {
var socketUtils = SocketUtils().socketUtils
socketUtils.connect(ip)
var isClean = socketUtils.changeWeight()
runOnUiThread {
Toast.makeText(this, if (isClean) "设置成功" else "设置失败", Toast.LENGTH_SHORT).show()
}
socketUtils.closeConnect()
}.start()
}
}
}
}
}
调用类
- 因涉及内部信息,内部执行代码已删除,大体就是这么个形式
/**
* @ClassName: PushDaHuaData
* @Description: 大华秤方法类
* @Author: 有时有晌
* @Date: 2021/12/1 14:34
*/
object PushDaHuaData {
var gson = Gson()
var addressList:ArrayList = ArrayList()
//type 1 测试连接 type2 单个商品同步 type 3 设置里批量同步商品 type 4 清除秤商品数据
fun getIpAddressFirst(mContext: Activity, goods: Goods?, type: Int) {
}
/**
* 大华秤下发数据push写入
*/
fun allPush(mContext:Activity,ipAddress: String) {
}
/**
* 单挑插入称重品到大华秤,非批量下发不弹出
*/
fun pushItem(mContext: Activity,goods: Goods,ipAddress:String){
}
/**
* 清除大华称内部数据
*/
fun cleanData(mContext:Activity,ipAddress: String){
}
/**
* 测试连接 ,测试成功直接改称重模式
*/
fun testConnect(mContext: Activity,daHuaSocketAddress: String,isAddIp:Boolean){
}
/**
* 回调到对应页面
*/
interface CallBack{
fun backErrorList(errorList:ArrayList) //下发错误返回
fun setProgress(progress:Int,total:Int) //下发进度
fun clean(isClean:Boolean) //清除
fun updateSuccess(isUpdateSuccess:Boolean)
}
}
内部应该含有jar,直接复制用就行了。没有jar的话自己编译一个就ok。基本不用怎么弄了