UPSTREAM: rmi4update: Make sure the device file exists when rebinding the driver

The /dev/hidrawX device may not exist immediately after writing to
the bind file. This change checks to see if it exists before attempting
to reopen the device.

(cherry picked from commit 8336b9c19bbf2adad93a4e193cd9258cf3fc7d0d)
Signed-off-by: Benson Leung <bleung@google.com>

Bug: 24809436

Change-Id: I02a662a2fc38e93df32190c03f35a1db3640f451
diff --git a/rmidevice/hiddevice.cpp b/rmidevice/hiddevice.cpp
index 8ea35da..7ebf5fd 100644
--- a/rmidevice/hiddevice.cpp
+++ b/rmidevice/hiddevice.cpp
@@ -567,6 +567,9 @@
 	std::string bindFile;
 	std::string unbindFile;
 	std::string hidrawFile;
+	struct stat stat_buf;
+	int rc;
+	int i;
 
 	Close();
 
@@ -608,7 +611,17 @@
 		return;
 	}
 
-	Open(hidrawFile.c_str());
+	for (i = 0; i < 200; i++) {
+		rc = stat(hidrawFile.c_str(), &stat_buf);
+		if (!rc)
+			break;
+		Sleep(5);
+	}
+
+	rc = Open(hidrawFile.c_str());
+	if (rc)
+		fprintf(stderr, "Failed to open device (%s) during rebind: %d: errno: %s (%d)\n",
+				hidrawFile.c_str(), rc, strerror(errno), errno);
 }
 
 bool HIDDevice::FindTransportDevice(int bus, std::string & hidDeviceName,