meta-bletchley: motor-ctrl: Add retry and error handle to motor-init service

1. While motor-init-calibration@.service fail,retry to start service with maximum count 5 times.
2. In case of service unexpected stopped while motor is running, add stop motor
command after service stopped to avoid motor runs forever.
3. Add sled present check in motor-ctrl tool

Change-Id: Ie636f3a7dbf656f8ea577bfffed150171f7f07be
Signed-off-by: Allen.Wang <Allen_Wang@quantatw.com>
diff --git a/meta-facebook/meta-bletchley/recipes-bletchley/motor-ctrl/files/motor-ctrl b/meta-facebook/meta-bletchley/recipes-bletchley/motor-ctrl/files/motor-ctrl
index 302c94b..d74909c 100755
--- a/meta-facebook/meta-bletchley/recipes-bletchley/motor-ctrl/files/motor-ctrl
+++ b/meta-facebook/meta-bletchley/recipes-bletchley/motor-ctrl/files/motor-ctrl
@@ -20,6 +20,23 @@
     return 0
 }
 
+function get_gpio()
+{
+    NET_NAME=$1
+    RET_VAL=2
+
+    mapfile -t -d " " GPIO_INFO < <(gpiofind "$NET_NAME")
+    if [ "${#GPIO_INFO[@]}" -ne 2 ]; then
+        echo "get_gpio: can not find gpio, $NET_NAME" >&2
+        return 1
+    fi
+    if ! RET_VAL=$(gpioget "${GPIO_INFO[0]}" "${GPIO_INFO[1]%$'\n'}") ; then
+        echo "get_gpio: get ${NET_NAME} failed" >&2
+        return 1
+    fi
+    echo "${RET_VAL}"
+    return 0
+}
 #######################################
 # Setting step motor control pins to start/stop motor
 # Arguments:
@@ -61,6 +78,13 @@
     exit 1;
 fi
 
+#Check if sled is present
+SLED_PRESENT=$(get_gpio "presence-sled${SLED_NUM}")
+if [ "$SLED_PRESENT" != 0 ];then
+    echo "${SLED} is not present!"
+    exit 1
+fi
+
 if [[ "$ACTION" == "s" ]]; then
     echo "stop motor"
     set_motor "$SLED_NUM" 1 0 0 1
diff --git a/meta-facebook/meta-bletchley/recipes-bletchley/motor-ctrl/files/motor-init-calibration@.service b/meta-facebook/meta-bletchley/recipes-bletchley/motor-ctrl/files/motor-init-calibration@.service
index aab61b7..41f81c2 100644
--- a/meta-facebook/meta-bletchley/recipes-bletchley/motor-ctrl/files/motor-init-calibration@.service
+++ b/meta-facebook/meta-bletchley/recipes-bletchley/motor-ctrl/files/motor-init-calibration@.service
@@ -1,11 +1,16 @@
 [Unit]
 Description=Motor Initialize for sled%i
+StartLimitIntervalSec=90
+StartLimitBurst=5
 
 [Service]
 ExecStart=/usr/libexec/motor-init sled%i
 SyslogIdentifier=Motor Initialize sled%i
 Type=oneshot
 RemainAfterExit=yes
+ExecStopPost=/usr/libexec/motor-ctrl sled%i s
+Restart=on-failure
+RestartSec=1
 
 [Install]
 WantedBy=multi-user.target