#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import logging
from l76x import L76X
import os

logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger('GPS_MAIN')

def clear_screen():
    os.system('clear' if os.name == 'posix' else 'cls')

def main():
    gps = L76X(port='/dev/ttyS0', baudrate=9600, timeout=1)
    
    if not gps.connect():
        logger.error("GPS模块连接失败，请检查硬件和串口！")
        return
    
    if not gps.wait_for_fix(timeout=60):
        logger.warning("GPS定位超时，展示原始数据！")
    
    try:
        logger.info("="*60)
        logger.info("树莓派4B GPS原始数据（WGS84）- 按Ctrl+C退出")
        logger.info("="*60)
        time.sleep(1)
        
        while True:
            clear_screen()
            gps_data = gps.get_formatted_data()
            logger.info("📌 GPS原始WGS84数据实时展示 📌")
            logger.info("-"*60)
            for key, value in gps_data.items():
                print(f"{key:<20} : {value:>20}")
            logger.info("-"*60)
            logger.info("按Ctrl+C退出 | 1秒刷新一次")
            time.sleep(1)
            
    except KeyboardInterrupt:
        logger.info("\n\n🛑 程序中断，关闭GPS模块...")
    except Exception as e:
        logger.error(f"\n❌ 程序出错：{str(e)}")
    finally:
        gps.disconnect()
        logger.info("✅ GPS模块已断开，程序退出！")

if __name__ == '__main__':
    main()