Skip to content

Instantly share code, notes, and snippets.

@kairos34
Created October 25, 2021 11:45
Show Gist options
  • Save kairos34/ffa549dd0a010ffed810811df24daf5f to your computer and use it in GitHub Desktop.
Save kairos34/ffa549dd0a010ffed810811df24daf5f to your computer and use it in GitHub Desktop.
Reset MCU
private val rebootCodesArray = intArrayOf(-1500, -1501, -1502, -4010)
private val resetMcuInterval = 25000
private var isReOpenDevice = false
private var lastResetTime = 0L
//Check error code after calling checkCardEx(buffer) and if there is a error reset it
//////// This block has to be called after checkCardEx(buffer)
(errorCode != -4013).ifTrue {
"Error $errorCode checking card ID".log(TAG)
}
(rebootCodesArray.contains(errorCode) && !isReOpenDevice).ifTrue {
resetMcu()
killMyself(errorCode)
}
////////////////////////////////////////////////////////////////
private fun resetMcu() {
if (SystemClock.elapsedRealtimeNanos() - lastResetTime > resetMcuInterval) {
var mcuUsbPath = "/dev/bus/usb/001/006"
val usbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager
for (usbDevice in usbManager.deviceList.values) {
if (usbDevice.vendorId == 1155 && usbDevice.productId == 22304) {
Log.i("MCU", "mcu path :${usbDevice.deviceName}")
mcuUsbPath = usbDevice.deviceName
break
}
}
try {
val ret = JniUsbController.resetUsb(mcuUsbPath)
Log.i(TAG, "usbReset $mcuUsbPath: "
+ if (ret) "success" else "failed")
} catch (e: Exception) {
//if catch the exception ,do reset directly
val directRet = JniUsbController.resetUsbDevice(mcuUsbPath)
Log.e(TAG, "direct reset usb $mcuUsbPath: $directRet")
e.printStackTrace()
} finally {
lastResetTime = SystemClock.elapsedRealtimeNanos()
}
} else {
Log.e(TAG, "The two intervals of reset mcu are too short")
}
}
private fun killMyself(code: Int) {
isReOpenDevice = true
val log = "MCU has error , error code $code kill myself"
Log.e(TAG, log)
execCommands("kill " + Process.myPid())
isReOpenDevice = false
}
/// This function comes from our library which was written JAVA it can be converted kotlin easily
public static int execCommands(final String... commands) throws IOException {
int result = 1;
final Runtime runTime = Runtime.getRuntime();
final Process process = runTime.exec("su");
final DataOutputStream os = new DataOutputStream(
process.getOutputStream());
try {
for (int i = 0; i < commands.length; i++) {
os.writeBytes(commands[i] + "\n");
os.flush();
}
os.writeBytes("exit\n");
os.flush();
process.waitFor();
result = process.exitValue();
Log.d(TAG, "process result is " + result);
} catch (final InterruptedException e) {
return result;
} finally {
os.close();
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment