zsh_mswitch
authorBernhard Tittelbach <xro@realraum.at>
Wed, 4 Dec 2013 07:45:16 +0000 (07:45 +0000)
committerBernhard Tittelbach <xro@realraum.at>
Wed, 4 Dec 2013 07:45:16 +0000 (07:45 +0000)
raspberrypi_gpio_relay_licht/mswitch.cgi

index dbfc79a..adf1d19 100755 (executable)
@@ -1,16 +1,14 @@
-#!/bin/sh
+#!/bin/zsh
 
-VALID_ONOFF_IDS="4 17 18 21 22 23"
+VALID_ONOFF_IDS=(4 17 18 21 22 23)
 GPIOPATH=/sys/class/gpio/gpio
-
+local -A GPIOS
 for QUERY in `echo $QUERY_STRING | tr '&' ' '`; do
   for VALIDID in $VALID_ONOFF_IDS; do
     if [ "$QUERY" = "$VALIDID=1" ]; then
-      eval "GPIO_$VALIDID"=1
+      GPIOS[$VALIDID]=1
     elif [ "$QUERY" = "$VALIDID=0" ]; then
-      eval "GPIO_$VALIDID=0"
-    elif [ "$QUERY" = "$VALIDID=q" ]; then
-      eval "GPIO_$VALIDID=q"
+      GPIOS[$VALIDID]=0
     fi
   done
   if [ "$QUERY" = "mobile=1" ]; then
@@ -24,7 +22,7 @@ done
 
 print_gpio_state() {
   GPIOVALUE=$(cat "${GPIOPATH}${1}/value")
-  if [ "$GPIOVALUE" = "0" ]; then
+  if [[ $GPIOVALUE == "0" ]]; then
     echo -n "true"
   else
     echo -n "false"
@@ -39,24 +37,17 @@ gpio_is_on() {
 echo "Content-type: text/html"
 echo ""
 
-echo "{"
+local -a GPIOSTATES
 for CHECKID in $VALID_ONOFF_IDS; do
-  VAL=""
-  VAL="$(eval echo \$GPIO_$CHECKID)"
-  [ -z $VAL ] && continue
-  if [ $VAL = 1 -o $VAL = 0 ]; then
-    [ $VAL = 1 ] && VAL=0 || VAL=1
+  VAL=$GPIOS[$CHECKID]
+  if [[ $VAL == 1 || $VAL == 0 ]]; then
+    [[ $VAL == 1 ]] && VAL=0 || VAL=1
     echo "$VAL" > "${GPIOPATH}${CHECKID}/value"
   fi
-  echo -n "\"$CHECKID\":"
-  print_gpio_state $CHECKID
-  echo ","
+  GPIOSTATES+=(\"${CHECKID}\":"$(print_gpio_state $CHECKID)")
 done
-echo "\"-1\":false}"
-#      echo "<html>"
-#      echo "<head>"
-#      echo "<title>Realraum Relay Switch</title>"
-#      echo '<script type="text/javascript">window.location="/cgi-bin/switch.cgi";</script>'
-#      echo "</head></html>"
-#      exit 0
-
+JSON_STATE="{${(j:,:)GPIOSTATES}}"
+print ${(q)JSON_STATE}
+if ((#GPIOS > 0)); then
+  print "[$(date +%s),\"$REMOTE_ADDR\",${(q)JSON_STATE}]," >> /var/log/licht/mswitch.log
+fi