public BLUETOOTH_DEVICE_INFO(BluetoothAddress address) { if (address == null) { throw new ArgumentNullException("address"); } dwSize = 560; this.Address = address.ToInt64(); ulClassofDevice = 0; fConnected = false; fRemembered = false; fAuthenticated = false; #if WinXP stLastSeen = new SYSTEMTIME(); stLastUsed = new SYSTEMTIME(); // The size is much smaller on CE (no times and string not inline) it // appears to ignore the bad dwSize value. So don't check this on CF. System.Diagnostics.Debug.Assert(Marshal.SizeOf(typeof(BLUETOOTH_DEVICE_INFO)) == dwSize, "BLUETOOTH_DEVICE_INFO SizeOf == dwSize"); #endif szName = ""; }
public CSADDR_INFO(BluetoothAddress local, BluetoothAddress remote, System.Net.Sockets.SocketType type, System.Net.Sockets.ProtocolType protocol) { //ensure zeros localAddr = IntPtr.Zero; localSize = 0; remoteAddr = IntPtr.Zero; remoteSize = 0; iSocketType = type; iProtocol = protocol; if (local != null) { #if V1 //have to use AllocHGlobal substitute localAddr = Marshal32.AllocHGlobal(40); Marshal.Copy(local.ToByteArray(), 0, new IntPtr(localAddr.ToInt32() + 8), 6); #else localAddr = Marshal.AllocHGlobal(40); Marshal.WriteInt64(localAddr, 8, local.ToInt64()); #endif Marshal.WriteInt16(localAddr, 0, 32); localSize = 40; } if (remote != null) { #if V1 remoteAddr = Marshal32.AllocHGlobal(40); Marshal.Copy(remote.ToByteArray(), 0, new IntPtr(remoteAddr.ToInt32() + 8), 6); #else remoteAddr = Marshal.AllocHGlobal(40); Marshal.WriteInt64(remoteAddr, 8, remote.ToInt64()); #endif remoteSize = 40; Marshal.WriteInt16(remoteAddr, 0, 32); } }
//#endif #region Set PIN /// <summary> /// This function stores the personal identification number (PIN) for the Bluetooth device. /// </summary> /// <param name="device">Address of remote device.</param> /// <param name="pin">Pin, alphanumeric string of between 1 and 16 ASCII characters.</param> /// <remarks><para>On Windows CE platforms this calls <c>BthSetPIN</c>, /// its MSDN remarks say: /// </para> /// <para>“Stores the pin for the Bluetooth device identified in pba. /// The active connection to the device is not necessary, nor is the presence /// of the Bluetooth controller. The PIN is persisted in the registry until /// BthRevokePIN is called. /// </para> /// <para>“While the PIN is stored, it is supplied automatically /// after the PIN request is issued by the authentication mechanism, so the /// user will not be prompted for it. Typically, for UI-based devices, you /// would set the PIN for the duration of authentication, and then revoke /// it after authentication is complete.” /// </para> /// <para>See also /// <see cref="M:InTheHand.Net.Bluetooth.BluetoothSecurity.RevokePin(InTheHand.Net.BluetoothAddress)"/> /// </para> /// </remarks> /// <returns>True on success, else False.</returns> /// <seealso cref="M:InTheHand.Net.Bluetooth.BluetoothSecurity.RevokePin(InTheHand.Net.BluetoothAddress)"/> public static bool SetPin(BluetoothAddress device, string pin) { #if WinCE if (pin.Length < 1 | pin.Length > 16) { throw new ArgumentException("Pin must be between 1 and 16 characters long."); } byte[] pinbytes = System.Text.Encoding.ASCII.GetBytes(pin); int len = pin.Length; int result = NativeMethods.BthSetPIN(device.ToByteArray(), len, pinbytes); if (result != 0) { int error = Marshal.GetLastWin32Error(); return false; } return true; #else //remove existing listener if(authenticators.ContainsKey(device)) { BluetoothWin32Authentication bwa = (BluetoothWin32Authentication)authenticators[device]; authenticators.Remove(device); bwa.Dispose(); } authenticators.Add(device, new BluetoothWin32Authentication(device, pin)); return true; //else //{ // throw new PlatformNotSupportedException("Use PairRequest to pair with a device from Windows XP"); //} #endif }
public static BluetoothDeviceInfo DeviceByAdress(string address) { return(new BluetoothDeviceInfo(BluetoothAddress.Parse(address))); }
/// <summary> /// Initializes a new instance of the <see cref="BluetoothListener"/> class /// that listens for incoming connection attempts on the specified local Bluetooth address and service identifier, /// publishing the specified SDP record. /// </summary> /// <param name="localaddr">A <see cref="BluetoothAddress"/> that represents the local Bluetooth radio address.</param> /// <param name="service">The Bluetooth service to listen for.</param> /// <param name="sdpRecord">Prepared SDP Record to publish</param> /// <param name="channelOffset"> /// The index in the <paramref name="sdpRecord"/> byte array where the RFCOMM Channel Number that the /// server is listening on is to be placed. /// However the supplied record is now parsed into an <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> /// instance, and the channel offset is not used. /// </param> /// <remarks> /// <note> /// The constructors taking the SDP record explicitly (as a byte array) should /// only be used if /// a specialized SDP record is required. For instance when using one of the /// standard profiles. Otherwise use one of the other constructors /// e.g. <see /// cref="M:InTheHand.Net.Sockets.BluetoothListener.#ctor(InTheHand.Net.BluetoothAddress,System.Guid)"/> /// which create a generic SDP Record from the specified service identifier. /// </note> /// <para>Instead of passing a byte array containing a hand-built record, /// the record can also be built using the <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/> /// and <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/> classes, and /// passed to the respective constuctor, e.g. /// <see cref="M:InTheHand.Net.Sockets.BluetoothListener.#ctor(InTheHand.Net.BluetoothAddress,System.Guid,InTheHand.Net.Bluetooth.ServiceRecord)"/> /// </para> /// <para>Any useful SDP record will include /// a <c>ProtocolDescriptor</c> element containing /// the RFCOMM Channel number that the server is listening on, /// and a <c>ServiceClassId</c> element containing the service UUIDs. /// The record supplied in the <paramref name="sdpRecord"/> parameter /// should contain those elements. On successful <see /// cref="M:InTheHand.Net.Sockets.BluetoothListener.Start"/>, /// the RFCOMM Channel number that the protocol stack has assigned to the /// server is retrieved, and copied into the service record before it is /// published. The <paramref name="channelOffset"/> indicates the location /// of the respective byte in the <paramref name="sdpRecord"/> byte array. /// </para> /// <para> /// An example SDP record is as follows. This is actually the format of the /// generic record used in the other constructors. For another example see /// the code in the <c>ObexListener</c> class. /// <code> /// // The asterisks note where the Service UUID and the Channel number are /// // to be filled in. /// byte[] record = new byte[] { /// //Element Sequence: /// 0x35,0x27, /// //UInt16: 0x0001 -- ServiceClassIdList /// 0x09,0x00,0x01, /// //Element Sequence: /// 0x35,0x11, /// // UUID128: 00000000-0000-0000-0000-000000000000 -- * Service UUID /// 0x1c, /// 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, /// 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, /// // /// //UInt16: 0x0004 -- ProtocolDescriptorList /// 0x09,0x00,0x04, /// //Element Sequence: /// 0x35,0x0c, /// // Element Sequence: /// 0x35,0x03, /// // UUID16: 0x0100 -- L2CAP /// 0x19,0x01,0x00, /// // Element Sequence: /// 0x35,0x05, /// // UUID16: 0x0003 -- RFCOMM /// 0x19,0x00,0x03, /// // UInt8: 0x00 -- * Channel Number /// 0x08,0x00 /// }; /// </code> /// For that record the <c>channelOffset</c> is 40. /// </para> /// </remarks> public BluetoothListener(BluetoothAddress localaddr, Guid service, byte[] sdpRecord, int channelOffset) : this(localaddr, service) { InitServiceRecord(sdpRecord, channelOffset); }
protected void Discovering() { while (discoveringThread == Thread.CurrentThread) { MsHid.NativeMethods.WSAStartup(); bluesoleil = BluesoleilService.Instance; bluesoleil.Initialize(); bluesoleil.ConnectionClosed += OnConnectionClosed; while (discoveringThread == Thread.CurrentThread) { EnsureBluesoleilStarted(bluesoleil); BluetoothDevice[] devices; try { // Scan for bluetooth-devices (like devices). devices = bluesoleil.InquireDevices(pollingTime); } catch (BluesoleilFailException) { // Happens sometimes randomly, but also happens sometimes when the bluetooth-dongle is unplugged. continue; } catch (BluesoleilNotReadyException) { // Happens when bluetooth is stopped or when the bluetooth-dongle is unplugged. Thread.Sleep(NotReadySleepTimeout); continue; } List<BluetoothAddress> notFoundAddresses = new List<BluetoothAddress>(lookupDeviceInfo.Keys); foreach (BluetoothDevice device in devices) { if (!IsWiiDevice(device)) continue; BluetoothAddress address = new BluetoothAddress(device.Address); if (lookupDeviceInfo.ContainsKey(address)) { notFoundAddresses.Remove(address); break; } BluetoothService[] services = null; try { // Scan for bluetooth-devices (like devices). services = bluesoleil.BrowseServices(device); Thread.Sleep(PostBrowseSleepTimeout); } catch (BluesoleilFailException) { // Happens sometimes randomly, but also happens sometimes when the bluetooth-dongle is unplugged. continue; } catch (BluesoleilNotReadyException) { // Happens when bluetooth is stopped or when the bluetooth-dongle is unplugged. continue; } if (services.Length != 3) continue; if (!lookupDeviceInfo.ContainsKey(address)) { BluesoleilDeviceInfo foundDevice = new BluesoleilDeviceInfo(device, services[1]); OnDeviceFound(foundDevice); } } // Remove the lost devices from the list and notify DeviceLost event. foreach (BluetoothAddress notFoundAddress in notFoundAddresses) { BluesoleilDeviceInfo notFoundDeviceInfo = lookupDeviceInfo[notFoundAddress]; OnDeviceLost(notFoundDeviceInfo); } Thread.Sleep(PollSleepTimeout); } bluesoleil.ConnectionClosed -= OnConnectionClosed; bluesoleil.Dispose(); } }
//TODO PairRequest XmlDocs for XP and CE pre 5.0. /// <summary> /// Intiates pairing for a remote device. /// </summary> /// <param name="device">Remote device with which to pair.</param> /// <param name="pin">Chosen PIN code, must be between 1 and 16 ASCII characters.</param> /// <remarks><para>On Windows CE platforms this calls <c>BthPairRequest</c>, /// its MSDN remarks say: /// </para> /// <para>“BthPairRequest passes the parameters to the <c>BthSetPIN</c> /// function and creates an ACL connection. Once the connection is established, /// it calls the <c>BthAuthenticate</c> function to authenticate the device.” /// </para> /// <para>On Windows XP/Vista platforms this calls <c>BluetoothAuthenticateDevice</c>, /// if the pin argument is set to null a Wizard is displayed to accept a PIN from the user, /// otherwise the function executes in transparent mode. /// </para> /// <para>See also /// <see cref="M:InTheHand.Net.Bluetooth.BluetoothSecurity.SetPin(InTheHand.Net.BluetoothAddress,System.String)"/> /// </para> /// </remarks> /// <returns>Whether the operation was successful.</returns> public static bool PairRequest(BluetoothAddress device, string pin) { if (device == null) { throw new ArgumentNullException("device"); } if (device.ToInt64() == 0) { throw new ArgumentNullException("device", "A non-blank address must be specified."); } #if WinCE if (pin == null) { throw new ArgumentNullException("pin"); } bool success = false; InTheHand.Net.Sockets.BluetoothDeviceInfo bdi = new InTheHand.Net.Sockets.BluetoothDeviceInfo(device); if (System.Environment.OSVersion.Version.Major >= 10) { byte[] pinbytes = System.Text.Encoding.ASCII.GetBytes(pin); int len = pin.Length; int result = NativeMethods.BthPairRequest(device.ToByteArray(), len, pinbytes); if (result == 0) { success = true; } } else { //BthPairRequest is CE 5.0 onwards so we will do it with individual steps //preset outgoing pin success = SetPin(device, pin); if (success) { int hresult; ushort handle = 0; //connect to device try { hresult = NativeMethods.BthCreateACLConnection(device.ToByteArray(), out handle); if (hresult != 0) { success = false; } else { // ushort default_sniff_max = 0x640; // 1 sec // ushort default_sniff_min = 0x4B0; // .75 sec m // ushort default_sniff_attempt = 0x20; // 0x1 // ushort default_sniff_to = 0x20; // 0x1 //force authentication hresult = NativeMethods.BthAuthenticate(device.ToByteArray()); if (hresult != 0) { success = false; } } } finally { if (handle != 0) { //close connection hresult = NativeMethods.BthCloseConnection(handle); } } } } if (success) { //setup UI pairing (registry) RegistryKey rkDevices = Registry.LocalMachine.CreateSubKey(NativeMethods.ceRegistryRoot + "\\Device"); RegistryKey rkNewDevice = rkDevices.CreateSubKey(device.ToString()); rkNewDevice.SetValue("name", bdi.DeviceName); rkNewDevice.SetValue("trusted", 1); rkNewDevice.SetValue("class", bdi.ClassOfDevice.GetHashCode()); #if V2 RegistryKey rkServices = rkNewDevice.CreateSubKey("Services"); ServiceRecord[] recs = bdi.GetServiceRecords(BluetoothService.SerialPort); //byte[][] recs = bdi.GetServiceRecordsUnparsedWindowsRaw(BluetoothService.SerialPort); if (recs.Length > 0) { byte[] servRecord = recs[0].SourceBytes; RegistryKey rkSerial = rkServices.CreateSubKey(BluetoothService.SerialPort.ToString()); rkSerial.SetValue("sdprecord", servRecord); rkSerial.SetValue("Name", "Serial Port"); rkSerial.SetValue("enabled", 1); int channel = ServiceRecordHelper.GetRfcommChannelNumber(recs[0]); if (channel != -1) { rkSerial.SetValue("channel", 0x14b0000 + channel); } else { System.Diagnostics.Debug.Fail("PairRequest CE, peer SPP record missing channel."); } rkSerial.Close(); } rkServices.Close(); #endif rkNewDevice.Close(); rkDevices.Close(); } return success; #else //use other constructor to ensure struct size is set BLUETOOTH_DEVICE_INFO bdi = new BLUETOOTH_DEVICE_INFO(device.ToInt64()); //string length, but allow for null pins for UI int length = 0; if (pin != null) { length = pin.Length; } int result = NativeMethods.BluetoothAuthenticateDevice(IntPtr.Zero, IntPtr.Zero, ref bdi, pin, length); if(result!=0) { //determine error cause from result... return false; } return true; #endif }
public static void RemoveDevice(BluetoothAddress address) { byte[] a = address.address; int result = BluetoothRemoveDevice(a); HandleError(result); }
// Runs on m_dataTread tread public void connectDevice() { //readFile(@"C:\Documents and Settings\Michael\My Documents\Downloads\Testdata.bin"); try { s_serialPort = null; s_client = null; string address = ApplicationSettings.Instance.DeviceAddress; if (address.Length > 0) { if (address.StartsWith("COM", true, null)) { try { s_serialPort = new SerialPort(address, 115200, Parity.None, 8, StopBits.One); s_serialPort.ReceivedBytesThreshold = 30; s_serialPort.Open(); s_stream = s_serialPort.BaseStream; s_serialPort.ReadTimeout = 300; readSerialPortLoop(); } catch (Exception ex) { Console.WriteLine("SerialPort Error:" + Environment.NewLine + ex.ToString()); } finally { s_serialPort.Close(); s_serialPort = null; } } else { BluetoothAddress btAddress = BluetoothAddress.Parse(address); if (m_channel == -1) { m_channel = GetRfcommChannelNumber(btAddress); } if (m_channel > -1) { BluetoothEndPoint endPoint = new BluetoothEndPoint(btAddress, SERVICE_UUID_STRING, m_channel); s_client = new BluetoothClient(); s_client.Connect(endPoint); s_stream = s_client.GetStream(); readStreamLoop(); } } } } catch (Exception ex) { Console.WriteLine("Connect To Device Error:" + Environment.NewLine + ex.ToString()); } try { if (BluetoothDisconnectEvent != null && m_connected && !m_exiting) { BluetoothDisconnectEvent(); } //m_form.Invoke(new EventHandler(m_form.OnDisconnect)); } catch (Exception ex) { Console.WriteLine("BluetoothDisconnectEvent Error:" + Environment.NewLine + ex.ToString()); } finally { m_connected = false; m_dataTread = null; } }
void DoConnect(BluetoothAddress address, Guid service) { }
public void ConnectSerial() { //let this thread recursively call scan until we get connected make_bt_thread = false; //this is the address we want BluetoothAddress addr = BluetoothAddress.Parse(address); nguid = new Guid("00001101-0000-1000-8000-00805F9B34FB"); BluetoothEndPoint ep = new BluetoothEndPoint(addr, nguid); //client.SetPin("1234"); if (client.Available == 1) { client.Authenticate = false; } //client.LingerState = new LingerOption(true,60); try { invoke_gui(ProcNameTrolley.BLUETOOTH_CONNECTION, "Attempting to pair with trolley", false); Thread.Sleep(100); client.Connect(ep); } catch (Exception e) { scan(); } connected = true; try { //if (serialstream != null) serialstream.Close(); if (client.Connected) { serialstream = client.GetStream(); } else { scan(); } } catch (InvalidOperationException) { scan(); } num_scans--; if (client.Connected && (num_scans == 0)) { make_bt_thread = true; //this thread will exit because we have a successfull connection and serial stream, allow for a new connect serial thread if connection is lost monitor = true; //allow for the connection to be monitored while (!no_monitor_threads) { ; //wait here until any previous monitor threads have exited } BluetoothMonitorThread = new Thread(new ThreadStart(MonitorConnection)); //create a new thread to monitor the connection BluetoothMonitorThread.IsBackground = true; BluetoothMonitorThread.Start(); invoke_gui(ProcNameTrolley.BLUETOOTH_CONNECTION, "Connected", false); } //BluetoothClientThread is now finishing, the only thread running from this point is monitor connection }
//---- internal static BluetopiaDeviceInfo CreateFromGivenAddress(BluetoothAddress addr, BluetopiaFactory factory) { return(new BluetopiaDeviceInfo(factory, addr)); }
public void SetAddress(String add) { addr = BluetoothAddress.Parse(add); }
public void SetPin(BluetoothAddress device, string pin) { #if WinXP if (pin != null) { m_authenticator = new BluetoothWin32Authentication(device, pin); } else { if (m_authenticator != null) { m_authenticator.Dispose(); } } #else byte[] link = new byte[32]; //copy remote device address if (device != null) { Buffer.BlockCopy(device.ToByteArray(), 0, link, 8, 6); } //copy PIN if (pin != null & pin.Length > 0) { if (pin.Length > 16) { throw new ArgumentOutOfRangeException("PIN must be between 1 and 16 ASCII characters"); } //copy pin bytes byte[] pinbytes = System.Text.Encoding.ASCII.GetBytes(pin); Buffer.BlockCopy(pinbytes, 0, link, 16, pin.Length); BitConverter.GetBytes(pin.Length).CopyTo(link, 0); } m_socket.SetSocketOption(BluetoothSocketOptionLevel.RFComm, BluetoothSocketOptionName.SetPin, link); #endif }
/// <summary> /// Gets the name of the specified remote device. /// </summary> /// <param name="a">Address of remote device.</param> /// <returns>Friendly name of specified device.</returns> public string GetRemoteMachineName(BluetoothAddress a) { #if WinXP BluetoothDeviceInfo bdi = new BluetoothDeviceInfo(a); return bdi.DeviceName; #else byte[] buffer = new byte[504]; //copy remote device address to buffer Buffer.BlockCopy(a.ToByteArray(), 0, buffer, 0, 6); try { clientSocket.SetSocketOption(BluetoothSocketOptionLevel.RFComm, BluetoothSocketOptionName.ReadRemoteName, buffer); string name = string.Empty; name = System.Text.Encoding.Unicode.GetString(buffer, 8, 496); int offset = name.IndexOf('\0'); if(offset > -1) { name = name.Substring(0, offset); } return name; } catch(SocketException ex) { System.Diagnostics.Debug.WriteLine("BluetoothClient GetRemoteMachineName(addr) ReadRemoteName failed: " + ex.Message); return null; } #endif }
/// <summary> /// Connects the client to a remote Bluetooth host using the specified Bluetooth address and service identifier. /// </summary> /// <param name="address">The BluetoothAddress of the remote host.</param> /// <param name="service">The Service Class Id of the service on the remote host. /// The standard Bluetooth service classes are provided on <see cref="BluetoothService"/>.</param> public void Connect(BluetoothAddress address, Guid service) { DoConnect(address, service); }
public MainWindow() { if (Settings.Default.UpdateSettings) { Settings.Default.Upgrade(); Settings.Default.UpdateSettings = false; Settings.Default.Save(); } DarkModeHelper.SetState(Settings.Default.DarkMode); _mainPage = new MainPage(this); _systemPage = new SystemPage(this); _selfTestPage = new SelfTestPage(this); _factoryResetPage = new FactoryResetPage(this); _findMyGearPage = new FindMyGearPage(this); _touchpadPage = new TouchpadPage(this); _customActionPage = new CustomActionPage(this); _ambientSoundPage = new AmbientSoundPage(this); _equalizerPage = new EqualizerPage(this); _connectionLostPage = new ConnectionLostPage(this); _deviceSelectPage = new DeviceSelectPage(this); _settingPage = new SettingPage(this); _updatePage = new UpdatePage(this); _advancedPage = new AdvancedPage(this); _unsupportedFeaturePage = new UnsupportedFeaturePage(this); _popupSettingPage = new PopupSettingPage(this); InitializeComponent(); _tbi = new TaskbarIcon(); Stream iconStream = Application.GetResourceStream(new Uri("pack://*****:*****@"CRITICAL: Unknown Win32 Bluetooth service error"); Console.WriteLine(e); } }
//-------- static string FromBluetoothAddress(BluetoothAddress address) { return(BluezUtils.FromBluetoothAddressToDbus(address)); }
// Implemented functions from IDevice public DevicePool Inquire() { DevicePool pool = new DevicePool(); IntPtr lpwsaqueryset = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WSAQUERYSET))); WSAQUERYSET wsaqueryset = new WSAQUERYSET(); wsaqueryset.dwSize = Marshal.SizeOf(typeof(WSAQUERYSET)); wsaqueryset.dwNameSpace = 16; WSAData data = new WSAData(); data.wHighVersion = 2; data.wVersion = 2; Marshal.StructureToPtr(wsaqueryset,lpwsaqueryset,false); int flags = (int)0x0002; flags |= (int)(0x1000|0x0010|0x0100); Int32 handle = 0; int result = 0; result = WSAStartup(36,data); if(result != 0) { throw new Exception("WSA Error, make sure you have the newest version (at least 2.2) of Winsock2!"); } result = WSALookupServiceBegin(wsaqueryset,flags,ref handle); if (result == -1) { int error = WSAGetLastError(); if (error == 10108) // No device attached { throw new Exception("You do not have a bluetooth device on your system."); } } while (0 == result) { Int32 dwBuffer = 0x10000; IntPtr pBuffer = Marshal.AllocHGlobal(dwBuffer); WSAQUERYSET qsResult = new WSAQUERYSET() ; result = WSALookupServiceNext(handle, flags, ref dwBuffer, pBuffer); if (0==result) { Marshal.PtrToStructure(pBuffer, qsResult); CS_ADDR_INFO addr = new CS_ADDR_INFO(); Marshal.PtrToStructure(qsResult.lpcsaBuffer, addr); sockaddr sa = new sockaddr(); Marshal.PtrToStructure(addr.RemoteAddr.lpSockaddr,sa); monotooth.BluetoothAddress ba = new BluetoothAddress(); for (int i = 5; i >= 0; i--) { ba.Array[i] = sa.sa_data[i]; } WindowsRemoteDevice dev = new WindowsRemoteDevice(ba, qsResult.szServiceInstanceName); pool.Add(dev); } else { WSALookupServiceEnd(handle); } Marshal.FreeHGlobal(pBuffer); } Marshal.FreeHGlobal(lpwsaqueryset); WSACleanup(); return pool; }
//---- public BluezRfcommEndPoint(BluetoothAddress address, int scn) : base(address, BluetoothService.Empty, scn) { }
private void Register(BluetoothAddress remoteAddress) { System.Diagnostics.Debug.Assert(m_pin == null ^ m_userCallback == null); // m_callback = new NativeMethods.BluetoothAuthenticationCallback(NativeCallback); BLUETOOTH_DEVICE_INFO bdi = new BLUETOOTH_DEVICE_INFO(remoteAddress); UInt32 ret = NativeMethods.BluetoothRegisterForAuthentication( ref bdi, out m_regHandle, m_callback, IntPtr.Zero); int gle = Marshal.GetLastWin32Error(); System.Diagnostics.Debug.Assert(ret == NativeErrorSuccess, "BluetoothRegisterForAuthentication failed, GLE=" + gle.ToString() + "=0x)" + gle.ToString("X")); if (ret != NativeErrorSuccess) { throw new System.ComponentModel.Win32Exception(gle); } m_regHandle.SetObjectToKeepAlive(m_callback); }
void AddKnownAddress(BluetoothAddress value) {//TO-DO Does Android have suggested input feature? }
/// <summary> /// <para><b>Not supported on Windows XP</b></para> /// </summary> /// <param name="a"></param> /// <param name="linkkey"></param> /// <remarks><para>On Windows CE platforms this calls <c>BthSetLinkKey</c>, /// its MSDN remarks say: /// </para> /// <para>“The link key is persisted in registry until <c>BthRevokeLinkKey</c> /// is called. /// </para> /// <para>“Typically, the Bluetooth stack manages link keys automatically, /// for example, it stores them when they are created. This function is useful /// primarily for backup purposes. /// </para> /// <para>“While link key is stored, it will be automatically supplied /// once the link key request is issued by the authentication mechanism. If /// the link key is incorrect, the renegotiation that involves the PIN is /// initiated by the Bluetooth adapter, and the PIN code may be requested /// from the user. /// </para> /// <para>“The link key length is 16 bytes. You cannot create link /// keys; they are generated by the Bluetooth hardware.” /// </para> /// </remarks> /// <returns></returns> public static bool SetLinkKey(BluetoothAddress a, Guid linkkey) { #if WinCE int result = NativeMethods.BthSetLinkKey(a.ToByteArray(), ref linkkey); if(result!=0) { return false; } return true; #else throw new PlatformNotSupportedException("Not supported on Windows XP"); #endif }
public BluezStream(BluetoothAddress address) : this(address.ToString()) { }
/// <summary> Inquire devices from the surrounding area, uses a native method to achieve good inquiry. </summary> /// <returns> A <c>DevicePool</c>, in which all the devices are added, if any. </returns> public DevicePool Inquire() { this.dev_id = hci_get_route(IntPtr.Zero); if( this.dev_id != -1) { int sock = hci_open_dev(this.dev_id); DevicePool pool = new DevicePool(); inquiry_info info = new inquiry_info(); IntPtr devs = IntPtr.Zero; byte[] lap = new byte[] { 0x33, 0x8b, 0x9e}; int max_rsp = 255; int length = 8; int flags = 1; int count = hci_inquiry(this.dev_id, length, max_rsp, lap, out devs,flags); if(!(devs==IntPtr.Zero)) { IntPtr element = devs; if (count>0) { for(int i = 0; i < count;i++) { //try //{ info = (inquiry_info)Marshal.PtrToStructure(element,typeof(inquiry_info)); element = (IntPtr)((int)element+Marshal.SizeOf(typeof(inquiry_info))); System.Text.StringBuilder bld2 = new System.Text.StringBuilder(248); monotooth.BluetoothAddress ba = new BluetoothAddress(); ba.Array = info.bdaddr; if(hci_read_remote_name(sock,ba,bld2.Capacity,bld2,0)==0) { LinuxRemoteDevice dev = new LinuxRemoteDevice(ba,bld2.ToString()); pool.Add(dev); } else { LinuxRemoteDevice dev = new LinuxRemoteDevice(ba,"NONAME"); pool.Add(dev); } } } } close(sock); return pool; } else { throw new Exception("You do not have a bluetooth device on your system."); } }
internal static BluetoothAddress ToBluetoothAddress(string address_) { return(BluetoothAddress.Parse(address_)); }
/// <summary> /// Set or change the PIN to be used with a specific remote device. /// </summary> /// <param name="device">Address of Bluetooth device.</param> /// <param name="pin">PIN string consisting of 1 to 16 ASCII characters.</param> /// <remarks>Assigning null (Nothing in VB) or an empty String will revoke the PIN.</remarks> public void SetPin(BluetoothAddress device, string pin) { m_optionHelper.SetPin(device, pin); }
void IBluetoothListener.SetPin(BluetoothAddress device, string pin) { throw new NotImplementedException(); }
/// <summary> /// Begins an asynchronous request for a remote host connection. /// The remote host is specified by a <see cref="BluetoothAddress"/> and a service identifier (Guid). /// </summary> /// <param name="address">The <see cref="BluetoothAddress"/> of the remote host.</param> /// <param name="service">The service identifier of the remote host.</param> /// <param name="requestCallback">An AsyncCallback delegate that references the method to invoke when the operation is complete.</param> /// <param name="state">A user-defined object that contains information about the connect operation. /// This object is passed to the requestCallback delegate when the operation is complete.</param> /// <returns></returns> public IAsyncResult BeginConnect(BluetoothAddress address, Guid service, AsyncCallback requestCallback, object state) { return BeginConnect(new BluetoothEndPoint(address, service), requestCallback, state); }
void IBluetoothListener.Construct(BluetoothAddress localAddress, Guid service) { ((IBluetoothListener)this).Construct(service); }
public DataProducerManager AddRawInertialSensor(BluetoothAddress btaddress, bool isreconnectable = false) { if (btaddress == null) { throw new ArgumentException(btaddress.GetType().Name + " Cannot be null."); } DataProducerManager RawInertialSensor; try { RawInertialSensor = new DataProducerManager(this) { UniqueDeviceAddress = btaddress.ToString(), IDataProducer = new RawInertialSensorProducer(btaddress), UISensorData = new UISensorData(true) { DeviceName = btaddress.ToString(), SensorType = SensorType.Inertial, MPS = -1, DataPreview = "Loading, Please wait :)", SensorLocation = SensorLocation.NotSet }, ChartInfo = this.SensorGrapher.SetupChartAreaFor(btaddress.ToString(), SensorGrapherControl.ChartTypes.Acceleration, DataProducerManagerCollection.RawIntertialSensorUpdateFreq) }; } catch { return(null); } RawInertialSensor.IDataProducer.NewIData += (senderNewIData, eNewIData) => { this.UISensorDataDictionary[RawInertialSensor.ChartInfo.RootName].DataPreview = eNewIData.ToPreviewString(); this.SensorGrapher.UpdateGraph(RawInertialSensor.ChartInfo, ((InertialSensorData)eNewIData).NormalizedAccelerations, eNewIData.NowInTicks); }; RawInertialSensor.IDataProducer.MeasuresPerSec += (senderMeasuresPerSec, eMeasuresPerSec) => { RawInertialSensor.UISensorData.MPS = eMeasuresPerSec; }; RawInertialSensor.UISensorData.SensorLocationSet += (senderSensorLocationSet, eSensorLocationSet) => { foreach (var child in RawInertialSensor.DPMChildrenList.Where(x => x.IDataProducer.SensorType == SensorType.Virtual)) { RemoveDataProducerManager(child); } //Note this can't be in the foreach b/c you can't remove from an Ienumerable collection RawInertialSensor.DPMChildrenList.RemoveAll(x => x.IDataProducer.SensorType == SensorType.Virtual); DataProducerManager tMappedVirtualInertialSensor = null; var tVirtualInertialSensor = this.AddVirtualInertialSensor(RawInertialSensor, this.DPMCollection[KinectProducer.KinectAddress], eSensorLocationSet); //check that the sensor was actually created, if it was add it if (tVirtualInertialSensor != null) { RawInertialSensor.DPMChildrenList.Add(tVirtualInertialSensor); tMappedVirtualInertialSensor = this.AddMappedVirtualInertialSensor(RawInertialSensor, this.DPMCollection[KinectProducer.KinectAddress], tVirtualInertialSensor, eSensorLocationSet.ToJointType()); if (tMappedVirtualInertialSensor != null) { RawInertialSensor.DPMChildrenList.Add(tMappedVirtualInertialSensor); } } }; this.DPMCollection[btaddress.ToString()] = RawInertialSensor; (RawInertialSensor.IDataProducer as IRestartable).Start(); this.MethodsToCallOnDispose.Add((Action) delegate() { RawInertialSensor.IDataProducer.Dispose(); }); return(RawInertialSensor); }
void IBluetoothListener.Construct(BluetoothAddress localAddress, Guid service, ServiceRecord sdpRecord) { throw new NotSupportedException("No support for creating Service Records on Android."); }
/* * Device */ public BluetoothAddress GetRegisteredDevice() { var isValid = BluetoothAddress.TryParse(Properties.Settings.Default.RegisteredDevice, out var savedAddress); return(isValid ? savedAddress : null); }
public static int cycleCounter = 0; // counts the number of times the function is sending data // in order to calculate the sensor sample rate private static void kinect_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e) { Skeleton[] skeletons = new Skeleton[0]; using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame()) { if (skeletonFrame != null) { skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength]; skeletonFrame.CopySkeletonDataTo(skeletons); } } if (skeletons.Length != 0) { foreach (Skeleton skel in skeletons) { if (skel.TrackingState == SkeletonTrackingState.Tracked) { SkeletonPoint leftWrist = skel.Joints[JointType.WristLeft].Position; SkeletonPoint rightWrist = skel.Joints[JointType.WristRight].Position; SkeletonPoint hipCenter = skel.Joints[JointType.HipCenter].Position; int hipCenter_Z = Convert.ToInt32(hipCenter.Z * 100); int leftWrist_Z = (hipCenter_Z - Convert.ToInt32(leftWrist.Z * 100)) < 0 ? 0 : hipCenter_Z - Convert.ToInt32(leftWrist.Z * 100); int leftWrist_Y = (Convert.ToInt32(leftWrist.Y * 100)) < 0 ? 0 : Convert.ToInt32(leftWrist.Y * 100); int rightWrist_Z = (hipCenter_Z - Convert.ToInt32(rightWrist.Z * 100)) < 0 ? 0 : hipCenter_Z - Convert.ToInt32(rightWrist.Z * 100); int rightWrist_Y = (Convert.ToInt32(rightWrist.Y * 100)) < 0 ? 0 : Convert.ToInt32(rightWrist.Y * 100); Console.WriteLine("{0} | {1} | {2} | {3} | {4} | {5}", skel.TrackingId, leftWrist_Z, leftWrist_Y, rightWrist_Z, rightWrist_Y, hipCenter_Z); try { BluetoothAddress addr = BluetoothAddress.Parse("00:80:37:2e:31:20"); Guid serviceClass; serviceClass = BluetoothService.BluetoothBase; var ep = new BluetoothEndPoint(addr, serviceClass, 2); var cli = new BluetoothClient(); Console.WriteLine("Trying to connect..."); cli.Connect(ep); Console.WriteLine("just connected"); Stream peerStream = cli.GetStream(); // Send this players left and right arm data string msg = String.Format("{0}{1}{2}{3}{4}", Convert.ToChar(skel.TrackingId), Convert.ToChar(leftWrist_Y), Convert.ToChar(leftWrist_Z), Convert.ToChar(rightWrist_Y), Convert.ToChar(rightWrist_Z)); Console.WriteLine("Sending msg");// Byte[] to_send = System.Text.Encoding.ASCII.GetBytes(msg); peerStream.Write(to_send, 0, to_send.Length); peerStream.Close(); cli.Close(); cycleCounter++; Console.WriteLine("Number of times called: " + cycleCounter); } catch (Exception) { Console.WriteLine("ERROR: Could not connect to Bluetooth Server"); } //Thread.Sleep(100); // 10Hz update rate } } } }
internal BluezDeviceInfo(BluetoothAddress bluetoothAddress, string name) { _Address = bluetoothAddress; _Name = name; _LastSeen = DateTime.Now; }
private BluetoothAddress GetLocalAddress() { return(BluetoothAddress.Parse(_adapter.Address)); }
public void Initialize() { this.name = new String('*', BLUETOOTH_MAX_NAME_SIZE); this.address = new BluetoothAddress(); this.size = (UInt32)Marshal.SizeOf(this); }
public PortStatusChangedEventArgs(bool connected, string portName, BluetoothAddress address) { Connected = connected; PortName = portName; Address = address; }
static bool DoPairRequest(BluetoothAddress device, string pin) { return(false); }
static bool DoRemoveDevice(BluetoothAddress device) { return(false); }
//-------------------------------------------------------------- /// <overloads> /// Initializes a new instance of the <see cref="T:BluetoothWin32Authentication"/> class. /// </overloads> /// - /// <summary> /// Initializes a new instance of the <see cref="T:BluetoothWin32Authentication"/> class, /// to respond to a specific address with a specific PIN string. /// </summary> /// - /// <remarks> /// <para>The instance will continue receiving authentication requests /// until it is disposed or garbage collected, so keep a reference to it /// whilst it should be active, and call /// <see cref="M:InTheHand.Net.Bluetooth.BluetoothWin32Authentication.Dispose"/> /// when you’re finished. /// </para> /// </remarks> /// - /// <param name="remoteAddress">The address of the device to authenticate, /// as a <see cref="T:InTheHand.Net.BluetoothAddress"/>. /// </param> /// <param name="pin">The PIN string to use for authentication, as a /// <see cref="T:System.String"/>. /// </param> public BluetoothWin32Authentication(BluetoothAddress remoteAddress, String pin) { #if ! WinXP throw new PlatformNotSupportedException(); #else if (remoteAddress == null) { throw new ArgumentNullException("remoteAddress"); } if (remoteAddress.ToInt64() == 0) { throw new ArgumentNullException("remoteAddress", "A non-blank address must be specified."); } if (pin == null) { throw new ArgumentNullException("pin"); } m_remoteAddress = remoteAddress; m_pin = pin; Register(remoteAddress); #endif }
public void One() { var stuff = BluetopiaTesting.InitMockery_Client(new ClientTestingBluetopia.Behaviour()); // const uint NullPeriodLengths = 0; const uint InquiryLen = 12; const uint CallbackParameter = 0; const uint MaximumResponses = 255; var callback = stuff.GetFactory()._inquiryEventCallback; Expect.Once.On(stuff.MockedApi).Method("GAP_Perform_Inquiry") .With(stuff.StackId, StackConsts.GAP_Inquiry_Type.GeneralInquiry, NullPeriodLengths, NullPeriodLengths, InquiryLen, MaximumResponses, callback, CallbackParameter) .Will(Return.Value(BluetopiaError.OK)); // IBluetoothClient cli = stuff.CreateBluetoothClient(); var ar = cli.BeginDiscoverDevices(255, false, false, false, true, null, null); Assert.IsFalse(ar.IsCompleted, "IsCompleted 0"); // IntPtr pItemData = IntPtr.Zero; IntPtr pCompleteData = IntPtr.Zero; try { Structs.GAP_Inquiry_Entry_Event_Data itemData = new Structs.GAP_Inquiry_Entry_Event_Data( Addr1Bytes, new byte[] { 0x03, 0x02, 0x01 } ); pItemData = Marshal.AllocHGlobal(Marshal.SizeOf(itemData)); Marshal.StructureToPtr(itemData, pItemData, false); Structs.GAP_Event_Data item1 = new Structs.GAP_Event_Data( StackConsts.GAP_Event_Type.Inquiry_Entry_Result, pItemData); // const ushort NumDevices = 1; Structs.GAP_Inquiry_Event_Data completeData = new Structs.GAP_Inquiry_Event_Data( NumDevices /*, pCompleteDeviceData*/); pCompleteData = Marshal.AllocHGlobal(Marshal.SizeOf(completeData)); Marshal.StructureToPtr(completeData, pCompleteData, false); Structs.GAP_Event_Data complete = new Structs.GAP_Event_Data( StackConsts.GAP_Event_Type.Inquiry_Result, pCompleteData); // // using (var done = new ManualResetEvent(false)) { ThreadPool.QueueUserWorkItem(delegate { try { callback(stuff.StackId, ref item1, CallbackParameter); callback(stuff.StackId, ref complete, CallbackParameter); } finally { done.Set(); } }); bool signalled = done.WaitOne(30000); Debug.Assert(signalled, "NOT signalled"); } } finally { if (pItemData != IntPtr.Zero) { Marshal.FreeHGlobal(pItemData); } if (pCompleteData != IntPtr.Zero) { Marshal.FreeHGlobal(pCompleteData); } } // Thread.Sleep(200); Assert.IsFalse(ar.IsCompleted, "notIsCompleted2 before rnr"); Thread.Sleep(2500); // Space for (possible!) name queries Thread.Sleep(200); Assert.IsTrue(ar.IsCompleted, "IsCompleted3"); var deviceList = cli.EndDiscoverDevices(ar); Assert.AreEqual(1, deviceList.Length, "deviceList.Length"); var dev = deviceList[0]; Assert.AreEqual(BluetoothAddress.Parse("001122334455"), dev.DeviceAddress, "dev.DeviceAddress"); Assert.AreEqual(new ClassOfDevice(0x010203), dev.ClassOfDevice, "dev.ClassOfDevice"); // stuff.Mockery_VerifyAllExpectationsHaveBeenMet(); }
/// <summary> /// This function revokes the personal identification number (PIN) for the Bluetooth device. /// </summary> /// <remarks><para>On Windows CE platforms this calls <c>BthRevokePIN</c>, /// its MSDN remarks say: /// </para> /// <para>“When the PIN is revoked, it is removed from registry. /// The active connection to the device is not necessary, nor is the presence /// of the Bluetooth controller.” /// </para> /// <para>On Windows CE platforms this removes any pending BluetoothWin32Authentication object but does not remove the PIN for an already authenticated device. /// Use RemoveDevice to ensure a pairing is completely removed.</para> /// <para>See also /// <see cref="M:InTheHand.Net.Bluetooth.BluetoothSecurity.SetPin(InTheHand.Net.BluetoothAddress,System.String)"/> /// </para> /// </remarks> /// <param name="device">The remote device.</param> /// <returns>True on success, else False.</returns> /// <seealso cref="M:InTheHand.Net.Bluetooth.BluetoothSecurity.SetPin(InTheHand.Net.BluetoothAddress,System.String)"/> public static bool RevokePin(BluetoothAddress device) { #if WinCE int result = NativeMethods.BthRevokePIN(device.ToByteArray()); if(result != 0) { int error = Marshal.GetLastWin32Error(); return false; } return true; #else if (authenticators.ContainsKey(device)) { BluetoothWin32Authentication bwa = (BluetoothWin32Authentication)authenticators[device]; authenticators.Remove(device); bwa.Dispose(); return true; } return false; //throw new PlatformNotSupportedException("Use RemoveDevice to remove a pairing with a device from Windows XP"); #endif }
public override string GetRemoteMachineName(BluetoothAddress a) { throw new NotImplementedException(); }
/// <summary> /// Remove the pairing with the specified device /// </summary> /// - /// <param name="device">Remote device with which to remove pairing.</param> /// - /// <returns>TRUE if device was successfully removed, else FALSE.</returns> public static bool RemoveDevice(BluetoothAddress device) { #if WinCE //remove stored PIN RevokePin(device); //purge registry data RegistryKey rk = Registry.LocalMachine.OpenSubKey(NativeMethods.ceRegistryRoot + "Device", true); if (rk != null) { //delete the device key and all contents string[] subkeys = rk.GetSubKeyNames(); for (int i = 0; (i < subkeys.Length); i++) { if (subkeys[i].Equals(device.ToString())) { rk.DeleteSubKeyTree(device.ToString()); break; } } return true; } return false; #else int result = NativeMethods.BluetoothRemoveDevice(device.ToByteArray()); if(result==0) { return true; } return false; #endif }
public override void SetPin(BluetoothAddress device, string pin) { throw new NotImplementedException(); }
/// <summary> /// Refuses an outstanding PIN request. /// <para><b>Not supported on Windows XP</b></para> /// </summary> /// <param name="device">Address of the requesting device.</param> /// <remarks><para>On Windows CE platforms this calls <c>BthRefusePINRequest</c>, /// its MSDN remarks say: /// </para> /// <para>“This function refuses an outstanding PIN request that is /// retrieved by <see cref="M:InTheHand.Net.Bluetooth.BluetoothSecurity.GetPinRequest()"/> /// function.” /// </para> /// <para>See also /// <see cref="M:InTheHand.Net.Bluetooth.BluetoothSecurity.GetPinRequest"/> /// and <see cref="M:InTheHand.Net.Bluetooth.BluetoothSecurity.AnswerPinRequest(InTheHand.Net.BluetoothAddress,System.String)"/> /// </para> /// </remarks> public static bool RefusePinRequest(BluetoothAddress device) { #if WinCE int hresult = NativeMethods.BthRefusePINRequest(device.ToByteArray()); if(hresult==0) { return true; } return false; #else throw new PlatformNotSupportedException("Not supported on Windows XP"); #endif }
public bool SetPin(BluetoothAddress device, string pin) { throw new NotImplementedException("The method or operation is not implemented."); }
internal MsBluetoothDeviceInfo(BluetoothAddress bluetoothAddress, NativeMethods.BluetoothDeviceInfo device) { _Address = bluetoothAddress; _Device = device; }
public bool RevokePin(BluetoothAddress device) { throw new NotImplementedException("The method or operation is not implemented."); }
protected void Discovering() { MsHid.NativeMethods.WSAStartup(); while (discoveringThread == Thread.CurrentThread) { List<BluetoothAddress> notFoundAddresses = new List<BluetoothAddress>(lookupFoundDevices.Keys); foreach (ReportDevice device in lookupConnectedDevices.Values) { notFoundAddresses.Remove(((MsBluetoothDeviceInfo)device.DeviceInfo).Address); } IEnumerable<NativeMethods.BluetoothDeviceInfo> devices; try { devices = NativeMethods.GetDeviceInfos(true, true, true, true, true, 2); } catch (System.ComponentModel.Win32Exception e) { if (e.ErrorCode == -2147467259) { // The dongle was not available, so try again later. Thread.Sleep(1000); continue; } else throw; } foreach (NativeMethods.BluetoothDeviceInfo deviceInfo in devices) { if (!IsWiiDevice(deviceInfo)) continue; if (deviceInfo.connected) continue; if (deviceInfo.remembered) { NativeMethods.RemoveDevice(deviceInfo.address); continue; } BluetoothAddress address = new BluetoothAddress(deviceInfo.address.address); notFoundAddresses.Remove(address); MsBluetoothDeviceInfo bluetoothDeviceInfo; if (lookupFoundDevices.TryGetValue(address, out bluetoothDeviceInfo)) { bluetoothDeviceInfo.Device = deviceInfo; } else { bluetoothDeviceInfo = new MsBluetoothDeviceInfo(address, deviceInfo); FoundDevices.Add(bluetoothDeviceInfo); lookupFoundDevices.Add(address, bluetoothDeviceInfo); OnDeviceFound(new DeviceInfoEventArgs(bluetoothDeviceInfo)); } } // Remove the lost devices from the list and notify DeviceLost event. foreach (BluetoothAddress notFoundAddress in notFoundAddresses) { IDeviceInfo notFoundDeviceInfo = lookupFoundDevices[notFoundAddress]; lookupFoundDevices.Remove(notFoundAddress); foundDevices.Remove(notFoundDeviceInfo); OnDeviceLost(new DeviceInfoEventArgs(notFoundDeviceInfo)); } Thread.Sleep(1000); } }
public bool RefusePinRequest(BluetoothAddress device) { throw new NotSupportedException(); }
private void OnConnectionClosed(object sender, BluetoothConnectionEventArgs e) { BluetoothAddress address = new BluetoothAddress(e.BluetoothConnection.Service.Device.Address); ReportDevice device; if (lookupDevice.TryGetValue(address, out device)) { device.Disconnect(); } }
public bool SetLinkKey(BluetoothAddress a, Guid linkkey) { throw new NotSupportedException(); }
/// <summary> /// Initializes a new instance of the <see cref="BluetoothListener"/> class /// that listens for incoming connection attempts on the specified local Bluetooth address and service identifier. /// </summary> /// <param name="localaddr">A <see cref="BluetoothAddress"/> that represents the local Bluetooth radio address.</param> /// <param name="service">The Bluetooth service on which to listen for incoming connection attempts.</param> /// <remarks> /// <para> /// An SDP record is published on successful <see cref="M:InTheHand.Net.Sockets.BluetoothListener.Start"/> /// to advertise the server. /// A generic record is created, containing the essential <c>ServiceClassIdList</c> /// and <c>ProtocolDescriptorList</c> attributes. The specified service identifier is /// inserted into the former, and the RFCOMM Channel number that the server is /// listening on is inserted into the latter. See the Bluetooth SDP specification /// for details on the use and format of SDP records. /// </para><para> /// If a SDP record with more elements is required, then use /// one of the other constructors that takes an SDP record e.g. /// <see cref="M:InTheHand.Net.Sockets.BluetoothListener.#ctor(InTheHand.Net.BluetoothAddress,System.Guid,InTheHand.Net.Bluetooth.ServiceRecord)"/>, /// or when passing it as a byte array, e.g. /// <see cref="M:InTheHand.Net.Sockets.BluetoothListener.#ctor(InTheHand.Net.BluetoothAddress,System.Guid,System.Byte[],System.Int32)"/>. /// The format of the generic record used here is shown there also. /// </para><para> /// Call the <see cref="M:InTheHand.Net.Sockets.BluetoothListener.Start"/> /// method to begin listening for incoming connection attempts. /// </para> /// </remarks> public BluetoothListener(BluetoothAddress localaddr, Guid service) { if (localaddr == null) { throw new ArgumentNullException("localaddr"); } if (service == Guid.Empty) { throw new ArgumentNullException("service"); } InitServiceRecord(service); this.serverEP = new BluetoothEndPoint(localaddr, service); serverSocket = new Socket(AddressFamily32.Bluetooth, SocketType.Stream, BluetoothProtocolType.RFComm); m_optionHelper = new BluetoothClient.SocketOptionHelper(serverSocket); }
public override void Initialize() { device = null; if (strm != null) { strm.Close(); } strm = null; _isConnected = false; string strAddress = ConfigurationManager.AppSettings["BTAddress"] ?? "CACA52BF713C"; byte[] bAddress = Enumerable.Range(0, strAddress.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(strAddress.Substring(x, 2), 16)) .ToArray(); BluetoothAddress btAddress = new BluetoothAddress(bAddress); var serviceClass = BluetoothService.RFCommProtocol; //.SerialPort; if (_cli != null) { _cli.Close(); } _cli = new BluetoothClient(); var bluetoothDeviceInfos = _cli.DiscoverDevices(); var deviceInfos = bluetoothDeviceInfos.ToList(); foreach (var bluetoothDeviceInfo in deviceInfos) { var scannedDeviceAddress = bluetoothDeviceInfo.DeviceAddress; if (scannedDeviceAddress == btAddress) { device = bluetoothDeviceInfo; } } if (device == null) { return; } ep = new BluetoothEndPoint(device.DeviceAddress, serviceClass); try { if (!device.Connected) { _cli.Connect(ep); strm = _cli.GetStream(); } _isConnected = true; } catch (System.Net.Sockets.SocketException e) { System.Console.WriteLine(e.Message); _cli.Close(); _isConnected = false; return; } SendVisualInitSequence(); }
/// <summary> /// Initializes a new instance of the <see cref="BluetoothListener"/> class /// that listens for incoming connection attempts on the specified local Bluetooth address and service identifier, /// publishing the specified SDP record. /// </summary> /// - /// <param name="localaddr">A <see cref="BluetoothAddress"/> that represents the local Bluetooth radio address.</param> /// <param name="service">The Bluetooth service to listen for.</param> /// <param name="sdpRecord">Prepared SDP Record to publish</param> /// - /// <remarks> /// <note> /// The constructors taking the SDP record explicitly should /// only be used if /// a specialized SDP record is required. For instance when using one of the /// standard profiles. Otherwise use one of the other constructors /// e.g. <see /// cref="M:InTheHand.Net.Sockets.BluetoothListener.#ctor(InTheHand.Net.BluetoothAddress,System.Guid)"/> /// which create a generic SDP Record from the specified service identifier. /// </note> /// <para>Any useful SDP record will include /// a <c>ProtocolDescriptor</c> element containing /// the RFCOMM Channel number that the server is listening on, /// and a <c>ServiceClassId</c> element containing the service UUIDs. /// The record supplied in the <paramref name="sdpRecord"/> parameter /// should contain those elements. On successful <see /// cref="M:InTheHand.Net.Sockets.BluetoothListener.Start"/>, /// the RFCOMM Channel number that the protocol stack has assigned to the /// server is retrieved, and copied into the service record before it is /// published. /// </para> /// <para> /// An example SDP record is as follows. This is actually the format of the /// generic record used in the other constructors. For another example see /// the code in the <c>ObexListener</c> class. /// <code lang="C#"> /// private static ServiceRecord CreateBasicRfcommRecord(Guid serviceClassUuid) /// { /// ServiceElement pdl = ServiceRecordHelper.CreateRfcommProtocolDescriptorList(); /// ServiceElement classList = new ServiceElement(ElementType.ElementSequence, /// new ServiceElement(ElementType.Uuid128, serviceClassUuid)); /// ServiceRecord record = new ServiceRecord( /// new ServiceAttribute( /// InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ServiceClassIdList, /// classList), /// new ServiceAttribute( /// InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList, /// pdl)); /// return record; /// } /// </code> /// </para> /// </remarks> public BluetoothListener(BluetoothAddress localaddr, Guid service, ServiceRecord sdpRecord) : this(localaddr, service) { InitServiceRecord(sdpRecord); }
/// <summary> /// Connects the client to a remote Bluetooth host using the specified Bluetooth address and service identifier. /// </summary> /// <param name="address">The <see cref="BluetoothAddress"/> of the host to which you intend to connect.</param> /// <param name="service">The service identifier to which you intend to connect.</param> public void Connect(BluetoothAddress address, Guid service) { if (address == null) { throw new ArgumentNullException("address"); } if (service==Guid.Empty) { throw new ArgumentNullException("service"); } BluetoothEndPoint point = new BluetoothEndPoint(address, service); this.Connect(point); }