#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
钧远·粮报 - 地磅数据采集程序（自适应版）
功能：自动识别常见地磅仪表协议，采集重量并同步到云服务器
支持：耀华、托利多、大华等常见品牌
"""

import serial
import time
import requests
import re
import json

# ========== 配置 ==========
# 串口号（Windows是COM1、COM2...，Linux是/dev/ttyUSB0...）
COM_PORT = 'COM1'
# 波特率（地磅常用9600，有些是4800、2400）
BAUD_RATES = [9600, 4800, 2400]
# 服务器地址
SERVER_URL = 'http://lb.gsynyfw.com/api/scale-data'
# 用户ID（登录后从后台获取）
USER_ID = 1


def parse_weight_auto(data):
    """
    自动识别数据格式，提取重量
    支持常见的地磅仪表协议
    """
    data_str = data.decode('ascii', errors='ignore').strip()
    
    # 格式1: 耀华XK3190 - ST,GS,+01234.5
    match = re.search(r'[+-]?(\d+\.?\d*)', data_str)
    if match:
        weight = float(match.group(1))
        # 过滤明显不合理的数字（地磅一般不会超过100吨=100000kg）
        if 0 < weight < 100000:
            return weight
    
    # 格式2: 纯数字结尾
    match = re.search(r'(\d+\.?\d*)\s*$', data_str)
    if match:
        weight = float(match.group(1))
        if 0 < weight < 100000:
            return weight
    
    return None


def upload_weight(weight):
    """上传重量到服务器"""
    try:
        data = {
            'user_id': USER_ID,
            'weight': weight,
            'timestamp': time.time()
        }
        response = requests.post(SERVER_URL, json=data, timeout=5)
        if response.status_code == 200:
            print(f"✅ 重量 {weight} kg 已同步到服务器")
        else:
            print(f"❌ 上传失败: {response.status_code}")
    except Exception as e:
        print(f"❌ 上传错误: {e}")


def try_read_scale():
    """尝试连接地磅，自动识别协议"""
    for baud in BAUD_RATES:
        try:
            print(f"🔍 尝试波特率 {baud}...")
            ser = serial.Serial(COM_PORT, baud, timeout=2)
            
            # 读取几行数据
            for i in range(10):
                data = ser.readline()
                if data:
                    weight = parse_weight_auto(data)
                    if weight:
                        print(f"✅ 成功连接！波特率: {baud}")
                        print(f"✅ 识别到重量: {weight} kg")
                        print(f"")
                        print(f"开始持续采集数据...")
                        print(f"按Ctrl+C退出")
                        print(f"")
                        
                        # 进入持续采集模式
                        while True:
                            data = ser.readline()
                            if data:
                                weight = parse_weight_auto(data)
                                if weight:
                                    print(f"📊 当前重量: {weight} kg")
                                    upload_weight(weight)
                            time.sleep(0.5)
            
            ser.close()
            
        except Exception as e:
            print(f"❌ 波特率 {baud} 连接失败: {e}")
            continue
    
    print("")
    print("❌ 所有波特率都尝试失败！")
    print("请检查：")
    print("1. 串口号是否正确")
    print("2. 串口线是否连接好")
    print("3. 地磅仪表是否开机")
    print("4. 是否安装了pyserial库（pip install pyserial）")
    print("5. 有问题请联系客服远程调试")


if __name__ == '__main__':
    print("=" * 60)
    print("  钧远·粮报 - 地磅数据采集程序（自适应版）")
    print("=" * 60)
    print()
    print("配置：")
    print(f"  串口号: {COM_PORT}")
    print(f"  自动尝试波特率: {BAUD_RATES}")
    print(f"  服务器: {SERVER_URL}")
    print()
    print("本程序自动识别常见地磅仪表协议")
    print("支持：耀华、托利多、大华等品牌")
    print()
    print("按Enter开始...")
    input()
    print()
    
    try_read_scale()
