public int OpenSPP(long bt_address) { int comPort = 0; WidcommAPI.SppCreateConnection(this.wdStack, 0, bt_address); int retry = 0; while (retry < 5) { System.Threading.Thread.Sleep(500); comPort = WidcommAPI.SppComPort(this.wdStack); retry++; } return(comPort); }
public bool Open() { try { lock (mylock) { if (processingThread != null) { processingThread.Abort(); } long bt_address = long.Parse(this._HexAddress, NumberStyles.HexNumber, CultureInfo.CurrentCulture.NumberFormat); //Thread.Sleep(10000); //int r = WidcommAPI.SppRemoveConnection(wdStack[0]); //Thread.Sleep(3000); int r = WidcommAPI.SppCreateConnection(wdStack[0], (byte)1, bt_address); Thread.Sleep(3000); if (r != 1) { WidcommAPI.SppRemoveConnection(wdStack[0]); if (wdStack[0] != IntPtr.Zero) { if (WidcommAPI.DeleteWidcommStack(wdStack[0]) == false) { throw new Exception("Cannot delete stack"); } } NetworkStacks._BluetoothStack = null; } /* RegistryKey rk = Registry.LocalMachine.OpenSubKey("Software\\WIDCOMM\\BTConfig\\AutoConnect"); * string[] subkeys = rk.GetSubKeyNames(); * if (subkeys.Length > 0) * { * for (int i = 0; (i < subkeys.Length); i++) * { * int com = Convert.ToInt32(subkeys[i]); * //if (WidcommBluetoothStack._PortUsed[com]) * // continue; * if (com == 11) * { * _COMPORT = "BTC1"; * WidcommBluetoothStack._PortUsed[com] = true; * } * else if (com == 12) * { * _COMPORT = "BTC2"; * WidcommBluetoothStack._PortUsed[com] = true; * } * else if (com == 13) * { * _COMPORT = "BTC3"; * WidcommBluetoothStack._PortUsed[com] = true; * } * * break; * * * } * * if (_COMPORT.Length > 2) * break; * }*/ int com = WidcommAPI.SppComPort(wdStack[0]); //if (com == 11) // _COMPORT = "BTC1"; //else if (com == 12) // _COMPORT = "BTC2"; //else if (com == 13) _COMPORT = "BTC3"; if ((_COMPORT.Length > 2) && ((r == 1) || (r == 3))) { spp[0] = new SerialPort(_COMPORT + ":", 38400, Parity.None, 8, StopBits.One);//new SerialPort(_COMPORT, 38400, Parity.None, 8, StopBits.One); if (!spp[0].IsOpen) { spp[0].Open(); } //spps.Add(this._HexAddress, spp); this._Status = BluetoothStatus.Connected; //start the processing thread processingThread = new Thread(new ThreadStart(Process)); processingThread.Start(); } } } catch (Exception e) { spp[0].Close(); spp[0].Dispose(); WidcommAPI.SppRemoveConnection(wdStack[0]); if (wdStack[0] != IntPtr.Zero) { if (WidcommAPI.DeleteWidcommStack(wdStack[0]) == false) { throw new Exception("Cannot delete stack"); } } NetworkStacks._BluetoothStack = null; CurrentWockets._LastError = Wockets.Exceptions.ErrorCodes.CONNECTION_FAILED_TO_OPEN; CurrentWockets._LastErrorMessage = "MicrosoftBluetoothStream failed at Open() " + this._HexAddress; this._Status = BluetoothStatus.Disconnected; return(false); } return(true); }