顯示具有 Linux Script 標籤的文章。 顯示所有文章
顯示具有 Linux Script 標籤的文章。 顯示所有文章

2024年9月26日 星期四

xlsx convert csv

xlsx2csv
$ sudo apt install xlsx2csv

Explanation: Array of Search Terms: an array called search_terms where you can add as many keywords as needed.
Loop Through Search Terms: For each converted CSV file, it loops through each search term and checks if it exists in that file using grep.
Output: The script will print messages indicating whether each keyword was found in each CSV file.
#!/bin/bash

# Directory containing the .xlsx files
input_directory="/path/to/xlsx/files"
# Output directory for CSV files
output_directory="/path/to/output/csv/files"
# File containing search terms (one per line)
search_terms_file="/path/to/search_terms.txt"

# Create output directory if it doesn't exist
mkdir -p "$output_directory"

# Read search terms from the specified file into an array
mapfile -t search_terms < "$search_terms_file"

# Loop through all .xlsx files in the input directory
for file in "$input_directory"/*.xlsx; do
    # Check if the file exists
    if [[ -f "$file" ]]; then
        # Generate the output CSV filename
        csv_filename="$output_directory/$(basename "${file%.xlsx}.csv")"
        
        # Convert .xlsx to .csv using xlsx2csv
        xlsx2csv "$file" "$csv_filename"
        
        # Check if the conversion was successful
        if [[ $? -eq 0 ]]; then
            echo "Converted: $file to $csv_filename"
            
            # Search for each term in the converted CSV file
            for search_term in "${search_terms[@]}"; do
                if grep -q "$search_term" "$csv_filename"; then
                    echo "Found '$search_term' in $csv_filename"
                else
                    echo "'$search_term' not found in $csv_filename"
                fi
            done
            
        else
            echo "Failed to convert: $file"
        fi
    fi
done

Create a text file named search_terms.txt and add your keywords, one per line. For example:
apple
banana
cherry



ref: Perplexity

2023年8月4日 星期五

USB conception

/sys/bus/usb/devices
1-0:1.0  3-0:1.0  3-10:1.0  3-11      3-11:1.1  3-4      3-4.2      3-4.4      3-4.4:1.1  3-4.4:1.3  3-4.4:1.5  3-4.4:1.7  3-4.4:1.9  3-8:1.0  3-9:1.0  4-0:1.0  usb2  usb4
2-0:1.0  3-10     3-10:1.1  3-11:1.0  3-11:1.2  3-4:1.0  3-4.2:1.0  3-4.4:1.0  3-4.4:1.2  3-4.4:1.4  3-4.4:1.6  3-4.4:1.8  3-8        3-9      3-9:1.1  usb1     usb3

解析:
<bus>-<port[.port[.port]]>:<config>.<interface>
For more info:
1. 【USB笔记】接口描述符Interface Descriptor
2. Understand USB (in Linux)
3. superuser.com/

dmesg
[13363.344895] cdc_acm 3-4.4:1.0: ttyACM0: USB ACM device
[13363.345308] cdc_acm 3-4.4:1.2: ttyACM1: USB ACM device
[13363.346187] cdc_acm 3-4.4:1.4: ttyACM2: USB ACM device
[13363.346989] cdc_acm 3-4.4:1.6: ttyACM3: USB ACM device
4G/5G 模組會有數個 multi interface (MI)
Windows:
    裝罝管理員裡, com port(右鍵,內容)
    詳細資料,屬性,硬體識別碼
    USB\VID_1E2D&PID_0069&REV_0000&MI_02

Linux:
    $ cat /sys/devices/pci0000:00/0000:00:14.0/usb3/3-4/3-4.4/3-4.4:1.6/bInterfaceNumber
    $ ls /sys/devices/pci0000:00/0000:00:14.0/usb3/3-4/3-4.4/3-4.4:1.6/tty





好用tool: lsusb.py
lsusb.py
Output:
$ ./lsusb.py -i
 WARNING: Failure to read usb.ids
usb1              1d6b:0002 09 1IF  [USB 2.00,   480 Mbps,   0mA] (xhci-hcd 0000:00:0d.0) hub
usb2              1d6b:0003 09 1IF  [USB 3.10, 10000 Mbps,   0mA] (xhci-hcd 0000:00:0d.0) hub
usb3              1d6b:0002 09 1IF  [USB 2.00,   480 Mbps,   0mA] (xhci-hcd 0000:00:14.0) hub
  3-4               1a40:0101 09 1IF  [USB 2.00,   480 Mbps, 100mA] () hub
    3-4.2             047d:2048 00 1IF  [USB 2.00,   1.5 Mbps, 100mA] (Primax Kensington Eagle Trackball)
      3-4.2:1.0         (IF) 03:01:02 1EP  () usbhid hidraw0 (hid-generic) input15 (hid-generic)
    3-4.4             1e2d:0069 ef 10IFs [USB 2.00,   480 Mbps, 500mA] (Cinterion Wireless Modules PLSx3 f7b292b4)
      3-4.4:1.0         (IF) 02:02:01 1EP  () cdc_acm tty/ttyACM0
      3-4.4:1.1         (IF) 0a:00:00 2EPs () cdc_acm
      3-4.4:1.2         (IF) 02:02:01 1EP  () cdc_acm tty/ttyACM1
      3-4.4:1.3         (IF) 0a:00:00 2EPs () cdc_acm
      3-4.4:1.4         (IF) 02:02:01 1EP  () cdc_acm tty/ttyACM2
      3-4.4:1.5         (IF) 0a:00:00 2EPs () cdc_acm
      3-4.4:1.6         (IF) 02:02:01 1EP  () cdc_acm tty/ttyACM3
      3-4.4:1.7         (IF) 0a:00:00 2EPs () cdc_acm
      3-4.4:1.8         (IF) 02:06:00 1EP  () cdc_ether net/wwx00a0c6292b40
      3-4.4:1.9         (IF) 0a:00:00 2EPs () cdc_ether
  3-8               04f3:0c11 00 1IF  [USB 2.00,    12 Mbps, 100mA] (ELAN ELAN:Fingerprint)
    3-8:1.0           (IF) ff:00:00 5EPs ()
  3-9               13d3:56a2 ef 2IFs [USB 2.00,   480 Mbps, 500mA] (Azurewave USB2.0 HD UVC WebCam 0x0001)
    3-9:1.0           (IF) 0e:01:00 1EP  () uvcvideo video4linux/video1 video4linux/video0 input/input19
    3-9:1.1           (IF) 0e:02:00 0EPs () uvcvideo
  3-10              8087:0029 e0 2IFs [USB 2.01,    12 Mbps, 100mA] ()
    3-10:1.0          (IF) e0:01:01 3EPs () btusb bluetooth/hci0
    3-10:1.1          (IF) e0:01:01 2EPs () btusb
  3-11              1044:7a3c 00 3IFs [USB 2.00,    12 Mbps, 500mA] (GIGABYTE Fusion RGB KB)
    3-11:1.0          (IF) 03:01:01 1EP  () usbhid hidraw1 (hid-generic) input16 (hid-generic)
    3-11:1.1          (IF) 03:01:01 1EP  () usbhid hidraw2 (hid-generic) input32 (hid-generic)
    3-11:1.2          (IF) 03:01:00 1EP  () usbhid hidraw3 (hid-generic) input34 input39 input35 input33 input36 (hid-generic)
usb4              1d6b:0003 09 1IF  [USB 3.10, 20000 Mbps,   0mA] (xhci-hcd 0000:00:14.0) hub



#!/bin/bash

# Function to check if the VID and PID match
function check_vid_pid {
    local vid_pid_dir="$1"
    local vid="$2"
    local pid="$3"

    local device_vid=$(cat "$vid_pid_dir/idVendor" 2>/dev/null)
    local device_pid=$(cat "$vid_pid_dir/idProduct" 2>/dev/null)

    if [[ "$device_vid" == "$vid" && "$device_pid" == "$pid" ]]; then
        echo "$vid_pid_dir"
        return 0 # Indicate a match was found
    else
        return 1 # Indicate no match was found
    fi
}

# Search for USB devices with matching VID and PID
function search_usb_devices {
    local vid="$1"
    local pid="$2"
    local -a paths=()

    for device in /sys/bus/usb/devices/*; do
        if [[ -d "$device" ]]; then
            if check_vid_pid "$device" "$vid" "$pid"; then
                paths+=("$device")
            fi
        fi
    done
}

function find_ttyUSB_ACM {
    local path="$1"
    local bInterface="04"
    local tty_devices=()

    cd $path
    # Find directories that contain bInterfaceNumber files, limiting depth to 2
    find ./ -maxdepth 2 -type f -name "bInterfaceNumber" -print0 | while IFS= read -r -d $'\0' bInterface_file; do
        # Extract the directory containing the bInterfaceNumber file
        interface_dir=$(dirname "$bInterface_file")

        # Read the bInterfaceNumber
        interface_number=$(cat "$bInterface_file")

        # Check if the interface number matches the desired value
        if [[ "$interface_number" == "$bInterface" ]]; then
            #echo "Found matching bInterface in: $interface_dir"

            # Search for ttyUSB* device nodes within the interface directory
            find "$interface_dir" -maxdepth 1 -type d -name "ttyUSB*" -print0 | while IFS= read -r -d $'\0' ttyname; do
                echo "/dev/$(basename "$ttyname")"
                #tty_devices+=("/dev/$(basename "$ttyname")")
            done
        fi
    done

    #echo "${tty_devices[*]}"
}

# Usage: ./find_usb_device.sh VID PID
if [[ $# -ne 2 ]]; then
    echo "Usage: $0 VID PID"
    exit 1
fi

if systemctl is-enabled ModemManager.service; then
    echo "ModemManager is enabled."

    systemctl stop ModemManager.service
    sleep 3
    systemctl disable ModemManager.service
    sleep 3
    echo "ModemManager has been stopped and disabled."
else
    echo "ModemManager is not enabled."
fi

paths=$(search_usb_devices "$1" "$2")

# Iterate over the paths and find ttyUSB/ACM devices
for path in $paths; do
    echo "Searching for ttyUSB/ACM devices in: $path"
    # Capture the tty devices returned by find_ttyUSB_ACM
    tty_devices=$(find_ttyUSB_ACM "$path")

    #echo "bbb-$tty_devices"
done

output:
./find_usb_device.sh 1e2d 0069
/sys/bus/usb/devices/3-2/, 480Mbits, 500mA, USB 2.00
/sys/bus/usb/devices/3-2/3-2:1.6/tty/ttyACM3
/sys/bus/usb/devices/3-2/3-2:1.4/tty/ttyACM2
/sys/bus/usb/devices/3-2/3-2:1.2/tty/ttyACM1
/sys/bus/usb/devices/3-2/3-2:1.0/tty/ttyACM0

ludev library
#include <libudev.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
  if (argc != 4) {
    fprintf(stderr, "Usage: %s <VID> <PID> <bInterfaceNumber>\n", argv[0]);
    return 1;
  }

  const char *target_vid = argv[1];
  const char *target_pid = argv[2];
  const char *target_bInterfaceNumber = argv[3];

  struct udev *udev = udev_new();
  if (!udev) {
    fprintf(stderr, "Failed to create udev object\n");
    return 1;
  }

  struct udev_enumerate *enumerate = udev_enumerate_new(udev);
  udev_enumerate_add_match_subsystem(enumerate, "tty");
  udev_enumerate_add_match_property(enumerate, "ID_VENDOR_ID", target_vid);
  udev_enumerate_add_match_property(enumerate, "ID_MODEL_ID", target_pid);

  udev_enumerate_scan_devices(enumerate);

  struct udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate);
  struct udev_list_entry *entry;

  udev_list_entry_foreach(entry, devices) {
    const char *path = udev_list_entry_get_name(entry);
    struct udev_device *dev = udev_device_new_from_syspath(udev, path);

    const char *devnode = udev_device_get_devnode(dev);
    const char *bInterface =
        udev_device_get_property_value(dev, "ID_USB_INTERFACE_NUM");

    // printf("devnode=%s, bInterface=%s\n", devnode, bInterface);

    if (devnode && bInterface &&
        strcmp(bInterface, target_bInterfaceNumber) == 0) {
      printf("Found device: %s\n", devnode);
    }

    udev_device_unref(dev);
  }

  udev_enumerate_unref(enumerate);
  udev_unref(udev);

  return 0;
}

output:
$ gcc find_usb_device.c -o find_usb_device -ludev

./find_usb_device 1bc7 1060 04
Found device: /dev/ttyUSB2
Found device: /dev/ttyUSB7
Found device: /dev/ttyUSB12

./find_usb_device 1e2d 0069 04
Found device: /dev/ttyACM2

udevadm
$ udevadm info --query=all --name=/dev/ttyUSB2
P: /devices/pci0000:00/0000:00:14.0/usb3/3-2/3-2:1.2/ttyUSB2/tty/ttyUSB2
N: ttyUSB2
L: 0
S: serial/by-id/usb-Telit_LE910C1-WWX_6db09e-if02-port0
S: serial/by-path/pci-0000:00:14.0-usb-0:2:1.2-port0
E: DEVPATH=/devices/pci0000:00/0000:00:14.0/usb3/3-2/3-2:1.2/ttyUSB2/tty/ttyUSB2
E: DEVNAME=/dev/ttyUSB2
E: MAJOR=188
E: MINOR=2
E: SUBSYSTEM=tty
E: ID_VENDOR_ID=1bc7
E: ID_MODEL_ID=1031
...
...
E: ID_USB_INTERFACE_NUM=02
E: ID_USB_DRIVER=option
E: ID_PATH=pci-0000:00:14.0-usb-0:2:1.2
E: ID_PATH_TAG=pci-0000_00_14_0-usb-0_2_1_2

2023年6月1日 星期四

Ping

Ping
#!/bin/sh

dns_ips=("8.8.8.8" "8.8.4.4" "1.1.1.1" "1.1.1.2")

ping_times=10
sleep_sec=10
selected_ip=""
ping_result=""
ping_dns() {
    random_index=$((RANDOM % ${#dns_ips[@]}))
    selected_ip=${dns_ips[$random_index]}

    if ping -c $ping_times $selected_ip &> /dev/null; then
        echo "Ping to $selected_ip successful!"
        ping_result="y"
    else
        echo "Ping to $selected_ip failed!"
        log_failure $selected_ip
        ping_result="n"
    fi
}

failed_ip=""
log_failure() {
    failed_ip=$1
    echo "Ping to $failed_ip failed!" >> ping_log.txt
}

while true; do
    ping_dns
    echo "sleep $sleep_sec"
    sleep $sleep_sec
    if [ "$ping_result" == "y" ]; then
        echo "Ping to $selected_ip $ping_times times successful" >> ping_log.txt
    else
        dmesg | grep -i "usb 1-1.2" -A 5 > dmesg_log.txt
    fi
done

2022年8月12日 星期五

影音書

這年代影音書都還是附CD ROM...冏
找台光碟機不容易

gio to get data from cdda://sr0
#/bin/bash

file_count=$(gio list cdda://sr0/ | wc -l)

for i in $(seq 1 $file_count)
do
        gio copy cdda://sr0/Track\ $i.wav ./
done


VOB cover to MP4
#/bin/bash
for f in /media/ubuntu/disc1/VIDEO_TS/*.VOB ;
do
   tmp=$f
   file_name=${tmp##*/}
   ffmpeg -i "$f" -b:v 3000k  -b:a 128k ~/$file_name.mp4;
done


WAV cover to MP3
轉檔後,檔名為Track 1.wav Track 2.wav
多了這個空格,煩麻…= =
#/bin/bash

list=$(find $1 -name '*.wav')
i=0
FPATH=""
FILE_NAME=""
for files in $list; 
do 
    if [ $i -eq 0 ]; then
        echo 0
        FPATH=${files%\Track}  #路徑
        echo d=$FPATH
        i=1
    else
        echo 1
        FILE_NAME=$files
        in_f=$(echo $FPATH/Track $FILE_NAME)
        out_f=$(echo $FPATH/Track ${FILE_NAME%.*})
        echo in_f=$in_f, out_f=$out_f
        ffmpeg -i "$in_f" -acodec mp3 -ab 160k -af aformat=s16:44100 "$out_f.mp3"
        i=0
    fi
done
exit 0
ref:
Ubuntu Forums

2022年8月4日 星期四

update-alternative to switch version of the command

env:
Debian update-alternatives version 1.19.7.
#!/bin/bash

function Install {
    SBUF=""

    if [ $DEBUG -eq 1 ]; then
        echo "update-alternatives"
    else
        SBUF="update-alternatives"
    fi

    # find main bin file to install
    while IFS= read -r bin_file
    do
        if [ "$bin_file" == "$1" ]; then
            if [ $DEBUG -eq 1 ]; then
                echo " --install $PATH_F/$1-$VERSION  $bin_file  $PATH_F/$1  $PRIORITY"
            else
                SBUF=$SBUF" --install $PATH_F/$1-$VERSION  $bin_file  $PATH_F/$1  $PRIORITY"
            fi
        fi
    done < <(ls $PATH_F)
    
    # find other bin file to slave
    while IFS= read -r bin_file
    do
        if [ "$bin_file" == "$1" ]; then
            continue;
        else
            if [ $DEBUG -eq 1 ]; then
                echo " --slave $PATH_F/$bin_file-$VERSION  $bin_file  $PATH_F/$bin_file"
            else
                SBUF=$SBUF" --slave $PATH_F/$bin_file-$VERSION  $bin_file  $PATH_F/$bin_file"
                #SBUF=$SBUF" bbb"
            fi
        fi
    done < <(ls $PATH_F)
    echo SBUF=$SBUF
    ${SBUF};

    #print the result
    if [ $? -eq 0 ] && [ $DEBUG -eq 0 ];then
        echo "Alreay install the $1 setting with update-alternatives"
        exit 0
    elif [ $DEBUG -eq 1 ]; then
        exit 0
    else
        echo "Error, please check again with DEBUG mode"
        exit 1
    fi

}

function Remove {
    SBUF=""

    if [ $DEBUG -eq 1 ]; then
        echo "update-alternatives --remove $1 $PATH_F/$1"
    else
        SBUF="update-alternatives --remove $1 $PATH_F/$1"
    fi

    #print the result
    if [ $? -eq 0 ] && [ $DEBUG -eq 0 ];then
        echo "Alreay remove the $1 setting with update-alternatives"
        exit 0
    elif [ $DEBUG -eq 1 ]; then
        exit 0
    else
        echo "Error, please check again with DEBUG mode"
        exit 1
    fi
}

PATH_F="/usr/lib/jvm/jdk1.7.0_25/bin"
VERSION=1.7.0.25
PRIORITY=1075

DEBUG=0 #only print the result
REMOVE=1
if [ $REMOVE -eq 1 ]; then
    Remove java
else
    Install java
fi

list
$ update-alternatives --get-selections

Display status
$ update-alternatives --display java
$ update-alternatives --query java

Switch version
$ update-alternatives --config java
ref:
1.update-alternatives︰管理指令和檔案的多個版本
2.update-alternatives-clang.sh
3.update-alternatives for clang

2022年6月5日 星期日

Add timestamp to cat output

$ awk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0; }' /dev/ttyUSB0 

$ awk '{ print strftime("%H:%M:%S"), $0; }' /dev/ttyUSB0 

$ awk '{ cmd = "date +\"%a, %b %d %Y %T.%6N\""; cmd | getline dt; close(cmd); print dt, $0; fflush(); }' /dev/ttyACM0 
save to file
$ stdbuf -oL awk '{ print strftime("%H:%M:%S"), $0; }' /dev/ttyUSB0 > file_name 

or

$ stdbuf -oL awk '{ print strftime("%H:%M:%S"), $0; }' /dev/ttyUSB0 | tee file_name


ref :
Add timestamp to cat output from shell script

2022年3月20日 星期日

Get IP for MV31-w

知識:
SNR是指信噪比,信号与噪声的比值,值越大就证明信号的功率比噪声功率大,信号质量越好。
C/N, C/No这两个是载噪声比值,一般是指GPS的射频噪声值,
C/N这个值是一般芯片或者是模块不包含发射链路的噪声值,
C/No是从信号到天线发射整条链路的噪声值,一般这两个值在模块中都有提及。
Copy it from SNR,C/N, C/N0分别是什么意思,啥啥分不清楚,请技术大拿帮忙解答下

環境: Xubunt20.04

 Get IP for MV31-W
#!/bin/bash

function cecho {
    if [ "$1" == "red" ]; then
        echo -e "\033[31m$2\033[0m"
    elif [ "$1" == "blue" ]; then
        echo -e "\033[34m$2\033[0m"
    else
        echo $2
    fi
    return 0
}

#Function to send an AT command and check the response.
function SendCommand {
    local usb_interface="$1"
    local at_command="$2"
    local response
    local line

    sleep 1 # Avoid running AT commands too fast

    echo -e "\nAT cmd: $at_command"
    echo -n -e "$at_command" >"$usb_interface"

    while IFS= read -r line <"$usb_interface"; do
        #while read line <$usb_interface; do

        if [[ "$line" == *COPS* ]]; then
            # Extract the part of the line after the last comma
            last_comma_part="${line##*,}"

            # Check if the extracted part contains 7 or 13
            if ! [[ "$last_comma_part" =~ (7|13) ]]; then
                cecho "red" "Error: AT+COPS response does not contain 7 or 13."
                exit 1
            fi
        fi
        #echo aa$response
        if [[ "$line" == *ERROR* ]]; then
            cecho "red" "Error Code: -1002, Invalid AT command"
            exit 1
        fi

        if [[ "$line" == *OK* ]]; then
            echo -e "$response" | grep -v 'OK' #Print the response without OK
            return 0
        fi

    done

    #If the loop finishes without finding OK, it means there was no OK, thus error.
    cecho "red" "Error: No OK response received for command: $at_command"
    exit 1
}

function PrepareDriver {

    local protocol=$1 # "mbim" or "qmi"
    if [ "$protocol" == "mbim" ]; then
        rv_name=("option" "usb_wwan" "usbserial" "cdc_mbim")
    elif [ "$protocol" == "qmi" ]; then
        drv_name=("option" "qmi_wwan")
    else
        cecho "red" "Error paramaters"
        exit 1
    fi

    ret=0
    for drv in ${drv_name[@]}; do
        ret=$(lsmod | grep $drv | cut -f 1 -d " ") #drv: driver
        if [ -z "$ret" ]; then
            cecho "red" "Please install the driver of \"$drv\" with modprobe"
        fi
    done
}

function CheckInterface {
    if ls "$1" >/dev/null 2>&1; then
        echo "$1"
    else
        cecho "red" "Error code: -1001, Can't find the $1" >&2
        echo ""
    fi
}

# Function to write network configuration
function write_network_config {
    local config_file=$1
    local apn=$2
    local apn_user=$3
    local apn_pass=$4
    local proxy=$5

    sudo tee $config_file >/dev/null <<EOF
APN=$apn
APN_USER=$apn_user
APN_PASS=$apn_pass
PROXY=$proxy
EOF
    if [ $? -ne 0 ]; then
        cecho "red" "Error writing to $config_file"
        exit 1
    fi
}

function install_if_missing {
    local package=$1
    local cmd=$2
    if ! type $cmd >/dev/null 2>&1; then
        cecho "blue" "Installing $package..."
        sudo apt-get install $package -y
    else
        cecho "blue" "$package is already installed."
    fi
}

function PrepareGetIP {
    local protocol=$1 # "mbim" or "qmi"
    local cdc_wdm_device
    local config_file
    local wwan0

    # Set config file and install utils based on protocol
    if [ "$protocol" == "mbim" ]; then
        config_file="/etc/mbim-network.conf"
        install_if_missing "libmbim-utils" "mbimcli"
    elif [ "$protocol" == "qmi" ]; then
        config_file="/etc/qmi-network.conf"
        install_if_missing "libqmi-utils" "qmicli"
    else
        cecho "red" "Invalid protocol: $protocol"
        exit 1
    fi

    # Install udhcpc
    install_if_missing "udhcpc" "udhcpc"

    if [ -z /dev/cdc-wdm[0-9] ]; then
        cecho "red" "Error Code: -1004, /dev/cdc-wdm* is null"
        exit 1
    else
        cdc_wdm_device=$(ls /dev/ | grep cdc)
        cdc_wdm_device=/dev/$cdc_wdm_device
    fi

    # Write network configuration
    APN="INTERNET" #CHT
    APN_USER=""
    APN_PASS=""
    PROXY="yes"
    write_network_config "$config_file" "$APN" "$APN_USER" "$APN_PASS" "$PROXY"

    # Check if /dev/cdc-wdm exists
    if [ ! -c "$cdc_wdm_device" ]; then
        cecho "red" "Error Code: -1004, $cdc_wdm_device does not exist"
        exit 1
    fi

    # Protocol-specific configuration
    if [ "$protocol" == "mbim" ]; then
        # Find wwan interface
        flag=0
        for wwan in $(ls /sys/class/net); do
            if [ -d "/sys/class/net/$wwan/device/driver" ]; then
                driver=$(basename $(realpath /sys/class/net/$wwan/device/driver))
                if [ "$driver" == "cdc_mbim" ]; then
                    flag=1
                    wwan0=$wwan
                    break
                fi
            fi
        done

        if [ "$flag" -eq 0 ]; then
            cecho "red" "Error Code: -1005, can't find wwan interface."
            exit 1
        fi

        # Get IP and connect to the Internet
        sudo ip link set "$wwan0" down
        sudo mbim-network "$cdc_wdm_device" start
        sudo mbimcli -d "$cdc_wdm_device" --device-open-proxy --query-ip-configuration
        sudo udhcpc -i "$wwan0"
        sudo ip link set "$wwan0" up

    elif [ "$protocol" == "qmi" ]; then
        # Get wwan interface
        wwan0=$(sudo qmicli -d "$cdc_wdm_device" -p --get-wwan-iface)
        if [ $? -gt 0 ]; then
            cecho "red" "Error Code: -1003, invalid wwan0 interface"
            exit 1
        fi

        # Get IP and connect to the Internet
        sudo qmicli -d "$cdc_wdm_device" --dms-set-operating-mode='online'
        sudo ip link set "$wwan0" down
        sudo tee /sys/class/net/"$wwan0"/qmi/raw_ip <<<'Y'
        sudo ip link set "$wwan0" up
        sudo qmicli -d "$cdc_wdm_device" --wda-get-data-format
        sudo qmi-network "$cdc_wdm_device" start
        sudo udhcpc -i "$wwan0"
    fi
}

function TestIP {

    #test
    sync
    sleep 3
    echo "Ping a Network for Testing Connectivity"
    ping -c 5 1.1.1.1
    if [ $? -eq 0 ]; then
        cecho "blue" "ping 1.1.1.1 successed"
    else
        cecho "red" "ping 1.1.1.1 failed"
    fi
    ping -c 5 tw.yahoo.com
    if [ $? -eq 0 ]; then
        cecho "blue" "ping tw.yahoo.com successed"
        exit 0
    else
        cecho "red" "ping tw.yahoo.com failed"
        exit 1
    fi
}

#--Help---------------------------------------------------------------------------------

Devinterface=
Open_Qxdm_RecLog=0
TEST=0
COUNTER=0
MBIM=1 #default
QMI=0

function usageExit() {
    cat >&2 <<EOF
    telit.sh - Quick link to Internet for test

    telit.sh [options]

    options:
    -h, --help                    Show this menu
    -p, --path device_path        Specify the port for AT command, such as: /dev/ttyUSB*
    -t, --test counter            Test the speed performance
    -q, --qmi                     QMI mode
    -m, --mbim                    MBIM mode (default)
EOF
    exit 0
}

function checkArgExit() {
    if [[ $# -lt 2 ]]; then
        echo "Missing argument for option $1" >&2
        usageExit
        exit 1
    fi
}

# Parse arguments
if [ $# -lt 1 ]; then
    cat >&2 <<EOF
Enter paramaters, such as:
sudo ./telit.sh -m -p /dev/ttyUSB0 for MV31,
sudo ./telit.sh -q -p /dev/ttyUSB2 for FN990,
The default mode is MBIM, please use paramater -q or -m to switch QMI/MBIM mode
EOF
    exit 0
else
    while [ -n "$1" ]; do
        case "$1" in
        -h | --help)
            usageExit
            ;;
        -q | --qmi)
            QMI=1
            MBIM=0
            shift 1
            ;;
        -m | --mbim)
            QMI=0
            shift 1
            ;;
        -p | --path)
            checkArgExit $@
            Devinterface=$2
            shift 2
            ;;
        -t | --test)
            checkArgExit $@
            COUNTER=$2
            TEST=1
            shift 2
            ;;
        -v | --version)
            echo version="1.2"
            exit
            ;;
        *)
            echo "Unknown option $1" >&2
            echo >&2
            usageExit
            ;;
        esac
    done
fi

if [ "$TEST" -eq 1 ]; then
    ii=0
    log=speedtest_log.txt
    if [ ! -f "./speedtest-cli" ]; then
        wget -O speedtest-cli https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py
        chmod +x speedtest-cli
    fi
    ret=$(whereis netperf | cut -f 2 -d " ")
    if [ "$ret" == "netperf:" ]; then
        sudo apt install netperf
    fi
    while [ $ii -lt $COUNTER ]; do
        TIMESTAMP=$(date +%Y-%m-%d_%H:%M:%S)
        ping -c 5 1.1.1.1
        echo -e "Timestamp: $TIMESTAMP, OK\n" >>$log
        if [ $? -eq 0 ]; then
            cecho "blue" "ping 1.1.1.1 successed"
            ./speedtest-cli >/tmp/speedtest_result
            cat /tmp/speedtest_result | grep "Download\|Upload\|Packet" >>$log
            echo -n -e "\r" >>$log

            echo -e "---> netperf -4 -H \"netperf-eu.bufferbloat.net\" -t TCP_MAERTS -l 10 -v 1 -P 1 "
            netperf -4 -H "netperf-eu.bufferbloat.net" -t TCP_MAERTS -l 10 -v 1 -P 1
            sleep 1

            echo -e "\n---> netperf UL test "
            echo -e "---> netperf -4 -H \"netperf-eu.bufferbloat.net\" -t TCP_STREAM -l 10 -v 1s -P 1 "
            netperf -4 -H "netperf-eu.bufferbloat.net" -t TCP_STREAM -l 10 -v 1 -P 1
            sleep 1

            sleep 60
        else
            cecho "red" "ping 1.1.1.1 failed"
            echo -e "Timestamp: $TIMESTAMP, Fail\n" >>$log
        fi
        ii=$((ii + 1))
    done
    exit 1
fi

dev=$(CheckInterface $Devinterface)
if [ -z $dev ]; then
    exit 1
fi
echo $dev

SendCommand $dev "AT+COPS?\r"
if [ "$MBIM" -eq 1 ]; then
    cecho "blue" "mbim"
    PrepareGetIP "mbim"
    PrepareDriver "mbim"
elif [ "$QMI" -eq 1 ]; then
    cecho "blue" "qmi"
    PrepareGetIP "qmi"
    PrepareDriver "qmi"
fi
TestIP

exit
如果 /dev/cdc-wdm* ( libmbim ) 一直沒有產生
systemctl disable ModemManager.service後,電腦重新開機
或是確認 cdc_mbim.ko 是否有掛載


Linux Driver:
4.9.309 support (keyword: 1e2d and 00b3)

2021年8月27日 星期五

Search keyword from library

#!/bin/bash

input="All_so_path.txt"
while IFS= read -r file;
do
    ret=$(readelf -d $file | grep -n "eisv2")
      #readelf -d $file | grep -n "libc.so"
    if [[ -n $ret ]];then
        printf '%s\n' "$file"
        echo $ret
    fi
done < "$input"

2021年8月26日 星期四

fix broken soft link

#!/bin/bash

OrigiName="AAA"
TargetName="BBB\/Projector"  #BBB/Projector


for f in $(find ./ -maxdepth 1 -type l -prune -or -name ".git" -prune )
do
    if [ ! -e "$f" ]; then
        ret=$(ls -alh $f | awk -F" " '{print $11}')
        echo "ret="$ret
        ret=$(echo "$ret" | sed -e "s/$OrigiName/$TargetName/g")
        echo "ret="$ret
        #ln -sf $ret $f #(確認好再打開)
    fi
done

2020年10月4日 星期日

iconv-改編碼

#!/bin/bash

javafile=$(find ./ -type f -name '*.java')

for files in $javafile
do
    f=${files##*/}   #檔名   (ex: a.java)
    f0=${f%.*}       #      (ex: a)
    f1=${f%.*}_iconv #      (ex: a_iconv)
    f2=${f##*.}      #副檔名 (ex: java)
    d=${files%/*}  #路徑
    #echo $d/$f0.$f2
    #echo $d/$f1.$f2
    iconv -f gbk -t utf-8 $d/$f0.$f2 > $d/$f1.$f2
    cp $d/$f1.$f2 $d/$f0.$f2
done

$(find ./ -type f -name '*_iconv*.java' | xargs rm -rf)

2020年8月20日 星期四

字串搜尋比較

run.sh
#!/bin/bash

str="Aug 20 10:34:45 cs2=home_ubuntu cs2_1234 Aug 20 10:34:45 cs2_1234 cs2=home_ubuntu12345"

ii=0
while true
do
    fstr=$(echo $str | awk -F" " '{print $argv0}' argv0=$ii)
    if [ -z "$fstr" ];
    then
        break
    fi  

    if [ ${fstr:0:4} = "cs2=" ];
    then
        echo $fstr
    fi  
    ii=$((ii+1))
    #echo "ii="$ii
done
$ time ./run.sh

cs2=home_ubuntu
cs2=home_ubuntu12345

real	0m0.033s
user	0m0.031s
sys	    0m0.011s
ref: how-do-i-use-shell-variables-in-an-awk-script

run.py
#!/bin/python3
import os
  
  def test():
  
      str="Aug 20 10:34:45 cs2=home_ubuntu cs2_1234 Aug 20 10:34:45 cs2_1234 cs2=home_ubuntu12345"
  
      fstr = str.split(" ")
  
      for i in fstr: 
          if "cs2=" in i:
              print(i)
  
  if __name__=='__main__':
       test()
$ time python3 ./run.py

cs2=home_ubuntu
cs2=home_ubuntu12345

real	0m0.027s
user	0m0.023s
sys 	0m0.004s

run.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char buf[128]="Aug 20 10:34:45 cs2=home_ubuntu cs2_1234 Aug 20 10:34:45 cs2_1234 cs2=home_ubuntu12345";
    char *target="cs2=";
    char *tmp;
    char *pch, *delim=" ";
    
    pch = strtok(buf,delim);
    for(; pch != NULL; ) 
    {
        tmp=strstr(pch, target);
        if(tmp != NULL)
        {
            printf("%s\n", tmp);
        }
        pch = strtok (NULL, delim);
    }
    return 0;
}
$ time ./run
cs2=home_ubuntu
cs2=home_ubuntu12345

real	0m0.001s
user	0m0.001s
sys	0m0.000s

2020年7月3日 星期五

Limit `nmcli dev wifi` to display one entry per unique SSID

copy it form Here

nmcli dev wifi | awk -F'  +' '{ if (!seen[$2]++) print}'
copy it form Here


others

2020年7月1日 星期三

GetMemInfo

getPIDMemInfo.sh
#!/bin/bash

get_main()
{
    #注意 awk print 有些系統是 $2 有些是 $1
    target=$(ps -ef | grep -v grep | grep $1 | awk '{print $2}')
    para1="grep -e State: -e Pid: -e Ppid: -e VmRSS: -e VmData: -e Threads:"
    para2="grep -v TracerPid:"

    for pid in $target
    do
        i=0
        if [ -d /proc/$pid ]; then
            #echo -n pid=$pid, `awk '{print $3 ", ppid="$4 ", tid_cnt="$20}' /proc/$pid/stat`
            val=$(cat /proc/$pid/status | $para1 | $para2 | awk '{print $2}')
        fi
        for ret in $val
        do
            if [ $i -eq 0 ]; then
                echo -n $ret
            elif [ $i -eq 1 ]; then
                echo -n " pid="$ret
            elif [ $i -eq 2 ]; then
                echo -n " ppid="$ret
            elif [ $i -eq 3 ]; then
                echo -n " VmRss="$(($ret/1024))"MB"
                vmrss=$ret
            elif [ $i -eq 4 ]; then
                echo -n " VmData="$(($ret/1024))"MB"
                vmdata=$ret
            elif [ $i -eq 5 ]; then
                echo -n " threads="$ret
            fi
            i=$((i+1))
        done
        echo -n -e '\t' "TotalMem="$(($(($vmrss+$vmdata))/1024))"MB"
        if [ -d /proc/$pid/fd ]; then
            echo " fd="$(ls -l /proc/$pid/fd | wc -l)
        else
            echo
        fi
    done
    echo ------
}

get_memory()
{
    ret=$(free -m | awk 'NR==3 {print "free="$4}')
    echo $ret"MB"
}


if [ $# -lt 1 ]; then
    echo "enter a execution name, ex: python3, java, chrome"
    exit
else
    echo "execution name:$1"
fi

while true;
do
    get_memory
    get_main $1
    sleep 3
done
  
./getPIDMemInfo.sh java


free 比較舊版本的格式
             total       used       free     shared    buffers     cached
Mem:           434        258        175          1          6         82
-/+ buffers/cache:        169        264
Swap:            0          0          0

ref:
1 .Linux Memory Usage 記憶體使用詳解
2. /proc/pid/stat說明
3. /proc/pid/status說明
4. 《嵌入式Linux内存使用与性能优化》笔记

2020年5月13日 星期三

Qt export 設定

目前使用到的
#!/bin/bash

export QTDIR=/opt/Qt/Qt5.12.5_guneabihf
export QML2_IMPORT_PATH=/opt/Qt/Qt5.12.5_guneabihf/qml
export QT_QPA_PLATFORM_PLUGIN_PATH=/opt/Qt/Qt5.12.5_guneabihf/plugins
export LD_LIBRARY_PATH=/opt/Qt/Qt5.12.5_guneabihf/lib
export QWS_MOUSE_PROTO=/dev/input/event0
export QT_QPA_PLATFORM=linuxfb:fb=/dev/fb0:rotation=90

######running
if [ $# -lt 1 ]; then
    echo "enter an app_name to running";
else
    $1
fi

2020年5月11日 星期一

overwrite 70-persistent-net.rules

#!/bin/bash

init="# USB device 0x:0x (rtl8723bu)"
sudo echo $init > "/etc/udev/rules.d/70-persistent-net.rules"

ii=0
if [ -f "/sys/class/net/wlan0/address" ];
then
    wlan_addr=$(</sys/class/net/wlan0/address)
else
while true
do
    if [ -f "/sys/class/net/rename$ii/address" ];
    then
        wlan_addr=$(</sys/class/net/rename$ii/address)
     break
    fi
    ii=$(($ii+1))
done
fi
rule=SUBSYSTEM=="\"net\", ACTION==\"add\", DRIVERS==\"?*\", ATTR{address}==\"$wlan_addr\", ATTR{dev_id}==\"0x0\", ATTR{type}==\"1\", KERNEL==\"wlan*\", NAME=\"wlan0\""
echo $rule
sudo echo $rule >> "/etc/udev/rules.d/70-persistent-net.rules"


if [ -f "/sys/class/net/wlan1/address" ];
then
    wlan_addr=$(</sys/class/net/wlan1/address)
else
    wlan_addr=$(</sys/class/net/p2p0/address)
fi
rule=SUBSYSTEM=="\"net\", ACTION==\"add\", DRIVERS==\"?*\", ATTR{address}==\"$wlan_addr\", ATTR{dev_id}==\"0x0\", ATTR{type}==\"1\", KERNEL==\"wlan*\", NAME=\"p2p0\""
echo $rule
sudo echo $rule >> "/etc/udev/rules.d/70-persistent-net.rules"

2020年4月8日 星期三

aplay loop

#!/bin/bash

if [ $# -lt 1 ];
then
 echo "enter a song name, format: wav, ex: happy.wav"
    exit
else
 echo "song name:$1"
fi

while true
do
    cmd=$( ps -ef | grep -v grep | grep -v $0 | grep $1 | awk '{print $2}')
    if [ "${cmd}" != "" ];
    then
        sleep 1
    else
        aplay $1 &
    fi
done

2020年4月7日 星期二

record

record...
#!/bin/bash

record()
{
    cd /home/ubuntu/
    temp=$(ls dump_*.wav | wc -l)
    count=$(($temp+1))
    echo "curr_wav:"dump_$count
    arecord -f S16_LE -r 16000 dump_$count.wav
}

record &

2019年6月25日 星期二

sox: modify RMS value for wav

安裝:
sudo apt-get install sox

audio info
soxi xxx.wav
sox xxx.wav -n stats


#!/bin/sh

if [ "$1" = "-h" ]; then
    echo " Usage:  ./test2.sh -22.99
      This will generate a new file that to modify the volume value
      "
    exit 0
fi
echo

##############  start work #############
target=$(echo | awk "{print $1}" | sed 's/-//g') #取正數
$(mkdir new_files)
for file in *.wav
do
    RMS_lev=$(sox $file -n stats 2>&1 | grep "RMS lev dB" | cut -d " " -f 7)
    echo $file="$RMS_lev"
    diff=$(echo | awk "{print $target+$RMS_lev}")
    #echo $diff
    intV=$(echo $diff | cut -d "." -f 1) #整數
    #echo $intV
    if [ $intV -lt 0 ]; then  #小於
        echo "< 0"
        a=$(echo | awk "{print $diff}" | sed 's/-//g') #取正數
        sox $file new_files/$file vol $a dB
    elif [ $intV -eq -0 ]; then
        echo "= -0"
        a=$(echo | awk "{print $diff}" | sed 's/-//g') #取正數
        sox $file new_files/$file vol $a dB
    elif [ $intV -eq 0 ]; then
        echo "= 0"
        sox $file new_files/$file vol -$diff dB
    else
        echo "> 0"
        sox $file new_files/$file vol -$diff dB
    fi  
done

sox command:
1. sox xxx.wav -n stats
2. sox xxx.wav -n stat
3. sox infile.wav outfile.wav vol 3 dB stats



ref:
1. 使用awk进行数字计算,保留指定位小数
2. stackoverflow
3. ubuntu forums

2019年6月10日 星期一

bash ps1 setting

快速設定 ps1 的格式

\u:  user name
\h:  hostname
\H:  The full hostname
\n:  Newline
\$:  for user
\#:  for root
\\:  A literal backslash "\" character

ex:
  export PS1="\h:\w~\n\\$ \[$(tput sgr0)\]"
電腦用:
  export PS1="\\033[48;5;016;38;5;010m$(tput bold)\h\\033[0m:\\033[48;5;016;38;5;012m$(tput bold)\w\\033[0m\n\$ "
minicom用:
  PS1="\\033[48;0;016;38;0;010m$(tput bold)\h\\033[0m:\\033[48;0;016;38;0;0012m$(tput bold)\w\\033[0m\n\$ "
  export LS_COLORS='rs=0:di=01;34:ln=01;36:mh=00:pi=40;33


還可以加些顏色:
\\033[48;5;foreground_color_value\\033[0m
\\033[48;5;background_color_value\\033[0m
example:
1.  echo -e "\\033[48;5;95;38;5;214mhello world\\033[0m"
2.  h:     export PS1="\\033[48;5;016;38;5;010m$(tput bold)\h\\033[0m"
3.  ~:     export PS1="\\033[48;5;016;38;5;012m$(tput bold)\w\\033[0m"



ref:
1. How To Customize Bash Prompt In Linux
2. Here (include color table)

2018年8月16日 星期四

Initializing GPIO

#!/bin/bash

#gpio33: AUX IN DET
#gpio63: AMP EN
#gpio78: DSP DET
#gpio79: AMP SD
#gpio80: AUDIO MUTE
#gpio81: DSP RST
#gpio108:Audio SW SEL1
#gpio109:Audio SW SEL2
#gpio118:WPS/RESET
#gpio120:Trigger word (blue genie)
#gpio124:LED_SDB

gpio_n=(33  63  78 79  80  81  108 109 118 120 124) #number
gpio_d=(in  out in out out out out in in  in  out) #direction
gpio_v=(0   1   0  0   0   1   1   0   0   0   0) #value

for ((i=0; i<${#gpio_n[@]}; i++)); do
    if [ -d "/sys/class/gpio/gpio${gpio_n[i]}" ]; then
        echo "The gpio${gpio_n[i]} already exists"
    else
        sudo echo ${gpio_n[i]} > /sys/class/gpio/export
        sudo echo ${gpio_d[i]} > /sys/class/gpio/gpio${gpio_n[i]}/direction
        sudo echo ${gpio_v[i]} > /sys/class/gpio/gpio${gpio_n[i]}/value
fi
done
/*nice*/