import asyncio import time from uhf.reader import * from tools_use import ProductInfoTokenManager, ProductImage async def tcp_client(host: str, port: int): # 创建 socket 对象 reader, writer = await asyncio.open_connection(host, port) print(f"已连接到 TCP 服务器 {host}:{port}") msg = MsgBaseInventoryEpc(antennaEnable=EnumG.AntennaNo_1.value, inventoryMode=EnumG.InventoryMode_Inventory.value) msg.pack() writer.write(msg.toByte(False)) await writer.drain() try: buffer = RingBuffer() while True: # 接收服务器返回的信息 response = await reader.read(1024) if response: buffer.writeData(response) if buffer.dataCount < 48: continue if buffer.indexData(0) != 0x5A: buffer.cleanData(1 * 8) continue if buffer.dataCount >= 56: temp = DynamicBuffer() temp.putBytes(buffer.readData(40)) dataLen = buffer.readBit(16) if dataLen != 0: temp.putShort(dataLen) if (dataLen + 2) * 8 > buffer.dataCount: if dataLen > 1024: buffer.cleanData(1 * 8) else: buffer.subPos(temp.len) continue else: temp.putBytes(buffer.readData(dataLen * 8)) data = buffer.readData(16) temp.putBytes(data) msg = Message().new(temp.hex) print(msg.msgId) if msg: if msg.checkCrc(): buffer.cleanAll() if msg.mt_8_11 == EnumG.Msg_Type_Bit_Base.value: if msg.msgId == EnumG.BaseLogMid_Epc.value: info = LogBaseEpcInfo() info.cData = msg.cData info.unPack() print("收到服务器消息:", info.epc) product_info_instance = ProductInfoTokenManager() product_image_instance = ProductImage() barcode = await product_info_instance.get_barcode_from_epc(info.epc) product_info = await product_info_instance.get_product_info_by_barcode(barcode) product_image = await product_image_instance.get_product_image_by_barcode(barcode) response_data = { "code": 1, "message": "ok", "data": { "barcode": barcode, "product_info": product_info, "product_image": product_image } } print(f'response_data*******{response_data["code"]}') mess = MsgAppGetBaseVersion() mess.pack() writer.write(mess.toByte(False)) await writer.drain() elif msg.mt_8_11 == EnumG.Msg_Type_Bit_App.value: if msg.msgId == EnumG.AppMid_Heartbeat.value: writer.write(msg.msgData) else: print('ok4 \n') mess = MsgAppGetBaseVersion() mess.pack() writer.write(mess.toByte(False)) await writer.drain() except Exception as e: print("连接或通信过程中发生错误:", e) finally: print('finally') writer.close() await writer.wait_closed() print("连接已关闭") if __name__ == "__main__": asyncio.run(tcp_client('10.41.191.107', 8160)) # 根据实际IP和端口修改 print(MsgAppGetBaseVersion())