ExternalAccessory on iOS at Xamarin

自闭症网瘾萝莉.ら 提交于 2019-12-03 09:10:54

Although it seems like you've worked this out, I thought I'd show some code snippets that show the basics (in this case connecting to a Sphero and turning it green):

EAAccessoryManager mgr = EAAccessoryManager.SharedAccessoryManager;
var accessories = mgr.ConnectedAccessories;
foreach(var accessory in accessories)
{
    myLabel.Text = "Got me an accessory";
    Console.WriteLine(accessory.ToString());
    Console.WriteLine(accessory.Name);
    var protocol = "com.orbotix.robotprotocol";

    if(accessory.ProtocolStrings.Where(s => s == protocol).Any())
    {
        myLabel.Text = "Got me a Sphero";

        var session = new EASession(accessory, protocol);
        var outputStream = session.OutputStream;
        outputStream.Delegate = new MyOutputStreamDelegate(myLabel);
        outputStream.Schedule(NSRunLoop.Current, "kCFRunLoopDefaultMode");
        outputStream.Open();
    }
}

and

public class MyOutputStreamDelegate : NSStreamDelegate
{
    UILabel label;
    bool hasWritten = false;

    public MyOutputStreamDelegate(UILabel label)
    {
        this.label = label;
    }
    public override void HandleEvent(NSStream theStream, NSStreamEvent streamEvent)
    {
        if(streamEvent == NSStreamEvent.HasSpaceAvailable && ! hasWritten)
        {
            //Set the color of the Sphero
            var written = ((NSOutputStream)theStream).Write(new byte[] {0xFF, 0xFF, 0x02, 0x20, 0x0e, 0x05, 0x1F, 0xFF, 0x1B, 0x00, 0x91}, 11);
            if(written == 11)
            {
                label.Text = "Sphero should be green";
            }
            hasWritten = true;
        }
    }
}

I know you specifically asked about writing data to the bluetooth device, but this is just expanding on reading data, as well as the general use of the External Accessory API for Xamarin.iOS because there isn't much documentation or Xamarin samples out there. This is a loose conversion from the Apple sample done with Objective-C. My accessory was a MFi certified microchip reader. I've only put in the "read" functionality since I only needed that for my app.

Create a SessionController class inheriting from NSStreamDelegate and this does a lot of the plumbing. Opens, closes sessions, handles events from the device and reads the data. You'd add your write methods here too I think.

public class EASessionController : NSStreamDelegate
{

    NSString SessionDataReceivedNotification = (NSString)"SessionDataReceivedNotification";

    public static EAAccessory _accessory;
    public static string _protocolString;

    EASession _session;
    NSMutableData _readData;

    public static EASessionController SharedController()
    {
        EASessionController sessionController = null;

        if (sessionController == null)
        {
            sessionController = new EASessionController();
        }

        return sessionController;

    }

    public void SetupController(EAAccessory accessory, string protocolString)
    {

        _accessory = accessory;
        _protocolString = protocolString;

    }

    public bool OpenSession()
    {

        Console.WriteLine("opening new session");

        _accessory.WeakDelegate = this;

        if (_session == null)
            _session = new EASession(_accessory, _protocolString);

        // Open both input and output streams even if the device only makes use of one of them

        _session.InputStream.Delegate = this;
        _session.InputStream.Schedule(NSRunLoop.Current, NSRunLoopMode.Default);
        _session.InputStream.Open();

        _session.OutputStream.Delegate = this;
        _session.OutputStream.Schedule(NSRunLoop.Current, NSRunLoopMode.Default);
        _session.OutputStream.Open();

        return (_session != null);

    }

    public void CloseSession()
    {
        _session.InputStream.Unschedule(NSRunLoop.Current, NSRunLoopMode.Default);
        _session.InputStream.Delegate = null;
        _session.InputStream.Close();

        _session.OutputStream.Unschedule(NSRunLoop.Current, NSRunLoopMode.Default);
        _session.OutputStream.Delegate = null;
        _session.OutputStream.Close();

        _session = null;

    }


    /// <summary>
    /// Get Number of bytes to read into local buffer
    /// </summary>
    /// <returns></returns>
    public nuint ReadBytesAvailable()
    {
        return _readData.Length;
    }



    /// <summary>
    /// High level read method
    /// </summary>
    /// <param name="bytesToRead"></param>
    /// <returns></returns>
    public NSData ReadData(nuint bytesToRead)
    {

        NSData data = null;

        if (_readData.Length >= bytesToRead)
        {
            NSRange range = new NSRange(0, (nint)bytesToRead);
            data = _readData.Subdata(range);
            _readData.ReplaceBytes(range, IntPtr.Zero, 0);
        }

        return data;

    }

    /// <summary>
    /// Low level read method - read data while there is data and space in input buffer, then post notification to observer
    /// </summary>
    void ReadData()
    {

        nuint bufferSize = 128;
        byte[] buffer = new byte[bufferSize];

        while (_session.InputStream.HasBytesAvailable())
        {
            nint bytesRead = _session.InputStream.Read(buffer, bufferSize);

            if (_readData == null)
            {
                _readData = new NSMutableData(); 
            }
            _readData.AppendBytes(buffer, 0, bytesRead);
            Console.WriteLine(buffer);


        }

        // We now have our data from the device (stored in _readData), so post the notification for an observer to do something with the data

        NSNotificationCenter.DefaultCenter.PostNotificationName(SessionDataReceivedNotification, this);

    }


    /// <summary>
    /// Handle the events occurring with the external accessory
    /// </summary>
    /// <param name="theStream"></param>
    /// <param name="streamEvent"></param>
    public override void HandleEvent(NSStream theStream, NSStreamEvent streamEvent)
    {

        switch (streamEvent)
        {

            case NSStreamEvent.None:
                Console.WriteLine("StreamEventNone");
                break;
            case NSStreamEvent.HasBytesAvailable:
                Console.WriteLine("StreamEventHasBytesAvailable");
                ReadData();
                break;
            case NSStreamEvent.HasSpaceAvailable:
                Console.WriteLine("StreamEventHasSpaceAvailable");
                // Do write operations to the device here
                break;
            case NSStreamEvent.OpenCompleted:
                Console.WriteLine("StreamEventOpenCompleted");
                break;
            case NSStreamEvent.ErrorOccurred:
                Console.WriteLine("StreamEventErroOccurred");
                break;
            case NSStreamEvent.EndEncountered:
                Console.WriteLine("StreamEventEndEncountered");
                break;
            default:
                Console.WriteLine("Stream present but no event");
                break;

        }
    }

}

In my ViewController that's going to display the data I've just read from the external accessory, we wire it all up. In ViewDidLoad, create observers so the view knows when an event has been fired by the device. Also check we're connected to the correct accessory and open a session.

  public EASessionController _EASessionController;
  EAAccessory[] _accessoryList;
  EAAccessory _selectedAccessory;
  NSString SessionDataReceivedNotification = (NSString)"SessionDataReceivedNotification";
  string myDeviceProtocol = "com.my-microchip-reader.1234";

  public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        NSNotificationCenter.DefaultCenter.AddObserver(EAAccessoryManager.DidConnectNotification, EADidConnect);
        NSNotificationCenter.DefaultCenter.AddObserver(EAAccessoryManager.DidDisconnectNotification, EADidDisconnect);
        NSNotificationCenter.DefaultCenter.AddObserver(SessionDataReceivedNotification, SessionDataReceived);
        EAAccessoryManager.SharedAccessoryManager.RegisterForLocalNotifications();



        _EASessionController = EASessionController.SharedController();
        _accessoryList = EAAccessoryManager.SharedAccessoryManager.ConnectedAccessories;

        foreach (EAAccessory acc in _accessoryList)
        {
            if (acc.ProtocolStrings.Contains(myDeviceProtocol))
            {
                // Connected to the correct accessory
                _selectedAccessory = acc;
                _EASessionController.SetupController(acc, myDeviceProtocol);
                _EASessionController.OpenSession();
                lblEAConnectionStatus.Text = acc.Name;

                Console.WriteLine("Already connected via bluetooth");

            }
            else
            {
                // Not connected
            }
        }

}

Create the DidConnect, DidDisconnect and SessionDataReceived methods. The device name is just updated on some labels when connected/disconnected and I'm displaying the data in text field.

void EADidConnect(NSNotification notification)
    {
        EAAccessory connectedAccessory = (EAAccessory)notification.UserInfo.ObjectForKey((NSString)"EAAccessoryKey");
        Console.WriteLine("I did connect!!");
        _accessoryList = EAAccessoryManager.SharedAccessoryManager.ConnectedAccessories;

        // Reconnect and open the session in case the device was disconnected
        foreach (EAAccessory acc in _accessoryList)
        {
            if (acc.ProtocolStrings.Contains(myDeviceProtocol))
            {
                // Connected to the correct accessory
                _selectedAccessory = acc;
                Console.WriteLine(_selectedAccessory.ProtocolStrings);

                _EASessionController.SetupController(acc, myDeviceProtocol);
                _EASessionController.OpenSession();

            }
            else
            {
                // Not connected
            }
        }

        Console.WriteLine(connectedAccessory.Name);

        // Update a label to show it's connected
        lblEAConnectionStatus.Text = connectedAccessory.Name;

    }

    void EADidDisconnect(NSNotification notification)
    {

        Console.WriteLine("Accessory disconnected");
        _EASessionController.CloseSession();
        lblEAConnectionStatus.Text = string.Empty;

    }


    /// <summary>
    /// Data receieved from accessory
    /// </summary>
    /// <param name="notification"></param>
    void SessionDataReceived(NSNotification notification)
    {

        EASessionController sessionController = (EASessionController)notification.Object;

        nuint bytesAvailable = 0;


        while ((bytesAvailable = sessionController.ReadBytesAvailable()) > 0)
        {

            // read the data as a string

            NSData data = sessionController.ReadData(bytesAvailable);
            NSString chipNumber = new NSString(data, NSStringEncoding.UTF8);

           // Displaying the data
            txtMircochipNumber.Text = chipNumber;
           }


        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!