public async Task <bool> Open(int baudRate) { Console.WriteLine("Getting permission"); var perm = await usbManager.RequestPermissionAsync(port.Driver.Device, ctx); if (perm) { try { conn = usbManager.OpenDevice(port.Driver.Device); port.Open(conn); port.SetParameters(baudRate, 8, StopBits.One, Parity.None); port.SetDTR(true); new Handler(Looper.MainLooper).Post(() => { Toast.MakeText(ctx, "Serial connected", ToastLength.Short).Show(); }); } catch (Java.IO.IOException) { // TODO: Handle this throw; } return(true); } else { return(false); } }
public void Open(UsbManager usbManager, int bufferSize = DEFAULT_BUFFERSIZE) { if (disposed) { throw new ObjectDisposedException(GetType().Name); } if (IsOpen) { throw new InvalidOperationException(); } var connection = usbManager.OpenDevice(port.GetDriver().GetDevice()); if (connection == null) { throw new Java.IO.IOException("Failed to open device"); } isOpen = true; buffer = new byte[bufferSize]; port.Open(connection); port.SetParameters(BaudRate, DataBits, StopBits, Parity); cancelationTokenSource = new CancellationTokenSource(); var cancelationToken = cancelationTokenSource.Token; cancelationToken.Register(() => Log.Info(TAG, "Cancellation Requested")); Task.Run(() => { Log.Info(TAG, "Task Started!"); try { while (true) { cancelationToken.ThrowIfCancellationRequested(); Step(); // execute step } } catch (OperationCanceledException) { throw; } catch (Exception e) { Log.Warn(TAG, "Task ending due to exception: " + e.Message, e); ErrorReceived.Raise(this, new UnhandledExceptionEventArgs(e, false)); } finally { port.Close(); port.Driver.Device.Dispose();//richard: avoid GREF leak buffer = null; isOpen = false; Log.Info(TAG, "Task Ended!"); } }, cancelationToken); }