Xamarin.Form 蓝牙ble

  本文介绍Xamarin.Form的蓝牙使用方法,开始之前说说题外话,就Xamarin.Form来说,在国内是没多少人在弄的,但对于我自己来说,是吃了这碗饭,也希望在这行做的人越来越多,越来越好,本人2016年开始入使用Xamarin.Form开发App,那时候刚微软刚收购Xamarin,也正式开源免费给开发者使用,但那时候的本说实话是有多不完善的,直到现在微软依然有很多不完善的功能,所以在国内学这个,一般是由公司高层推这个技术,直接至底向上的非常少。微软的东西在国内环境来说,多不太好,很多大的互联网公司都比较少用,但是我要强调的是,Xamarin.Form本身其实并不太适合做界面变化太多,变化太大的东西,如果你的项目需要优秀的界面,炫酷的特效,那原生是比较好的选择,而这个特性是互联网公司的特性,所以互联网公司不太适合使用Xamarin.Form。Xamarin适合界面少,但是业务比较复杂的项目,如IOT项目。也比较适合传统企业而不是互联网公司。所以在前面一篇文章中,我介绍了MQTT协议,现在介绍底功耗蓝牙协议。

  这里使用ble.net库,直接使用nuget查找相应的包就可以了,ble.net库是一个混合平台的低功耗蓝牙库,可用于开发Android、iOS、UWP平台的BLE客户端。支持的平台和版本如下

Platform Version
Xamarin.iOS iOS 8.3+
Xamarin.Android API 18+
Windows 10(UWP) 1709+

  在引用包的时候注意:在Xamarin.Form层引用ble.net包,在xamarin.Android层引用ble.net 和ble.net-android包,在Xamarin.Form层引用ble.net和ble.net-ios包。

  Android 平台

  添加权限,在Android 6.0或更高版本中需要获取危险的位置权限,所以在AndroidManifesst.xml文件中添加

1 <uses-permission android:name="android.permission.BLUETOOTH" />
2     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
3     <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
4   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
5   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
6   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

  初始化BluetoothLowEnergyAdapter(只有Android平台需要,iOS和UWP平台不需要)。如果你想让IBluetoothLowEnergyAdapter.DisableAdapter() 和 IBluetoothLowEnergyAdapter.EnableAdapter()起作用,你需要在你的Main Activity中添加:

protected override void OnCreate( Bundle bundle )
{
   // ...
   BluetoothLowEnergyAdapter.Init( this );
   // ...
}

  如果你要IBluetoothLowEnergyAdapter.CurrentState.Subscribe()方法起作用,你还需要在Activity中添加:

protected sealed override void OnActivityResult( Int32 requestCode, Result resultCode, Intent data )
{
   BluetoothLowEnergyAdapter.OnActivityResult( requestCode, resultCode, data );
}

  iOS 平台

  必须添加使用蓝牙的提示,并且苹果公司上架App会审核,需正确填写Info.plist文件

1 <key>UIBackgroundModes</key>
2 <array>
3    <string>bluetooth-central</string>
4 </array>
5 <key>NSBluetoothPeripheralUsageDescription</key>
6 <string>[MyAppNameHere] would like to use bluetooth.</string>

  所有平台都需要初始化一个

IBluetoothLowEnergyAdapter ble =
BluetoothLowEnergyAdapter.ObtainDefaultAdapter()

同时传到Xamarin.Form层。

  App内开启蓝牙:使用如下方法检查和启用手机蓝牙适配器

if(ble.AdapterCanBeEnabled && ble.CurrentState.IsDisabledOrDisabling()) {
   await ble.EnableAdapter();
}

  开始扫描附近的蓝牙设备,可以扫描到各种设备,注意:超时时间不宜设置过长,通过测试,蓝牙设备不能一直扫描,需停一会在扫描一会这样使用。扫描能扫描出附近的蓝牙设备和特性。

var cts = new CancellationTokenSource(TimeSpan.FromSeconds( 30 ));
await ble.ScanForBroadcasts(
   // providing ScanSettings is optional
   new ScanSettings()
   {
      // Setting the scan mode is currently only applicable to Android and has no effect on other platforms.
      // If not provided, defaults to ScanMode.Balanced
      Mode = ScanMode.LowPower,

      // Optional scan filter to ensure that the observer will only receive peripherals
      // that pass the filter. If you want to scan for everything around, omit the filter.
      Filter = new ScanFilter()
      {
         AdvertisedDeviceName = "foobar",
         AdvertisedManufacturerCompanyId = 76,
         // peripherals must advertise at-least-one of any GUIDs in this list
         AdvertisedServiceIsInList = new List<Guid>(){ someGuid },
      },

      // ignore repeated advertisements from the same device during this scan
      IgnoreRepeatBroadcasts = false
   },
   // Your IObserver<IBlePeripheral> or Action<IBlePeripheral> will be triggered for each discovered
   // peripheral based on the provided scan settings and filter (if any).
   ( IBlePeripheral peripheral ) =>
   {
      // read the advertising data
      var adv = peripheral.Advertisement;
      Debug.WriteLine( adv.DeviceName );
      Debug.WriteLine( adv.Services.Select( x => x.ToString() ).Join( "," ) );
      Debug.WriteLine( adv.ManufacturerSpecificData.FirstOrDefault().CompanyName() );
      Debug.WriteLine( adv.ServiceData );

      // if we found what we needed, stop the scan manually
      cts.Cancel();

      // perhaps connect to the device (see next example)...
   },
   // Provide a CancellationToken to stop the scan, or use the overload that takes a TimeSpan.
   // If you omit this argument, the scan will timeout after BluetoothLowEnergyUtils.DefaultScanTimeout
   cts.Token
);

// scanning has stopped when code reached this point since the scan was awaited

  如果你要连接蓝牙设备,采用如下方法:

var connection = await ble.ConnectToDevice(
   // The IBlePeripheral to connect to
   peripheral,
   // TimeSpan or CancellationToken to stop the
   // connection attempt.
   // If you omit this argument, it will use
   // BluetoothLowEnergyUtils.DefaultConnectionTimeout
   TimeSpan.FromSeconds( 15 ),
   // Optional IProgress<ConnectionProgress>
   progress => Debug.WriteLine(progress)
);

if(connection.IsSuccessful())
{
   var gattServer = connection.GattServer;
   // ... do things with gattServer here... (see later examples...)
}
else
{
   // Do something to inform user or otherwise handle unsuccessful connection.
   Debug.WriteLine( "Error connecting to device. result={0:g}", connection.ConnectionResult );
   // e.g., "Error connecting to device. result=ConnectionAttemptCancelled"
}

  断开蓝牙方法:

await gattServer.Disconnect();

  下列方法用来连接指定的蓝牙设备:

var connection = await ble.FindAndConnectToDevice(
   new ScanFilter()
      .SetAdvertisedDeviceName( "foo" )
      .SetAdvertisedManufacturerCompanyId( 0xffff )
      .AddAdvertisedService( guid ),
   TimeSpan.FromSeconds( 30 ) );
if(connection.IsSuccessful())
{
   // ...
}

  调用蓝牙的读特性

try
{
   var value = await gattServer.ReadCharacteristicValue( someServiceGuid, someCharacteristicGuid );
}
catch(GattException ex)
{
   Debug.WriteLine( ex.ToString() );
}

  监听通知特性

IDisposable notifyHandler;

try
{
   // Will also stop listening when gattServer
   // is disconnected, so if that is acceptable,
   // you don‘t need to store this disposable.
   notifyHandler = gattServer.NotifyCharacteristicValue(
      someServiceGuid,
      someCharacteristicGuid,
      // IObserver<Tuple<Guid, Byte[]>> or IObserver<Byte[]> or
      // Action<Tuple<Guid, Byte[]>> or Action<Byte[]>
      bytes => {/* do something with notification bytes */} );
}
catch(GattException ex)
{
   Debug.WriteLine( ex.ToString() );
}

// ... later, once done listening for notifications ...
notifyHandler.Dispose();

  调用写特性,注意:在写的时候不能一直不停的调用这个方法,不然会发送不了,需要停顿500毫秒左右在发送第二个包。这点非常重要。

try
{
   // The resulting value of the characteristic is returned. In nearly all cases this
   // will be the same value that was provided to the write call (e.g. `byte[]{ 1, 2, 3 }`)
   var value = await gattServer.WriteCharacteristicValue(
      someServiceGuid,
      someCharacteristicGuid,
      new byte[]{ 1, 2, 3 } );
}
catch(GattException ex)
{
   Debug.WriteLine( ex.ToString() );
}

  蓝牙有很多应用,需要自己多尝试,对于蓝牙的升级DFU功能,需要的可以找我。

原文地址:https://www.cnblogs.com/zuimengaitianya/p/12153093.html

时间: 2024-08-02 05:32:40

Xamarin.Form 蓝牙ble的相关文章

C# 移动开发(Xamarin.Form) Plugin.BLE 蓝牙连接

随着Xamarin.Form项目接近尾声,仔细一算才发现过来大半年时间了. 期间除了刚开始有闲情写写,期间各种开发坑,老板坑,状态不好搞得没心情写博了,现在总算有空来总结一下了. 来先说 Plugin.BLE (https://github.com/xabre/xamarin-bluetooth-le),在NuGet里搜索 Bluetooth ,Plugin.BLE是下载最多的Xamarin.Form可用的库,有16.3K(1.63万)人下载(2017-11-23). 几乎可用库都试过 调用 P

蓝牙(BLE)应用框架接口设计和应用开发——以TI CC2541为例

本文从功能需求的角度分析一般蓝牙BLE单芯片的应用框架(SDK Framework)的接口设计过程,并以TI CC2541为例说明BLE的应用开发方法. 一.应用框架(Framework) 我们熟知的Framework包括Android Framework.Linux QT.Windows MFC.应用框架抽象并封装实现了一般应用场景的需求,完成应用开发的80%,剩下的20%则以回调(callback)和接口的方式供应用开发人员调用以完成具体的需求. 一般Framework完成的工作包括:任务分

Xamarin.Form 下拉刷新动画

好像园子里对 Xamarin 感兴趣的人很少啊... 来, 先给各位爷们逗个笑, 本山大爷本色出演: 照例, 上源码: https://github.com/gruan01/ListViewExtend 目前只有 WP 的效果, Android 还在研究, IOS 的还没计划. ------------------------------------------------------ Xamarin.Form 的 ListView 只支持下拉刷新 (这里有用法), 上拉 加载更多 没有对应的事

FlipView For Xamarin.Form 之 IOS

之前写过两篇博文 是关于 Android 和 Windows Phone 下的 FlipView 的实现. 上上周,有个印度佬通过 GitHub 找到我, 问我有没有打算个 ios 端的,还说比较了相同功能的几个开源项目,我的这个项目值得推荐.说的我心潮澎湃,上周末花了一个周末升级到最新的 XCode 7,顺便也升级到了 OS X EI Capitan, 安装了最新的 Xamarin, 使用了 IOS 9 提供的免费证书,终于于今天凌晨1点(10月25)把 ios 端的 renderer 给写出

【转】蓝牙ble app开发(三) -- 抓包

原文网址:http://blog.csdn.net/lckj686/article/details/43156617 关于android 蓝牙app开发抓包的重要性在 android 蓝牙ble app开发(二) -- 关键概念,连接参数,连接请求 中已经详细描述就不再熬述了固件基于cc2540  cc2541 1.环境 需要一个抓包器几十块钱, USBdongle 装Packet Sniffer软件进行抓包. 环境搭建可以参考:http://blog.csdn.net/mzy202/artic

Xamarin.Form 实例: Discuz BBS 客户端 源码分享

感谢台风, 这个十一长假让我好好的休息了一回, 睡觉到腰酸背疼, 看电影看到眼发红. 今天最后一天, 不敢出去逛, 不知道哪会还会下暴雨... 嗯嗯..这个项目其实在十一之前就开始了, 工作无聊,没有新任务, 我就搞起它. 至于为什么选 Discuz 的 BBS , 因为我常上的几个网站, 都有一堆的 APP , 官方的, 第三方的 . BBS 虽然已经没落了, 但是官方的 APP 居然用不了! 写这个东西之前, 本来想拿来看 1024 的, 但是 1024 要么不是最新版本, 要么禁用了 AP

挣扎着写 FlipView For Xamarin.Form

Xamarin.Form 中没有 FlipView, 也没有 CarouselView , 有的只是一个 CarouselPage, 它是一个 Page, 不是一个 View ! Windows Phone 8.1 下有个控件叫 FlipView, 但是它不存于在 WP Siliverlight ! 而Xamarin.Form 的 WP 项目又是基于 WP Siliverlight 的. Android 原生也没有 FlipView 类似的控件. IOS 下冒似也没有. 我急切的想弄一个这样的东

Xamarin.Form 初学 之 服务引用-WCF服务引用

最近研究一下Xamarin.Form,感觉这个东西确实不错,之前一直做WPF相关,然后看到Xamarin.Form开发与WPF特别相似的语法.很有兴趣! 可是环境部署对于小白的我,可是费了不少功夫!安装VS2015费了我好些时间!安装部署以后再说!先说说引用WCF服务的坑吧! 官方文档:Xamarin可以调用WCF,可以怎么调用???(满脑子问号)https://developer.xamarin.com/guides/xamarin-forms/web-services/consuming/w

&lt;转&gt;主流蓝牙BLE控制芯片详解(4):Nordic nRF51822

导读] nRF51822 是功能强大.高灵活性的多协议 SoC,非常适用于 Bluetooth® 低功耗和 2.4GHz 超低功耗无线应用. 同系列芯片资料推荐:    主流蓝牙BLE控制芯片详解(1):TI CC2540    主流蓝牙BLE控制芯片详解(2):CSR BC6130    主流蓝牙BLE控制芯片详解(3):创杰 IS1685S Nordic nRF51822简介 nRF51822 是功能强大.高灵活性的多协议 SoC,非常适用于 Bluetooth® 低功耗和 2.4GHz 超