public static EdInterfaceObd.InterfaceErrorResult InterfaceSetConfig(EdInterfaceObd.Protocol protocol, int baudRate, int dataBits, EdInterfaceObd.SerialParity parity, bool allowBitBang) { if (_usbPort == null) { return(EdInterfaceObd.InterfaceErrorResult.ConfigError); } if (protocol != EdInterfaceObd.Protocol.Uart) { return(EdInterfaceObd.InterfaceErrorResult.ConfigError); } try { Parity parityLocal; switch (parity) { case EdInterfaceObd.SerialParity.None: parityLocal = Parity.None; break; case EdInterfaceObd.SerialParity.Even: parityLocal = Parity.Even; break; case EdInterfaceObd.SerialParity.Odd: parityLocal = Parity.Odd; break; case EdInterfaceObd.SerialParity.Mark: parityLocal = Parity.Mark; break; case EdInterfaceObd.SerialParity.Space: parityLocal = Parity.Space; break; default: return(EdInterfaceObd.InterfaceErrorResult.ConfigError); } _usbPort.SetParameters(baudRate, dataBits, StopBits.One, parityLocal); _currentBaudRate = baudRate; _currentWordLength = dataBits; _currentParity = parity; if (!_usbPort.PurgeHwBuffers(true, true)) { return(EdInterfaceObd.InterfaceErrorResult.ConfigError); } lock (QueueLock) { ReadQueue.Clear(); } } catch (Exception) { return(EdInterfaceObd.InterfaceErrorResult.ConfigError); } return(EdInterfaceObd.InterfaceErrorResult.NoError); }
public void Open(int bufferSize = DEFAULT_BUFFERSIZE) { if (disposed) { throw new ObjectDisposedException(GetType().Name); } if (IsOpen) { throw new InvalidOperationException(); } var connection = _usbManager.OpenDevice(port.Driver.Device); 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(); buffer = null; isOpen = false; Log.Info(TAG, "Task Ended!"); } }, cancelationToken); }
private void StartBotClicked(object sender, EventArgs e) { serialAttached = true; manager = (UsbManager)GetSystemService(Context.UsbService); driver = UsbSerialProber.DefaultProber.FindAllDrivers(manager)[0]; port = driver.Ports[0]; var connection = manager.OpenDevice(driver.Device); port.Open(connection); port.SetParameters(9600, 8, StopBits.One, Parity.None); ip = text.Text; Thread t = new Thread(x => tcpCommunication()); t.Start(); udp = new UDPCommunication(ip, 4815); mc.start(); }
public virtual void Run(UsbManager usbManager) { if (usbManager == null) { throw new ArgumentNullException(nameof(usbManager)); } if (_isDisposed) { throw new ObjectDisposedException(nameof(PortManager)); } // ReSharper disable once RedundantAssignment bool startRunning = false; lock (_stateLocker) { if (GetCurrentState() != ManagerState.Stopped) { throw new InvalidOperationException("Already running."); } else { _managerState = ManagerState.Running; startRunning = true; } } // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (startRunning) { try { UsbDeviceConnection connection = usbManager.OpenDevice(_port.Driver.Device); if (connection == null) { throw new UsbSerialException("Failed to connect to device."); } _portBuffer = new byte[BufferSize]; _port.Open(connection); _port.SetParameters(BaudRate, DataBits, StopBits, Parity); _runCancellationSource = new CancellationTokenSource(); CancellationToken runCancellationToken = _runCancellationSource.Token; runCancellationToken.Register(() => Log.Info(nameof(PortManager), "Cancellation Requested")); Task.Run(() => { Log.Info(nameof(PortManager), "Running .."); try { bool isRunning; do { ManagerState currentState; lock (_stateLocker) { isRunning = ((currentState = GetCurrentState()) == ManagerState.Running); } if (isRunning) { runCancellationToken.ThrowIfCancellationRequested(); Step(); } else { Log.Info(nameof(PortManager), $"Stopping mState={currentState}"); } } while (isRunning); } catch (OperationCanceledException) { throw; } catch (Exception e) { Log.Warn(nameof(PortManager), $"Task ending due to exception: {e.Message}", e); ErrorReceived.RaiseEvent(this, new UnhandledExceptionEventArgs(e, false)); } finally { _port.Close(); _portBuffer = null; lock (_stateLocker) { _managerState = ManagerState.Stopped; Log.Info(nameof(PortManager), "Stopped."); } } }, runCancellationToken); } catch (Exception e) { lock (_stateLocker) { _managerState = ManagerState.Stopped; Log.Info(nameof(PortManager), "Stopped."); } Log.Warn(nameof(PortManager), $"Run ending due to exception: {e.Message}", e); ErrorReceived.RaiseEvent(this, new UnhandledExceptionEventArgs(e, false)); } } }
public static bool InterfaceConnect(string port, object parameter) { if (_usbPort != null) { return(true); } try { _connectPort = port; _connectParameter = parameter; if (!(parameter is ConnectParameterType connectParameter)) { return(false); } if (!port.StartsWith(PortId, StringComparison.OrdinalIgnoreCase)) { InterfaceDisconnect(); return(false); } List <IUsbSerialDriver> availableDrivers = GetDriverList(connectParameter.UsbManager); if (availableDrivers.Count <= 0) { InterfaceDisconnect(); return(false); } string portData = port.Remove(0, PortId.Length); int portIndex = -1; if ((portData.Length > 0) && (portData[0] == ':')) { // special id if (portData.StartsWith(":SER=", StringComparison.OrdinalIgnoreCase)) { // serial number string id = portData.Remove(0, 5); int index = 0; foreach (IUsbSerialDriver serialDriver in availableDrivers) { if (serialDriver.Ports[0] != null && string.Compare(serialDriver.Ports[0].Serial, id, StringComparison.Ordinal) == 0) { portIndex = index; break; } index++; } } } else { portIndex = Convert.ToInt32(port.Remove(0, PortId.Length)); } if ((portIndex < 0) || (portIndex >= availableDrivers.Count)) { InterfaceDisconnect(); return(false); } IUsbSerialDriver driver = availableDrivers[portIndex]; UsbDeviceConnection connection = connectParameter.UsbManager.OpenDevice(driver.Device); if (connection == null) { InterfaceDisconnect(); return(false); } if (driver.Ports.Count < 1) { InterfaceDisconnect(); return(false); } _usbPort = driver.Ports[0]; _usbPort.Open(connection); _usbPort.SetParameters(9600, 8, StopBits.One, Parity.None); if (_usbPort is FtdiSerialDriver.FtdiSerialPort ftdiPort) { ftdiPort.LatencyTimer = LatencyTime; if (ftdiPort.LatencyTimer != LatencyTime) { InterfaceDisconnect(); return(false); } } _currentWordLength = 8; _currentParity = EdInterfaceObd.SerialParity.None; _usbPort.DTR = false; _usbPort.RTS = false; lock (QueueLock) { ReadQueue.Clear(); } _serialIoManager = new SerialInputOutputManager(_usbPort); _serialIoManager.DataReceived += (sender, e) => { lock (QueueLock) { foreach (byte value in e.Data) { ReadQueue.Enqueue(value); } DataReceiveEvent.Set(); } }; _serialIoManager.Start(UsbBlockSize); if (_currentBaudRate != 0 && _currentWordLength != 0) { if (InterfaceSetConfig(EdInterfaceObd.Protocol.Uart, _currentBaudRate, _currentWordLength, _currentParity, false) != EdInterfaceObd.InterfaceErrorResult.NoError) { InterfaceDisconnect(); return(false); } InterfaceSetDtr(_currentDtr); InterfaceSetRts(_currentRts); } Ediabas?.LogString(EdiabasNet.EdLogLevel.Ifh, "Connected"); _reconnectRequired = false; } catch (Exception) { InterfaceDisconnect(); return(false); } return(true); }
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.Driver.Device); 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 (holdWhile) { Thread.Sleep(7000); //new line cancelationToken.ThrowIfCancellationRequested(); sending(); //sending data (new line) Step(); // execute comming data /////////////////////////new line///////////////////////////////////////// ConnectivityManager ConnectivityManager = (ConnectivityManager)Application.Context.GetSystemService(Context.ConnectivityService); NetworkInfo conn = ConnectivityManager.ActiveNetworkInfo; if (conn == null || !conn.IsConnected) { holdWhile = false; } ////////////////////////////////////////////////////////////////////////////// } } 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(); buffer = null; isOpen = false; Log.Info(TAG, "Task Ended!"); } }, cancelationToken); }
public void OnClick(View v) { if (v.Id == btn_Connect.Id) { manager = (UsbManager)GetSystemService(UsbService); IList <IUsbSerialDriver> availableDrivers = UsbSerialProber.DefaultProber.FindAllDrivers(manager); if (availableDrivers.Count == 0) { tv_Info.Append("No devices found"); } else { // Open a connection to the first available driver. PendingIntent mPermissionIntent = PendingIntent.GetBroadcast(this, 0, Intent.SetAction("ACTION_USB_PERMISSION"), 0); driver = availableDrivers[0]; manager.RequestPermission(driver.Device, mPermissionIntent); connection = manager.OpenDevice(driver.Device); if (connection == null) { tv_Info.Append("You probably need to call UsbManager.requestPermission(driver.getDevice(), ..)"); } else { port = driver.Ports[0]; tv_Info.Append("Connected to USB"); port.Open(connection); port.SetParameters(9600, 8, StopBits.One, Parity.None); byte[] bytes = new byte[1024]; port.Read(bytes, 1000); } } ThreadPool.QueueUserWorkItem(delegate(object state) { while (connection != null) { try { byte[] readBuffer = new byte[1024]; int message = port.Read(readBuffer, readBuffer.Length); string input = Encoding.ASCII.GetString(readBuffer, 0, message); if (input != "") { RunOnUiThread(() => { tv_Info.Text = input; }); } } catch (TimeoutException e) { // Console.WriteLine(e.ToString()); } } }, null); } else if (v.Id == btn_Send.Id) { try { //port.SetParameters(115200, 8, StopBits.One, Parity.None); byte[] buffer = Encoding.ASCII.GetBytes(et_SendToServer.Text); int numBytesRead = port.Write(buffer, 1024); } catch (IOException e) { tv_Info.Append(e.ToString()); } } else if (v.Id == btn_Disconnect.Id) { port.Close(); } else if (v.Id == btn_clear.Id) { tv_Info.Text = null; } }