import socket import json import time target_weight = 660 # 目标重量 # 称重指令 cmd_set_target = { # 称量 "command": "set_target", "payload": { "target_weight": target_weight, "algorithm": "pid", "direction_control": False, }, } # 清零 cmd_set_zero = { # 去皮 "command": "set_zero" } cmd_get_weight = { # 获取重量 "command": "get_weight" } def start_weight(host="192.168.58.25", port=5000): """ 连接称重设备,发送目标重量并等待达到指定值 Args: target_weight: 目标重量值 cmd_set_zero: 去皮 cmd_set_target: 称重 cmd_get_weight: 获取重量 host: 服务器IP地址 port: 服务器端口 Returns: 成功时返回达到的目标重量, 失败时返回None """ try: with socket.socket() as s: s.connect((host, port)) # 去皮 s.sendall(json.dumps(cmd_set_zero).encode()) time.sleep(1) # 等待去皮完成 # 检查去皮是否完成 s.sendall(json.dumps(cmd_get_weight).encode()) weight_data = s.recv(1024) response = json.loads(weight_data.decode()) zero_weight = response.get("current_weight") print("清零后的重量:", zero_weight) except (socket.error, json.JSONDecodeError, UnicodeDecodeError) as e: print(f"start_weight错误: {e}") return None try: with socket.socket() as s: if isinstance(zero_weight, (int, float)) and abs(zero_weight) < 0.01: s.connect((host, port)) # 称重 s.sendall(json.dumps(cmd_set_target).encode()) while True: data = s.recv(1024) if not data: print("start_weight错误: 服务器连接已关闭") return None try: decoded = data.decode() response = json.loads(decoded) current_weight = response.get("current_weight") if current_weight is not None: print(f"当前重量:{current_weight}") if current_weight >= target_weight: return current_weight # 达到目标重量后返回 else: print(f"获取的重量为None: {current_weight}") return None except json.JSONDecodeError: print(f"start_weight错误: 无效的JSON格式: {decoded}") return None except UnicodeDecodeError: print( f"start_weight错误: 字节解码错误, 无法解析字节流data为字符串" ) return None else: print("start_weight错误: 去皮失败, 中止称量流程, 请检查设备") return None except socket.error as e: print(f"start_weight错误: 通信错误: {e}") return None if __name__ == "__main__": if start_weight(): print("称重完毕") else: print("称重发生错误") exit(-1)