Search code examples
c#cross-platformmaui.net-mauimaui-windows

How to write raw data to usb connected device using .NET MAUI


I would like to write an application that will send raw data to a device that is connected to my mobile phone with Android OS through USB cable. For this purpose, I would like to use .NET MAUI. I know that this is a quite new framework, yet I would like to give it a shot. I'm wondering if there is a way that I can use SerialPort from System.IO namespace or some other library that will allow me to accomplish this task. So far I have found a library Device.Net but it didn't support .NET MAUI. I would be very grateful for any hint if/how this is possible.


Solution

  • Activity act = Platform.CurrentActivity;
    
    UsbManager manager = (UsbManager)act.GetSystemService(Context.UsbService);
    
    IDictionary<string, UsbDevice> devicesDictionary = manager.DeviceList;
    
    UsbDevice dvc = devicesDictionary.ElementAt(0).Value;
    
    string ACTION_USB_PERMISSION = "rzepak";
    
    var interf = dvc.GetInterface(1);
    
    outEndpoint = interf.GetEndpoint(1);
    
    PendingIntent mPermissionIntent = PendingIntent.GetBroadcast(act, 0, new Intent(ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    
    if (manager.HasPermission(dvc) == false)
       manager.RequestPermission(dvc, mPermissionIntent);
    
    deviceConnection = manager.OpenDevice(dvc);
    
    if (deviceConnection != null)
        deviceConnection.ClaimInterface(interf, true).ToString();
        else return false;
    

    deviceConnection is an Android.Hardware.Usb.UsbDeviceConnection type, opened in connect method:

    byte[] test = new byte[] { input };
    
    if (deviceConnection.BulkTransfer(outEndpoint, test, test.Length, 500) < 0)
        Connected = false;