传称基本逻辑

文章详细描述了如何从对象中提取PLU码、商品编码、价格等信息,并使用JavaScript进行编码处理。还涉及大华称和顶尖称的网络通信,包括使用TCP客户端、动态链接库以及执行设备信息同步任务。
摘要由CSDN通过智能技术生成
// 获取合成大华传秤参数
getStr(obj) {
    var name = obj.goods_name

    name = name.split('')
    let i = name.length,
        f = ''
    for (var x = 0; x < i; x++) {
        let temp = '',
            qu = '',
            wei = ''
        if (escape(name[x]).indexOf('%u') < 0) {
            temp = this.toDBC(name[x])
            temp = $URL.encode(temp)
            temp = temp.split('%')
            qu = this.hex2int(temp[1]) - 160 + ''
            wei = this.hex2int(temp[2]) - 160 + ''
        } else {
            temp = $URL.encode(name[x])
            temp = temp.split('%')
            qu = this.hex2int(temp[1]) - 160 + ''
            wei = this.hex2int(temp[2]) - 160 + ''
        }
        if (qu.length == 1) {
            qu = '0' + qu
        }
        if (wei.length == 1) {
            wei = '0' + wei
        }
        f = f + qu + wei
    }
    // 4位plu码
    var PLU = this.PrefixInteger(obj.plu_code, 4)
    // 7位商品编码
    var number = this.PrefixInteger(obj.goods_number, 7)
    // 6位商品价格
    var price = this.PrefixInteger(toDecimal(obj.retail_price * 100), 6)
    // 3位有效期
    var day = this.PrefixInteger(obj.quality_guarantee_period, 3)
    var pricing_method = obj.pricing_method == 1 ? 2 : 0
    var qwm = f
    return {PLU, number, price, pricing_method, day, qwm}
},	



// 获取顶尖传秤数据
getDJStr(obj) {
    // 6位plu码
    // var PLU = '90' + this.PrefixInteger(obj.plu_code, 4)
	PLU = obj.plu_code
    // 商品名称
    var name = obj.goods_name
    // 商品价格
    var price = obj.retail_price
    console.log(price)
    // 3位有效期
    var day = obj.quality_guarantee_period == null || obj.quality_guarantee_period == '' ? 0 : obj.quality_guarantee_period

    var pricing_method = obj.pricing_method == 1 ? 1 : 0
    return {PLU, name, price, day, pricing_method}
},		
//大华称
var strObj = this.getStr(this.goodsInfoSelection[index])
var str = `!0V${strObj.PLU}A${strObj.number}${strObj.price}${strObj.pricing_method}000000${strObj.day}27000000000000000000000000000000000000000000000000B${strObj.qwm}CDE\r\n`


//顶尖称
var strObj = this.getDJStr(this.goodsInfoSelection[index])
var dataTitle = `ID\tItemCode\tDepartmentID\tGroupID\tName1\tPrice\tUnitID\tBarcodeType1\tLabel1ID\tValidDate\tFlag1\tFlag2\r\n`
var data = `${strObj.PLU}\t${strObj.PLU}\t27\t1\t${strObj.name}\t${strObj.price}\t4\t7\t1\t12\t60\t240\r\n`
var str = JSON.stringify(dataTitle + data)

PLU即商品plu码, 

利用上述代码时,需要传称数据进行编辑 ,将str, ip 作为请求处理数据发送至连接称的方法中 

大华称方法 (已验证)

var client = new net.Socket()
client.connect(port, req.body.ip, () => {  //根据端口和ip连接大华称台
    var isSuccess = client.write(req.body.str)
    if (!isSuccess) {
        client.once('drain', () => {
            client.write(req.body.str)  // 将req.body.str中的数据通过client对象写入到连接中
        })
    }
})

// 为客户端添加“data”事件处理函数
// data是服务器发回的数据
client.on('data', function (data) {
    res.json({status: 1})    //数据处理成功,返回状态为1
    client.end()
})

// 产生错误时触发
client.on('error', function (err) {
    console.log('Socket Error:' + err)
    res.json({status: 0})
    //发生错务重新连接
    client.connect(port, req.body.ip, () => {
        console.log('连接到:' + req.body.ip)
        var isSuccess = client.write(req.body.str)
        if (!isSuccess) {
            client.once('drain', () => {
                client.write(req.body.str)
            })
        }
    })
})


// 为客户端添加“close”事件处理函数
client.on('close', function () {
    console.log('Connection closed')
})

 大华称方法 (暂未验证)

// 引入需要的模块  
const net = require('net');  
const url = require('url');  
const querystring = require('querystring');  
  
// 创建一个TCP客户端  
const client = net.createConnection({ port: 8080, host: '127.0.0.1' }, () => {  
  console.log('连接到服务器');  
    
  // 发送请求数据  
  const requestData = querystring.stringify({  
    str: 'your_request_data',  
    ip: 'your_ip_address'  
  });  
  client.write(requestData);  
});  
  
// 错误处理函数  
client.on('error', (err) => {  
  console.error('Socket Error:', err);  
  handleError(client, err);  
});  
  
// 定义一个处理错误的辅助函数  
function handleError(client, err) {  
  console.log('尝试重新连接...');  
     
  // 尝试重新连接,最多重试3次,每次间隔1秒  
  const retries = 3;  
  let attempt = 0;  
  const reconnect = () => {  
    attempt++;  
    if (attempt > retries) {  
      console.error('重试次数过多,停止连接。');  
      return;  
    }  
    client.connect({ port: 8080, host: '127.0.0.1' }, () => {  
      console.log('重新连接到服务器:', '127.0.0.1');  
      client.write(requestData);  
    });  
  };  
  setTimeout(reconnect, 1000); // 1秒后尝试重新连接  
}

 顶尖称(已验证)

app.post('/DJChuancheng', function (req, res, next) {
    console.log(res)
    debugger
	var str = JSON.parse(req.body.str)
    var ip = req.body.ip;
	console.log(str)
	console.log(ip)	// 获取绝对路径
	var basefile = path.resolve()
    console.log("sdsfdsfhsfd"+basefile);
	// 截取开头
	var fileHeader = basefile.substring(0, 3)
	var file = path.join(fileHeader, 'PLUTest.txt')
	fs.writeFile(file, iconv.encode(str, 'gbk'), { encoding: 'ascii' }, (err) => {
		if (err) {
			console.log('写入错误')
			res.json({ status: 0 })
		} else {
			var deviceInfoResult = refStruct({
				ProtocolType: ref.types.int32,
				Addr: ref.types.int32,
				Port: ref.types.int32,
				Name: refArraynapi('byte',16),
				ID: ref.types.int32,
				Version: ref.types.int8,
				Country: ref.types.int8,
				DepartmentID: ref.types.int8,
				KeyType: ref.types.int8,
				PrinterDot: ref.types.int64,
				PrnStartDate: ref.types.long,
				LabelPage: ref.types.int32,
				PrinterNo: ref.types.int32,
				PLUStorage: ref.types.int16,
				HotKeyCount: ref.types.int16,
				NutritionStorage: ref.types.int16,
				DiscountStorage: ref.types.int16,
				Note1Storage: ref.types.int16,
				Note2Storage: ref.types.int16,
				Note3Storage: ref.types.int16,
				Note4Storage: ref.types.int16,
				// FirmwareVersion:refArraynapi('byte',12),
				// DefaultProtocol:ref.types.byte,
				// LFCodeLen:ref.types.byte,
				// DeviceId:refArraynapi('byte',4),
				// StockId:refArraynapi('byte',4),
				Adjunct: refArraynapi('byte',177),
			})
			let dll = ffi.Library('./dll/AclasSDK.dll', {
				// 初始化动态链接库(pointer指向任何类型参数,此处传nil或null)
				'AclasSDK_Initialize': ['bool', ['Pointer']],
				// 获取设备协议类型
				'AclasSDK_GetDeviceType': ['int', ['UInt32', 'UInt32', 'UInt32']],
				// 获取设备信息
				'AclasSDK_GetDeviceInfo': [
					deviceInfoResult,
					['UInt32', 'UInt32', 'UInt32',deviceInfoResult],
				],

				// 无回调函数执行任务
				'AclasSDK_Sync_ExecTaskA_PB': [
					'int',
					[
						'string',
						'UInt32',
						'UInt32',
						'UInt32',
						'UInt32',
						'string',
					],
				],
				// 释放动态链接库
				'AclasSDK_Finalize': ['void', []],
			})
			var ipArr = ip.split('.')
			// 定义秤ip,需要转换秤数值
			var numberIp =
				+ipArr[0] * 256 * 256 * 256 + +ipArr[1] * 256 * 256+ ipArr[2] * 256+ +ipArr[3]
			// 初始化dll链接库,返回bool值
			var initSuccess = dll.AclasSDK_Initialize(null)
			if (initSuccess) {
				// 链接库初始化成功后获取设备协议类型,返回0代表连接秤类型不存在
				var deviceType = dll.AclasSDK_GetDeviceType(numberIp, 0, 0)
				if (deviceType !== 0) {
					// 获取秤类型后获取秤信息
					console.log("AclasSDK_GetDeviceType++"+deviceType)
					var deviceInfo = dll.AclasSDK_GetDeviceInfo(
						numberIp,
						0,
						deviceType,deviceInfoResult
					)
					console.log("AclasSDK_GetDeviceInfo++"+deviceInfo)
					if (Object.keys(deviceInfo).length > 0) {
						// 定义设备ip供AclasSDK_Sync_ExecTask_PB函数使用
						var Addr = ip
						// 定义执行任务的目标文件绝对路径
						var FileName = file
						// 开始执行任务(没有回调函数)
						var startWork = dll.AclasSDK_Sync_ExecTaskA_PB(
							Addr, // ip地址
							deviceInfo.Port, // 端口号
							deviceInfo.ProtocolType, // 协议类型
							0, // 操作类型 0代表下载文件
							0, // 数据类型 0代表PLU文件
							FileName // 文件地址(绝对路径)
						)
						if (startWork == 0) {
							res.json({ status: 1 })
						} else {
							res.json({ status: startWork })
						}
					}
				}
			} else {
				res.json({ status: 2 })
			}
			// 释放动态链接库
			dll.AclasSDK_Finalize()
		}
	})
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值