LEDSTRIPS="esp-mainroom-leds.base48.cz esp-srk-leds.base48.cz esp-basestation-leds.base48.cz"
LEDDELAY=0.3
STATE=~/.bashrc_leds-state

export LEDSDEFAULTCOLOR="255,32,32"

leds-color-save(){
	> $STATE
	for ledstrip in $LEDSTRIPS; do
		TRY=$(timeout 0.7 bash -c "exec 3<>/dev/tcp/$ledstrip/23;
		echo \"get()\" >&3; sleep 0.1;
		head -n3 <&3;")
		if [ "$TRY" != "" ]; then
			set $TRY
			echo $ledstrip $1,$2,$3 >> $STATE
		fi
	done
}

leds-color-restore(){
	cat $STATE | while read line; do
		set $line
		leds-set-color $1 $2
	done
}


leds-set-color(){
	STRIP=$1
	shift
	timeout 0.2 bash -c "echo \"go($*)\" > /dev/tcp/$STRIP/23"
}

leds-set-color-all(){
	for ledstrip in $LEDSTRIPS; do
		leds-set-color $ledstrip $*
	done
}

leds-blink-with-color(){
	leds-set-color $*
	sleep $LEDDELAY
	leds-set-color-all 0,0,0
	sleep $LEDDELAY
	leds-set-color $LEDSDEFAULTCOLOR
}


leds-blink-with-color-all(){
	COLOR=${1:-"0,255,0"}
	leds-color-save

	leds-set-color-all 0,0,0
	sleep $LEDDELAY
	leds-set-color-all $COLOR
	sleep $LEDDELAY
	leds-set-color-all 0,0,0
	sleep $LEDDELAY
	leds-set-color-all $COLOR
	sleep $LEDDELAY
	leds-set-color-all 0,0,0
	sleep $LEDDELAY
	
	leds-color-restore
}

leds-blink-red-all(){
	leds-blink-with-color-all 255,0,0
}

leds-blink-green-all(){
	leds-blink-with-color-all 0,255,0
}

leds-eval(){
	$*
	if [ "$?" == "0" ]; then
		leds-blink-green-all
	else
		leds-blink-red-all
	fi
}