0

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.

paweltru
  • 67
  • 6
  • USB serial port is available on Maui with : using Android.Hardware.Usb; – jdweng Aug 29 '22 at 21:40
  • Thanks, @jdweng I didn't know that. Do you know where I can find some examples for .NET MAUI. There are some examples for Xamarin, but I couldn't find any for this new framework. Or, is it somehow transferable for Xamarin to MAUI? – paweltru Aug 30 '22 at 20:12
  • Serial port code usually transfer easily. You should be able to use any c# serial port example. Just set Baud Rate correctly to USB speed. Usually 56K. – jdweng Aug 30 '22 at 21:22

1 Answers1

0
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;
Maku
  • 1,464
  • 11
  • 20
leon
  • 16
  • Where would this code go in the MAUI app? Would it be in the `Platforms -> Android -> MainAcvtivity.cs` file? – est005 May 25 '23 at 07:53