#!/bin/bash set -e # ============================================ # 串口关机控制器 - 安装脚本 # ============================================ INSTALL_DIR="/opt/ttyshutdown" SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" # 颜色定义 RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' CYAN='\033[0;36m' NC='\033[0m' info() { echo -e "${GREEN}[INFO]${NC} $1"; } warn() { echo -e "${YELLOW}[WARN]${NC} $1"; } error() { echo -e "${RED}[ERROR]${NC} $1"; } # 检查 root 权限 check_root() { if [ "$(id -u)" -ne 0 ]; then error "请使用 root 权限运行此脚本: sudo bash install.sh" exit 1 fi } # 扫描可用串口 scan_serial_ports() { local ports=() for pattern in "ttyUSB*" "ttyACM*" "ttyS*"; do for dev in /dev/$pattern; do if [ -e "$dev" ]; then ports+=("$dev") fi done done echo "${ports[@]}" } # 交互选择串口 select_serial_port() { echo -e "${CYAN}========================================${NC}" echo -e "${CYAN} 串口关机控制器 - 安装向导${NC}" echo -e "${CYAN}========================================${NC}" echo "" local ports ports=$(scan_serial_ports) if [ -z "$ports" ]; then warn "未检测到串口设备" echo -e "请手动输入串口设备路径 (如 ${YELLOW}/dev/ttyUSB0${NC}): " read -r SELECTED_PORT if [ ! -e "$SELECTED_PORT" ]; then warn "设备 $SELECTED_PORT 当前不存在,仍将配置(设备可能稍后接入)" fi return fi # 转为数组 local port_array=($ports) echo -e "检测到以下串口设备:${GREEN}" local i=1 for p in "${port_array[@]}"; do local desc="" case "$p" in /dev/ttyUSB*) desc="USB转串口" ;; /dev/ttyACM*) desc="USB CDC虚拟串口" ;; /dev/ttyS*) desc="原生串口(COM口)" ;; esac echo " [$i] $p ($desc)" ((i++)) done echo -e "${NC}" local last_index=${#port_array[@]} echo " [$((last_index + 1))] 手动输入其他路径" echo "" local choice while true; do read -rp "请选择串口 [1-$((last_index + 1))]: " choice if [[ "$choice" =~ ^[0-9]+$ ]] && [ "$choice" -ge 1 ] && [ "$choice" -le "$((last_index + 1))" ]; then break fi error "无效选择,请重新输入" done if [ "$choice" -le "$last_index" ]; then SELECTED_PORT="${port_array[$((choice - 1))]}" else read -rp "请输入串口设备路径: " SELECTED_PORT if [ -z "$SELECTED_PORT" ]; then error "路径不能为空" exit 1 fi fi } # 生成 config.json generate_config() { local port="$1" local baud_rate="$2" local shutdown_word="$3" cat > "${INSTALL_DIR}/config.json" < "/usr/lib/systemd/system-shutdown/send_signal.sh" < "\$TTY_DEVICE" fi fi exit 0 EOF chmod +x "/usr/lib/systemd/system-shutdown/send_signal.sh" info "已安装关机钩子: /usr/lib/systemd/system-shutdown/send_signal.sh" } # 生成 systemd service generate_service() { cat > /etc/systemd/system/ttyshutdown.service <