public bool UnBond(BluetoothAddress address) { byte[] bdaddr = WidcommUtils.FromBluetoothAddress(address); bool ret = NativeMethods.BtIf_UnBond(m_pBtIf, bdaddr); return(ret); }
public ISdpDiscoveryRecordsBuffer ReadDiscoveryRecords(BluetoothAddress address, int maxRecords, ServiceDiscoveryParams args) { byte[] bdaddr = WidcommUtils.FromBluetoothAddress(address); IntPtr pList; Guid filter = args.serviceGuid; int count; if (args.searchScope == SdpSearchScope.Anywhere) { count = NativeMethods.BtIf_ReadDiscoveryRecords(m_pBtIf, bdaddr, maxRecords, out pList); } else { Debug.Assert(args.searchScope == SdpSearchScope.ServiceClassOnly, "the other enum"); try { count = NativeMethods.BtIf_ReadDiscoveryRecordsServiceClassOnly(m_pBtIf, bdaddr, maxRecords, out pList, ref filter); } catch (EntryPointNotFoundException ex) { ReportNeedNeedNativeDllUpgrade(ex, true); count = NativeMethods.BtIf_ReadDiscoveryRecords(m_pBtIf, bdaddr, maxRecords, out pList); } catch (MissingMethodException ex) { // for NETCF ReportNeedNeedNativeDllUpgrade(ex, true); count = NativeMethods.BtIf_ReadDiscoveryRecords(m_pBtIf, bdaddr, maxRecords, out pList); } } ISdpDiscoveryRecordsBuffer recBuf = new SdpDiscoveryRecordsBuffer( _factory, pList, count, args); return(recBuf); }
public BOND_RETURN_CODE Bond(BluetoothAddress address, string passphrase) { byte[] bdaddr = WidcommUtils.FromBluetoothAddress(address); byte[] pinUtf8; byte[] pinUtf16; // As seen used in WM sample with CString::GetBuffer(). if (passphrase != null) { // TODO should be ASCII?? pinUtf8 = Encoding.UTF8.GetBytes(passphrase + "\0"); pinUtf16 = Encoding.Unicode.GetBytes(passphrase + "\0"); } else { // ????????? pinUtf8 = null; pinUtf16 = null; } // BOND_RETURN_CODE ret2; #if !NETCF int retBtw = NativeMethods.BtIf_Bond(m_pBtIf, bdaddr, pinUtf8); ret2 = (BOND_RETURN_CODE)retBtw; #else int retWce = NativeMethods.BtIf_Bond(m_pBtIf, bdaddr, pinUtf16); ret2 = Convert((BOND_RETURN_CODE__WCE)retWce); #endif return(ret2); }
public IAsyncResult BeginServiceDiscovery(BluetoothAddress address, Guid serviceGuid, SdpSearchScope searchScope, AsyncCallback asyncCallback, Object state) { BeginServiceDiscoveryKillInquiry(); // Just in case the user modifies the original address!!! BluetoothAddress addr2 = (BluetoothAddress)address.Clone(); AsyncResult <ISdpDiscoveryRecordsBuffer, ServiceDiscoveryParams> ar = new AsyncResult <ISdpDiscoveryRecordsBuffer, ServiceDiscoveryParams>(asyncCallback, state, new ServiceDiscoveryParams(addr2, serviceGuid, searchScope)); lock (lockServiceDiscovery) { if (m_arServiceDiscovery != null) { throw new NotSupportedException("Currently support only one concurrent Service Lookup operation."); } bool success = false; try { m_arServiceDiscovery = ar; bool ret = m_btIf.StartDiscovery(addr2, serviceGuid); Debug.WriteLine(WidcommUtils.GetTime4Log() + ": StartDiscovery ret: " + ret); if (!ret) { WBtRc ee = GetExtendedError(); throw WidcommSocketExceptions.Create_StartDiscovery(ee); } success = true; } finally { if (!success) { m_arServiceDiscovery = null; } } } return(ar); }
public bool IsConnected(out BluetoothAddress p_remote_bdaddr) { byte[] bdaddr = new byte[WidcommStructs.BD_ADDR_LEN]; WidcommL2CapClient.NativeMethods.L2CapConn_GetRemoteBdAddr(m_pPort, bdaddr, bdaddr.Length); p_remote_bdaddr = WidcommUtils.ToBluetoothAddress(bdaddr); return(true); }
public DISCOVERY_RESULT GetLastDiscoveryResult(out BluetoothAddress address, out UInt16 p_num_recs) { byte[] bdaddr = WidcommUtils.FromBluetoothAddress(BluetoothAddress.None); DISCOVERY_RESULT ret = NativeMethods.BtIf_GetLastDiscoveryResult(m_pBtIf, bdaddr, out p_num_recs); address = WidcommUtils.ToBluetoothAddress(bdaddr); return(ret); }
internal WidcommRfcommStreamBase[] GetPortList() { lock (_livePorts) { var a = _livePorts.ToArray(); Debug.WriteLine(WidcommUtils.GetTime4Log() + ": GetPortList returned " + a.Length + " ports."); return(a); } }
public bool IsConnected(out BluetoothAddress p_remote_bdaddr) { byte[] bdaddr = new byte[WidcommStructs.BD_ADDR_LEN]; bool ret = NativeMethods.RfcommPort_IsConnected(m_pRfcommPort, bdaddr, bdaddr.Length); p_remote_bdaddr = WidcommUtils.ToBluetoothAddress(bdaddr); return(ret); }
internal static void GetBluetoothCallbackValues(IntPtr bdAddr, IntPtr devClass, IntPtr deviceName, out byte[] bdAddrArr, out byte[] devClassArr, out byte[] deviceNameArr) { bdAddrArr = WidcommUtils.GetByteArray(bdAddr, 6); devClassArr = WidcommUtils.GetByteArray(devClass, 3); const int DoWeNeedToAddOneForTheNullTerminator_CheckFor248InTheBtSpec = 1; deviceNameArr = WidcommUtils.GetByteArrayNullTerminated(deviceName, 248 + DoWeNeedToAddOneForTheNullTerminator_CheckFor248InTheBtSpec); }
internal WidcommBluetoothRadio(WidcommBluetoothFactoryBase factory) { System.Threading.ThreadStart handleError = delegate { }; #if !NETCF // On my old iPAQ the radio info functions fail sometimes even though // the stack is working fine so we ignored the errors in the first // release. On Win32 this is a problem when the stack is installed // but no radio is attached, so fail in that case. handleError = delegate { throw new PlatformNotSupportedException( "Widcomm Bluetooth stack not supported (Radio)."); }; #endif // Debug.Assert(factory != null); _factory = factory; var tmp = BtIf; bool ret; ret = BtIf.GetLocalDeviceVersionInfo(ref m_dvi); Debug.Assert(ret, "GetLocalDeviceVersionInfo failed"); if (!ret) { handleError(); // Call handleError first so that one Win32 we don't get the Assert if there's no stack present. Debug.Assert(ret, "GetLocalDeviceVersionInfo failed"); m_dvi = new DEV_VER_INFO(HciVersion.Unknown); // Reset to overwrite any garbage returned by GetLocalDeviceVersionInfo. } byte[] bdName = new byte[WidcommStructs.BD_NAME_LEN]; ret = BtIf.GetLocalDeviceName(bdName); Debug.Assert(ret, "GetLocalDeviceName failed"); if (ret) { m_name = WidcommUtils.BdNameToString(bdName); } else { bdName = null; handleError(); } // // Did GetLocalDeviceVersionInfo get the address? It doesn't work on // my iPAQ, but then again this way doesn't work either! if (LocalAddress == null || LocalAddress.ToInt64() == 0) { Utils.MiscUtils.Trace_WriteLine("GetLocalDeviceVersionInfo's bd_addr is empty, trying GetLocalDeviceInfoBdAddr..."); if (m_dvi.bd_addr == null) { m_dvi.bd_addr = new byte[WidcommStructs.BD_ADDR_LEN]; } ret = BtIf.GetLocalDeviceInfoBdAddr(m_dvi.bd_addr); Debug.Assert(ret, "GetLocalDeviceInfoBdAddr failed"); if (!ret) { m_dvi.bd_addr = new byte[WidcommStructs.BD_ADDR_LEN]; handleError(); } } }
void HandleDeviceResponded(IntPtr bdAddr, IntPtr devClass, IntPtr deviceName, bool connected) { byte[] bdAddrArr; byte[] devClassArr; byte[] deviceNameArr; WidcommUtils.GetBluetoothCallbackValues(bdAddr, devClass, deviceName, out bdAddrArr, out devClassArr, out deviceNameArr); m_parent.HandleDeviceResponded(bdAddrArr, devClassArr, deviceNameArr, connected); }
//-------- internal static WidcommBluetoothDeviceInfo CreateFromGivenAddressNoLookup(BluetoothAddress address, WidcommBluetoothFactoryBase factory) { REM_DEV_INFO rdi = new REM_DEV_INFO(); rdi.bda = WidcommUtils.FromBluetoothAddress(address); WidcommBluetoothDeviceInfo bdi = new WidcommBluetoothDeviceInfo(rdi, factory); return(bdi); }
//------------- public bool StartDiscovery(BluetoothAddress address, Guid serviceGuid) { Utils.MiscUtils.Trace_WriteLine("WidcommBtIf.StartDiscovery"); byte[] bdaddr = WidcommUtils.FromBluetoothAddress(address); int sizeofSdpDiscoveryRec; // just for interests sake bool ret = NativeMethods.BtIf_StartDiscovery(m_pBtIf, bdaddr, ref serviceGuid, out sizeofSdpDiscoveryRec); return(ret); }
internal void RemovePort(WidcommRfcommStreamBase port) { bool found; lock (_livePorts) { found = _livePorts.Remove(port); } Debug.WriteLine(WidcommUtils.GetTime4Log() + ": RemovePort found it: " + found); }
//---- internal string CreatePort(BluetoothAddress addr) { if (IsSet(_waitConnect)) { throw new InvalidOperationException("Already used."); } _addr = addr; byte[] bd_addr = WidcommUtils.FromBluetoothAddress(addr); byte[] tcharzServiceName = { 0, 0 }; var inUse = Interlocked.CompareExchange(ref _sfInConnect, 1, 0); if (inUse != 0) { throw new InvalidOperationException("Widcomm only allows one SPP Connect attempt at a time."); } SPP_CLIENT_RETURN_CODE ret = (SPP_CLIENT_RETURN_CODE)(-1); _singleThreader.AddCommand(new WidcommPortSingleThreader.MiscNoReturnCommand( () => ret = NativeMethods.SppClient_CreateConnection( _pSppCli, bd_addr, tcharzServiceName) )).WaitCompletion(); Debug.WriteLine("SppClient_CreateConnection ret: " + ret); int timeout = 30000; bool signalled = _waitConnect.WaitOne(timeout, false); // Eeek want to set this even when we got NO callback........ // Do for now because Win32 is not working at all...... Interlocked.Exchange(ref _sfInConnect, 0); if (!signalled) { throw CommonSocketExceptions.Create_NoResultCode( WidcommSppSocketExceptions.SocketError_Misc, "CreatePort failed (time-out)."); } MemoryBarrier(); if (_statusState != SPP_STATE_CODE.CONNECTED) { throw WidcommSppSocketExceptions.Create(_statusState, "CreatePort"); } if (_statusComPort == null) { throw CommonSocketExceptions.Create_NoResultCode( WidcommSppSocketExceptions.SocketError_Misc, "CreatePort did not complete (cpn)."); } // // TODO Move these into the native-event handler. //string comPort = MakePortName(_statusComPort.Value); //_comNum = _statusComPort.Value; //_comPortName = comPort; Debug.Assert(_comPortName != null, "_comPortName IS null"); Debug.Assert(WidcommUtils.ToBluetoothAddress(_statusBda) == addr, "addr NOT equal, is: " + WidcommUtils.ToBluetoothAddress(_statusBda)); return(_comPortName); }
protected override bool TryBondingIf_inLock(BluetoothAddress addressToConnect, int ocScn, out Exception error) { const bool Retrying = true; const bool NotRetrying = false; // /* * if(havePin) * if(Bond success) * if(OpenClient success) * return Retrying; * return NotRetrying; */ try { // Mustn't die on this thread, need to report all exceptions back!! // if (m_passcodeToTry != null) { if (addressToConnect == null) { Debug.Fail("In retry, have passcode, but looks like Server mode!!"); error = null; return(NotRetrying); } // string passcodeToTry = m_passcodeToTry; m_passcodeToTry = null; Debug.Assert(addressToConnect != null, "addressToConnect != null"); bool didPair = Bond(addressToConnect, passcodeToTry); if (didPair) { //TODO Destroy old port! SetPort(m_factory.GetWidcommRfcommPort()); PORT_RETURN_CODE ret = m_port.OpenClient(ocScn, WidcommUtils.FromBluetoothAddress(addressToConnect)); Utils.MiscUtils.Trace_WriteLine("OpenClient/AB ret: {0}=0x{0:X}", ret); if (ret == PORT_RETURN_CODE.SUCCESS) { error = null; return(Retrying); } else { error = WidcommSocketExceptions.Create(ret, "OpenClient/AB"); return(NotRetrying); } } } // error = null; } catch (Exception ex) { error = ex; } return(NotRetrying); }
protected override void SetupListener(BluetoothEndPoint bep, int requestedScn, out BluetoothEndPoint liveLocalEP) { SetupRfcommIf(); int scn = m_RfCommIf.SetScnForLocalServer(bep.Service, requestedScn); BTM_SEC secLevel = WidcommUtils.ToBTM_SEC(true, m_authenticate, m_encrypt); m_RfCommIf.SetSecurityLevelServer(secLevel, new byte[] { (byte)'h', (byte)'a', (byte)'c', (byte)'k', (byte)'S', (byte)'v', (byte)'r', } ); liveLocalEP = new BluetoothEndPoint(BluetoothAddress.None, BluetoothService.Empty, scn); }
private void StartInquiry() // We are inside the lock. { // BTW InquiryLength is set-up in BeginInquiry. Debug.WriteLine(WidcommUtils.GetTime4Log() + ": calling StartInquiry."); bool success = m_btIf.StartInquiry(); Debug.WriteLine(WidcommUtils.GetTime4Log() + ": StartInquiry ret: " + success); if (!success) { throw CommonSocketExceptions.Create_StartInquiry("StartInquiry"); } }
void UnloadedKill_Runner(object state) { Utils.MiscUtils.Trace_WriteLine( WidcommUtils.GetTime4Log() + ": " + "PortKill_Runner"); var livePorts = _factory.GetPortList(); foreach (var cur in livePorts) { cur.CloseInternalAndAbort_willLock(); } Utils.MiscUtils.Trace_WriteLine( "PortKill_Runner done ({0}).", livePorts.Length); }
internal static WidcommBluetoothDeviceInfo CreateFromGivenAddress(BluetoothAddress address, WidcommBluetoothFactoryBase factory) { REM_DEV_INFO rdi = new REM_DEV_INFO(); rdi.bda = WidcommUtils.FromBluetoothAddress(address); WidcommBluetoothDeviceInfo bdi = factory.GetWidcommBtInterface() .ReadDeviceFromRegistryAndCheckAndSetIfPaired(address, factory); if (bdi == null) { bdi = CreateFromGivenAddressNoLookup(address, factory); } return(bdi); }
private static WidcommBluetoothDeviceInfo CreateFromStoredRemoteDeviceInfo( BluetoothAddress devAddress, byte[] devName, byte[] devClass, WidcommBluetoothFactoryBase factory) { REM_DEV_INFO rdi = new REM_DEV_INFO(); rdi.bda = WidcommUtils.FromBluetoothAddress(devAddress); rdi.bd_name = devName; rdi.dev_class = devClass; // rdi.b_connected = ... // rdi.b_paired = ... WidcommBluetoothDeviceInfo bdi = WidcommBluetoothDeviceInfo.CreateFromStoredRemoteDeviceInfo(rdi, factory); string nameStr = bdi.DeviceName; Debug.Assert(nameStr.Length == 0 || nameStr[nameStr.Length - 1] != 0, "null terminator!!"); int idxDbg; Debug.Assert((idxDbg = nameStr.IndexOf((char)0)) == -1, "null terminator!! at: " + idxDbg); return(bdi); }
protected override void DoOpenClient(int scn, BluetoothAddress addressToConnect) { byte[] address = WidcommUtils.FromBluetoothAddress(addressToConnect); PORT_RETURN_CODE ret; if (_singleThreader != null) { WidcommPortSingleThreader.OpenClientCommand cmd = AddCommand( new WidcommPortSingleThreader.OpenClientCommand(scn, address, m_port)); ret = cmd.WaitCompletion(); } else { ret = m_port.OpenClient(scn, address); } Utils.MiscUtils.Trace_WriteLine("OpenClient ret: {0}=0x{0:X}", ret); if (ret != PORT_RETURN_CODE.SUCCESS) { throw WidcommSocketExceptions.Create(ret, "OpenClient"); } }
//------------- void HandleStackStatusChange(int new_status) { var newStatus = (STACK_STATUS)new_status; Utils.MiscUtils.Trace_WriteLine( WidcommUtils.GetTime4Log() + ": " + "StackStatusChange: {0}", newStatus); // switch (newStatus) { case STACK_STATUS.Down: case STACK_STATUS.Error: case STACK_STATUS.Unloaded: _factory._seenStackDownEvent = true; ThreadPool.QueueUserWorkItem(UnloadedKill_Runner); break; default: Debug.Assert(newStatus == STACK_STATUS.Reloaded || newStatus == STACK_STATUS.Up, "Unknown state: " + newStatus); break; } }
void HandleClientStateChange(IntPtr bdAddr, IntPtr devClass, IntPtr deviceName, short com_port, SPP_STATE_CODE state) { try { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0} HandleServerStateChange: state: {1} = 0x{2:X}, COM: {3}", DateTime.Now.TimeOfDay.ToString(), state, (int)state, com_port)); WidcommUtils.GetBluetoothCallbackValues(bdAddr, devClass, deviceName, out _statusBda, out _statusDevClass, out _statusName); _statusComPort = com_port; _statusState = state; MemoryBarrier(); if (state == SPP_STATE_CODE.CONNECTED) { if (!IsSet(_waitConnect)) { string comPort = MakePortName(_statusComPort.Value); _comNum = com_port; _comPortName = comPort; _waitConnect.Set(); } else { Debug.WriteLine("_waitConnect already set!"); } } switch (state) { case SPP_STATE_CODE.CONNECTED: break; case SPP_STATE_CODE.DISCONNECTED: break; case SPP_STATE_CODE.RFCOMM_CONNECTION_FAILED: break; case SPP_STATE_CODE.PORT_IN_USE: break; case SPP_STATE_CODE.PORT_NOT_CONFIGURED: break; case SPP_STATE_CODE.SERVICE_NOT_FOUND: break; case SPP_STATE_CODE.ALLOC_SCN_FAILED: break; case SPP_STATE_CODE.SDP_FULL: break; default: break; } // TODO SyncCtx.Post ThreadPool.QueueUserWorkItem(Event_Runner, new PortStatusChangedEventArgs( state == SPP_STATE_CODE.CONNECTED, _comPortName, _addr)); } catch (Exception ex) { // Let's not kill a Widcomm thread! Utils.MiscUtils.Trace_WriteLine("HandleClientStateChange ex: " + ex); } }
void HandleDataReceived(IntPtr buffer, UInt16 len) { Utils.MiscUtils.Trace_WriteLine("HandleReceive: len: {0}", len); byte[] arr = WidcommUtils.GetByteArray(buffer, len); m_parent.HandlePortReceive(arr, this); }
void HandleDataReceived(IntPtr buffer, UInt16 len) { //Debug.WriteLine("HandleReceive: len: " + len.ToString()); byte[] arr = WidcommUtils.GetByteArray(buffer, len); m_parent.HandlePortReceive(arr, this); }
//-- public RemoteDeviceState FindIfPresentOrConnected(BluetoothAddress addr) { return(FindIfPresentOrConnected(WidcommUtils.FromBluetoothAddress(addr))); }
internal override void EnsureLoaded() { Debug.WriteLine(WidcommUtils.GetTime4Log() + ": WcBtFcty EnsureLoaded ENTRY (for v.L)"); if (_st != null) { if (WidcommBtInterface.IsWidcommSingleThread(_st)) // DEBUG { } } lock (typeof(WidcommBluetoothFactory)) { Debug.WriteLine(WidcommUtils.GetTime4Log() + ": WcBtFcty EnsureLoaded IN lock"); // In case Widcomm is forced to shutdown when CBtIf is extant we monitor // for the stack-down event so we can force reload next time // we're used. var seenStackDownEvent = _seenStackDownEvent; _seenStackDownEvent = false; if (seenStackDownEvent) { Debug.WriteLine(WidcommUtils.GetTime4Log() + ": WcBtFcty seenStackDownEvent"); if (!DoPowerDownUpReset) { Utils.MiscUtils.Trace_WriteLine("Ignoring stack/radio shutdown due to DoPowerDownUpReset=false."); } else { Utils.MiscUtils.Trace_WriteLine("Restarting due to stack/radio shutdown."); bool respectLocks = true; // -- Shutdown -- ThreadStart doDispose = () => Dispose(true, respectLocks); var st = GetSingleThreader(); if (st != null && !WidcommBtInterface.IsWidcommSingleThread(st)) { respectLocks = false; var c = st.AddCommand(new WidcommPortSingleThreader.MiscNoReturnCommand( doDispose)); c.WaitCompletion(); MemoryBarrier(); } else { doDispose(); } Debug.WriteLine(WidcommUtils.GetTime4Log() + ": WcBtFcty done Dispose"); Debug.Assert(s_btIf == null, "After Dispose but NOT s_btIf == null"); Debug.Assert(s_btInterface == null, "After Dispose but NOT s_btInterface == null"); Thread.Sleep(5000); } } //-- Create -- // CBtIf: MUST ONLY be ONE of these, and must be FIRST created! // "Only one object of this class should be instantiated by the application." // "This class must be instantiated before any other DK classes are used" if (s_btIf == null) { #if KILL_SINGLE_THREAD_AT_DISPOSAL Debug.Assert(_st == null); #endif if (_st == null) { _st = new WidcommPortSingleThreader(); } Debug.Assert(GetSingleThreader() != null); IBtIf btIf; Func <IBtIf> f = () => new WidcommBtIf(this); var st = GetSingleThreader(); if (st != null && !WidcommBtInterface.IsWidcommSingleThread(st)) { var c = st.AddCommand(new WidcommPortSingleThreader.MiscReturnCommand <IBtIf>( f)); btIf = c.WaitCompletion(); } else { btIf = f(); } Debug.WriteLine(WidcommUtils.GetTime4Log() + ": WcBtFcty done new WidcommBtIf"); if (st != null) { btIf = new WidcommStBtIf(this, btIf); Utils.MiscUtils.Trace_WriteLine("IBtIf using WidcommStBtIf."); } Debug.Assert(s_btInterface == null); WidcommBtInterface btInterface = new WidcommBtInterface(btIf, this); // Don't set these until we're sure that initialisation has // all completed successfully. s_btIf = btIf; s_btInterface = btInterface; } else { Debug.Assert(s_btInterface != null, "One set but not the other!"); } }//lock Debug.WriteLine(WidcommUtils.GetTime4Log() + ": WcBtFcty EnsureLoaded EXIT"); }
void StopInquiry() { Utils.MiscUtils.Trace_WriteLine("StopInquiry"); Debug.WriteLine(WidcommUtils.GetTime4Log() + ": StopInquiry done"); m_btIf.StopInquiry(); }