protected async override void OnResume()
        {
            Log.Info(TAG, "OnResume");

            base.OnResume();

            var portInfo   = Intent.GetParcelableExtra(EXTRA_TAG) as UsbSerialPortInfo;
            int vendorId   = portInfo.VendorId;
            int deviceId   = portInfo.DeviceId;
            int portNumber = portInfo.PortNumber;

            Log.Info(TAG, string.Format("VendorId: {0} DeviceId: {1} PortNumber: {2}", vendorId, deviceId, portNumber));

            var drivers = await DeviceListActivity.FindAllDriversAsync(usbManager);

            var driver = drivers.Where((d) => d.Device.VendorId == vendorId && d.Device.DeviceId == deviceId).FirstOrDefault();

            if (driver == null)
            {
                throw new Exception("Driver specified in extra tag not found.");
            }

            port = driver.Ports [portNumber];
            if (port == null)
            {
                titleTextView.Text = "No serial device.";
                return;
            }
            Log.Info(TAG, "port=" + port);

            titleTextView.Text = "Serial device: " + port.GetType().Name;

            serialIoManager = new SerialInputOutputManager(port)
            {
                BaudRate = 115200,
                DataBits = 8,
                StopBits = StopBits.One,
                Parity   = Parity.None,
            };
            serialIoManager.DataReceived += (sender, e) => {
                RunOnUiThread(() => {
                    UpdateReceivedData(e.Data);
                });
            };
            serialIoManager.ErrorReceived += (sender, e) => {
                RunOnUiThread(() => {
                    var intent = new Intent(this, typeof(DeviceListActivity));
                    StartActivity(intent);
                });
            };

            Log.Info(TAG, "Starting IO manager ..");
            try {
                serialIoManager.Open(usbManager);
            }
            catch (Java.IO.IOException e) {
                titleTextView.Text = "Error opening device: " + e.Message;
                return;
            }
        }
 public static bool InterfaceDisconnect()
 {
     try
     {
         if (_serialIoManager != null)
         {
             _serialIoManager.Stop();
             _serialIoManager.Dispose();
             _serialIoManager = null;
         }
         if (_usbPort != null)
         {
             _usbPort.Close();
             _usbPort.Dispose();
             _usbPort = null;
         }
         lock (QueueLock)
         {
             ReadQueue.Clear();
         }
     }
     catch (Exception)
     {
         return(false);
     }
     return(true);
 }
        public UsbSerialPortInfo(IUsbSerialPort port)
        {
            var device = port.Driver.Device;

            VendorId   = device.VendorId;
            DeviceId   = device.DeviceId;
            PortNumber = port.PortNumber;
        }
        //public ParcelablePortInfo()
        //{
        //}

        internal ParcelablePortInfo(IUsbSerialPort port)
        {
            var device = port?.Driver?.Device ?? throw new ArgumentNullException(nameof(port));

            VendorId   = device.VendorId;
            DeviceId   = device.DeviceId;
            PortNumber = port.PortNumber;
        }
Exemple #5
0
 public SerialInputOutputManager(IUsbSerialPort port)
 {
     this.port = port;
     BaudRate  = DEFAULT_BAUDRATE;
     Parity    = DEFAULT_PARITY;
     DataBits  = DEFAULT_DATABITS;
     StopBits  = DEFAULT_STOPBITS;
 }
 public PortManager(IUsbSerialPort port, int?bufferSize = null, int?writeTimeoutMilliseconds = null)
 {
     _port      = port ?? throw new ArgumentNullException(nameof(port));
     BufferSize = bufferSize ?? DefaultBufferSize;
     WriteTimeoutMilliseconds = writeTimeoutMilliseconds ?? DefaultWriteTimeoutMilliseconds;
     BaudRate = DefaultBaudRate;
     Parity   = DefaultParity;
     DataBits = DefaultDataBits;
     StopBits = DefaultStopBits;
 }
        public static void PutExtraPortInfo(this Intent intent, IUsbSerialPort port)
        {
            if (intent == null)
            {
                throw new ArgumentNullException(nameof(intent));
            }
            if (port == null)
            {
                throw new ArgumentNullException(nameof(port));
            }

            intent.PutExtra(ParcelablePortInfo.ExtraName, new ParcelablePortInfo(port));
        }
        async Task OpenActivity()
        {
            ////////////////////////////////////new line///////////////////////////////////////
            try
            {
                if (firstTime == true)
                {
                    await Task.Delay(3000);

                    if (adapter.Count != 0)
                    {
                        selectedPort = adapter.GetItem(0);
                        //var permissionGranted = true/*await usbManager.RequestPermissionAsync(selectedPort.Driver.Device, this)*/;
                        //if (!File.Exists(System.IO.Path.Combine((string)Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads), "granted.flx")))
                        //{
                        var permissionGranted = await usbManager.RequestPermissionAsync(selectedPort.Driver.Device, this);

                        //if (permissionGranted)
                        //{
                        //    Toast.MakeText(this, System.IO.Path.Combine((string)Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads), "granted.flx"), ToastLength.Long).Show();
                        //    File.Create(System.IO.Path.Combine((string)Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads), "granted.flx"));
                        //}

                        //}
                        if (permissionGranted)
                        {
                            // start the SerialConsoleActivity for this device
                            var newIntent = new Intent(this, typeof(SerialConsoleActivity));
                            newIntent.SetFlags(newIntent.Flags | ActivityFlags.NoHistory);
                            newIntent.PutExtra(SerialConsoleActivity.EXTRA_TAG, new UsbSerialPortInfo(selectedPort));
                            StartActivity(newIntent);
                        }
                    }
                    firstTime = false;
                }
            }
            catch (System.Exception ex)
            {
                //Toast.MakeText(this, ex.Message, ToastLength.Long).Show();
                //OpenActivity();
            }
            //////////////////////////////////////////////////////////////////////////////////
        }
Exemple #9
0
        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();
        }
Exemple #10
0
        async Task OnItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            Log.Info(TAG, "Pressed item " + e.Position);
            if (e.Position >= adapter.Count)
            {
                Log.Info(TAG, "Illegal position.");
                return;
            }

            // request user permisssion to connect to device
            // NOTE: no request is shown to user if permission already granted
            selectedPort = adapter.GetItem(e.Position);
            var permissionGranted = await usbManager.RequestPermissionAsync(selectedPort.Driver.Device, this);

            if (permissionGranted)
            {
                // start the SerialConsoleActivity for this device
                var newIntent = new Intent(this, typeof(SerialConsoleActivity));
                newIntent.PutExtra(SerialConsoleActivity.EXTRA_TAG, new UsbSerialPortInfo(selectedPort));
                StartActivity(newIntent);
            }
        }
Exemple #11
0
        private void RefreshStatus()
        {
            CriteriaRow.ResetAll();

            // Clear the main container
            contentRow.CloseAllChildren();

            // Regen and refresh the troubleshooting criteria
            var printerNameLabel = new TextWidget(string.Format("{0}:", "Connection Troubleshooting".Localize()), 0, 0, labelFontSize)
            {
                TextColor = theme.TextColor,
                Margin    = new BorderDouble(bottom: 10)
            };

#if __ANDROID__
            IUsbSerialPort serialPort = FrostedSerialPort.LoadSerialDriver(null);

#if ANDROID7
            // Filter out the built-in 002 device and select the first item from the list
            // On the T7 Android device, there is a non-printer device always registered at usb/002/002 that must be ignored
            UsbDevice usbPrintDevice = usbManager.DeviceList.Values.Where(d => d.DeviceName != "/dev/bus/usb/002/002").FirstOrDefault();
#else
            UsbDevice usbPrintDevice = usbManager.DeviceList.Values.FirstOrDefault();
#endif

            UsbStatus usbStatus = new UsbStatus()
            {
                IsDriverLoadable   = (serialPort != null),
                HasUsbDevice       = true,
                HasUsbPermission   = false,
                AnyUsbDeviceExists = usbPrintDevice != null
            };

            if (!usbStatus.IsDriverLoadable)
            {
                usbStatus.HasUsbDevice = usbPrintDevice != null;

                if (usbStatus.HasUsbDevice)
                {
                    // TODO: Testing specifically for UsbClass.Comm seems fragile but no better alternative exists without more research
                    usbStatus.UsbDetails = new UsbDeviceDetails()
                    {
                        ProductID   = usbPrintDevice.ProductId,
                        VendorID    = usbPrintDevice.VendorId,
                        DriverClass = usbManager.DeviceList.Values.First().DeviceClass == Android.Hardware.Usb.UsbClass.Comm ? "cdcDriverType" : "ftdiDriverType"
                    };
                    usbStatus.Summary = string.Format("No USB device definition found. Click the 'Fix' button to add an override for your device ", usbStatus.UsbDetails.VendorID, usbStatus.UsbDetails.ProductID);
                }
            }

            usbStatus.HasUsbPermission = usbStatus.IsDriverLoadable && FrostedSerialPort.HasPermissionToDevice(serialPort);

            contentRow.AddChild(printerNameLabel);

            contentRow.AddChild(new CriteriaRow(
                                    "USB Connection",
                                    "Retry",
                                    "No USB device found. Check and reseat cables and try again",
                                    usbStatus.AnyUsbDeviceExists,
                                    () => UiThread.RunOnIdle(RefreshStatus),
                                    theme));

            contentRow.AddChild(new CriteriaRow(
                                    "USB Driver",
                                    "Fix",
                                    usbStatus.Summary,
                                    usbStatus.IsDriverLoadable,
                                    () =>
            {
                string overridePath         = Path.Combine(ApplicationDataStorage.ApplicationUserDataPath, "data", "usboverride.local");
                UsbDeviceDetails usbDetails = usbStatus.UsbDetails;
                File.AppendAllText(overridePath, string.Format("{0},{1},{2}\r\n", usbDetails.VendorID, usbDetails.ProductID, usbDetails.DriverClass));

                UiThread.RunOnIdle(() => RefreshStatus());
            },
                                    theme));

            contentRow.AddChild(new CriteriaRow(
                                    "USB Permission",
                                    "Request Permission",
                                    "Click the 'Request Permission' button to gain Android access rights",
                                    usbStatus.HasUsbPermission,
                                    () =>
            {
                if (checkForPermissionTimer == null)
                {
                    checkForPermissionTimer = new System.Threading.Timer((state) =>
                    {
                        if (FrostedSerialPort.HasPermissionToDevice(serialPort))
                        {
                            UiThread.RunOnIdle(this.RefreshStatus);
                            checkForPermissionTimer.Dispose();
                        }
                    }, null, 200, 200);
                }

                FrostedSerialPort.RequestPermissionToDevice(serialPort);
            },
                                    theme));
#endif
            connectToPrinterRow = new CriteriaRow(
                "Connect to Printer".Localize(),
                "Connect".Localize(),
                "Click the 'Connect' button to retry the original connection attempt".Localize(),
                false,
                () => printer.Connection.Connect(),
                theme);

            contentRow.AddChild(connectToPrinterRow);

            if (CriteriaRow.ActiveErrorItem != null)
            {
                var errorText = new FlowLayoutWidget()
                {
                    Padding = new BorderDouble(0, 15)
                };

                errorText.AddChild(
                    new TextWidget(CriteriaRow.ActiveErrorItem.ErrorText)
                {
                    TextColor = theme.PrimaryAccentColor
                });

                contentRow.AddChild(errorText);
            }
        }
Exemple #12
0
 public FtdiSerialDriver(UsbDevice device)
 {
     Device = device;
     _port  = new FtdiSerialPort(this, Device, 0);
 }
Exemple #13
0
 public Cp21xxSerialDriver(UsbDevice device)
 {
     Device = device;
     _port  = new Cp21xxSerialPort(this, Device, 0);
 }
Exemple #14
0
 public CdcAcmSerialDriver(UsbDevice device)
 {
     Device = device;
     _port  = new CdcAcmSerialPort(this, device, 0);
 }
 public SerialInputOutputManager(IUsbSerialPort port)
 {
     _port = port;
 }
        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 ProlificSerialDriver(UsbDevice device)
 {
     Device = device;
     _port  = new ProlificSerialPort(this, Device, 0);
 }
        // Réception de données Li-Fi avec port série micro USB
        private async Task OpenLiFiReceiverPort()
        {
            UsbManager UsbSerialManager = AppActivity.ApplicationContext.GetSystemService(Context.UsbService) as UsbManager;

            var Table = UsbSerialProber.DefaultProbeTable;

            Table.AddProduct(0x1b4f, 0x0008, Java.Lang.Class.FromType(typeof(CdcAcmSerialDriver))); // IOIO OTG
            var Prober  = new UsbSerialProber(Table);
            var Drivers = await Prober.FindAllDriversAsync(UsbSerialManager);

            LiFiReceiverPort = null;
            foreach (var Driver in Drivers) // On cherche notre driver (le récepteur Li-Fi)
            {
                foreach (var Port in Driver.Ports)
                {
                    if (HexDump.ToHexString((short)Port.Driver.Device.VendorId) == "0403" && HexDump.ToHexString((short)Port.Driver.Device.ProductId) == "6015")
                    {
                        LiFiReceiverPort = Port;
                    }
                }
            }

            if (LiFiReceiverPort == null) // Si il n'est pas branché on affiche un message
            {
                AppActivity.RunOnUiThread(() => { ReceiverStatus.Text = "Récepteur Li-Fi absent"; });
            }
            else
            {
                var IsPermissionGranted = await UsbSerialManager.RequestPermissionAsync(LiFiReceiverPort.Driver.Device, AppActivity.ApplicationContext);

                if (IsPermissionGranted)                                             // On demande la permission à l'utilisateur d'utiliser le récepteur (Android)
                {
                    SerialIOManager = new SerialInputOutputManager(LiFiReceiverPort) // Configuration du port série
                    {
                        BaudRate = 115200,
                        DataBits = 8,
                        StopBits = StopBits.One,
                        Parity   = Parity.None
                    };

                    SerialIOManager.DataReceived += (source, args) =>            // Thread de réception de données
                    {
                        ReceivedSerialData = Encoding.UTF8.GetString(args.Data); // Données recu
                    };

                    SerialIOManager.ErrorReceived += (source, args) => // Thread si il y a une erreur
                    {
                        AppActivity.RunOnUiThread(() =>
                        {
                            ReceiverStatus.Text = "Récepteur Li-Fi absent"; // On affiche un message de débranchement
                            SerialIOManager.Close();
                        });
                    };

                    try
                    {
                        SerialIOManager.Open(UsbSerialManager); // On ouvre le port
                        AppActivity.RunOnUiThread(() => { ReceiverStatus.Text = "Récepteur Li-Fi opérationnel"; });
                    }
                    catch (Java.IO.IOException Exception)
                    {
                        AppActivity.RunOnUiThread(() => { ReceiverStatus.Text = "Erreur récepteur Li-Fi: " + Exception.Message; });
                    }
                }
                else
                {
                    AppActivity.RunOnUiThread(() => { ReceiverStatus.Text = "Permission requise"; });
                }
            }
        }
        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;
            }
        }