/// <overloads>
 /// Initializes a new instance of the <see cref="BluetoothListener"/> class.
 /// </overloads>
 /// ----
 /// <summary>
 /// Initializes a new instance of the <see cref="BluetoothListener"/> class
 /// to listen on the specified service identifier.
 /// </summary>
 /// <param name="service">The Bluetooth service to listen for.</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(System.Guid,InTheHand.Net.Bluetooth.ServiceRecord)"/>,
 /// or when passing it as a byte array 
 /// <see cref="M:InTheHand.Net.Sockets.BluetoothListener.#ctor(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(Guid service)
 {
     InitServiceRecord(service);
     this.serverEP = new BluetoothEndPoint(BluetoothAddress.None, service);
     serverSocket = new Socket(AddressFamily32.Bluetooth, SocketType.Stream, BluetoothProtocolType.RFComm);
     m_optionHelper = new BluetoothClient.SocketOptionHelper(serverSocket);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="BluetoothClient"/> class and binds it to the specified local endpoint.
        /// </summary>
        /// <param name="localEP">The <see cref="BluetoothEndPoint"/> to which you bind the Bluetooth Socket.
        /// Only necessary on multi-radio system where you want to select the local radio to use.</param>
        public BluetoothClient(BluetoothEndPoint localEP)
            : this()
        {
            if (localEP == null)
            {
                throw new ArgumentNullException("localEP");
            }

            //bind to specific local endpoint
            this.Client.Bind(localEP);
        }
Beispiel #3
0
 public void refreshDevices()
 {
     localEnd  = new BluetoothEndPoint(chosenRadio.LocalAddress, BluetoothService.SerialPort);
     client    = new BluetoothClient(localEnd);
     btDevices = client.DiscoverDevices();
 }
Beispiel #4
0
        private void menuSendLog_Click(object sender, EventArgs e)
        {
            /* GeoFrameworks welcomes log files from all developers and end-users.  This method will
             * transmit the contents of a log file to us via our web site.
             *
             * PRIVACY NOTICE: No log files contain any personally identifiable information.  The information
             *                 is used strictly for troubleshooting GPS device issues and for building statistics
             *                 such as the most commonly-used GPS devices.
             */
            if (MessageBox.Show("Sending this log file to GeoFrameworks helps us improve your GPS software.  The information is anonymous and confidential.  An internet connection is required.  Would you like to continue?", "Send Log", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                try
                {
                    // Show a wait cursor until we're finished
                    Cursor.Current = Cursors.WaitCursor;
                    Application.DoEvents();

                    // Make a new web request
                    HttpWebRequest request = null;
                    if (_Device != null)
                    {
                        // We're reporting a log file for a specific device
                        request = (HttpWebRequest)WebRequest.Create("http://www.geoframeworks.com/GPSDeviceDiagnostics.aspx");
                    }
                    else
                    {
                        // We're reporting a log file for the whole device detection process
                        request = (HttpWebRequest)WebRequest.Create("http://www.geoframeworks.com/GPSDiagnostics.aspx");
                    }

                    // Provide standard credentials for the web request
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Credentials = CredentialCache.DefaultCredentials;
                    request.UserAgent   = "GPS Diagnostics";
                    request.Method      = "POST";

                    string data = "";

                    // Is a specific device being logged?
                    if (_Device != null)
                    {
                        // Yes.  Include some information about the device
                        GpsIntermediateDriver gpsid           = _Device as GpsIntermediateDriver;
                        SerialDevice          serialDevice    = _Device as SerialDevice;
                        BluetoothDevice       bluetoothDevice = _Device as BluetoothDevice;

                        data  = "Device=" + _Device.Name;
                        data += "&IsGps=" + _Device.IsGpsDevice.ToString();
                        data += "&Reliability=" + _Device.Reliability.ToString();

                        if (gpsid != null)
                        {
                            data += "&Type=GPSID";
                            data += "&ProgramPort=" + gpsid.Port;

                            if (gpsid.HardwarePort == null)
                            {
                                data += "&HardwarePort=None&HardwareBaud=0";
                            }
                            else
                            {
                                data += "&HardwarePort=" + gpsid.HardwarePort.Port;
                                data += "&HardwareBaud=" + gpsid.HardwarePort.BaudRate;
                            }
                        }
                        else if (serialDevice != null)
                        {
                            data += "&Type=Serial";
                            data += "&Port=" + serialDevice.Port;
                            data += "&BaudRate=" + serialDevice.BaudRate.ToString();
                        }
                        else if (bluetoothDevice != null)
                        {
                            data += "&Type=Bluetooth";
                            data += "&Address=" + bluetoothDevice.Address.ToString();

                            BluetoothEndPoint endPoint = (BluetoothEndPoint)bluetoothDevice.EndPoint;
                            data += "&Service=" + endPoint.Name;
                        }
                    }

                    // Now append the log
                    data += "&Log=" + _Body;

                    // Get a byte array
                    byte[] buffer = System.Text.UTF8Encoding.UTF8.GetBytes(data);

                    // Transmit the request
                    request.ContentLength = buffer.Length;

                    // Get the request stream.
                    Stream dataStream = request.GetRequestStream();

                    // Write the data to the request stream.
                    dataStream.Write(buffer, 0, buffer.Length);

                    // Close the Stream object.
                    dataStream.Close();

                    // Get the response.
                    WebResponse response = request.GetResponse();

                    // Display the status.
                    string result = ((HttpWebResponse)response).StatusDescription;

                    response.Close();
                    Cursor.Current = Cursors.Default;
                    Application.DoEvents();

                    if (result == "OK")
                    {
                        // Disable the menu now that we've received the file.
                        menuSendLog.Enabled = false;
                        MessageBox.Show("We've received your log and will study it further.  Thanks for taking the time to send it!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                    }
                    else
                    {
                        // An error occurred while trying to transmit the log.
                        MessageBox.Show("The diagnostics server may not be responding.  Please check to see if you have an internet connection, then try again.", result, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    }
                }
                catch (Exception ex)
                {
                    // Reset the cursor
                    Cursor.Current = Cursors.Default;
                    Application.DoEvents();

                    // Inform the user about the error.  What exactly happened?
                    MessageBox.Show("A log could not be sent.  " + ex.Message, "Unable to Send", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                }
            }
        }
Beispiel #5
0
 //--------
 internal IAsyncResult BeginConnect(BluetoothEndPoint bep, string pin,
                                    AsyncCallback asyncCallback, Object state)
 {
     m_passcodeToTry = pin;
     return(base.BeginConnect(bep, asyncCallback, state));
 }
Beispiel #6
0
        IBluetoothDeviceInfo[] DoDiscoverDevices(int maxDevices,
                                                 bool authenticated, bool remembered, bool unknown, bool discoverableOnly,
                                                 InTheHand.Net.Sockets.BluetoothClient.LiveDiscoveryCallback liveDiscoHandler, object liveDiscoState)
        {
            WqsOffset.AssertCheckLayout();
            CsaddrInfoOffsets.AssertCheckLayout();
            //
#if !NETCF
            Debug.Assert(liveDiscoHandler == null, "Don't use the NETCF live-disco feature on Win32!");
#endif
#if WinXP
            const bool Win32DiscoverableOnlyIncludesAllDevices = false;
#endif
            var prototype                = new BluetoothEndPoint(BluetoothAddress.None, BluetoothService.Empty);
            int discoveredDevices        = 0;
            List_IBluetoothDeviceInfo al = null;

            IntPtr handle       = IntPtr.Zero;
            int    lookupresult = 0;

            /* Windows XP SP3
             * Begin takes the full Inquiry time.
             *          12:09:15.7968750: Begin
             *  10.265s 12:09:26.0625000: Begin complete
             *          12:09:26.0625000: Next
             *          12:09:26.0625000: Next Complete
             *          ...
             *          12:09:26.1718750: Next
             *          12:09:26.1718750: Next Complete
             *          12:09:26.1718750: End
             *          12:09:26.1718750: End Complete
             */
            /* WM 6 SP
             * Begin is quick, Next blocks until a device is found.
             *         13:46:47.1760000: Begin
             *         13:46:47.2350000: Begin complete
             *         13:46:47.2360000: Next
             * 10.537s	13:46:57.7730000: Next Complete
             *         13:46:57.8910000: Next
             *         13:46:57.8940000: Next Complete
             *         13:46:57.8950000: Next
             *         13:46:57.8960000: Next Complete
             *         13:46:57.8960000: End
             *         13:46:57.8990000: End Complete
             *
             */
            System.Text.StringBuilder timings = null;
#if DEBUG
            //      timings = new System.Text.StringBuilder();
#endif
            Action <string> markTime = delegate(string name) {
                if (timings != null)
                {
                    timings.AppendFormat(CultureInfo.InvariantCulture,
                                         "{1}: {0}\r\n", name, DateTime.UtcNow.TimeOfDay);
                }
            };

#if WinXP
            if (discoverableOnly && !Win32DiscoverableOnlyIncludesAllDevices)
            {
                // No way to separate out the devices-in-range on Win32. :-(
                return(new IBluetoothDeviceInfo[0]);
            }
#endif
#if NETCF
            DateTime discoTime = DateTime.UtcNow;
            if (unknown || discoverableOnly)
            {
#endif
            al = new List_IBluetoothDeviceInfo();
            byte[] buffer = new byte[1024];
            BitConverter.GetBytes(WqsOffset.StructLength_60).CopyTo(buffer, WqsOffset.dwSize_0);
            BitConverter.GetBytes(WqsOffset.NsBth_16).CopyTo(buffer, WqsOffset.dwNameSpace_20);

            int bufferlen = buffer.Length;


            BTHNS_INQUIRYBLOB bib = new BTHNS_INQUIRYBLOB();
            bib.LAP = iac;// 0x9E8B33;

#if NETCF
            bib.length        = Convert.ToByte(inquiryLength.TotalSeconds / 1.28);
            bib.num_responses = Convert.ToByte(maxDevices);
#else
            bib.length = Convert.ToByte(inquiryLength.TotalSeconds);
#endif
            GCHandle hBib = GCHandle.Alloc(bib, GCHandleType.Pinned);
            IntPtr pBib   = hBib.AddrOfPinnedObject();

            BLOB b = new BLOB(8, pBib);


            GCHandle hBlob = GCHandle.Alloc(b, GCHandleType.Pinned);

            Marshal32.WriteIntPtr(buffer, WqsOffset.lpBlob_56, hBlob.AddrOfPinnedObject());


            //start looking for Bluetooth devices
            LookupFlags flags = LookupFlags.Containers;

#if WinXP
            //ensure cache is cleared on XP when looking for new devices
            if (unknown || discoverableOnly)
            {
                flags |= LookupFlags.FlushCache;
            }
#endif
            markTime("Begin");
            lookupresult = NativeMethods.WSALookupServiceBegin(buffer, flags, out handle);
            markTime("Begin complete");

            hBlob.Free();
            hBib.Free();

            // TODO ?Change "while(...maxDevices)" usage on WIN32?
            while (discoveredDevices < maxDevices && lookupresult != -1)
            {
                markTime("Next");
#if NETCF
                lookupresult = NativeMethods.WSALookupServiceNext(handle, LookupFlags.ReturnAddr | LookupFlags.ReturnBlob, ref bufferlen, buffer);
#else
                LookupFlags flagsNext = LookupFlags.ReturnAddr;
#if WIN32_READ_BTH_DEVICE_INFO
                flagsNext |= LookupFlags.ReturnBlob;
#endif
                lookupresult = NativeMethods.WSALookupServiceNext(handle, flagsNext, ref bufferlen, buffer);
#endif
                markTime("Next Complete");

                if (lookupresult != -1)
                {
                    //increment found count
                    discoveredDevices++;


                    //status
#if WinXP
                    BTHNS_RESULT status   = (BTHNS_RESULT)BitConverter.ToInt32(buffer, WqsOffset.dwOutputFlags_52);
                    bool         devAuthd = ((status & BTHNS_RESULT.Authenticated) == BTHNS_RESULT.Authenticated);
                    bool         devRembd = ((status & BTHNS_RESULT.Remembered) == BTHNS_RESULT.Remembered);
                    if (devAuthd && !devRembd)
                    {
                        System.Diagnostics.Debug.WriteLine("Win32 BT disco: Auth'd but NOT Remembered.");
                    }
                    bool devUnkwn = !devRembd && !devAuthd;
                    bool include  = (authenticated && devAuthd) || (remembered && devRembd) || (unknown && devUnkwn);
                    Debug.Assert(!discoverableOnly, "Expected short circuit for Win32 unsupported discoverableOnly!");
                    if (include)
#else
                    if (true)
#endif
                    {
#if NETCF
                        IntPtr           lpBlob = (IntPtr)BitConverter.ToInt32(buffer, 56);
                        BLOB             ib     = (BLOB)Marshal.PtrToStructure(lpBlob, typeof(BLOB));
                        BthInquiryResult bir    = (BthInquiryResult)Marshal.PtrToStructure(ib.pBlobData, typeof(BthInquiryResult));
#endif
                        //struct CSADDR_INFO {
                        //    SOCKET_ADDRESS LocalAddr;
                        //    SOCKET_ADDRESS RemoteAddr;
                        //    INT iSocketType;
                        //    INT iProtocol;
                        //}
                        //struct SOCKET_ADDRESS {
                        //    LPSOCKADDR lpSockaddr;
                        //    INT iSockaddrLength;
                        //}
                        //pointer to outputbuffer
                        IntPtr bufferptr = Marshal32.ReadIntPtr(buffer, WqsOffset.lpcsaBuffer_48);
                        //remote socket address
                        IntPtr sockaddrptr = Marshal32.ReadIntPtr(bufferptr, CsaddrInfoOffsets.OffsetRemoteAddr_lpSockaddr_8);
                        //remote socket len
                        int sockaddrlen = Marshal.ReadInt32(bufferptr, CsaddrInfoOffsets.OffsetRemoteAddr_iSockaddrLength_12);


                        SocketAddress btsa = new SocketAddress(AddressFamily32.Bluetooth, sockaddrlen);

                        for (int sockbyte = 0; sockbyte < sockaddrlen; sockbyte++)
                        {
                            btsa[sockbyte] = Marshal.ReadByte(sockaddrptr, sockbyte);
                        }

                        var bep = (BluetoothEndPoint)prototype.Create(btsa);

                        //new deviceinfo
                        IBluetoothDeviceInfo newdevice;

#if NETCF
                        newdevice = new WindowsBluetoothDeviceInfo(bep.Address, bir.cod);
                        // Built-in to Win32 so only do on NETCF
                        newdevice.SetDiscoveryTime(discoTime);
#else
                        newdevice = new WindowsBluetoothDeviceInfo(bep.Address);
#if WIN32_READ_BTH_DEVICE_INFO
                        ReadBlobBTH_DEVICE_INFO(buffer, newdevice);
#endif
#endif
                        //add to discovered list
                        al.Add(newdevice);
                        if (liveDiscoHandler != null)
                        {
                            liveDiscoHandler(newdevice, liveDiscoState);
                        }
                    }
                }
            }//while
#if NETCF
        }
#endif

            //stop looking
            if (handle != IntPtr.Zero)
            {
                markTime("End");
                lookupresult = NativeMethods.WSALookupServiceEnd(handle);
                markTime("End Complete");
            }
            if (timings != null)
            {
                Debug.WriteLine(timings);
#if !NETCF
                Console.WriteLine(timings);
#endif
            }

#if NETCF
            List_IBluetoothDeviceInfo known = WinCEReadKnownDevicesFromRegistry();
            al = BluetoothClient.DiscoverDevicesMerge(authenticated, remembered, unknown,
                                                      known, al, discoverableOnly, discoTime);
#endif


            //return results
            if (al.Count == 0)
            {
                //special case for empty collection
                return(new IBluetoothDeviceInfo[0] {
                });
            }

            return((IBluetoothDeviceInfo[])al.ToArray(
#if V1
                       typeof(IBluetoothDeviceInfo)
#endif
                       ));
        }
        /// <summary>
        /// Start listening for incoming connections of the provided <see cref="ConnectionType"/>.
        /// If the desired localEndPoint is not available will throw a CommsSetupShutdownException.
        /// </summary>
        /// <param name="connectionType">The <see cref="ConnectionType"/> to start listening for.</param>
        /// <param name="desiredLocalEndPoint">The desired localEndPoint. For IPEndPoints use IPAddress.Any
        /// to listen on all <see cref="HostInfo.IP.FilteredLocalAddresses()"/> and port 0 to randomly select an available port.</param>
        /// <param name="allowDiscoverable">Determines if the listeners created will be discoverable if <see cref="Tools.PeerDiscovery"/> is enabled.</param>
        /// <returns>A list of all listeners used.</returns>
        public static List <ConnectionListenerBase> StartListening <T>(ConnectionType connectionType, T desiredLocalEndPoint, bool allowDiscoverable = false) where T : EndPoint
        {
            if (connectionType == ConnectionType.Undefined)
            {
                throw new ArgumentException("ConnectionType.Undefined is not a valid parameter value.", "connectionType");
            }
            if (desiredLocalEndPoint == null)
            {
                throw new ArgumentNullException("desiredLocalEndPoint", "desiredLocalEndPoint cannot be null.");
            }

            List <ConnectionListenerBase> listeners = new List <ConnectionListenerBase>();

            if (connectionType == ConnectionType.TCP || connectionType == ConnectionType.UDP)
            {
                IPEndPoint desiredLocalIPEndPoint = desiredLocalEndPoint as IPEndPoint;
                if (desiredLocalIPEndPoint == null)
                {
                    throw new ArgumentException("The provided desiredLocalEndPoint must be an IPEndPoint for TCP and UDP connection types.", "desiredLocalEndPoint");
                }

                //Collect a list of IPEndPoints we want to listen on
                List <IPEndPoint> localListenIPEndPoints = new List <IPEndPoint>();

                if (desiredLocalIPEndPoint.Address == IPAddress.Any)
                {
                    foreach (IPAddress address in HostInfo.IP.FilteredLocalAddresses())
                    {
                        localListenIPEndPoints.Add(new IPEndPoint(address, desiredLocalIPEndPoint.Port));
                    }

                    //We could also listen on the IPAddress.Any adaptor here
                    //but it is not supported by all platforms so use the specific start listening override instead
                }
                else
                {
                    localListenIPEndPoints.Add(desiredLocalIPEndPoint);
                }

                //Initialise the listener list
                for (int i = 0; i < localListenIPEndPoints.Count; i++)
                {
                    if (connectionType == ConnectionType.TCP)
                    {
                        listeners.Add(new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, allowDiscoverable));
                    }
                    else if (connectionType == ConnectionType.UDP)
                    {
                        listeners.Add(new UDPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, UDPConnection.DefaultUDPOptions, allowDiscoverable));
                    }
                }

                //Start listening on all selected listeners
                //We do this is a separate step in case there is an exception
                try
                {
                    for (int i = 0; i < localListenIPEndPoints.Count; i++)
                    {
                        StartListening(listeners[i], localListenIPEndPoints[i], false);
                    }
                }
                catch (Exception)
                {
                    //If there is an exception here we remove any added listeners and then rethrow
                    for (int i = 0; i < listeners.Count; i++)
                    {
                        if (listeners[i].IsListening)
                        {
                            StopListening(listeners[i].ConnectionType, listeners[i].LocalListenEndPoint);
                        }
                    }

                    throw;
                }
            }
#if NET35 || NET4
            else if (connectionType == ConnectionType.Bluetooth)
            {
                BluetoothEndPoint desiredLocalBTEndPoint = desiredLocalEndPoint as BluetoothEndPoint;
                if (desiredLocalBTEndPoint == null)
                {
                    throw new ArgumentException("The provided desiredLocalEndPoint must be a BluetoothEndPoint for Bluetooth connection types.", "desiredLocalEndPoint");
                }

                //Collect a list of BluetoothEndPoints we want to listen on
                List <BluetoothEndPoint> localListenBTEndPoints = new List <BluetoothEndPoint>();
                if (desiredLocalBTEndPoint.Address == BluetoothAddress.None)
                {
                    foreach (var address in HostInfo.BT.FilteredLocalAddresses())
                    {
                        localListenBTEndPoints.Add(new BluetoothEndPoint(address, desiredLocalBTEndPoint.Service));
                    }
                }
                else
                {
                    localListenBTEndPoints.Add(desiredLocalBTEndPoint);
                }

                //Initialise the listener list
                for (int i = 0; i < localListenBTEndPoints.Count; i++)
                {
                    listeners.Add(new BluetoothConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, allowDiscoverable));
                }

                //Start listening on all selected listeners
                //We do this is a separate step in case there is an exception
                try
                {
                    for (int i = 0; i < localListenBTEndPoints.Count; i++)
                    {
                        StartListening(listeners[i], localListenBTEndPoints[i], false);
                    }
                }
                catch (Exception)
                {
                    //If there is an exception here we remove any added listeners and then rethrow
                    for (int i = 0; i < listeners.Count; i++)
                    {
                        if (listeners[i].IsListening)
                        {
                            StopListening(listeners[i].ConnectionType, listeners[i].LocalListenEndPoint);
                        }
                    }

                    throw;
                }
            }
#endif
            else
            {
                throw new NotImplementedException("This method has not been implemented for the provided connections of type " + connectionType);
            }

            return(listeners);
        }
		/// <summary>
		/// Connects a client to a specified endpoint.
		/// </summary>
        /// <param name="remoteEP">A <see cref="BluetoothEndPoint"/> that represents the remote device.</param>
        public void Connect(BluetoothEndPoint remoteEP)
		{
            if (cleanedUp)
            {
                throw new ObjectDisposedException(base.GetType().FullName);
            }
            if (remoteEP == null)
            {
                throw new ArgumentNullException("remoteEP");
            }

            //StartAuthenticator(remoteEP.Address);
            clientSocket.Connect(remoteEP);
            active = true;
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="BluetoothListener"/> class
        /// with the specified local endpoint.
		/// </summary>
        /// <param name="localEP">A <see cref="BluetoothEndPoint"/> that represents the local endpoint to which to bind the listener <see cref="Socket"/>.</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.BluetoothEndPoint,InTheHand.Net.Bluetooth.ServiceRecord)"/>,
        /// or when passing it as a byte array
        /// <see cref="M:InTheHand.Net.Sockets.BluetoothListener.#ctor(InTheHand.Net.BluetoothEndPoint,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(BluetoothEndPoint localEP)
		{
            if (localEP == null)
            {
                throw new ArgumentNullException("localEP");
            }

            InitServiceRecord(localEP.Service);
            this.serverEP = localEP;
            serverSocket = new Socket(AddressFamily32.Bluetooth, SocketType.Stream, BluetoothProtocolType.RFComm);
            m_optionHelper = new BluetoothClient.SocketOptionHelper(serverSocket);
        }
Beispiel #10
0
 protected override BluetoothEndPoint PrepareConnectEndPoint(BluetoothEndPoint serverEP)
 {
     throw new NotImplementedException();
 }
Beispiel #11
0
 internal BluezClient(BluezFactory fcty, BluetoothEndPoint localEP)
     : base(fcty, localEP)
 {
     _fcty = fcty;
     //TODO _radio = _fcty.GetAdapterWithAddress(localEP.DeviceAddress);
 }
Beispiel #12
0
            //----
            protected override IAsyncResult ConnBeginConnect(BluetoothEndPoint remoteEP, AsyncCallback requestCallback, object state)
            {
                var connEP = PrepareConnectEndPoint(remoteEP);

                return(m_sock.BeginConnect(connEP, requestCallback, state));
            }
Beispiel #13
0
        //--------

        public override void Connect(BluetoothEndPoint remoteEP)
        {
            EndConnect(BeginConnect(remoteEP, null, null));
        }
 /// <summary>
 /// Begins an asynchronous request for a remote host connection.
 /// The remote host is specified by a <see cref="BluetoothEndPoint"/>. 
 /// </summary>
 /// <param name="remoteEP">A <see cref="BluetoothEndPoint"/> containing the 
 /// address and UUID of the remote service.</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(BluetoothEndPoint remoteEP, AsyncCallback requestCallback, object state)
 {
     //StartAuthenticator(remoteEP.Address);
     return this.Client.BeginConnect(remoteEP, requestCallback, state);
 }
 /// <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);
 }
Beispiel #16
0
        public override void Connect(BluetoothEndPoint remoteEP)
        {
            if (remoteEP.Port != 0 && remoteEP.Port != -1)
            {
                throw new NotSupportedException("Don't support connect to particular port.  Please can someone tell me how.");
            }
            //
            _factory.SdkInit();
            _factory.RegisterCallbacksOnce(); // Need to use event DISC_IND to close the Stream/SerialPort.
            //
            BluesoleilDeviceInfo bdi = BluesoleilDeviceInfo.CreateFromGivenAddress(remoteEP.Address, _factory);
            UInt32 hDev = bdi.Handle;
            UInt32 hConn;
            byte   channel;
            int    comPort;

            ConnectRfcomm(remoteEP, hDev, out hConn, out channel, out comPort);
            //if (_HasPort(remoteEP)) {
            //    ConnectRfcomm(remoteEP, hDev, out hConn, out channel, out comPort);
            //} else {
            //    UInt16? svcClass16;
            //    if (!ServiceRecordUtilities.IsUuid16Value(remoteEP.Service)) {
            //        svcClass16 = null;
            //    } else {
            //        svcClass16 = (UInt16)ServiceRecordUtilities.GetAsUuid16Value(remoteEP.Service);
            //    }
            //    UInt16[] specialClasses = { };
            //    if (svcClass16.HasValue && IsIn(svcClass16.Value, specialClasses)) {
            //        throw new NotImplementedException("Internal Error: Should not use this code.");
            //// The original method we used for connecting did not work for
            //// profiles that BlueSoleil has support for -- returning no COM
            //// port but enabling per-profile support
            //// We have a second way, which seems to work in those cases
            //// but it is more complex -- we manually allocate the port etc
            //// (also it doesn't give us the remote RFCOMM channel).
            //// Use the first method for now except in special cases...
            //        //UInt32 comSerialNum;
            //        //UInt32? comSerialNum;
            //        //ConnectRfcommPreAllocateComPort(svcClass16.Value, hDev,
            //        //    out hConn, out channel, out comPort
            //        //    //, out comSerialNum
            //        //    );
            //    } else {
            //        ConnectRfcomm(remoteEP, hDev, out hConn, out channel, out comPort);
            //    }
            //}
            _remoteEp = new BluetoothEndPoint(remoteEP.Address, BluetoothService.Empty, channel);
            //
            var serialPort = CreateSerialPort();

            if (BufferSize.HasValue)
            {
                serialPort.ReadBufferSize  = BufferSize.Value;
                serialPort.WriteBufferSize = BufferSize.Value;
            }
            serialPort.PortName  = "COM" + comPort;
            serialPort.Handshake = Handshake.RequestToSend;
            serialPort.Open();
            //((System.ComponentModel.IComponent)serialPort).Disposed
            //    += delegate { System.Windows.Forms.MessageBox.Show("BlueSoleil's SerialPort disposed"); };
            //
            // We pass '_hConn' as the Stream handles calling
            // Btsdk_Disconnect to close the RFCOMM connection.
            var strm = new BlueSoleilSerialPortNetworkStream(serialPort, hConn, this, _factory);

            _stream = strm;
            int liveCount = _factory.AddConnection(hConn, strm);

            Debug.WriteLine(string.Format(CultureInfo.InvariantCulture,
                                          "BlueSoleilClient.Connect LiveConns count: {0}.", liveCount));
            // TODO who handles closing the connection if opening the port fails
        }
Beispiel #17
0
 internal BluesoleilClient(BluesoleilFactory fcty, BluetoothEndPoint localEP)
     : this(fcty)
 {
     Debug.Fail("Ignoring localEP");
 }
Beispiel #18
0
 protected override BluetoothEndPoint PrepareBindEndPoint(BluetoothEndPoint serverEP)
 {
     Console.WriteLine("Calling BluezRfcommEndPoint.CreateBindEndPoint");
     return(BluezRfcommEndPoint.CreateBindEndPoint(serverEP));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="BluetoothListener"/> class
 /// with the specified local endpoint,
 /// publishing the specified SDP record.
 /// </summary>
 /// <param name="localEP">A <see cref="BluetoothEndPoint"/> that represents the local endpoint to which to bind the listener <see cref="Socket"/>.</param>
 /// <param name="sdpRecord">Prepared SDP Record to publish</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.BluetoothEndPoint)"/>
 /// 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(BluetoothEndPoint localEP, ServiceRecord sdpRecord)
     : this(localEP)
 {
     InitServiceRecord(sdpRecord);
 }
Beispiel #20
0
 protected abstract IBluetoothClient GetBluetoothClient(BluetoothEndPoint localEP);
Beispiel #21
0
        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();
        }
Beispiel #22
0
 public IBluetoothClient DoGetBluetoothClient(BluetoothEndPoint localEP)
 {
     return(GetBluetoothClient(localEP));
 }
        void DoStart()
        {
            if (handle != IntPtr.Zero)
            {
                throw new InvalidOperationException();
            }

            endPoint = new BluetoothEndPoint(BluetoothAddress.None, serviceUuid, NativeMethods.BTH_PORT_ANY);

            if (NativeMethods.IsRunningOnMono())
            {
                socket = new Win32Socket();
                ((Win32Socket)socket).Bind(endPoint);
                Debug.WriteLine(socket.IsBound);
                ((Win32Socket)socket).Listen(1);
                // get endpoint with channel
                endPoint = ((Win32Socket)socket).LocalEndPoint as BluetoothEndPoint;
            }
            else
            {
                socket = new Socket(BluetoothClient.AddressFamilyBluetooth, SocketType.Stream, BluetoothProtocolType.RFComm);
                socket.Bind(endPoint);
                Debug.WriteLine(socket.IsBound);
                socket.Listen(1);
                // get endpoint with channel
                endPoint = socket.LocalEndPoint as BluetoothEndPoint;
            }

            var socketAddressBytes = endPoint.Serialize().ToByteArray();


            WSAQUERYSET qs = new WSAQUERYSET();

            qs.dwSize      = Marshal.SizeOf(qs);
            qs.dwNameSpace = NativeMethods.NS_BTH;
            //var uuidh = GCHandle.Alloc(serviceUuid, GCHandleType.Pinned);
            //qs.lpServiceClassId = uuidh.AddrOfPinnedObject();
            //qs.lpszServiceInstanceName = ServiceName;

            qs.dwNumberOfCsAddrs = 1;

            var csa = new CSADDR_INFO
            {
                lpLocalSockaddr      = Marshal.AllocHGlobal(NativeMethods.BluetoothSocketAddressLength),
                iLocalSockaddrLength = NativeMethods.BluetoothSocketAddressLength,
                iSocketType          = SocketType.Stream,
                iProtocol            = NativeMethods.PROTOCOL_RFCOMM
            };

            Marshal.Copy(socketAddressBytes, 0, csa.lpLocalSockaddr, NativeMethods.BluetoothSocketAddressLength);

            IntPtr pcsa = Marshal.AllocHGlobal(Marshal.SizeOf(csa));

            Marshal.StructureToPtr(csa, pcsa, false);
            qs.lpcsaBuffer = pcsa;

            var blob     = new BLOB();
            var blobData = new BTH_SET_SERVICE();
            int sdpVer   = 1;

            blobData.pSdpVersion = Marshal.AllocHGlobal(IntPtr.Size);
            Marshal.WriteInt32(blobData.pSdpVersion, sdpVer);
            blobData.pRecordHandle = Marshal.AllocHGlobal(IntPtr.Size);
            Marshal.WriteIntPtr(blobData.pRecordHandle, 0, IntPtr.Zero);
            blobData.fCodService = ServiceClass;

            if (ServiceRecord == null)
            {
                ServiceRecordBuilder builder = new ServiceRecordBuilder();
                builder.AddServiceClass(serviceUuid);
                builder.ProtocolType = BluetoothProtocolDescriptorType.Rfcomm;

                if (!string.IsNullOrEmpty(ServiceName))
                {
                    builder.ServiceName = ServiceName;
                }

                ServiceRecord = builder.ServiceRecord;
            }
            ServiceRecordHelper.SetRfcommChannelNumber(ServiceRecord, socketAddressBytes[26]);

            byte[] rawBytes = ServiceRecord.ToByteArray();
            blobData.ulRecordLength = (uint)rawBytes.Length;
            int structSize = (2 * IntPtr.Size) + (7 * 4);

            blob.size     = structSize + rawBytes.Length;
            blob.blobData = Marshal.AllocHGlobal(blob.size);
            Marshal.StructureToPtr(blobData, blob.blobData, false);
            Marshal.Copy(rawBytes, 0, IntPtr.Add(blob.blobData, structSize), rawBytes.Length);

            var blobh = GCHandle.Alloc(blob, GCHandleType.Pinned);

            qs.lpBlob = blobh.AddrOfPinnedObject();

            try
            {
                int result = NativeMethods.WSASetService(ref qs, WSAESETSERVICEOP.RNRSERVICE_REGISTER, 0);

                var newstruct = Marshal.PtrToStructure <BTH_SET_SERVICE>(blob.blobData);
                handle = Marshal.ReadIntPtr(newstruct.pRecordHandle);
                if (result == -1)
                {
                    int werr = Marshal.GetLastWin32Error();
                    throw new SocketException(werr);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(csa.lpLocalSockaddr);
                Marshal.FreeHGlobal(qs.lpcsaBuffer);

                Marshal.FreeHGlobal(blobData.pSdpVersion);
                Marshal.FreeHGlobal(blobData.pRecordHandle);

                Marshal.FreeHGlobal(blob.blobData);
                blobh.Free();
            }
        }
Beispiel #24
0
        //----
        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);
        }
Beispiel #25
0
 protected virtual BluetoothEndPoint PrepareBindEndPoint(BluetoothEndPoint serverEP)
 {
     return(serverEP);
 }
Beispiel #26
0
        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
        }
Beispiel #27
0
 protected override void DoOtherSetup(BluetoothEndPoint bep, int scn)
 {
     m_RfCommIf.SetScnForPeerServer(bep.Service, scn);
     m_RfCommIf.SetSecurityLevelClient(BTM_SEC.NONE);
 }
        // 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 IBluetoothListener.Construct(BluetoothEndPoint localEP, ServiceRecord sdpRecord)
 {
     throw new NotSupportedException("No support for creating Service Records on Android.");
 }
Beispiel #30
0
        public IAsyncResult BeginConnect(BluetoothEndPoint endpoint, AsyncCallback requestCallback, object state)
        {
            IAsyncResult result = Client.BeginConnect(endpoint, requestCallback, state);

            return(result);
        }
Beispiel #31
0
 protected override IBluetoothClient GetBluetoothClient(BluetoothEndPoint localEP)
 {
     throw new NotImplementedException("The method or operation is not implemented.");
 }
Beispiel #32
0
 internal static BluezRfcommEndPoint CreateConnectEndPoint(BluetoothEndPoint localEP)
 {
     return(CreateBindEndPoint(localEP));
 }
Beispiel #33
0
 //----
 public override IAsyncResult BeginConnect(BluetoothEndPoint remoteEP, AsyncCallback requestCallback, object state)
 {
     return(_beginConnectDlgt.BeginInvoke(remoteEP, requestCallback, state));
 }
 /// <summary>
 /// NOT FINISHED
 /// </summary>
 /// <param name="serviceGuid"></param>
 public void Bind(Guid serviceGuid)
 {
     _localEndPoint = new BluetoothEndPoint(new BluetoothAddress(1234), serviceGuid);
 }
        /// <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);
        }
Beispiel #36
0
        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
                    }
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="BluetoothListener"/> class
 /// with the specified local endpoint,
 /// publishing the specified SDP record.
 /// </summary>
 /// <param name="localEP">A <see cref="BluetoothEndPoint"/> that represents the local endpoint to which to bind the listener <see cref="Socket"/>.</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.BluetoothEndPoint)"/>
 /// 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.BluetoothEndPoint,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(BluetoothEndPoint localEP, byte[] sdpRecord, int channelOffset)
     : this(localEP)
 {
     InitServiceRecord(sdpRecord, channelOffset);
 }
 public BluetoothAdapter(BluetoothDeviceInfo deviceInfo)
 {
     Client = new BluetoothClient();
     ep     = new BluetoothEndPoint(deviceInfo.DeviceAddress, BluetoothService.SerialPort);
 }
 public BluetoothAdapter(BluetoothClient cli, BluetoothEndPoint ep)
 {
     this.Client = cli;
     this.ep     = ep;
 }
		/// <summary>
		/// Discovers accessible Bluetooth devices and returns their names and addresses.
		/// </summary>
		/// <param name="maxDevices">The maximum number of devices to get information about.</param>
		/// <param name="authenticated">True to return previously authenticated/paired devices.</param>
		/// <param name="remembered">True to return remembered devices.</param>
		/// <param name="unknown">True to return previously unknown devices.</param>
		/// <returns>An array of BluetoothDeviceInfo objects describing the devices discovered.</returns>
		public BluetoothDeviceInfo[] DiscoverDevices(int maxDevices, bool authenticated, bool remembered, bool unknown)
		{
            WqsOffset.AssertCheckLayout();
            CsaddrInfoOffsets.AssertCheckLayout();
            //
			int discoveredDevices = 0;
			ArrayList al = new ArrayList();
			
			int handle = 0;
			int lookupresult = 0;


			
#if WinCE
            if(unknown)
            {
#endif
				byte[] buffer = new byte[1024];
				BitConverter.GetBytes(WqsOffset.StructLength_60).CopyTo(buffer, WqsOffset.dwSize_0);
				BitConverter.GetBytes(WqsOffset.NsBth_16).CopyTo(buffer, WqsOffset.dwNameSpace_20);

				int bufferlen = buffer.Length;

				
                BTHNS_INQUIRYBLOB bib = new BTHNS_INQUIRYBLOB();
                bib.LAP = 0x9E8B33;

#if WinCE
                bib.length = Convert.ToInt16(inquiryLength.TotalSeconds / 1.28);
                bib.num_responses = Convert.ToInt16(maxDevices);
#else
                bib.length = Convert.ToByte(inquiryLength.TotalSeconds);
#endif
                GCHandle hBib = GCHandle.Alloc(bib, GCHandleType.Pinned);
                IntPtr pBib = hBib.AddrOfPinnedObject();
                
                BLOB b = new BLOB(8, pBib);

			
                GCHandle hBlob = GCHandle.Alloc(b, GCHandleType.Pinned);

                Marshal32.WriteIntPtr(buffer, WqsOffset.lpBlob_56, hBlob.AddrOfPinnedObject());
                		

				//start looking for Bluetooth devices
                LookupFlags flags = LookupFlags.Containers;

#if WinXP
                //ensure cache is cleared on XP when looking for new devices
                if(unknown)
                {
                    flags |= LookupFlags.FlushCache;
                }
#endif
                lookupresult = NativeMethods.WSALookupServiceBegin(buffer, flags, out handle);

				hBlob.Free();
                hBib.Free();

				while(discoveredDevices < maxDevices && lookupresult != -1)
				{
#if WinCE
					lookupresult = NativeMethods.WSALookupServiceNext(handle, LookupFlags.ReturnAddr | LookupFlags.ReturnBlob , ref bufferlen, buffer);
#else
                    lookupresult = NativeMethods.WSALookupServiceNext(handle, LookupFlags.ReturnAddr , ref bufferlen, buffer);
#endif

                    if (lookupresult != -1)
					{
						//increment found count
						discoveredDevices++;

				
						//status
#if WinXP
                        BTHNS_RESULT status = (BTHNS_RESULT)BitConverter.ToInt32(buffer, WqsOffset.dwOutputFlags_52);
                        bool devAuthd = ((status & BTHNS_RESULT.Authenticated) == BTHNS_RESULT.Authenticated);
                        bool devRembd = ((status & BTHNS_RESULT.Remembered) == BTHNS_RESULT.Remembered);
                        if (devAuthd && !devRembd) {
                            System.Diagnostics.Debug.WriteLine("Win32 BT disco: Auth'd but NOT Remembered.");
                        }
                        bool devUnkwn = !devRembd && !devAuthd;
                        bool include = (authenticated && devAuthd) || (remembered && devRembd) || (unknown && devUnkwn);
                        if (include)
#else
                        if(true)
#endif
                        {
#if WinCE
                            IntPtr lpBlob = (IntPtr)BitConverter.ToInt32(buffer, 56);
                            BLOB ib = (BLOB)Marshal.PtrToStructure(lpBlob, typeof(BLOB));
                            BthInquiryResult bir = (BthInquiryResult)Marshal.PtrToStructure(ib.pBlobData, typeof(BthInquiryResult));
#endif
                            //struct CSADDR_INFO {
                            //    SOCKET_ADDRESS LocalAddr;
                            //    SOCKET_ADDRESS RemoteAddr;
                            //    INT iSocketType;
                            //    INT iProtocol;
                            //}
                            //struct SOCKET_ADDRESS {
                            //    LPSOCKADDR lpSockaddr;
                            //    INT iSockaddrLength;
                            //}
							//pointer to outputbuffer
                            IntPtr bufferptr = Marshal32.ReadIntPtr(buffer, WqsOffset.lpcsaBuffer_48);
							//remote socket address
							IntPtr sockaddrptr = Marshal32.ReadIntPtr(bufferptr, CsaddrInfoOffsets.OffsetRemoteAddr_lpSockaddr_8);
							//remote socket len
							int sockaddrlen = Marshal.ReadInt32(bufferptr, CsaddrInfoOffsets.OffsetRemoteAddr_iSockaddrLength_12);
					

							SocketAddress btsa = new SocketAddress(AddressFamily32.Bluetooth, sockaddrlen);
						
							for(int sockbyte = 0; sockbyte < sockaddrlen; sockbyte++)
							{
								btsa[sockbyte] = Marshal.ReadByte(sockaddrptr, sockbyte);
							}

							BluetoothEndPoint bep = new BluetoothEndPoint(null, BluetoothService.Empty);
							bep = (BluetoothEndPoint)bep.Create(btsa);
				
							//new deviceinfo
							BluetoothDeviceInfo newdevice;

#if WinCE
							newdevice = new BluetoothDeviceInfo(bep.Address, bir.cod);
#else
                            newdevice = new BluetoothDeviceInfo(bep.Address);
#endif
							//add to discovered list
							al.Add(newdevice);
						}


					}
				}
#if WinCE
			}
#endif

			//stop looking
            if(handle!=0)
			{
				lookupresult = NativeMethods.WSALookupServiceEnd(handle);
			}

#if WinCE

            //open bluetooth device key
            RegistryKey devkey = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Bluetooth\\Device");
            bool addFromRegistry = authenticated || remembered;
                
            if (devkey != null)
            {
                    
                //enumerate the keys
                foreach (string devid in devkey.GetSubKeyNames())
                {    
                    BluetoothAddress address;

                    if (BluetoothAddress.TryParse(devid, out address))
                    {
                            //get friendly name
                            RegistryKey thisdevkey = devkey.OpenSubKey(devid);
                            string name = thisdevkey.GetValue("name", "").ToString();
                            uint classOfDevice = Convert.ToUInt32(thisdevkey.GetValue("class", 0));
                            thisdevkey.Close();

                            //add to collection
                            BluetoothDeviceInfo thisdevice = new BluetoothDeviceInfo(address, name, classOfDevice, true);

                            int devindex = al.IndexOf(thisdevice);

                            if (devindex == -1)
                            {
                                //if we intended to search for authenticated devices add this one to the collection
                                if (addFromRegistry)
                                {
                                    al.Add(thisdevice);
                                }
                            }
                            else
                            {
                                if (addFromRegistry)
                                {
                                    //set authenticated flag on existing discovered device
                                    ((BluetoothDeviceInfo)al[devindex]).Authenticated = true;
                                }
                                else
                                {
                                    //we want to exclude already authenticated devices so remove it from the collection
                                    al.RemoveAt(devindex);
                                }
                            }
                        }
                    }

                    devkey.Close();
            }
#endif

			
			//return results
			if(al.Count == 0)
			{
				//special case for empty collection
				return new BluetoothDeviceInfo[0]{};
			}

			return (BluetoothDeviceInfo[])al.ToArray(typeof(BluetoothDeviceInfo));
		}