Xamarin蓝牙LE

时间:2016-03-07 17:27:51

标签: ios iphone xamarin bluetooth

我是蓝牙LE的新手,我在阅读和写入设备方面遇到了一些困难。

我一直在关注Monkey.Robotics项目,以指导我。我现在已经达到了我已经保存了我需要的特性及其相应描述符(用于读取和写入)的部分。我尝试实现写入功能,但我没有成功。

我一直在尝试使用这种方法执行写操作:

connectedPeripheral.WriteValue( NSData.FromString (sendText.Text), write_desc);

我还打印了我保存的所有特征的UUID,并使用我的Mac的LightBlue应用验证了它们是正确的。

我只是好奇我是否需要做任何其他准备工作才能执行此写作?

我已将我的代码附加到此帖的底部。

谢谢,

奥斯汀

CODE:

partial class ThirdViewController : UIViewController
{
        CBService serviceNeeded;
    private string serv_to_find  = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
    private string read_to_find  = "6e400003-b5a3-f393-e0a9-e50e24dcca9e";
    private string write_to_find = "6e400002-b5a3-f393-e0a9-e50e24dcca9e";
    CBPeripheral connectedPeripheral;
    CBCharacteristic write;
    CBCharacteristic read;
    CBDescriptor write_desc;

    private string value = "";
    List<CBPeripheral> ps = new List<CBPeripheral> ();

    public ThirdViewController (IntPtr handle) : base (handle)
    {
    }

    public ThirdViewController ()
    {
    }

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

        MyPickerModel model = new MyPickerModel ();

        // Tie model to selected event
        model.comSelected += (object sender, EventArgs e) => 
        {
            value = model.selectedCom;
        };

        // wire up the DiscoveredPeripheral event to update the table
        BluetoothLEManager.Current.DeviceDiscovered += (object sender, CBDiscoveredPeripheralEventArgs e) => {
            ps = BluetoothLEManager.Current.DiscoveredDevices;

            textBox.Text += "\nFound device: ";
            foreach (var temp in ps)
            {
                model.Add(temp.Name);
                if (value == ""){
                    value = temp.Name;
                }
                textBox.Text += temp.Name + "\n";
            }

            Blue_Picker.Model = model;
        };

        BluetoothLEManager.Current.ScanTimeoutElapsed += (sender, e) => {
            textBox.Text += "\nScan Timeout.";
            BluetoothLEManager.Current.StopScanningForDevices ();
        };
    }

    partial void Logout_Button_TouchUpInside (UIButton sender)
    {
        // Create an instance of our AppDelegate
        var appDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;

        // Get an instance of our MainStoryboard.storyboard
        var mainStoryboard = appDelegate.MainStoryboard;

        // Get an instance of our Login Page View Controller
        var loginPageViewController = appDelegate.GetViewController(mainStoryboard, "LoginPageViewController") as LoginPageViewController;

        // Wire our event handler to show the MainTabBarController after we successfully logged in.
        loginPageViewController.OnLoginSuccess += (s, e) => 
        {
            var tabBarController = appDelegate.GetViewController(mainStoryboard, "MainTabBarController");
            appDelegate.SetRootViewController(tabBarController, true);
        };

        // Set the Login Page as our RootViewController
        appDelegate.SetRootViewController(loginPageViewController, true);
    }

    partial void ScanButton_TouchUpInside (UIButton sender)
    {
        if (BluetoothLEManager.Current.IsScanning)
        {
            BluetoothLEManager.Current.StopScanningForDevices ();
            textBox.Text += "\nDone Scanning";
        }
        else
        {
            BluetoothLEManager.Current.BeginScanningForDevices ();
            textBox.Text += "\nNow Scanning";
        }
    }

    partial void DisconnectButton_TouchUpInside (UIButton sender)
    {
        if (connectedPeripheral == null) {
            textBox.Text += "\nNo device connected.";
            return;
        }

        textBox.Text += "\nDisconnecting from device " + connectedPeripheral.Name + "...";

        BluetoothLEManager.Current.DisconnectPeripheral (connectedPeripheral);
        connectedPeripheral = null;

        Blue_Picker.Hidden = false;
    }

    async partial void ConnectButton_TouchUpInside (UIButton sender)
    {
        if (connectedPeripheral != null) {
            textBox.Text += "\nDevice already connected.";
            return;
        }

        StopScanning ();

        textBox.Text += "\nConnecting to device " + value + "...";

        foreach (var temp in ps){
            if (temp.Name == value){
                BluetoothLEManager.Current.CentralBleManager.ConnectPeripheral (temp, new PeripheralConnectionOptions ());
                await Task.Delay(5000);
                connectedPeripheral = temp;
                InitializePeripheral();
                break;
            }
        }

        Blue_Picker.Hidden = true;
    }

    void StopScanning()
    {
        Task.Factory.StartNew (() => {
            if (!BluetoothLEManager.Current.IsScanning)
                return;

            BluetoothLEManager.Current.StopScanningForDevices ();
        });
    }

    void InitializePeripheral ()
    {
        // update all our shit

        // > peripheral
        //   > service[s]
        //      > characteristic
        //          > value
        //          > descriptor[s]

        connectedPeripheral.DiscoveredService += HandleDiscoveredService;
        connectedPeripheral.DiscoveredCharacteristic += (sender, e) => {
            HandleDiscoveredCharacteristic((CBPeripheral)sender, serviceNeeded);
        };
        connectedPeripheral.DiscoveredDescriptor += HandleDiscoveredDescriptor;

        connectedPeripheral.DiscoverServices ();
        textBox.Text += "\nLooking for services";
    }

    void HandleDiscoveredService (object sender, NSErrorEventArgs e)
    {
        var peripheral = (CBPeripheral)sender;

        //foreach (CBService service in peripheral.Services) {
        //  textBox.Text += "\nDiscovered Service: " + service.UUID.ToString();
        //  if (!services.Contains (service))
        //      services.Add (service);
        //}

        foreach (CBService service in peripheral.Services) {
            if (service.UUID.ToString().Contains(serv_to_find)) {
                serviceNeeded = service;
            }
        }

        if (serviceNeeded == null)
            return;

        textBox.Text += "\nDiscovered service: " + serviceNeeded.UUID.ToString ();

        // discover the charactersistics
        connectedPeripheral.DiscoverCharacteristics(serviceNeeded);
    }

    void HandleDiscoveredCharacteristic (CBPeripheral peripheral, CBService service)
    {
        foreach (CBService srv in peripheral.Services) {

            // if the service has characteristics yet
            if (srv.Characteristics == null)
                continue;

            foreach (var characteristic in service.Characteristics) {
                if (characteristic.UUID.ToString ().Contains (read_to_find)) {
                    read = characteristic;
                    textBox.Text += "\nDiscovered read characteristic: " + read.UUID.ToString();
                    connectedPeripheral.DiscoverDescriptors (read);
                }
                else if (characteristic.UUID.ToString ().Contains (write_to_find)) {
                    write = characteristic;
                    textBox.Text += "\nDiscovered write characteristic: " + write.UUID.ToString();
                    connectedPeripheral.DiscoverDescriptors (write);
                }
            }
        }
    }

    void HandleDiscoveredDescriptor (object sender, CBCharacteristicEventArgs e)
    {
        foreach (var descriptor in e.Characteristic.Descriptors) {
            if (e.Characteristic.UUID == write.UUID) {
                textBox.Text += "\nWrite descriptor: " + descriptor.ToString ();
                write_desc = descriptor;
            }
            else if (e.Characteristic.UUID == read.UUID) {
                textBox.Text += "\nRead descriptor: " + descriptor.ToString ();
            }
        }
    }

    partial void SendButton_TouchUpInside (UIButton sender)
    {
        textBox.Text += "\nNow writing: " + sendText.Text;
        connectedPeripheral.WriteValue( NSData.FromString (sendText.Text), write_desc);
    }
}

我也尝试过:

connectedPeripheral.WriteValue( NSData.FromString (sendText.Text), write, CBCharacteristicWriteType.WithoutResponse);

这似乎也不起作用。

1 个答案:

答案 0 :(得分:3)

Monkey Robotics有点过时且不完整。看看xabre/xamarin-bluetooth-le。它基本上是Monkey Robotics,填补了空白。更容易使用。