ios - Xamarin 低功耗蓝牙

标签 ios iphone xamarin 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 低功耗蓝牙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35850094/

相关文章:

ios - 如何在iOS中对包含字典的nsmutable数组进行排序

iphone - 想要添加UInavigationBar rightBarButton,如ipod的 'Now Playing'按钮,它不会在 View 转换之间消失

c# - xamarin 表单更改选定的选项卡颜色文本

iOS 自动在文本字段中添加连字符

ios - 有没有什么方法可以以编程方式发送短信,而无需打开 iPhone 中的默认短信应用程序?

iphone - 从 UIImagePickerController 抓取视频的第一帧?

iphone - iOS iVar 命名为 "Size"语法错误?

javascript - 捏缩放后 iPhone 谷歌地图 v3 平移

c# - System.IO.FileNotFoundException : Could not load assembly. ..可能不存在于 Android 配置文件的 Mono 中?

ios - 如何在 Xamarin.Forms 中设置 ListView 行高