Files
ElecScalesMeasur/send_target.py

74 lines
1.8 KiB
Python
Raw 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
cmd_set_target = {
# 称量
"command": "set_target",
"payload": {
"target_weight": 200,
"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 = {
# 去皮
"command": "set_zero"
# "payload": {
# "target_weight": 200,
# "algorithm": "pid"
# }
}
cmd_set_vibrate = { # 振动控制
"command": "set_vibrate",
"payload": {
"time": 0 # 单位S
}
}
# 使用 with 语句确保 socket 在使用完毕后正确关闭
2025-02-18 11:28:24 +08:00
with socket.socket() as s:
s.connect(('127.0.0.1', 5000))
# 发送命令
try:
s.sendall(json.dumps(cmd_set_target).encode())
except socket.error as e:
print(f"发送数据时发生错误: {e}")
# break # 如果发送失败,退出循环
start_time = time.time()
# 接收数据
while True:
try:
data = s.recv(1024)
if not data:
print("没有收到数据,连接可能已关闭")
# break # 如果没有数据,退出循环
time.sleep(1)
print(data.decode())
end_time = time.time()
elapsed_time = end_time - start_time
print(f"代码执行时间:{elapsed_time:.6f}")
break
except socket.error as e:
print(f"接收数据时发生错误: {e}")
#break # 如果接收失败,退出循环