import sys
import time
import serial
import datetime
import os

executable_path = sys.argv[0]
path = os.path.dirname(os.path.abspath(executable_path))
resourcesPath = path + os.sep
# 创建日志文件保存目录

current_time = datetime.datetime.now()

# 创建日志文件名
log_filename = os.path.join(resourcesPath, f"signal_log_{current_time.strftime('%Y%m%d_%H%M%S')}.bin")

# 检查日志文件是否已经存在
if os.path.exists(log_filename):
    # 如果文件存在，则继续写入现有文件
    with open(log_filename, 'ab') as log_file:
        ser = serial.Serial('/dev/ttyUSB2', 2000000, timeout=2)
        
        try:
            while True:
                ser.write(b'AT+CSQ\r\n')
                response = ser.read_until(b'OK')
                data = response.decode('utf-8')
                signal = data.split(':')[1].split(',')[0].strip()
                
                # 获取当前时间并将其转换为二进制形式
                current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S').encode('utf-8')
                
                # 将信号值和时间写入日志文件
                log_file.write(current_time + b'\n')
                log_file.write(signal.encode('utf-8') + b'\n')
                time.sleep(60)
        finally:
            ser.close()  # 确保串口在程序结束时关闭
else:
    # 如果文件不存在，则创建新文件
    with open(log_filename, 'wb') as log_file:
        ser = serial.Serial('/dev/ttyUSB2', 2000000, timeout=2)
        
        try:
            while True:
                ser.write(b'AT+CSQ\r\n')
                response = ser.read_until(b'OK')
                data = response.decode('utf-8')
                signal = data.split(':')[1].split(',')[0].strip()
                
                # 获取当前时间并将其转换为二进制形式
                current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S').encode('utf-8')
                
                # 将信号值和时间写入日志文件
                log_file.write(current_time + b'\n')
                log_file.write(signal.encode('utf-8') + b'\n')
                time.sleep(60)
        finally:
            ser.close()  # 确保串口在程序结束时关闭