#!/bin/bash
# CAN-USB适配器快速配置脚本
# 使用方法: sudo ./setup_can_usb.sh [设备路径]
# 示例: sudo ./setup_can_usb.sh /dev/ttyACM0

DEVICE=${1:-/dev/ttyACM0}
INTERFACE="can0"
BITRATE="s8"  # s8 = 1Mbps

echo "=========================================="
echo "CAN-USB适配器配置脚本"
echo "=========================================="

# 检查设备是否存在
if [ ! -e "$DEVICE" ]; then
    echo "[错误] 设备 $DEVICE 不存在!"
    echo "可用的串口设备:"
    ls -la /dev/ttyACM* /dev/ttyUSB* 2>/dev/null || echo "  未找到串口设备"
    echo ""
    echo "可用的CAN接口:"
    ip link show type can 2>/dev/null || echo "  未找到CAN接口"
    exit 1
fi

# 关闭已有的slcand进程
echo "[1/4] 关闭已有的slcand进程..."
killall slcand 2>/dev/null

# 关闭已有的can0接口
echo "[2/4] 关闭已有的can0接口..."
ip link set $INTERFACE down 2>/dev/null

# 启动slcand
echo "[3/4] 启动slcand (设备: $DEVICE, 波特率: 1Mbps)..."
slcand -o -c -$BITRATE $DEVICE $INTERFACE
sleep 1

# 启动CAN接口
echo "[4/4] 启动CAN接口..."
ip link set $INTERFACE up

# 验证
echo ""
echo "=========================================="
echo "配置完成! 接口状态:"
echo "=========================================="
ip link show $INTERFACE

echo ""
echo "测试命令:"
echo "  监听: candump $INTERFACE"
echo "  发送: cansend $INTERFACE 123#DEADBEEF"
echo ""
