#!/bin/bash /etc/rc.common
# par shtroumfarceur avec l'aide de youpi
#
#
# 				- script pour leds des nanostations sous Openwrt -
#
#
# ! -> opkg install bash; opkg install iwinfo; 
# (iwinfo pour les AP: cat /proc/net/wireless ne renvoi rien)	#	#	#	#	#	#	#

START=97
USE_PROCD=1


	start_service() {

		logger starting script4leds.sh   

		Led_On() { 
			  echo 1 > /sys/class/leds/$1/brightness 
		}
		Led_Off() {
			  echo 0 > /sys/class/leds/$1/brightness
		}

		md=$(cat /etc/config/wireless | grep -i "option mode") 
		if [ ${md:13:5} == "'sta'" ]; then mode=station;
		else mode=ap;
		fi
	
# 	pour adapter au nombre de leds:
		tbl=( `ls /sys/class/leds | grep "ubnt" | sed 's/\([^0-9]*\)\([0-9]*\)/\2\1/' | sort -n | sed 's/\([0-9]*\)\([^0-9]*\)/\2\1/'` )
		NBR_LEDS=${#tbl[*]}
		y=-110;			# de -110dBm à -40dBm  
		x=$((70/$NBR_LEDS))	# donc notation sur /70 

# 	tableau indexé sur le signal: 
		declare -A array
		j=-110
		for (( i=1; i<=$NBR_LEDS; i++ ))
		do
			y=$(( $y+$x ))
			for (( j; j<=y; j++ ))
			do
				array[$j]=$i;  
			done
		done

#	et la boucle:	
		while true 
		do
	
		if [ $mode == "station" ]; then SIGNAL=`cat /proc/net/wireless | awk 'NR==3 {print $4}' | sed 's/\.//'`;
		else info=$(iwinfo wlan0 info | grep -i signal); SIGNAL=${info:18:3};
		fi

		if [ -z $SIGNAL ] || [ $SIGNAL == "unk" ]; then STRENGTH=0;  
		elif [ $SIGNAL -ge 0 ]; then STRENGTH=0; 
		else STRENGTH=${array[$SIGNAL]};
		fi
	
		if [ "$OLD_STRENGTH" != "$STRENGTH" ] 
		then
		for (( i=0; i < STRENGTH; i++ ))
		do
			  Led_On ${tbl[$i]};
		done
		for (( i=NBR_LEDS - 1; i - STRENGTH >= 0; i-- ))
		do
			  Led_Off ${tbl[$i]};
		done 
		echo "STRENGTH (0-4): $STRENGTH"
		fi
		OLD_STRENGTH=$STRENGTH

		sleep 1
		done
	}
