scripts: add support script for 'make flash' over DFU

Flashing the Arduino 101 board over DFU can be tricky: the
dfu-util command line is cumbersome, and the reset button
must be pressed at the right time.

This script brings the convenience of 'make flash' for the
Arduino 101 board and for other boards that support the DFU
protocol. It checks whether the board is in DFU mode, and
prompts the user to reset it when needed.

The dfu-util command line is constructed from the following
environment variables, to be exported from the Makefile:
- DFUUTIL: path to the dfu-util executable, default: dfu-util
- DFUUTIL_PID: vendor_ID:product_ID of the board in DFU mode
- DFUUTIL_ALT: alternate setting name of the DFU interface
- DFUUTIL_IMG: path to the binary image sent to the board

Change-Id: Ia9577ec96102a92d4c60481f980f30f4f6e7cd9e
Signed-off-by: Patrice Buriez <patrice.buriez@intel.com>
diff --git a/scripts/support/dfuutil.sh b/scripts/support/dfuutil.sh
new file mode 100755
index 0000000..feac1a8
--- /dev/null
+++ b/scripts/support/dfuutil.sh
@@ -0,0 +1,64 @@
+#!/bin/sh
+
+# This script is inspired from ./openocd.sh, and from both flash_dfu.sh and
+# fwversion.sh, included in arduino101-factory_recovery-flashpack.tar.bz2,
+# which is available from https://downloadcenter.intel.com/download/25470
+
+DFUUTIL_EXE=${DFUUTIL:-dfu-util}
+DFUUTIL_CMD="$DFUUTIL_EXE -d,$DFUUTIL_PID"
+
+test_exe() {
+    if ! which $DFUUTIL_EXE >/dev/null 2>&1; then
+        echo "Error: Unable to locate dfu-util executable: $DFUUTIL_EXE"
+        exit 1
+    fi
+}
+
+test_img() {
+    if [ ! -f "$DFUUTIL_IMG" ]; then
+        echo "Error: Unable to locate binary image: $DFUUTIL_IMG"
+        exit 1
+    fi
+}
+
+find_dfu() {
+    $DFUUTIL_CMD -l |grep "$DFUUTIL_ALT" >/dev/null 2>&1
+}
+
+do_flash() {
+    test_exe
+    test_img
+
+    # Wait until DFU device is ready
+    reset_dfu=0
+    if ! find_dfu; then
+        reset_dfu=1
+        echo "Please reset your board to switch to DFU mode..."
+        until find_dfu; do
+            sleep 0.1
+        done
+    fi
+
+    # Flash DFU device with specified image
+    # Do NOT reset with -R, to avoid random 'error resetting after download'
+    $DFUUTIL_CMD -a $DFUUTIL_ALT -D $DFUUTIL_IMG
+    ok=$?
+    if [ $ok -eq 0 -a $reset_dfu -eq 1 ]; then
+        echo "Now reset your board again to switch back to runtime mode."
+    fi
+    return $ok
+}
+
+CMD=$1
+shift
+
+case "$CMD" in
+  flash)
+    do_flash "$@"
+    ;;
+  *)
+    echo "Unsupported command '$CMD'"
+    exit 1
+    ;;
+esac
+