我对Bluetooth LE相当陌生,并且在读写设备时遇到一些困难。

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

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

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


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

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

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

谢谢,

奥斯丁

码:

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);


这似乎也不起作用。

最佳答案

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

关于ios - Xamarin蓝牙LE,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35850094/

10-11 18:06