#!/bin/sh

# Load common functions
. /usr/share/fan-control/common.sh

NAME="Fibocom FM350"
MANUFACTURER="Fibocom"
DESCRIPTION="Fibocom 5G modem FM350"
AT_PORT_PRIORITY="ttyUSB2,ttyUSB1,ttyUSB3"

get_modem_temperature() {
    local device="$1"
    local temp=0
    
    if [ ! -c "$device" ]; then
        echo "0"
        return 1
    fi
    
    # Try TEMP command
    response=$(sms_tool_query "AT+TEMP=0" "$device")
    temp=$(echo "$response" | awk -F'[ :"]+' '/soc_max/{ printf "%.0f", $3 }')
    
    if [ -n "$temp" ] && [ "$temp" -gt 0 ] && [ "$temp" -lt 120 ]; then
        echo "$temp"
        return 0
    fi
    
    # Try ETHERMAL command
    response=$(sms_tool_query "AT+ETHERMAL?" "$device")
    temp=$(echo "$response" | awk -F, '/\+ETHERMAL:/{ sum+=$2; count++ } END { if(count > 0) { printf "%.0f", sum/count } else { print 0 } }')
    
    if [ -n "$temp" ] && [ "$temp" -gt 0 ] && [ "$temp" -lt 120 ]; then
        echo "$temp"
        return 0
    fi
    
    # Try GTSENRDTEMP command
    gt_response=$(sms_tool_query "AT+GTSENRDTEMP=1" "$device")
    temp=$(echo "$gt_response" | awk -F'[ ,:]+' '/\+GTSENRDTEMP:/{ value=$3; result=value/1000; printf "%.0f", result }')
    
    if [ -n "$temp" ] && [ "$temp" -gt 0 ] && [ "$temp" -lt 120 ]; then
        echo "$temp"
        return 0
    fi
    
    # Fallback
    echo "0"
    return 1
}

test_port() {
    local device="$1"
    
    if [ ! -c "$device" ]; then
        return 1
    fi
    
    response=$(sms_tool_query "ATI" "$device")
    echo "$response" | grep -qv "ERROR" && echo "$response" | grep -q "."
    return $?
}