别再死记硬背了!用Python脚本自动化测试EC20 4G模块的AT指令(附串口助手实战)
用Python脚本自动化测试EC20 4G模块的AT指令
在物联网开发中,频繁手动输入AT指令测试4G模块既耗时又容易出错。本文将介绍如何用Python脚本实现EC20模块的自动化测试,涵盖串口通信、指令批量执行和响应解析全流程。
1. 环境准备与基础配置
开始前需要准备以下硬件和软件环境:
硬件设备:
- 移远EC20 4G模块
- USB转TTL串口模块(如CH340、CP2102)
- 4G天线和SIM卡
软件依赖:
- Python 3.6+
- pyserial库(
pip install pyserial) - 可选:移远串口调试助手(用于对照测试)
连接硬件时需特别注意:
确保EC20模块的VCC引脚电压匹配(通常3.3V),错误供电可能损坏模块。建议先通过AT指令确认基础通信:
import serial ser = serial.Serial('COM3', 115200, timeout=1) ser.write(b'AT\r\n') response = ser.read(100) print(response.decode()) # 应输出'OK'2. AT指令自动化测试框架设计
2.1 核心通信类封装
创建一个EC20Controller类处理底层串口通信:
class EC20Controller: def __init__(self, port, baudrate=115200): self.ser = serial.Serial(port, baudrate, timeout=2) def send_at_command(self, command, expected='OK', wait=1): self.ser.write((command + '\r\n').encode()) time.sleep(wait) response = self.ser.read_all().decode().strip() if expected not in response: raise Exception(f"指令{command}执行失败,响应:{response}") return response2.2 常用指令测试用例
通过继承实现具体业务逻辑:
class EC20Tester(EC20Controller): def check_sim_status(self): return self.send_at_command('AT+CPIN?') def get_signal_quality(self): response = self.send_at_command('AT+CSQ') # 解析信号强度值(示例:+CSQ: 24,0 → RSSI=24) return int(response.split(':')[1].split(',')[0])3. 高级功能自动化实现
3.1 TCP连接压力测试
模拟持续建立/断开TCP连接:
def tcp_stress_test(controller, host, port, cycles=100): for i in range(cycles): try: # 建立连接 controller.send_at_command(f'AT+QIOPEN=1,0,"TCP","{host}",{port}') # 发送测试数据 controller.send_at_command('AT+QISEND=0,5', '>') controller.send_at_command('hello', 'SEND OK') # 关闭连接 controller.send_at_command('AT+QICLOSE=0') print(f"第{i+1}次测试成功") except Exception as e: print(f"测试失败:{str(e)}")3.2 MQTT协议自动化配置
封装MQTT全流程操作:
def mqtt_auto_config(controller): # 打开MQTT网络 controller.send_at_command('AT+QMTOPEN=1,"mqtt.eclipse.org",1883') # 连接服务器 controller.send_at_command('AT+QMTCONN=1,"python_client"') # 订阅主题 controller.send_at_command('AT+QMTSUB=1,1,"test/topic",1') # 发布消息 controller.send_at_command('AT+QMTPUBEX=1,0,0,0,"test/topic",16', '>') controller.send_at_command('{"status":"ok"}')4. 异常处理与日志系统
4.1 健壮性增强设计
添加重试机制和超时控制:
def robust_command(controller, command, retries=3, delay=1): for attempt in range(retries): try: return controller.send_at_command(command) except Exception as e: if attempt == retries - 1: raise time.sleep(delay)4.2 日志记录与分析
集成logging模块实现分级日志:
import logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler('ec20_test.log'), logging.StreamHandler() ] ) class LoggedEC20Tester(EC20Tester): def send_at_command(self, command, **kwargs): logging.info(f"发送指令:{command}") try: response = super().send_at_command(command, **kwargs) logging.debug(f"收到响应:{response}") return response except Exception as e: logging.error(f"指令执行异常:{str(e)}") raise5. 实战:批量模块配置工具
开发完整的配置工具示例:
def batch_configure(port, config_file): controller = LoggedEC20Tester(port) with open(config_file) as f: commands = [line.strip() for line in f if line.strip()] results = [] for cmd in commands: try: res = controller.send_at_command(cmd) results.append((cmd, '成功', res)) except Exception as e: results.append((cmd, '失败', str(e))) # 生成报告 report = "\n".join( f"{cmd[:30]:<32} {status:<8} {result[:50]}" for cmd, status, result in results ) with open('config_report.txt', 'w') as f: f.write(report)使用方式:
python configure.py COM4 settings.txt典型配置文件内容:
AT+CFUN=1 AT+CPIN? AT+CREG? AT+QICSGP=1,1,"APN" AT+QIACT=1