import struct import sqlite3 import time import sys import matplotlib.pyplot as plt…
- User
import struct import sqlite3 import time import sys import matplotlib.pyplot as plt import numpy as np import argparse #import Exceptions from pymodbus.client import ModbusSerialClient as ModbusClient from pymodbus.exceptions import ModbusInvalidResponseError
打开串口
client = ModbusClient(method=“rtu”, port=‘COM1’, baudrate=9600) client.connect()
args
def usage(): print(‘’‘ -h, --help: 帮助 -m, --measure: 读取测量值 -w, --warning: 读取继电器报警 -s, --setting: 写寄存器 -r, --read: 读取寄存器 -mo, --monitor: 持续读取测量值并记录 -o, --output: 输出文件名 ‘’’)
寄存器操作
def read_register(reg_addr, reg_count) -> int:
读取寄存器并返回值
rr = client.read_holding_registers(reg_addr, reg_count,unit=0x01) ans = rr.registers[0] return ans
def read_float(register_addr) -> int:
读取寄存器并转换为浮点数
count: 2
ans = read_register(register_addr,2) result = struct.unpack(‘>f’, struct.pack(‘>HH’, ans))[0] return result
def write_register(register_addr, value) -> int:
往一个寄存器写入值
result = client.write_register(register_addr, value, unit=0x01) return result
def write_float(register_addr, value) -> int:
往一个寄存器写入浮点数
val = struct.unpack(‘>HH’, struct.pack(‘>f’, value)) result = client.write_registers(register_addr, val, unit=0x01) return result
测量操作
def measure_float() -> float:
读取测量值浮点数
addr: 0x20
count: 2
ans = read_float(0x20) return ans.round(4)
读取操作
def read_current_ct():
读取电流变比
addr: 0x1C
count: 1
ans = read_register(0x1C, 1) return ans
def read_comm_addr():
读取通讯地址
addr: 0x1B
count: 1
ans = read_register(0x1B, 1) return ans
def read_comm_bin():
读取通讯比特率
addr: 0x1C
count: 1
ans = read_register(0x1C, 1) return ans
def read_dp():
小数点位置
addr: 0x1E
count: 1
ans = read_register(0x1E, 1) dp = ans.registers[0] return bin(dp)[-1]
def measure_int():
DM5 不支持
pass
def read_war_uperhigh():
读取上上限
addr: 0x20
ans = read_float(0x20) return ans.round(4)
def read_war_high():
读取上限
addr: 0x22
ans = read_float(0x22) return ans.round(4)
def read_out_delay():
读取输出延时
addr: 0x24
ans = read_float(0x24) return ans.round(4)
def read_war_low():
读取下限
addr: 0x26
ans = read_float(0x26) return ans.round(4)
def read_war_uperlow():
读取下下限
addr: 0x28
ans = read_float(0x28) return ans.round(4)
def read_out_offset():
读取输出偏移
addr: 0x2C
ans = read_float(0x2C) return ans.round(4)
def read_warning():
继电器报警
addr: 0x2E
war = read_register(0x2E, 2) war = client.read_holding_registers(0x002E, 2, unit=0x01).registers[0] war_HH = int(war & 0b1111000000000000) >> 12 #上上限 war_HI = int(war & 0b0000111100000000) >> 8 #上限 war_GO = int(war & 0b0000000011110000) >> 4 war_LO = int(war & 0b0000000000001111) #下限 war_LL = int(war & 0b1111000000000000) >> 12 #下下限 return war_HH, war_HI, war_GO, war_LO, war_LL
写入操作
def setting(current_ct=None, comm_addr=None, comm_bin=None, war_uperhigh=None, war_high=None, war_uperlow=None, war_low=None, out_delay=None, out_offset=None):
配置
Int
current_ct: 电流变比CT 0x14 1
comm_addr: 通讯地址 0x1B 1
comm_bin: 通讯比特率 0x1C 1
Float
war_uperhigh: 上上限 0x20 2
war_high: 上限 0x22 2
war_uperlow: 下下限 0x28 2
war_low: 下限 0x26 2
out_delay: 输出延时 0x24 2
out_offset: 输出偏移 0x2C 2
写入电流变比触发器 CT 值
if current_ct is not None: write_register(0x14, current_ct)
写入通讯地址
if comm_addr is not None: write_register(0x1B, comm_addr)
写入通讯比特率
if comm_bin is not None: write_register(0x1C, comm_bin)
写入上上限
if war_uperhigh is not None: write_float(0x20, war_uperhigh)
写入上限
if war_high is not None: write_float(0x22, war_high)
写入下下限
if war_uperlow is not None: write_float(0x28, war_uperlow)
写入下限
if war_low is not None: write_float(0x26, war_low)
写入输出延时
if out_delay is not None: write_float(0x24, out_delay)
写入输出偏移
if out_offset is not None: write_float(0x2C, out_offset)
记录操作
def record(filename):
创建数据库
conn = sqlite3.connect(filename) cursor = conn.cursor() cursor.execute(‘CREATE TABLE IF NOT EXISTS data(id INTEGER PRIMARY KEY AUTOINCREMENT,data FLOAT,warning INT,date DATE,time TIME,timestamp TIMESTAMP)’)
记录
try:
持续记录数据
while True:
读取寄存器
result = measure_float() warnings = read_warning() if any(warnings): warning = warnings.index(1) else: warning = 0
存储数据
date = time.strftime(“%Y-%m-%d”, time.localtime()) current_time = time.strftime(“%H:%M:%S”, time.localtime()) timestamp = int(time.time()) cursor.execute(‘INSERT INTO data(data, warning, date, time, timestamp) VALUES(?, ?, ?, ?, ?)’, (result, warning, date, current_time, timestamp)) conn.commit()
打印数据
print(f"Received data: {result}, Date: {date}, Time: {current_time}“)
等待
time.sleep(0.1) except Exception as e: print(e) finally:
关闭串口和数据库连接
client.close() cursor.close() conn.close()
监控操作
def monitor(): try: result = measure_float() warnings = read_warning() date = time.strftime(”%Y-%m-%d", time.localtime()) current_time = time.strftime(“%H:%M:%S”, time.localtime()) print(f"Received data: {result}, Date: {date}, Time: {current_time}") time.sleep(0.1) except Exception as e: print(e) finally: client.close()
if name == “main”:
parser = argparse.ArgumentParser(description=‘Modbus device record utility’) parser.add_argument(‘-m’, ‘-measure’, action=‘store_true’, help=‘measure the value’) parser.add_argument(‘-w’, ‘-warning’, action=‘store_true’, help=‘read the relay warning’) parser.add_argument(‘-s’, ‘-setting’, nargs=‘+’ ,action=‘store_true’, help=‘write the register’) parser.add_argument(‘-r’, ‘-read’, nargs=‘+’, type=str, action=‘store_true’, help=‘read the register’) parser.add_argument(‘-mo’, ‘-monitor’, action=‘store_true’, help=‘monitor the value and record’) parser.add_argument(‘-o’, ‘-output’, type=str, dest=‘filename’, help=‘output filename’)
args = parser.parse_args()
if args.measure: print(“Value:”,measure_float()) if args.warning: print(‘Warning:’,read_warning) if args.setting: print(‘Writing the register’) if args.read: print(‘Reading the register’) if args.monitor: if args.output: record(args.output) else: monitor() if args.filename: print(f’Output filename: {args.filename}')
结合这段代码,你能修改monitor 函数,使之可以将采集到的数据实时绘图为折线图吗?只需要输出修改相关的部分就可以,不必全部输出
- Assistant
def monitor(): fig, ax = plt.subplots() x = [] y = [] ax.plot(x,y) plt.ion() plt.show() try: while True: result = measure_float() warnings = read_warning() date = time.strftime("%Y-%m-%d", time.localtime()) current_time = time.strftime("%H:%M:%S", time.localtime()) print(f"Received data: {result}, Date: {date}, Time: {current_time}") # 实时绘图 x.append(current_time) y.append(result) ax.plot(x,y,'-') ax.set_xlim(left=max(0, len(x)-50), right=len(x)+5) plt.pause(0.1) except Exception as e: print(e) finally: client.close()
- User
这样数据多了之后会不会让图像变小?可以拖动吗?还有会不会出现内存泄漏的问题?
- Assistant
是的,随着数据的增多,图像会变小,无法拖动。而且如果不手动关闭图像窗口,可能会出现内存泄漏的问题。
为了避免这些问题,可以在每次更新数据时,仅仅更新图像上的最近一段数据,通过设置x轴的范围来控制显示的数据数量。另外,在监控结束时需要手动关闭图像窗口来释放内存。
下面是修改后的代码示例:
def monitor(): fig, ax = plt.subplots() x = [] y = [] line, = ax.plot(x,y) plt.ion() plt.show() try: while True: result = measure_float() warnings = read_warning() date = time.strftime("%Y-%m-%d", time.localtime()) current_time = time.strftime("%H:%M:%S", time.localtime()) print(f"Received data: {result}, Date: {date}, Time: {current_time}") # 实时绘图 x.append(current_time) y.append(result) if len(x) > 50: # 只显示最近50个数据点 x = x[-50:] y = y[-50:] line.set_xdata(x) line.set_ydata(y) ax.relim() ax.autoscale_view(True, True, True) plt.pause(0.1) except Exception as e: print(e) finally: client.close() plt.ioff() plt.show() - User
不需要ax.plot语句?
- Assistant
对的,在实时更新数据时,不需要反复调用
ax.plot来绘制新的折线段。而是通过调用line.set_xdata和line.set_ydata来更新已有的折线段。这样做不会使图像变小,因为绘制的是同一条折线。 - User
你能给出一个生成实时更新的随机数的函数吗,我想用来测试这个monitor函数
- Assistant
当然可以,请看下面的示例代码:
import random def generate_random_data(): while True: yield random.uniform(1, 10) # 给出一个范围为[1,10]的随机数generate_random_data函数会生成一个生成器,每次调用返回一个需要更新的随机数,可以这样使用:# 生成数据的生成器 data_gen = generate_random_data() # 监控数据生成并实时更新 try: while True: result = next(data_gen) date = time.strftime("%Y-%m-%d", time.localtime()) current_time = time.strftime("%H:%M:%S", time.localtime()) print(f"Received data: {result}, Date: {date}, Time: {current_time}") # 实时绘图 x.append(current_time) y.append(result) if len(x) > 50: # 只显示最近50个数据点 x = x[-50:] y = y[-50:] line.set_xdata(x) line.set_ydata(y) ax.relim() ax.autoscale_view(True, True, True) plt.pause(0.1) except Exception as e: print(e) finally: client.close() plt.ioff() plt.show()这样就可以在监控功能上使用随机数了,你可以根据自己的需求,修改
generate_random_data函数来生成符合你监控对象的随机数。 - User
但是报错 'list' object has no attribute 'set_xdata'
- Assistant
抱歉,之前的代码在更新数据时是直接对 x 和 y 进行的添加操作,所以可以直接调用
set_xdata和set_ydata。但是当使用生成器时,x 和 y 是列表,不能直接调用这两个方法。针对这种情况,可以将 x 和 y 封装为 numpy 数组(或者 pandas Series),这样就可以使用上述方法了。如果你不想用 numpy 或 pandas,也可以使用一个队列来存储数据。每次更新数据时,只需要弹出队列头部的数据,重新生成 x 和 y,并调用
plot来绘制新的折线段即可。下面是修改后的代码示例:
import random import numpy as np def generate_random_data(): while True: yield random.uniform(1, 10) # 给出一个范围为[1,10]的随机数 # 生成数据的生成器 data_gen = generate_random_data() fig, ax = plt.subplots() x = np.array([]) y = np.array([]) line, = ax.plot(x, y) plt.ion() plt.show() try: while True: result = next(data_gen) date = time.strftime("%Y-%m-%d", time.localtime()) current_time = time.strftime("%H:%M:%S", time.localtime()) print(f"Received data: {result}, Date: {date}, Time: {current_time}") # 实时绘图 x = np.append(x, [current_time]) y = np.append(y, [result]) if len(x) > 50: # 只显示最近50个数据点 x = x[-50:] y = y[-50:] line.set_xdata(x) line.set_ydata(y) ax.relim() ax.autoscale_view(True, True, True) plt.pause(0.1) except Exception as e: print(e) finally: client.close() plt.ioff() plt.show()这样就可以实时更新随机数的折线图了。
- User
报错Failed to convert value(s) to axis units: ['17:10:08']
- Assistant
这个错误是由于 Matplotlib 把x轴坐标设为文本格式后,无法解析时间格式导致的。Matplotlib 在将字符串转为x轴坐标时,需要将其转为datetime对象。可以通过 datetime 模块将字符串转为 datetime 对象,再将 datetime 对象转为 Matplotlib 能够解析的类型。
下面是修改后的代码示例:
import random import numpy as np from datetime import datetime def generate_random_data(): while True: yield random.uniform(1, 10) # 给出一个范围为[1,10]的随机数 # 生成数据的生成器 data_gen = generate_random_data() fig, ax = plt.subplots() x = np.array([]) y = np.array([]) line