import struct import sqlite3 import time import sys import getopt #import Exceptions…
- User
import struct import sqlite3 import time import sys import getopt #import Exceptions from pymodbus.client import ModbusSerialClient as ModbusClient from pymodbus.exceptions import ModbusInvalidResponseError
打开串口
client = ModbusClient(method="rtu", port='COM1', baudrate=9600) client.connect()
filename = 'data.db'
创建数据库
conn = sqlite3.connect(filename) cursor = conn.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS data(id INTEGER PRIMARY KEY AUTOINCREMENT,data FLOAT,date DATE,time TIME,timestamp TIMESTAMP)')
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 | 46 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(): # 记录 try: # 持续记录数据 while True: # 读取寄存器 result = measure_float()
# 存储数据 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, date, time, timestamp) VALUES(?, ?, ?, ?)', (result, date, current_time, timestamp)) conn.commit() # 打印数据 print(f"Received data: {result}, Date: {date}, Time: {current_time}") # 等待 time.sleep(0.1) except KeyboardInterrupt: # 关闭串口和数据库连接 print('KeyboardInterrupt') client.close() cursor.close() conn.close()if name == "main": record() 看一下这个代码,对于args部分你可以帮我修改补充代码吗?
- Assistant
当然可以,以下是一个参考代码:
import argparse
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', action='store_true', help='write the register') parser.add_argument('-r', '--read', 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('Measuring the value') if args.warning: print('Reading the relay warning') if args.setting: print('Writing the register') if args.read: print('Reading the register') if args.monitor: print('Monitoring the value and record') if args.filename: print(f'Output filename: {args.filename}')
- User
如何读取用户输入的参数?
- Assistant
在使用
argparse解析命令行参数之后,可以通过访问相应的属性读取用户输入的参数。例如:import argparse 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', action='store_true', help='write the register') parser.add_argument('-r', '--read', 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('Measuring the value') if args.warning: print('Reading the relay warning') if args.setting: print('Writing the register') if args.read: print('Reading the register') if args.monitor: print('Monitoring the value and record') if args.filename: print(f'Output filename: {args.filename}')在以上代码中,
args.measure、args.warning、args.setting、args.read和args.monitor为布尔类型,代表用户是否选择了相应的操作;args.filename为字符串类型,代表用户指定的输出文件名。可以根据需要在相应的条件分支中进行不同的操作。 - User
如果我想在一个arg后面读取多个对象呢,比如 -s reg1=1 reg2=3
- Assistant
这种情况下,可以使用
nargs参数来指定需要读取的对象数量。同时,可以使用action参数来自定义处理逻辑。下面是一个示例代码:import argparse # 自定义处理函数 def process_setting(args): for setting_str in args.setting: # 将形如 "reg1=1" 的设置字符串解析为变量名和值 var_name, var_value = setting_str.split('=') print(f'Setting {var_name} to {var_value}') # 创建解析器 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='+', help='write the register') parser.add_argument('-r', '--read', 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') # 注册处理函数 parser.set_defaults(func=None) parser.set_defaults(func=lambda args: print(parser.print_help())) parser.set_defaults(func=process_setting) # 解析命令行参数并执行相应操作 args = parser.parse_args() if args.func: args.func(args)在以上代码中,
nargs='+'表示需要读取多个对象,这些对象将被存储在一个列表中。而process_setting函数则用于处理-s参数,并将其解析为多个变量名和值。如果用户没有输入-s参数,则执行默认的print_help函数。如果输入命令如下:
python my_script.py -s reg1=1 reg2=3则输出如下:
Setting reg1 to 1 Setting reg2 to 3可以根据需要在
process_setting函数中实现相应的逻辑。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.