#!/usr/bin/env python # -*- coding: utf-8 -*- ''' # @Time : 2025/2/14 14:44 # @Author : hjw # @File : send_target.py ''' import socket import json import time target_weight = 200 set_vibrate_time = 10 cmd_set_target = { # 称量 "command": "set_target", "payload": { "target_weight": target_weight, "algorithm": "pid", "direction_control": False } } cmd_get_weight = { # 获取重量 "command": "get_weight" # "payload": { # "target_weight": 200, # "algorithm": "pid" # } } cmd_set_zero = { # 去皮 "command": "set_zero", "payload": { # "target_weight": 200, # "algorithm": "pid" } } cmd_set_vibrate = { # 振动控制 "command": "set_vibrate", "payload": { "time": set_vibrate_time # 单位S } } # 使用 with 语句确保 socket 在使用完毕后正确关闭 with socket.socket() as s: s.connect(('127.0.0.1', 5000)) # 发送称重命令 try: s.sendall(json.dumps(cmd_set_target).encode()) print("已发送目标值设定指令") start_time = time.time() # 接收数据 while True: data = s.recv(1024) if not data: print("连接已关闭") break decoded = data.decode() print(f"收到数据: {decoded}") try: 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: print("目标已达到,发送振动控制指令") s.sendall(json.dumps(cmd_set_vibrate).encode()) break except socket.error as e: print(f"接收数据时发生错误: {e}") # break # 如果接收失败,退出循环 except socket.error as e: print(f"发送数据时发生错误: {e}") # break # 如果发送失败,退出循环