精华内容
下载资源
问答
  • 2022-03-28 14:11:32

    编程工具:Visual Studio 2022社区版
    创建C# Form项目
    需要在__工具__>>__ NuGet包__下载InTheHand.Net.Bluetooth

    蓝牙连接部分

    program.cs中的代码如下
    这部分只负责蓝牙连接

    using System;
    using InTheHand.Net.Sockets;
    using InTheHand;
    using InTheHand.Net.Bluetooth;
    using System.Threading;
    using System.IO;
    using System.Text;
    using System.Collections.Generic;
    using System.Diagnostics;
    
    namespace blueTooth1
    {
        internal static class Program
        {
            
    
            public static BluetoothClient bluetoothClient;
            public static bool isConnected;
    
            public static bool getDevice()
            {
                Trace.WriteLine("Finding Devides...");
                //BluetoothRadio.PrimaryRadio.Mode = InTheHand.Net.Bluetooth.RadioMode.Connectable;
                BluetoothClient cli = new BluetoothClient();
                IReadOnlyCollection<BluetoothDeviceInfo> devices = cli.DiscoverDevices();
                foreach (BluetoothDeviceInfo device in devices) //设备搜寻           
                {
                    //device.Update();
                    device.Refresh();
                    Trace.WriteLine(device.DeviceName);
                    if (device.DeviceName == "JDY-31-SPP")//蓝牙名称,需要自己修改,连接前请打开蓝牙
                    {
                        Trace.WriteLine("Connecting...");
                        try
                        {
                            if (!device.Connected)
                            {
                                Debug.WriteLine(device.DeviceAddress);
                                Debug.WriteLine(BluetoothService.SerialPort);
                                cli.Connect(device.DeviceAddress, BluetoothService.Handsfree);//BluetoothService.Handsfree
                                Trace.WriteLine("Connected!");
    
                                bluetoothClient = cli;
                                ReceiveData();
                            }
                            else
                                Trace.WriteLine("Has Been Connected!");
                        }
                        catch (Exception e)
                        { Trace.WriteLine("Failed:" + e);
                            try
                            {
                                cli.Connect(device.DeviceAddress, BluetoothService.SerialPort);//BluetoothService.Handsfree
                                Trace.WriteLine("Connected!");
    
                                bluetoothClient = cli;
                                ReceiveData();
                            }
                            catch (Exception e0)
                            {
                                Trace.WriteLine("Failed:" + e0);
                            }
                            
                        }
    
                        break;
                    }
                }
    
                //Thread ReceiveThread = new Thread(ReceiveData);
                //ReceiveThread.Start();
                return true;
            }
    
            private static void ReceiveData()
            {
                isConnected = bluetoothClient.Connected;
    //下面这部分是获取所连接的蓝牙设备发送的信息
                //while (isConnected)
                //{
                //    try
                //    {
                //        string receive = string.Empty;
    
                //        Stream peerStream = bluetoothClient.GetStream();
                //        byte[] buffer = new byte[255];
                //        peerStream.Read(buffer, 0, 255);
                //        receive = Encoding.UTF8.GetString(buffer).ToString().Replace("\0", "");
    
                //        //Trace.ReadKey();
                //        Trace.Write(receive);
                //    }
                //    catch (Exception e)
                //    {
                //        Trace.Write("Error:" + e);
                //        break;
                //    }
                //}
            }
    
        }
    }
    
    
    
    namespace blueTooth
    {
        internal static class Program
        {
            /// <summary>
            ///  The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                Trace.WriteLine("hello"); 
                blueTooth1.Program.getDevice();
                // To customize application configuration such as set high DPI settings or default font,
                // see https://aka.ms/applicationconfiguration.
                ApplicationConfiguration.Initialize();
                Application.Run(new Form1());
            }
        }
    }
    

    蓝牙消息发送部分

    发送的是ConnectPacket 数据类型需要自己定义

    在51单片机C语言程序里用SBUF 接收蓝牙发送的消息(注意大写)

    private void send()
            {
                if (ConnectPacket != null)
                {
                    if (blueTooth1.Program.isConnected)
                    {
    
                        try
                        {
                            string receive = string.Empty;
                            BluetoothClient BC = blueTooth1.Program.bluetoothClient;
                            Stream peerStream = BC.GetStream();
                            //byte[] buffer = new byte[255];
                            peerStream.WriteByte((byte)ConnectPacket);//发送ConnectPacket消息
    
                            //Trace.ReadKey();
                           // Trace.Write(ConnectPacket);
                        }
                        catch (Exception er)
                        {
                            Trace.Write("Error:" + er);
                        }
    
                    }
                    Thread.Sleep(100);
                }
            }
    
    更多相关内容
  • C# 蓝牙通讯实例

    2018-11-22 11:33:32
    主要实现了PC蓝牙基本通信,具有一定的参考价值,包括蓝牙配对和文件收发,本文实例为大家分享了C#实现PC蓝牙通信代码。
  • c# 蓝牙通讯 winform

    2021-12-27 20:44:37
    c#蓝牙通讯代码,在win10机器间可以通讯。代码是我根据网上找的资料整合起来的,在稍稍加上自己的业务逻辑。
  • c#蓝牙通讯源码

    2018-11-08 08:36:46
    这是一个c#蓝牙通讯源代码,供大家参考学习。
  • 蓝牙,异步初始化,
  • #SimpleBTComms 这是我几年前为一个类项目编写的一个简单示例应用程序。 该应用程序旨在从连接了蓝牙控制器的Arduino主板读取数据。 该代码可能无法维护,因此使用后果自负!
  • C#ble低功耗蓝牙

    热门讨论 2019-03-07 17:27:28
    弄了好久的C#WINFORM上的低功耗蓝牙,需要在WIN10上 VS2017上运行的。
  • 1、蓝牙介绍 蓝牙技术是一种无线数据和语音通信开放的全球规范,它是基于低成本的近距离无线连接,为固定和移动设备建立通信环境的一种特殊的近距离无线技术连接。 蓝牙作为一种小范围无线连接技术,能在设备间...

    1、蓝牙介绍

    蓝牙技术是一种无线数据和语音通信开放的全球规范,它是基于低成本的近距离无线连接,为固定和移动设备建立通信环境的一种特殊的近距离无线技术连接。

    蓝牙作为一种小范围无线连接技术,能在设备间实现方便快捷、灵活安全、低成本、低功耗的数据通信和语音通信,因此它是实现无线个域网
    通信的主流技术之一。与其他网络相连接可以带来更广泛的应用。是一种尖端的开放式无线通信,能够让各种数码设备无线沟通,是无线网络传输技术的一种,原本用来取代红外
    线通信。

    2、蓝牙在项目中应用

    最近一个项目中要求采集设备和Windows平板之间需要通过无线,低功耗的设备进行传输,由于蓝牙的特点完全适合与本项目,因此选用蓝牙进行Windows计算机与下位机单片机进行通讯,在Windows下对于蓝牙的编程很小众,基本无资料,本人对蓝牙通讯做了以下的了解和使用。

    a、蓝牙设备连接和配置

    在Windows系统中,使用蓝牙设备其实作为串口设备进行通讯的,其实就是无线版的串口设备,对蓝牙操作就需要在系统中连接好蓝牙并设置蓝牙的串口,步骤见下图,①单击通知->②右击蓝牙图标,进入配置界面

    在系统中进行下位机蓝牙模块进行配对连接,配对之后需要点击右侧的“更多蓝牙选项”标签,对蓝牙设备的串口进行配置。

    单击添加按钮选择传入,配置蓝牙的串口号,注:不要与主板上其他的串口号冲突,可以到设备管理器中查看空闲的串口号

    b、蓝牙串口通讯

    前面的博文介绍了C#的SerialPort控件,在此不在赘述,此控件就是针对与串口通讯的,对于蓝牙的通讯其实就是串口的通讯了,这里要注意一下,由于蓝牙的串口是通过无线接入的,和主板自带的串口存在差别,蓝牙的串口在未连接到下位机设备时会存在Write()方法出现写超时卡顿的现象,因此需要根据发送数据的时间进行WriteTimeout写超时数据配置,这个值默认为60秒,在作者的项目中,这个值设定为5秒,防止蓝牙断开后发送数据长时间阻塞的问题,影响通讯效率,蓝牙在断开后Windows系统会自动进行重连,串口访问时无需再次调用打开串口。

    展开全文
  • 详细介绍了 在.netcf如何与蓝牙设备互相通讯
  • C#连接低耗蓝牙源码例子,支持连接,发送,接收
  • c#下BLE蓝牙通信

    2022-04-14 19:34:26
    c#BLE蓝牙通信简单记录

            工作需要,要求在原有的c#界面中添加ble蓝牙通信模块,想要嵌入到原有代码中;这里网上也是有很多实例,也是参考了许多博主的文章其实都大同小异,主要还是在环境搭建这里;

            我首先新建了一个c#控制台应用,初步实现对蓝牙的搜索和链接后续在将其移植到代码中实现需要的逻辑;下面主要以在控制台实现的通信作为一个记录。

            这里和蓝牙模块初步实现了一个通信协议,所以在下文中会出现数据的发送和接收;

    一:环境准备

    1:修改 “工程.csproj” ,在其中增加:

    <TargetPlatformVersion>10.0</TargetPlatformVersion>

    2:重新加载项目

    3:右键点击工程选择“添加”--->"引用"

     二:核心代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.Devices.Bluetooth;
    using Windows.Devices.Bluetooth.Advertisement;
    using Windows.Devices.Bluetooth.GenericAttributeProfile;
    using Windows.Devices.Enumeration;
    using Windows.Foundation;
    using Windows.Security.Cryptography;
    using Windows.Storage.Streams;
    using System.IO;
    using System.Windows.Forms;
    using System.Timers;
    //using bluetoothLE;
    
    
    namespace bluetoothLE
    {
       
        class BleCore
        {
            //设置定时器来限制搜索时间
            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
            //static string _name;
            // static string _rid, _wid, _nid;
            //  public static string Redastr;
    
            public static Guid Wid { get; set; }
            public static Guid Rid { get; set; }
            public static Guid Nid { get; set; }
            
    
            private static List<GattCharacteristic> characteristics = new List<GattCharacteristic>();
    
           
            private static void CharacteristicFinish(int size)
            {
                if (size <= 0)
                {
                    Console.WriteLine("设备未连上");
                    return;
                }
            }
    
            private static void Recdata(GattCharacteristic sender, byte[] data)
            {
                string str = BitConverter.ToString(data);
                Console.WriteLine(sender.Uuid + "             " + str);
            }
    
            private void CharacteristicAdded(GattCharacteristic gatt)
            {
                Console.WriteLine(
                    "handle:[0x{0}]  char properties:[{1}]  UUID:[{2}]",
                    gatt.AttributeHandle.ToString("X4"),
                    gatt.CharacteristicProperties.ToString(),
                    gatt.Uuid);
                if (gatt.CharacteristicProperties.ToString() == "Notify")
                {
                    Console.WriteLine(gatt.Uuid);
                    Nid = gatt.Uuid;
                }
                if (gatt.CharacteristicProperties.ToString() == "Read")
                {
                    Console.WriteLine(gatt.Uuid);
                   // Rid = gatt.Uuid;
                }
                if (gatt.CharacteristicProperties.ToString() == "WriteWithoutResponse, Write")
                {
                    Console.WriteLine(gatt.Uuid);
                    Wid = gatt.Uuid;
                }
    
                characteristics.Add(gatt);
            }
    
            private void DeviceWatcherChanged(BluetoothLEDevice currentDevice,string signal )
            {
                byte[] _Bytes1 = BitConverter.GetBytes(currentDevice.BluetoothAddress);
                Array.Reverse(_Bytes1);
                string address = BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower();
                Console.WriteLine("发现设备:<" + currentDevice.Name + ">  address:<" + address + ">"+ "  信号值:<"+ signal + ">");
                //Console.WriteLine("发现设备:{0,-  30}   address:<{1,15}>   信号值:{2,4}", currentDevice.Name, address,signal);
    
                //string str = getName();
    
                //string str = Name;
                string str = currentDevice.Name.Substring(0, 2);
                Console.WriteLine("截取的字符串长度:"+str);
    
                //   if (currentDevice.Name.Equals(str) || currentDevice.DeviceId.Contains("C1-29-63-15-A1-21"))
                // if (currentDevice.Name.Equals(str))
                if (str.Equals("G1"))
                {
                    ConnectDevice(currentDevice);
    
                    //GattCharacteristic gattCharacteristic = characteristics.Find((x) => { return x.Uuid.Equals(new Guid("6e400003-b5a3-f393-e0a9-e50e24dcca9e")); });
                    //  GattCharacteristic gattCharacteristic = characteristics.Find((x) => { return x.Uuid.Equals(Rid); });
                    // this.SetOpteron(gattCharacteristic);
    
                    //gattCharacteristic = characteristics.Find((x) => { return x.Uuid.Equals(new Guid("00002a00-0000-1000-8000-00805f9b34fb")); });
                    GattCharacteristic gattCharacteristic = characteristics.Find((x) => { return x.Uuid.Equals(Wid); });
                    this.SetOpteron(gattCharacteristic);
    
                    //gattCharacteristic = characteristics.Find((x) => { return x.Uuid.Equals(new Guid("6e400002-b5a3-f393-e0a9-e50e24dcca9e")); });
                    gattCharacteristic = characteristics.Find((x) => { return x.Uuid.Equals(Nid); });
    
                    this.SetOpteron(gattCharacteristic);
                    byte[] b = { 0x52, 0x4d, 0x10, 0x05, 0x05, 0x00, 0x01, 0x02, 0x03 };
                    this.Write(b);
    
                }
    
            }
    
            private void ConnectDevice(BluetoothLEDevice Device)
            {
                characteristics.Clear();
                this.StopBleDeviceWatcher();
                this.StartMatching(Device);
                this.FindService();
            }
    
             /* public static string getName()
              {
                  return _name;
              }
    
              public void setName(string name)
              {
                  _name = name;
              }
         */
    
            public string Name { get; set; }
            /*public void setRWNuuid(string Rid, string Wid, string Nid)
            {
                _rid = Rid;
                _wid = Wid;
                _nid = Nid;
            }
    
            public static string GetRid()
            {
                return _rid;
            }
    
            public static string GetWid()
            {
                return _wid;
            }
    
            public static string GetNid()
            {
                return _nid;
            }
    */
            
            /*
            public string getReadValue()
            {
                return Redastr;
            }
    
            public void setReadValue(string str)
            {
                Redastr = null;
                Redastr = str;
            }*/
            public string ReadValue { get; set; }
    
    
    
            private bool asyncLock = false;
    
            /// <summary>
            /// 当前连接的服务
            /// </summary>
            private GattDeviceService CurrentService { get;  set; }
    
            /// <summary>
            /// 当前连接的蓝牙设备
            /// </summary>
            private BluetoothLEDevice CurrentDevice { get; set; }
    
            /// <summary>
            /// 写特征对象
            /// </summary>
            private GattCharacteristic CurrentWriteCharacteristic { get; set; }
    
            /// <summary>
            /// 通知特征对象
            /// </summary>
            private GattCharacteristic CurrentNotifyCharacteristic { get; set; }
    
            /// <summary>
            /// 存储检测到的设备
            /// </summary>
            private List<BluetoothLEDevice> DeviceList { get;  set; }
    
            /// <summary>
            /// 特性通知类型通知启用
            /// </summary>
            private const GattClientCharacteristicConfigurationDescriptorValue CHARACTERISTIC_NOTIFICATION_TYPE = GattClientCharacteristicConfigurationDescriptorValue.Notify;
    
    
            /// <summary>
            /// 当前连接的蓝牙Mac
            /// </summary>
            private string CurrentDeviceMAC { get; set; }
    
            private BluetoothLEAdvertisementWatcher Watcher = null;
    
            public BleCore()
            {
                DeviceList = new List<BluetoothLEDevice>();
    
                timer.Enabled = true;
                timer.Interval = 1500;//规定搜索15秒
                timer.Tick += new EventHandler(this.Timer1_Tick);
                timer.Stop();
            }
    
            /// <summary>
            /// 搜索蓝牙设备
            /// </summary>
            public void StartBleDeviceWatcher()
            {
    
                Watcher = new BluetoothLEAdvertisementWatcher();
    
                Watcher.ScanningMode = BluetoothLEScanningMode.Active;
    
                // only activate the watcher when we're recieving values >= -80
               // Watcher.SignalStrengthFilter.InRangeThresholdInDBm = -80;
    
                // stop watching if the value drops below -90 (user walked away)
                //Watcher.SignalStrengthFilter.OutOfRangeThresholdInDBm = -90;
    
                // register callback for when we see an advertisements
                Watcher.Received += OnAdvertisementReceived;
    
                // wait 5 seconds to make sure the device is really out of range
                Watcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(5000);
                Watcher.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(2000);
    
                // starting watching for advertisements
                //设置定时器来限制蓝牙搜索时间
    
                timer.Start();
                Watcher.Start();
    
                
    
                Console.WriteLine("自动发现设备中..");
            }
    
            private void Timer1_Tick(object sender, EventArgs e)
            {
                StopBleDeviceWatcher();//停止搜索蓝牙
                Console.WriteLine("停止搜索");
                timer.Stop();
                //throw new NotImplementedException();
            }
    
            /// <summary>
            /// 停止搜索蓝牙
            /// </summary>
            public void StopBleDeviceWatcher()
            {
                if (Watcher != null)
                    this.Watcher.Stop();
            }
    
            /// <summary>
            /// 主动断开连接
            /// </summary>
            /// <returns></returns>
            public void Dispose()
            {
                CurrentDeviceMAC = null;
                CurrentService?.Dispose();
                CurrentDevice?.Dispose();
                CurrentDevice = null;
                CurrentService = null;
                CurrentWriteCharacteristic = null;
                CurrentNotifyCharacteristic = null;
                Console.WriteLine("主动断开连接");
            }
    
            /// <summary>
            /// 匹配
            /// </summary>
            /// <param name="Device"></param>
            private void StartMatching(BluetoothLEDevice Device)
            {
                this.CurrentDevice = Device;
            }
    
            /// <summary>
            /// 发送数据接口
            /// </summary>
            /// <returns></returns>
            public void Write(byte[] data)
            {
                if (CurrentWriteCharacteristic != null)
                 {
                     CurrentWriteCharacteristic.WriteValueAsync(CryptographicBuffer.CreateFromByteArray(data), GattWriteOption.WriteWithResponse).Completed = (asyncInfo, asyncStatus) =>
                     {
                         if (asyncStatus == AsyncStatus.Completed)
                         {
                             
                             GattCommunicationStatus a = asyncInfo.GetResults();
                             Console.WriteLine("发送数据:" + BitConverter.ToString(data) + " State : " + a);
                         }
                     };
                 }
                
    
    
            }
    
            /// 获取蓝牙服务
            /// </summary>
            private void FindService()
            {
                this.CurrentDevice.GetGattServicesAsync().Completed = (asyncInfo, asyncStatus) =>
                {
                    if (asyncStatus == AsyncStatus.Completed)
                    {
                        var services = asyncInfo.GetResults().Services;
                        Console.WriteLine("GattServices size=" + services.Count);
                        foreach (GattDeviceService ser in services)
                        {
                            FindCharacteristic(ser);
                        }
                        //CharacteristicFinish?.Invoke(services.Count);
                        CharacteristicFinish(services.Count);
                    }
                };
    
            }
    
            /// <summary>
            /// 按MAC地址直接组装设备ID查找设备
            /// </summary>
            public void SelectDeviceFromIdAsync(string MAC)
            {
                CurrentDeviceMAC = MAC;
                CurrentDevice = null;
                BluetoothAdapter.GetDefaultAsync().Completed = (asyncInfo, asyncStatus) =>
                {
                    if (asyncStatus == AsyncStatus.Completed)
                    {
                        BluetoothAdapter mBluetoothAdapter = asyncInfo.GetResults();
                        byte[] _Bytes1 = BitConverter.GetBytes(mBluetoothAdapter.BluetoothAddress);//ulong转换为byte数组
                        Array.Reverse(_Bytes1);
                        string macAddress = BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower();
                        string Id = "BluetoothLE#BluetoothLE" + macAddress + "-" + MAC;
                        Matching(Id);
                    }
                };
            }
    
            /// <summary>
            /// 获取操作
            /// </summary>
            /// <returns></returns>
            private void SetOpteron(GattCharacteristic gattCharacteristic)
            {
                byte[] _Bytes1 = BitConverter.GetBytes(this.CurrentDevice.BluetoothAddress);
                Array.Reverse(_Bytes1);
                this.CurrentDeviceMAC = BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower();
    
                string msg = "正在连接设备<" + this.CurrentDeviceMAC + ">..";
                Console.WriteLine(msg);
               
    
                if (gattCharacteristic.CharacteristicProperties == GattCharacteristicProperties.Write)
                {
                    this.CurrentWriteCharacteristic = gattCharacteristic;
                }
                if (gattCharacteristic.CharacteristicProperties == GattCharacteristicProperties.Notify)
                {
                    this.CurrentNotifyCharacteristic = gattCharacteristic;
                    this.CurrentNotifyCharacteristic.ProtectionLevel = GattProtectionLevel.Plain;
                    this.CurrentNotifyCharacteristic.ValueChanged += Characteristic_ValueChanged;
                    this.CurrentDevice.ConnectionStatusChanged += this.CurrentDevice_ConnectionStatusChanged;
                    this.EnableNotifications(CurrentNotifyCharacteristic);
                } 
                if (gattCharacteristic.CharacteristicProperties == (GattCharacteristicProperties.WriteWithoutResponse |GattCharacteristicProperties.Write) )
                {
                    //Console.WriteLine("WriteWithoutResponse----------");
                    this.CurrentWriteCharacteristic = gattCharacteristic;
                }
                if ((uint)gattCharacteristic.CharacteristicProperties == 26)
                {
                   // Console.WriteLine("Write26----------");
    
                }
    
                if (gattCharacteristic.CharacteristicProperties == (GattCharacteristicProperties.Write | GattCharacteristicProperties.Notify))
                {
                    this.CurrentWriteCharacteristic = gattCharacteristic;
                    this.CurrentNotifyCharacteristic = gattCharacteristic;
                    this.CurrentNotifyCharacteristic.ProtectionLevel = GattProtectionLevel.Plain;
                    this.CurrentNotifyCharacteristic.ValueChanged += Characteristic_ValueChanged;
                    this.CurrentDevice.ConnectionStatusChanged += this.CurrentDevice_ConnectionStatusChanged;
                    this.EnableNotifications(CurrentNotifyCharacteristic);
                }
    
            }
    
            private void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
            {
    
                Int16 rssi = eventArgs.RawSignalStrengthInDBm;
                BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress).Completed = (asyncInfo, asyncStatus) =>
                {
                    if (asyncStatus == AsyncStatus.Completed)
                    {
                        if (asyncInfo.GetResults() == null)
                        {
                            //Console.WriteLine("没有得到结果集");
                        }
                        else
                        {
                            BluetoothLEDevice currentDevice = asyncInfo.GetResults();
    
                            if (DeviceList.FindIndex((x) => { return x.Name.Equals(currentDevice.Name); }) < 0)
                            {
                                this.DeviceList.Add(currentDevice);
                                // DeviceWatcherChanged?.Invoke(currentDevice);
                                DeviceWatcherChanged(currentDevice, rssi.ToString());
                            }
    
                        }
    
                    }
                };
            }
    
            /// <summary>
            /// 获取特性
            /// </summary>
            private void FindCharacteristic(GattDeviceService gattDeviceService)
            {
                this.CurrentService = gattDeviceService;
                this.CurrentService.GetCharacteristicsAsync().Completed = (asyncInfo, asyncStatus) =>
                {
                    if (asyncStatus == AsyncStatus.Completed)
                    {
                        var services = asyncInfo.GetResults().Characteristics;
                        foreach (var c in services)
                        {
                            //this.CharacteristicAdded?.Invoke(c);
                            CharacteristicAdded(c);
                        }
    
                    }
                };
            }
    
            /// <summary>
            /// 搜索到的蓝牙设备
            /// </summary>
            /// <returns></returns>
            private void Matching(string Id)
            {
                try
                {
                    BluetoothLEDevice.FromIdAsync(Id).Completed = (asyncInfo, asyncStatus) =>
                    {
                        if (asyncStatus == AsyncStatus.Completed)
                        {
                            BluetoothLEDevice bleDevice = asyncInfo.GetResults();
                            this.DeviceList.Add(bleDevice);
                            Console.WriteLine(bleDevice);
                        }
    
                        if (asyncStatus == AsyncStatus.Started)
                        {
                            Console.WriteLine(asyncStatus.ToString());
                        }
                        if (asyncStatus == AsyncStatus.Canceled)
                        {
                            Console.WriteLine(asyncStatus.ToString());
                        }
                        if (asyncStatus == AsyncStatus.Error)
                        {
                            Console.WriteLine(asyncStatus.ToString());
                        }
                    };
                }
                catch (Exception e)
                {
                    string msg = "没有发现设备" + e.ToString();
                    Console.WriteLine(msg);
                    this.StartBleDeviceWatcher();
                }
            }
    
    
            private void CurrentDevice_ConnectionStatusChanged(BluetoothLEDevice sender, object args)
            {
                if (sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected && CurrentDeviceMAC != null)
                {
                    if (!asyncLock)
                    {
                        asyncLock = true;
                        Console.WriteLine("设备已断开");
                        this.CurrentDevice?.Dispose();
                        this.CurrentDevice = null;
                        CurrentService = null;
                        CurrentWriteCharacteristic = null;
                        CurrentNotifyCharacteristic = null;
                        SelectDeviceFromIdAsync(CurrentDeviceMAC);
                    }
                }
                else
                {
                    if (!asyncLock)
                    {
                        asyncLock = true;
                        Console.WriteLine("设备已连接");
                    }
                }
            }
    
            /// <summary>
            /// 设置特征对象为接收通知对象
            /// </summary>
            /// <param name="characteristic"></param>
            /// <returns></returns>
            private void EnableNotifications(GattCharacteristic characteristic)
            {
                Console.WriteLine("收通知对象=" + CurrentDevice.Name + ":" + CurrentDevice.ConnectionStatus);
                characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(CHARACTERISTIC_NOTIFICATION_TYPE).Completed = (asyncInfo, asyncStatus) =>
                {
                    if (asyncStatus == AsyncStatus.Completed)
                    {
                        GattCommunicationStatus status = asyncInfo.GetResults();
                        if (status == GattCommunicationStatus.Unreachable)
                        {
                            Console.WriteLine("设备不可用");
                            if (CurrentNotifyCharacteristic != null && !asyncLock)
                            {
                                this.EnableNotifications(CurrentNotifyCharacteristic);
                            }
                            return;
                        }
                        asyncLock = false;
                        Console.WriteLine("设备连接状态" + status);
                    }
                };
            }
    
            /// <summary>
            /// 接受到蓝牙数据
            /// </summary>
            private void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
            {
                byte[] data;
                CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out data);
              //  Recdate?.Invoke(sender, data);
    
                string byteResult = BitConverter.ToString(data).Replace("-"," ");
    
                ReadValue = byteResult;
    
                Console.WriteLine(byteResult);
     
            }
    
        }
    }

    三:如何引用

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using bluetoothLE;
    
    namespace bluetoothLE
    {
        class MainFun
        {
           // private static BleCore bleCore = null;
            public static void Main(string[] args)
            {
                BleCore b = new BleCore();
                //bleCore = b.getBleCore();
                b.StartBleDeviceWatcher();
                
                byte[] by = { 0x52, 0x4d, 0x10, 0x05, 0x05, 0x00, 0x01, 0x02, 0x03 };
                string s = "52 4d 10 05 05 00 01 02 03";
                byte[] byteArray = System.Text.Encoding.Default.GetBytes(s);
                //byte[] byteArray = BitConverter.GetBytes()
                Console.WriteLine(BitConverter.ToString(byteArray));
                while (true)
                {
    
                    if (Console.ReadLine() == "q")
                    {
                        b.Dispose();
                    }
                    b.Write(by);
                   // if (b.getReadValue() != null)
                    //{
                        Console.WriteLine("接收到的数据:"+ b.ReadValue);
                   // }
    
                }
            }
        }
    }
    

    展开全文
  • C#编写的蓝牙通讯程序源码,常用WIN系统蓝牙识别和驱动。
  • C#代码连接蓝牙设备

    2019-09-05 11:40:29
    c#代码编写连接 PC 蓝牙连接到苹果手机的蓝牙,测试连接可行,网上很多代码,很混乱,不好连接!
  • C# 蓝牙通信

    2015-04-10 17:43:39
    C# 蓝牙通信 获取电子设备发送的数据。上传下载
  • 主要介绍了Windows系统中使用C#编写蓝牙通信程序的简单实例,文中的例子使用到了32feet.NET中的InTheHand.Net.Personal类库,需要的朋友可以参考下
  • c#编写的蓝牙通讯程序源码用c#编写的程序,用与两个蓝牙设备的通讯,有发送数据等功能.
  • C#蓝牙检索、通讯.rar

    2021-06-22 11:23:38
    通过第三方库InTheHand.Net.Personal.dll,检索附近可用蓝牙设备,实现通信,可直接运行
  • 之前做项目的时候,需要使用电脑程序通过蓝牙向硬件设备发送指令,于是便研究了一下怎么用C#程序和蓝牙进行通信。 1、思路 电脑蓝牙蓝牙模块配对连接 和我们平时正常连接蓝牙设备一样,需要先搜索附近的蓝牙设备...

    之前做项目的时候,需要使用电脑程序通过蓝牙向硬件设备发送指令,于是便研究了一下怎么用C#程序和蓝牙进行通信。

    1、思路

    1. 电脑蓝牙和蓝牙模块配对连接
      和我们平时正常连接蓝牙设备一样,需要先搜索附近的蓝牙设备,然后根据设备名来选择要连接的蓝牙模块,连接时就根据该蓝牙模块的地址(惟一标识号)来进行连接。
    2. 发送数据给蓝牙模块
      发送的过程就和平时读写文件很类似,只是IO流不一样的区别

    2、实现

    2.1 使用的库

    C#进行蓝牙操作需要用到的库是 InTheHand.Net。在VS中可以直接在Nuget中安装,这是我觉得VS最好用的一个找各种库的最好的方法。
    工具菜单->NuGet包管理器->管理解决方案的Nuget程序包
    在这里插入图片描述
    然后直接搜索 InTheHand.Net,选择对应的库文件之后点击安装即可使用
    在这里插入图片描述

    2.2 搜索附近的蓝牙设备

    BluetoothClient client = new BluetoothClient();     //处理蓝牙的对象
    BluetoothRadio radio = BluetoothRadio.PrimaryRadio;  //获取电脑蓝牙
    radio.Mode = RadioMode.Connectable;     //设置电脑蓝牙可被搜索到
    BluetoothAddress blueAddress ;  		//需要连接的蓝牙模块的唯一标识符
    BluetoothDeviceInfo[] devices = client.DiscoverDevices(); 	//搜索蓝牙设备,10秒
     //从搜索到的所有蓝牙设备中选择需要的那个
     foreach (var item in devices) 
     {
         if(item.DeviceName.Equals("需要连接的蓝牙模块名字"))	//根据蓝牙名字找
         {
             Console.WriteLine(item.DeviceAddress);
             Console.WriteLine(item.DeviceName);
             blueAddress = item.DeviceAddress;			//获得蓝牙模块的唯一标识符
             break;
         }
         Console.WriteLine(item.DeviceAddress);
         Console.WriteLine(item.DeviceName);
     }
    

    搜索蓝牙设备的目的是为了得到想要连接的那个蓝牙模块的唯一标识符,如果之前这个蓝牙设备已经和电脑连接过,那么电脑上就会有设备记录,可以直接找到唯一标识符从而就可以省去上面的这一步直接进行连接。
    控制面板->设备和打印机-》右键想要连接的蓝牙设备->属性->蓝牙->唯一标识符
    在这里插入图片描述
    在这里插入图片描述
    在代码中只需要创建一个蓝牙唯一标识符的对象即可,但是填写唯一标识符的时候需要倒着填并且用16进制表示

    BluetoothAddress blueAddress = new BluetoothAddress(new byte[] { 0x21, 0x18, 0x28, 0x03, 0x19, 0x20 }) ; 
    

    3、样例代码

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using InTheHand.Net;
    using InTheHand.Net.Bluetooth;
    using InTheHand.Net.Sockets;
    
    namespace BluetoothStudy
    {
        class Program
        {
            static void Main(string[] args)
            {
                BluetoothClient client = new BluetoothClient();     //处理蓝牙的对象
                BluetoothRadio radio = BluetoothRadio.PrimaryRadio;  //获取电脑蓝牙
                radio.Mode = RadioMode.Connectable;     //设置电脑蓝牙可被搜索到
                BluetoothAddress blueAddress ;  		//需要连接的蓝牙模块的唯一标识符
                BluetoothDeviceInfo[] devices = client.DiscoverDevices(); 	//搜索蓝牙设备,10秒
                 //从搜索到的所有蓝牙设备中选择需要的那个
                 foreach (var item in devices) 
                 {
                     if(item.DeviceName.Equals("需要连接的蓝牙模块名字"))	//根据蓝牙名字找
                     {
                         Console.WriteLine(item.DeviceAddress);
                         Console.WriteLine(item.DeviceName);
                         blueAddress = item.DeviceAddress;			//获得蓝牙模块的唯一标识符
                         break;
                     }
                     Console.WriteLine(item.DeviceAddress);
                     Console.WriteLine(item.DeviceName);
                 }
                 
                BluetoothEndPoint ep = new BluetoothEndPoint(blueAddress, BluetoothService.SerialPort);
                Console.WriteLine("正在连接!");
                client.Connect(ep);   //开始配对 蓝牙4.0不需要setpin
                if(client.Connected)
                {
                    Console.WriteLine("连接成功!");
                    Stream peerStream = client.GetStream();		//创建IO流对象
                    string str = "发送的内容";
                    peerStream.Write(str,0,str.Length); // 发送开门指令
                    Console.WriteLine("发送成功!");
                }
            }
        }
    }
    
    

    4、总结

    • 处理类似蓝牙等和硬件相关的程序,一定是存在某个库专门来处理的,就拿InTheHand.Net这个库来举例子,我看了他们的官网,除了可以对蓝牙进行处理之外,还可以对NFC进行处理。所以在遇到一些不知道不同东西怎么结合的情况时,就多上网查有没有什么类似的库可以用
    • 一般拿到一个库时,大多数情况只需要一些最基本的功能,最好的学习方法就是找一个经典的代码例子,看懂了基本就知道怎么用了。但如果需要深度使用的话,最好就是上官网,官网都会有开发文档介绍具体的用法
    展开全文
  • C# 关于电脑通过蓝牙与手机手机进行通信的软件。通过简单算法和蓝牙技术实现手机客户端的和电脑的通信,这样就可以使得手机能够和电脑很好的通信,在此基础上,更加方便的实现手机和电脑通过蓝牙聊天,手机控制电脑...
  • C#编写的蓝牙通讯程序源码
  • 此软件来自一次课程设计,需要在PC端打开系统选择蓝牙对话框并与目标蓝牙进行连接,配对成功后,可以打开系统选择文件对话框,选择好要发送的文件后,可以向目标蓝牙发送文件,也可以向目标蓝牙发送指定字符。...
  • PC蓝牙通信C#代码实现

    2020-09-01 13:06:05
    主要为大家详细介绍了PC蓝牙通信C#代码实现,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
  • c#编写的蓝牙通讯侦听的程序 c#编写的蓝牙通讯侦听的程序 c#编写的蓝牙通讯侦听的程序
  • 有关蓝牙通信的小例子,自己写的,发上来跟大家交流一下
  • 蓝牙通讯示例

    2018-01-31 08:44:37
    基于 InTheHand.Net.Personal.dll的蓝牙通讯。完整项目代码。
  • 这边做了一个以c# wfm后台运行程序为服务的蓝牙通信中介(VS2017),调通了数据,但是后期与unity通信需要自己根据自己项目去设计研发。这边只做了Windows 端与低功耗蓝牙设备的检测,连接,通信,关闭。
  • 汇承HC-08蓝牙C#通讯 目录问题背景感谢BLE介绍参考代码参考业务逻辑参考库和例程难点介绍难点介绍新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片...
  • C#编写的蓝牙通讯程序源码codesky_net.rar

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 683
精华内容 273
关键字:

c#蓝牙通讯

c# 订阅
友情链接: shiwaiqihoujisuan.zip