⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bluetoothradio.cs

📁 老外的一个开源项目
💻 CS
字号:
// Copyright (c) David Vescovi.  All rights reserved.
// Part of Project DrumStix
// Windows Embedded Developers Interest Group (WE-DIG) community project.
// http://www.we-dig.org
// Copyright (c)  Microsoft Corporation.  All rights reserved.
//
//
// This source code is licensed under Microsoft Shared Source License
// Version 1.0 for Windows CE.
// For a copy of the license visit http://go.microsoft.com/?linkid=2933443.
//

#region Using directives

using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections;
using Gumstix.Utilities;
using Gumstix;
using OpenNETCF.IO;

#endregion

namespace Gumstix.Bluetooth 
{
	/// <summary>
	/// Represents the state of the Bluetooth radio and paired devices.
	/// </summary>
	public class BluetoothRadio : IDisposable
	{
		/// <summary>
		/// Initializes the networking system
		/// </summary>
		public BluetoothRadio()
		{
			disposed = false;

			// init winsock
			ushort winsockVersion = ((ushort)(((byte)(2)) | ((ushort)((byte)(2))) << 8));

			byte[] wsaData = new byte[512];

			int result = 0;

			result = SafeNativeMethods.WSAStartup(winsockVersion, wsaData);

			if (result != 0)
			{
				throw new System.Net.Sockets.SocketException();
			}
		}

		~BluetoothRadio()
		{
			Dispose();
		}


        private class BTD : StreamInterfaceDriver
        {
            private const Int32 FILE_DEVICE_SERVICE = 0x00000104;
            private const Int32 FILE_ANY_ACCESS = 0x0;
            private const Int32 METHOD_BUFFERED = 0x0;

            private enum BTD_IOCTL
		    {
			    ServiceStart = (((FILE_DEVICE_SERVICE) << 16) | ((FILE_ANY_ACCESS) << 14) | ((1) << 2) | (METHOD_BUFFERED)),
                ServiceStop  = (((FILE_DEVICE_SERVICE) << 16) | ((FILE_ANY_ACCESS) << 14) | ((2) << 2) | (METHOD_BUFFERED))
		    }

		    #region ctor / dtor
		    public BTD() : base("BTD0:")
		    {              
			    // open the driver
			    Open(FileAccess.ReadWrite, FileShare.ReadWrite);
		    }

		    ~BTD()
		    {
			    // close the driver
			    Close();
		    }
		    #endregion
            
            
            public void StartStack(bool start)
            {
                byte[] inbuffer = new byte[10];
                inbuffer[0] = 0x63;     // 'c'
                inbuffer[2] = 0x61;     // 'a'
                inbuffer[4] = 0x72;     // 'r'
                inbuffer[6] = 0x64;     // 'd'
                if (start)
                {
                    try
                    {
                        DeviceIoControl((int)BTD_IOCTL.ServiceStart, inbuffer, null);
                        System.Threading.Thread.Sleep(5000);        // time to start
                    }
                    catch (Exception)
                    {
                        throw new Exception("Unable to start Bluetooth stack");
                    }
                }
                else
                {
                    try
                    {
                        DeviceIoControl((int)BTD_IOCTL.ServiceStop, inbuffer, null);
                        System.Threading.Thread.Sleep(2000);        // time to stop
                    }
                    catch (Exception)
                    {
                        throw new Exception("Unable to stop Bluetooth stack:" + Marshal.GetLastWin32Error());
                    }
                }
            }
        }
        
        
        
        
        /// <summary>
		/// A collection representing Bluetooth devices which have been previously paired with this device.
		/// </summary>
		public BluetoothDeviceCollection PairedDevices
		{
			get
			{
				BluetoothDeviceCollection pairedDevices = new BluetoothDeviceCollection();

				const string BT_DEVICE_KEY_NAME = "Software\\Microsoft\\Bluetooth\\Device";

				IntPtr btDeviceKey = Registry.OpenKey(Registry.GetRootKey(Registry.HKey.LOCAL_MACHINE), BT_DEVICE_KEY_NAME);

				ArrayList subKeyNames = Registry.GetSubKeyNames(btDeviceKey);

				foreach (string deviceAddr in subKeyNames)
				{
					string deviceName = "";
					byte[] deviceAddress = new byte[8];

					IntPtr currentDeviceKey = Registry.OpenKey(btDeviceKey, deviceAddr);

					deviceName = (string)Registry.GetValue(currentDeviceKey, "name");

					Registry.CloseKey(currentDeviceKey);

					long longDeviceAddress = long.Parse(deviceAddr, System.Globalization.NumberStyles.HexNumber);
					BitConverter.GetBytes(longDeviceAddress).CopyTo(deviceAddress, 0);

					BluetoothDevice currentDevice = new BluetoothDevice(deviceName, deviceAddress);

					pairedDevices.Add(currentDevice);
				}

				Registry.CloseKey(btDeviceKey);

				return pairedDevices;
			}
		}


        /// <summary>
		/// The current state of the Bluetooth radio
		/// </summary>
		public BluetoothRadioMode BluetoothRadioMode
		{
			get
			{
				BluetoothRadioMode currentMode = BluetoothRadioMode.Off;
                int status = 0;

                if (0 == SafeNativeMethods.BthGetHardwareStatus(ref status))
                {
                    if (BluetoothRadioHardware.RUNNING == (BluetoothRadioHardware)status)
                    {
                        currentMode = BluetoothRadioMode.On;
                    }

                }

				return currentMode;
			}

			set
			{
                BTD btd = new BTD();
                switch (value)
                {
                    case BluetoothRadioMode.On:
                        if (BluetoothRadioMode == BluetoothRadioMode.Off)
                        {
                            btd.StartStack(true);
                        }
                        break;
                    case BluetoothRadioMode.Off:
                        if (BluetoothRadioMode == BluetoothRadioMode.On)
                        {
                            btd.StartStack(false);
                        }
                        break;

                    // TBD discoverable?
                }
            }
		}

		#region IDisposable Members

		public void Dispose()
		{
			if (!disposed)
			{
				SafeNativeMethods.WSACleanup();
				disposed = true;
			}
		}

		#endregion

		bool Disposed
		{
			get
			{
				return disposed;
			}
		}

		private bool disposed = false;
	}

	/// <summary>
	/// Represents the Bluetooth radio state
	/// </summary>
	public enum BluetoothRadioMode : int
	{
		/// <summary>
		/// Off: Bluetooth hardware is powered off
		/// </summary>
		Off,
		/// <summary>
		/// On: Bluetooth hardware is powered on
		/// </summary>
		On,
        /// <summary>
		/// Discoverable: Bluetooth hardware is powered on and device advertises itself to others
		/// </summary>
		Discoverable
    };

	/// <summary>
	/// Represents the Bluetooth hardware status
    /// HCI_HARDWARE
	/// </summary>
    public enum BluetoothRadioHardware : int
    {
        UNKNOWN = 0,
        NOT_PRESENT = 1,
        INITIALIZING = 2,
        RUNNING = 3,
        SHUTDOWN = 4,
        ERROR = 5
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -