dots

git clone git://mattcarlson.org/repos/dots.git
Log | Files | Refs

cpu.sh (2064B)


      1 #!/bin/sh
      2 #
      3 # cpu
      4 
      5 LOAD_ICON=''
      6 TEMP_EMPTY_ICON=''
      7 TEMP_QUARTER_ICON=''
      8 TEMP_HALF_ICON=''
      9 TEMP_THREE_QUARTERS_ICON=''
     10 TEMP_FULL_ICON=''
     11 
     12 # approx delay with top alternative
     13 DELAY=3.15
     14 
     15 # thermal zone for temp differs on machine
     16 hostname='/etc/hostname'
     17 if [ -f "${hostname}" ]; then
     18     if [ "$(cat "${hostname}")" = 'laptop' ]; then
     19         TEMP="$(ls /sys/class/thermal/thermal_zone2*/temp)"
     20     elif [ "$(cat "${hostname}")" = 'pc' ]; then
     21         TEMP="$(ls /sys/class/thermal/thermal_zone0*/temp)"
     22     fi
     23 fi
     24 
     25 # cache used b/c awk and delay is time expensive
     26 USAGE="${XDG_CACHE_HOME:-${HOME}/.cache/}/dots/bar/usage"
     27 
     28 calculate_temp() {
     29     [ -f "${TEMP}" ] && temp=$(cat "${TEMP}")
     30     # convert millidegree celsius to celsius
     31     temp=$((temp/1000))
     32 }
     33 
     34 calculate_usage() {
     35     # perform math on cpu numbers from /proc/stat to get usage
     36     printf '%s\n' "$({ cat /proc/stat; sleep "${DELAY}"; cat /proc/stat; } |
     37         awk '/^cpu / { usr=$2-usr; sys=$4-sys; idle=$5-idle; iow=$6-iow }
     38         END { total=usr+sys+idle+iow; printf "%.0f\n", (total-idle)*100/total }')" > "${USAGE}"
     39 }
     40 
     41 # top ten intensive processes
     42 get_procs() { procs="$(ps -eo comm,%cpu | sort -k 2 -n -r | head | tail | sed 's/$/%/')" ; }
     43 
     44 get_usage() { [ -f "${USAGE}" ] && usage=$(cat "${USAGE}") ; }
     45 
     46 bar() {
     47     # temp
     48     calculate_temp
     49     case ${temp} in
     50         [0-9][0-9][0-9]*)  TEMP_ICON="${TEMP_FULL_ICON}"           ;;
     51         7[5-9]|[8-9][0-9]) TEMP_ICON="${TEMP_THREE_QUARTERS_ICON}" ;;
     52         [5-6][0-9]|7[0-4]) TEMP_ICON="${TEMP_HALF_ICON}"           ;;
     53         [0-4][0-9])        TEMP_ICON="${TEMP_QUARTER_ICON}"        ;;
     54         0)                 TEMP_ICON="${TEMP_EMPTY_ICON}"          ;;
     55     esac
     56 
     57     calculate_usage &
     58 
     59     get_usage
     60 
     61     # print load in percentage and temp in celsius
     62     printf '%s\n' "${LOAD_ICON} ${usage}% ${TEMP_ICON} ${temp}°C"
     63 }
     64 
     65 main() {
     66     # called from bar
     67     [ ${#} -eq 0 ] && bar
     68 
     69     # bar usage
     70     case ${BLOCK_BUTTON} in
     71         1) get_procs
     72            herbe "${procs}"
     73            ;;
     74     esac
     75 }
     76 
     77 main "${@}"