代码拉取完成,页面将自动刷新
import os.path
import serial
import socket
import binascii
# PART 1:data collcet
# 创建Serial对象
ser = serial.Serial()
# 设置串口参数
ser.port = '/dev/ttyAMA0' # 串口号(根据实际情况修改)
ser.baudrate = 115200 # 波特率
ser.bytesize = serial.EIGHTBITS # 数据位
ser.parity = serial.PARITY_NONE # 校验位
ser.stopbits = serial.STOPBITS_ONE # 停止位
# 打开串口
ser.open()
try:
data = bytes.fromhex('01 03 00 00 00 0A C5 CD') # 将十六进制字符串转换为字节类型
ser.write(data)
# 读取数据直到指定长度
received_data = ser.read(25) # 假设Modbus返回的数据长度为20字节
print(received_data.hex()) # 将接收到的数据转换为十六进制字符串输出
print(received_data)
except KeyboardInterrupt:
pass
finally:
# 关闭串口
ser.close()
# PART 2:data save
data = received_data.hex()
file_path = "/home/pi/Desktop/data.txt"
file_path = os.path.expanduser(file_path)
try:
with open(file_path,"w") as file:
file.write(data)
print("data write sucessfully",file_path)
except Exception as e:
print("data write worng".str(e))
# PART 3:data transfer
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '112.125.89.8'
port = 45951
s.connect((host, port))
with open("/home/pi/Desktop/data.txt", "r") as f:
fdata = [ord(char) for char in f.read()]
data = bytes(fdata)
# 创建套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# 连接到目标IP和端口
client_socket.connect((host, port))
# 控制发送数据的长度
total_sent = 0
data_with_spaces = b' '.join([data[i:i+2] for i in range(0, len(data), 2)]) # 每两个字符后添加空格
while total_sent < len(data_with_spaces):
chunk = data_with_spaces[total_sent : total_sent + 1] # 每次发送一个字节
sent = client_socket.send(chunk)
total_sent += sent
print("成功发送数据。")
except ConnectionRefusedError:
print("无法连接到目标IP地址和端口号。")
s.send(data)
s.close()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。