Xamarin.forms 安卓Usb通讯

Xamarin.forms 安卓Usb通讯使用的是开源库LusoVU.XamarinUsbSerialForAndroid
第一步:使用Nuget获取LusoVU.XamarinUsbSerialForAndroid包

第二步:在.Android下新建ComportHelp类

using Android.App;
using Android.Content;
using Android.Hardware.Usb;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.Content.PM;
using Hoho.Android.UsbSerial.Driver;
using Hoho.Android.UsbSerial.Util;
using Xamarin.Forms;
using System.Threading;

///注册DependencyService
///因为是forms跨平台,整个串口针对的是安卓,所以需要注册一个接口,在UI里面调用
[assembly:Dependency(typeof(LansoApp.ComportHelp))]

namespace LansoApp
{

    public class ComportHelp:ComportHelpInterface
    {

       ///
        static ContextWrapper contextWrapper;

        public static ComportHelp comportHelp= new ComportHelp();

        static Context context;
        private static string ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
        public static void InitialContext(Context c)
        {
            contextWrapper = new ContextWrapper(c);
            context = c;
            ///获取USB service
            manager = (UsbManager)contextWrapper.GetSystemService(Context.UsbService);
            UsbReciever usbReciever = new UsbReciever();
            PendingIntent mPermissionIntent = PendingIntent.GetBroadcast(c, 0, new Intent(
                ACTION_USB_PERMISSION), 0);
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            //RegisterReceiver(usbReciever, filter);

        }
        /// <summary>
        /// usb设备列表
        /// </summary>
        static IList<IUsbSerialDriver> availableDrivers;
        /// <summary>
        /// 服务管理
        /// /// </summary>
        static UsbManager manager;
        /// <summary>
        /// USB连接实例
        /// </summary>
        static UsbDeviceConnection connection;
        /// <summary>
        /// USB设备
        /// </summary>
        static IUsbSerialDriver driver;
        /// <summary>
        /// 串口
        /// </summary>
        static IUsbSerialPort Comport;
        static PendingIntent mPermissionIntent;

        static string usbName;

        public string UsbName { get { return usbName; } }

        private bool isOpen;
        ///接收到数据的委托,返回数据给前台界面
        public event Action<byte[]> DataRecvHandle;

        public event Action<string> DataHandle;

        private SerialInputOutputManager serialIoManager;
        public bool IsOpen
        {
            get { return isOpen; }
            set { }
        }
        public bool Open(out string msg, Action<byte[]> action)
        {
            if (!IsOpen)
            {
                if (availableDrivers.Count > 0)
                {
                    try
                    {
                        connection = manager.OpenDevice(driver.Device);
                        if (connection == null)
                        {
                            msg = "串口连接异常";
                            return false;
                        }
                        Comport = driver.Ports[0];
                        serialIoManager = new SerialInputOutputManager(Comport)
                        {
                            BaudRate = 9600,
                            DataBits = 8,
                            StopBits = StopBits.One,
                            Parity = Parity.None,
                        };
                        serialIoManager.Open(manager, 1024);
                        serialIoManager.DataReceived += SerialInputOutputManager_DataReceived;
                        this.DataRecvHandle += action;
                        isOpen = true;
                        msg = "成功";
                        return true;
                    }
                    catch(Exception ex) {
                        msg = ex.ToString();
                        return false;
                    }
                }
                isOpen = false;
                msg = "串口打开失败";
                return false;
            }
            msg = "成功2";
            return true;
        }
        public List<byte> recvByte = new List<byte>();
        public bool Open(out string msg, Action<string> action)
        {
            if (!IsOpen)
            {
                if (availableDrivers.Count > 0)
                {
                    try
                    {
                        connection = manager.OpenDevice(driver.Device);
                        if (connection == null)
                        {
                            msg = "串口连接异常";
                            return false;
                        }
                        Comport = driver.Ports[0];
                        serialIoManager = new SerialInputOutputManager(Comport)
                        {
                            BaudRate = 9600,
                            DataBits = 8,
                            StopBits = StopBits.One,
                            Parity = Parity.None,
                        };
                        serialIoManager.Open(manager, 1024);
                        serialIoManager.DataReceived += SerialInputOutputManager_DataReceived;
                        this.DataHandle += action;
                        isOpen = true;
                        msg = "成功";
                        return true;
                    }
                    catch (Exception ex)
                    {
                        msg = ex.ToString();
                        return false;
                    }
                }
                isOpen = false;
                msg = "串口打开失败";
                return false;
            }
            msg = "成功2";
            return true;
        }
        private void SerialInputOutputManager_DataReceived(object sender, SerialDataReceivedArgs e)
        {
            DataRecvHandle?.Invoke(e.Data);
        }

        public bool Close()
        {
            if (Comport != null)
            {
                Comport.Close();
            }
            isOpen = false;
            return true;
        }
        public bool SendRecv(byte[] sendByte, ref byte[] recvByte,out string msg)
        {
            if (isOpen)
            {
                Comport.Write(sendByte, 1024);
                byte[] rec=new byte[1024];
                try
                {
                    int recvCount = 0;
                    List<byte> recvList = new List<byte>();
                    while(recvCount<recvByte.Length)
                    {
                        int count=Comport.Read(rec, 1024);
                        if (count > 0)
                        {
                            for (int i = 0; i < count; i++)
                            {
                                recvList.Add(rec[i]);
                            }
                        }
                        recvCount += count;
                        Thread.Sleep(100);
                    }
                    for (int i = 0; i < recvByte.Length; i++)
                    {
                        recvByte[i] = recvList[i];
                    }
                    msg = "成功";
                    return true;
                }
                catch(Exception ex) {
                    msg = ex.ToString();
                    return false;
                }
                
            }
            else {
                msg = "没打开";
                return false;
            }
        }

        public string GetComport()
        {
            availableDrivers = UsbSerialProber.DefaultProber.FindAllDrivers(manager);
            if (availableDrivers.Count > 0)
            {
                driver = availableDrivers[0];
                if (!manager.HasPermission(driver.Device))
                {
                    mPermissionIntent = PendingIntent.GetBroadcast(context, 0, new Intent(
                   "com.android.example.USB_PERMISSION"), 0);
                    manager.RequestPermission(driver.Device, mPermissionIntent);
                }
                connection =manager.OpenDevice(driver.Device);
                usbName = driver.Device.ProductName;
                return driver.Device.ToString();
            }
            return "";
        }

        public string GetUsbName()
        {
            return usbName;
        }

        public void Send(byte[] sendByte)
        {
            if (isOpen)
            {
                if (Comport != null)
                {
                    Comport.Write(sendByte, 1024);
                }
                
            }
        }
        public ComportHelpInterface GetComportHelpInterface()
        {
            if (comportHelp == null)
            {
                comportHelp = new ComportHelp();
            }
            return comportHelp;
        }

    }
    public class UsbReciever : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            String action = intent.Action;
            if ("com.android.example.USB_PERMISSION".Equals(action))
            {
                lock (this)
                {
                    UsbDevice device = (UsbDevice)intent
                            .GetParcelableExtra(UsbManager.ExtraDevice);

                    if (intent.GetBooleanExtra(
                            UsbManager.ExtraPermissionGranted, false))
                    {
                        if (device != null)
                        {
                          
                        }
                    }
                    else
                    {

                    }
                }
            }
        }
    }

}

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
private static string ACTION_USB_PERMISSION = “com.android.example.USB_PERMISSION”;
protected void USBTest()
{
var usbManager = (UsbManager)this.Application.ApplicationContext.GetSystemService(UsbService);
UsbDevice usbDevice = null;
foreach (var key in usbManager.DeviceList.Keys)
{
var device = usbManager.DeviceList[key];
var productId = device.ProductId;
var vendorId = device.VendorId;

        // 根据 厂商id 与 设备id 找设备
        if (productId == 8211 && vendorId == 1305)
        {
            usbDevice = device;
            break;
        }
    }

    if (usbDevice == null)
    {
        return "没USB设备!";
    }

    UsbReciever usbReciever = new UsbReciever();
    PendingIntent mPermissionIntent = PendingIntent.GetBroadcast(this, 0, new Intent(
        ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    RegisterReceiver(usbReciever, filter);

    usbManager.RequestPermission(usbDevice, mPermissionIntent);

    /*
    if (!usbManager.HasPermission(usbDevice))
    {
        // 没权限.
        // log "没USB权限!";
    }
    */

    UsbDeviceConnection connection = null;
    // 待发数据
    var buffer = new byte[100];
    try
    {
        connection = usbManager.OpenDevice(usbDevice);
        var endPoint = usbDevice.GetInterface(0).GetEndpoint(0);
        connection.BulkTransfer(endPoint, buffer, buffer.Length, 0);
    }
    catch (Exception ex)
    {
        // log "打印失败," + System.Environment.NewLine + ex.Message + System.Environment.NewLine + ex.StackTrace;
    }
    finally
    {
        if (connection != null)
        {
            connection.Close();
        }
    }
}

public class UsbReciever : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        String action = intent.Action;
        if (ACTION_USB_PERMISSION.Equals(action))
        {
            lock (this)
            {
                UsbDevice device = (UsbDevice)intent
                        .GetParcelableExtra(UsbManager.ExtraDevice);

                if (intent.GetBooleanExtra(
                        UsbManager.ExtraPermissionGranted, false))
                {
                    if (device != null)
                    {
                        // call method to set up device communication
                    }
                }
                else
                {

                }
            }
        }
    }
}

}

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值