Files
ElecScalesMeasur/send_target.py

87 lines
2.1 KiB
Python
Raw Permalink Normal View History

2025-02-18 11:28:24 +08:00
#!/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
2025-02-18 11:28:24 +08:00
2025-09-30 14:57:14 +08:00
target_weight = 200
set_vibrate_time = 10
2025-02-18 11:28:24 +08:00
cmd_set_target = {
# 称量
"command": "set_target",
"payload": {
2025-09-30 14:57:14 +08:00
"target_weight": target_weight,
"algorithm": "pid",
"direction_control": False
2025-02-18 11:28:24 +08:00
}
}
cmd_get_weight = {
# 获取重量
"command": "get_weight"
# "payload": {
# "target_weight": 200,
# "algorithm": "pid"
# }
}
cmd_set_zero = {
# 去皮
2025-09-30 14:57:14 +08:00
"command": "set_zero",
"payload": {
# "target_weight": 200,
# "algorithm": "pid"
}
2025-02-18 11:28:24 +08:00
}
cmd_set_vibrate = { # 振动控制
"command": "set_vibrate",
"payload": {
2025-09-30 14:57:14 +08:00
"time": set_vibrate_time # 单位S
2025-02-18 11:28:24 +08:00
}
}
2025-09-30 14:57:14 +08:00
# 使用 with 语句确保 socket 在使用完毕后正确关闭
2025-02-18 11:28:24 +08:00
with socket.socket() as s:
s.connect(('127.0.0.1', 5000))
2025-09-30 14:57:14 +08:00
# 发送称重命令
try:
s.sendall(json.dumps(cmd_set_target).encode())
2025-09-30 14:57:14 +08:00
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 # 如果发送失败,退出循环