LED color based on value from spectrum range

If you want to change color of LED based on value from range, you can use this small bash function.

[/root/bin/led-color.sh]

#!/bin/bash

#$1 - min_value
#$2 - max_value
#$3 - value
function led_color {
  min_value=$1
  max_value=$2
  value=$(awk -v val="$3" -v min="${min_value}" -v max="${max_value}" 'BEGIN{print (val < min ? min : (val > max ? max : val))}')
  ratio=$(awk -v val="${value}" -v min="${min_value}" -v max="${max_value}" 'BEGIN{print 2 * (val - min) / (max - min)}')
  b1=$(awk -v r="${ratio}" 'BEGIN{print 255 * (1 - r)}')
  b=$(awk -v b="${b1}" 'BEGIN{print int(b > 0 ? b : 0)}')
  r1=$(awk -v r="${ratio}" 'BEGIN{print 255 * (r - 1)}')
  r=$(awk -v r="${r1}" 'BEGIN{print int(r > 0 ? r : 0)}')
  g=$(awk -v r="${r}" -v b="${b}" 'BEGIN{print 255 - b - r}')
  echo "$(awk -v val="${r}" 'BEGIN{printf("%02x\n",val)}')$(awk -v val="${g}" 'BEGIN{printf("%02x\n",val)}')$(awk -v val="${b}" 'BEGIN{printf("%02x\n",val)}')"
}

Example usage e.g. when you say that 5 people is maximum connected people to public wifi, you can use:

source /root/bin/led-color.sh

count=$(iw dev wlan1-1 station dump | grep -c Station 2>/dev/null)
color=$(led_color 0 5 $count)
rainbow usr2 $color enable

Function is based on python function from this post

3 Likes