Beispiel #1
0
        public void JoinWifi(string ssidToJoin, Wlan.Dot11BssType bssType, BackgroundWorker worker, DoWorkEventArgs e)
        {
            IJcwTaskResult result = new JcwTaskResult();

            result.Status   = TaskResultStatus.Failed;
            Error.LastError = null;

            // If the ssid to join is null, return without attempting to join.
            if (string.IsNullOrEmpty(ssidToJoin))
            {
                return;
            }

            // The SSID profile name for adhoc access points includes the -adhoc suffix.
            string ssidProfileName = ssidToJoin;

            if (bssType == Wlan.Dot11BssType.Independent)
            {
                ssidProfileName += "-adhoc";
            }

            // If we are already connected to that ssid, return without attempting to join. Note that the SSID in the
            // CurrentAccessPoint is actually the SSID profile name.
            if (ssidProfileName.Equals(CurrentAccessPoint.SSID))
            {
                result.Status = TaskResultStatus.Passed;
                result.Text   = string.Format("Already connected to wifi access point: {0}", ssidProfileName);
                e.Result      = result;
                return;
            }

            try
            {
                if (worker != null && worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                // If we are currently connected to a wireless access point other than the one we want to join, disconnect from it.
                if (!Wifi.NotConnected.Equals(CurrentAccessPoint.SSID))
                {
                    DisconnectWifi();
                }

                if (worker != null && worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                // Check to see if the profile exists on this system before trying to connect.
                try
                {
                    string profileXml = WlanInterface.GetProfileXml(ssidProfileName);
                }
                catch (Win32Exception ex)
                {
                    // If the exception is 'Element not found' this profile has not been registered.  If it is an adhoc access point we
                    // should register the profile for it.
                    if ("Element not found".Equals(ex.Message) && bssType == Wlan.Dot11BssType.Independent)
                    {
                        string profileXml = WifiHelper.GetAdhocProfileXmlForSSID(ssidToJoin);
                        Debug.WriteLine(string.Format("Setting wifi profile xml {0}.", profileXml));
                        WlanInterface.SetProfile(Wlan.WlanProfileFlags.AllUser, profileXml, true);
                    }
                }

                if (worker != null && worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                bool      connectComplete = false;
                Stopwatch sw = new Stopwatch();
                sw.Start();
                try
                {
                    // Create unsignaled manual reset event that will be signaled in the NetworkAddressChanged handler.
                    ConnectionStatusChangedManualResetEvent = new ManualResetEvent(false);

                    // Windows XP with SP3 and Wireless LAN API for Windows XP with SP2:  Only the wlan_connection_mode_profile value is supported.
                    WlanInterface.Connect(Wlan.WlanConnectionMode.Profile, bssType, ssidProfileName);

                    // Subscribe to the NetworkAddressChanged event and wait for either the manual reset event to be signaled or the connection timeout.
                    NetworkChange.NetworkAddressChanged += NetworkAddressChanged_ConnectStatus;

                    int totalWaitTime = 0;
                    int loopWaitTime  = ConnectionTimeout / ConnectionIntervals;
                    do
                    {
                        connectComplete = ConnectionStatusChangedManualResetEvent.WaitOne(loopWaitTime);
                        totalWaitTime  += loopWaitTime;

                        if (worker != null && worker.CancellationPending)
                        {
                            e.Cancel = true;
                            return;
                        }
                    }while (!connectComplete && totalWaitTime < ConnectionTimeout);

                    if (connectComplete)
                    {
                        // Create unsignaled manual reset event that will be signaled in the NetworkAddressChanged handler.
                        ActiveConnectionMonitoringManualResetEvent = new ManualResetEvent(false);

                        // If the connection was established successfully, queue a method to the thread pool to monitor this active connection.
                        ThreadPool.QueueUserWorkItem(MonitorActiveWifiConnection);

                        result.Status = TaskResultStatus.Passed;
                        result.Text   = "Joined wifi access point";
                    }
                    else
                    {
                        result.Text = "Timeout attempting to join wifi access point";
                    }
                }
                finally
                {
                    NetworkChange.NetworkAddressChanged -= NetworkAddressChanged_ConnectStatus;
                    sw.Stop();
                    Debug.WriteLine(string.Format("Time attempting to connect: {0}ms", sw.ElapsedMilliseconds));

                    // If the user canceled the connect disconnect before exiting. Use the internal disconnect because
                    // the regular disconnect checks to see if we are connected to the current access point and only
                    // then would it attempt to disconnect.
                    if (e.Cancel)
                    {
                        DisconnectWifiInternal();
                    }
                }
            }
            catch (Win32Exception ex)
            {
                Error.LastError = ex.ToString();
            }
            finally
            {
                e.Result = result;
            }
        }
Beispiel #2
0
        private void RunDiscover(BackgroundWorker worker, DoWorkEventArgs e)
        {
            IJcwTaskResult result = new JcwTaskResult();

            result.Status   = TaskResultStatus.Failed;
            Error.LastError = null;

            try
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                Device[] devices = m_network.DiscoverDevices();
                if (devices.Length == 0)
                {
                    throw new Exception("No devices found. Verify that " + m_deviceName + " is on and in range");
                }

                bool exactMatch = true;
                if (m_deviceName.Contains("%"))
                {
                    m_deviceName = m_deviceName.Replace("%", "");
                    exactMatch   = false;
                }

                // go through the devices we found, looking for our gcog
                bool foundOurDevice = false;
                foreach (Device d in devices)
                {
                    RemoteDevice rd = d as RemoteDevice;

                    // verify that the device name we found matches the one we were looking for
                    if ((exactMatch && rd.Name == m_deviceName) || rd.Name.Contains(m_deviceName))
                    {
                        m_device        = rd;
                        m_deviceAddress = rd.Address.ToString();
                        foundOurDevice  = true;
                        break;
                    }
                }
                if (!foundOurDevice)
                {
                    throw new Exception("Could not find device " + m_deviceName);
                }

                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                // before trying to discover services, enter the pin code
                if (!m_device.Bonded)
                {
                    m_device.Bond(m_pinCode);
                }

                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                // discover all services offered by the device
                Service[] services = m_device.DiscoverServices(ServiceType.SerialPort);

                if (services.Length == 0)
                {
                    // try to discover services a second time
                    services = m_device.DiscoverServices(ServiceType.SerialPort);
                    if (services.Length == 0)
                    {
                        throw new Exception("No services found");
                    }
                }

                exactMatch = true;
                if (m_serviceName.Contains("%"))
                {
                    m_serviceName = m_serviceName.Replace("%", "");
                    exactMatch    = false;
                }

                bool foundOurService = false;
                foreach (Service s in services)
                {
                    RemoteService rs = s as RemoteService;

                    // verify that the service name we found matches the one we were looking for
                    if ((exactMatch && rs.Name == m_serviceName) || rs.Name.Contains(m_serviceName))
                    {
                        m_service        = rs;
                        m_stream         = rs.Stream;
                        m_serviceAddress = rs.Address.ToString();
                        m_serviceChannel = rs.Address.ServiceChannelNumber;
                        foundOurService  = true;
                        break;
                    }
                }

                if (!foundOurService)
                {
                    throw new Exception("Could not find service " + m_serviceName);
                }

                result.Status = TaskResultStatus.Passed;
                result.Text   = "Found bluetooth device";
            }
            catch (ThreadAbortException) { }
            catch (BlueToolsException ex)
            {
                Error.LastError = ex.Message + ex.StackTrace;
                result.Text     = Error.LastError;
            }
            catch (Exception ex)
            {
                Error.LastError = ex.Message + ex.StackTrace;
                result.Text     = Error.LastError;
            }
            finally
            {
                e.Result = result;
            }
        }
Beispiel #3
0
        private void RunDirectConnect(BackgroundWorker worker, DoWorkEventArgs e)
        {
            IJcwTaskResult result = new JcwTaskResult();

            result.Status   = TaskResultStatus.Failed;
            Error.LastError = null;

            try
            {
                do
                {
                    m_device = m_network.ConnectDevice(new Address(m_deviceAddress), m_deviceName);

                    if (m_device == null)
                    {
                        Thread.Sleep(m_bluetoothDirectConnectIntervalMilliseconds);
                    }
                    else
                    {
                        // before trying to discover services, enter the pin code
                        if (!m_device.Bonded)
                        {
                            m_device.Bond(m_pinCode);
                        }

                        // this will connect without regard for whether the service exists
                        m_service = m_device.ConnectService(m_serviceChannel, m_serviceName);

                        if (m_service == null)
                        {
                            Thread.Sleep(m_bluetoothDirectConnectIntervalMilliseconds);
                        }
                        else
                        {
                            try
                            {
                                m_stream = m_service.Stream;
                                break;
                            }
                            catch (Exception)
                            {
                                Thread.Sleep(m_bluetoothDirectConnectIntervalMilliseconds);
                            }
                        }
                    }
                }while (m_bluetoothStopwatch.Elapsed.Seconds < m_bluetoothDirectConnectTimeoutSeconds);

                if (m_device == null)
                {
                    throw new Exception("Could not connect to device: " + m_deviceName);
                }
                if (m_service == null)
                {
                    throw new Exception("Could not connect to service " + m_serviceName);
                }

                result.Status = TaskResultStatus.Passed;
                result.Text   = "Direct connect completed successfully";
            }
            catch (ThreadAbortException) { }
            catch (BlueToolsException ex)
            {
                Error.LastError = ex.Message + ex.StackTrace;
                result.Text     = Error.LastError;
            }
            catch (Exception ex)
            {
                Error.LastError = ex.Message + ex.StackTrace;
                result.Text     = Error.LastError;
            }
            finally
            {
                e.Result = result;
            }
        }
Beispiel #4
0
        /// <summary>
        /// Cancelled status is the default which means that a status check is already running so we
        /// won't check status this go around.  All other cases will return status of passed except if we
        /// hit an exception in which case we will return a status of Failed.
        /// </summary>
        /// <returns></returns>
        public IJcwTaskResult TestConnectionStatus()
        {
            IJcwTaskResult result = new JcwTaskResult();

            result.Status = TaskResultStatus.Cancelled;

            if (!m_statusCheckRunning)
            {
                m_statusCheckRunning = true;
                try
                {
                    if (!m_network.IsHardwareAvailable)
                    {
                        if (OnDeviceLost != null)
                        {
                            OnDeviceLost(this, new JcwEventArgs <string> (m_deviceName));
                            result.Text   = "Hardware not available. Raising device lost";
                            result.Status = TaskResultStatus.Passed;
                            return(result);
                        }
                    }
                    else if (!m_network.DiscoveryPending)
                    {
                        Device[] devices = m_network.DiscoverDevices();

                        List <string> deviceNames = new List <string> ();
                        foreach (Device device in devices)
                        {
                            deviceNames.Add(device.Name);
                        }
                        StringBuilder sb = new StringBuilder();
                        foreach (string deviceName in deviceNames)
                        {
                            sb.Append(deviceName + ",");
                        }

                        Debug.WriteLine("Devices: " + sb.ToString());

                        foreach (Device device in devices)
                        {
                            if (device.Name == m_deviceName)
                            {
                                // If there was a direct connect, the services for the device won't populated without discovery of them.
                                // In that case, we will assume that you are connected so return.
                                if (device.Services.Length == 0)
                                {
                                    result.Text   = string.Format("Found device: {0} via direct connect.", m_deviceName);
                                    result.Status = TaskResultStatus.Passed;
                                    return(result);
                                }

                                foreach (Service service in device.Services)
                                {
                                    if (service.Name == m_serviceName)
                                    {
                                        result.Text   = string.Format("Found device: {0}, service: {1}", m_deviceName, m_serviceName);
                                        result.Status = TaskResultStatus.Passed;
                                        return(result);
                                    }
                                }
                            }
                        }

                        if (OnDeviceLost != null)
                        {
                            OnDeviceLost(this, new JcwEventArgs <string> (m_deviceName));
                            result.Text   = string.Format("Device not available. Raising device lost for: {0}", m_deviceName);
                            result.Status = TaskResultStatus.Passed;
                            return(result);
                        }
                    }
                }
                catch (BlueToolsException bte)
                {
                    Error.LastError = result.Text = bte.ToString();
                    result.Status   = TaskResultStatus.Failed;
                }
                catch (Exception e)
                {
                    Error.LastError = result.Text = e.ToString();
                    result.Status   = TaskResultStatus.Failed;
                }
                finally
                {
                    m_statusCheckRunning = false;
                    result.Status        = TaskResultStatus.Passed;
                }
            }

            return(result);
        }