/// <summary>Retrieve credentials if not already stored with data model</summary>
        /// <param name="dataModel">The data on the connection</param>
        private WifiErrorCode WifiGetConnectCredentials(WifiNetworkInfo dataModel, ref bool save)
        {
            // By default we do not want to save unless
            this.log.Info("WifiGetConnectCredentials", () => string.Format(""));
            WifiErrorCode result = WifiErrorCode.Success;

            if (dataModel.RemoteHostName.Trim().Length == 0 ||
                dataModel.RemoteServiceName.Trim().Length == 0 ||
                dataModel.Password.Trim().Length == 0)
            {
                this.log.Info("********************************", "Comm Wrapper - GetConnectionCredentials");


                this.log.Info("WifiGetConnectCredentials", () => string.Format("No data in data model"));
                if (!this.WifiGetStoredCredentials(dataModel))
                {
                    this.log.Info("WifiGetConnectCredentials", () => string.Format("No stored data - get from user"));
                    result = this.GetUserCredentials(dataModel, ref save);
                    this.log.Info("WifiGetConnectCredentials", () => string.Format("result {0}", result));
                    //if (result == WifiErrorCode.Success) {
                    //    if (save) {
                    //        this.WifiStoreCredentials(dataModel);
                    //    }
                    //}
                }
            }
            else
            {
                this.log.Info("WifiGetConnectCredentials",
                              () => string.Format("Has data:{0}:{1}", dataModel.RemoteHostName, dataModel.RemoteServiceName));
            }
            return(result);
        }
        public List <KeyValuePropertyDisplay> Wifi_GetDeviceInfoForDisplay(WifiNetworkInfo info)
        {
            List <KeyValuePropertyDisplay> list = new List <KeyValuePropertyDisplay>();

            // TODO - language

            list.Add(new KeyValuePropertyDisplay("SSID", info.SSID));
            list.Add(new KeyValuePropertyDisplay(this.GetText(MsgCode.AuthenticationType), info.AuthenticationType.ToString().UnderlineToSpaces()));
            list.Add(new KeyValuePropertyDisplay(this.GetText(MsgCode.EncryptionType), info.EncryptionType.ToString().UnderlineToSpaces()));
            list.Add(new KeyValuePropertyDisplay(this.GetText(MsgCode.UpTime), info.UpTime.ToString("g")));
            list.Add(new KeyValuePropertyDisplay(string.Format("{0} (Bars)", this.GetText(MsgCode.SignalStrength)), info.SignalStrengthInBars));
            list.Add(new KeyValuePropertyDisplay("RSSI (Decible Milliwatts)", info.RssiInDecibleMilliwatts));
            list.Add(new KeyValuePropertyDisplay("Physical Layer Kind", info.PhysicalLayerKind.ToString().UnderlineToSpaces()));
            list.Add(new KeyValuePropertyDisplay(string.Format("{0} (BSSID)", this.GetText(MsgCode.MacAddress)), info.MacAddress_BSSID));
            list.Add(new KeyValuePropertyDisplay(this.GetText(MsgCode.Kind), info.Kind));
            list.Add(new KeyValuePropertyDisplay("WIFI Direct", this.Translate(info.IsWifiDirect)));
            list.Add(new KeyValuePropertyDisplay("Channel Center Frequency (Khz)", info.ChanneCenterFrequencyKlhz));
            list.Add(new KeyValuePropertyDisplay(this.GetText(MsgCode.BeaconInterval), info.BeaconInterval.ToString("g")));


            // The host name and service name are credentials that are added to connect to exposed service
            //list.Add(new KeyValuePropertyDisplay(this.GetText(MsgCode.Port), info.RemoteServiceName));
            //list.Add(new KeyValuePropertyDisplay(this.GetText(MsgCode.HostName), info.RemoteHostName));
            // User name not used in connections
            //list.Add(new KeyValuePropertyDisplay("User Name", info.UserName));
            return(list);
        }
        private void Wifi_OnWifiConnectionAttemptCompletedHandler(object sender, MsgPumpResults result)
        {
            ErrReport report;

            WrapErr.ToErrReport(out report, 2000355, "Failure on Wifi_OnWifiConnectionAttemptCompletedHandler", () => {
                this.log.Info("Wifi_OnWifiConnectionAttemptCompletedHandler", () => string.Format(
                                  "Is OnWifiConnectionAttemptCompleted null={0}",
                                  this.OnWifiConnectionAttemptCompleted == null));

                // Set when the current connection is using new parameters
                if (this.pendingSaveConnectNetInfo != null)
                {
                    if (result.Code == MsgPumpResultCode.Connected)
                    {
                        this.WifiStoreNewCredentials(this.pendingSaveConnectNetInfo);
                    }
                    else
                    {
                        // Wipping out password will cause dialog to come up on next connect
                        this.pendingSaveConnectNetInfo.Password = "";
                    }
                    this.pendingSaveConnectNetInfo = null;
                }
                this.OnWifiConnectionAttemptCompleted?.Invoke(sender, result);
            });
            this.RaiseIfException(report);
        }
Пример #4
0
 private void DelegateRunConnection(WifiNetworkInfo info)
 {
     Device.BeginInvokeOnMainThread(() => { this.activity.IsRunning = true; });
     Task.Run(() => {
         App.Wrapper.WifiConnectPreValidatedAsync(this.networkInfo);
     });
 }
Пример #5
0
        private async void OnUpdateButtonClick(object sender, RoutedEventArgs e)
        {
            WifiNetworkInfo info = ComboBoxWifi.SelectedItem as WifiNetworkInfo;

            if (info != null && info.SSID == "disabled")
            {
                info = null;
            }

            device.CameraInfo.WifiNetwork = info;

            string error = await device.UpdateWifiSettings();

            if (error != null)
            {
                ShowError(error);
                return;
            }

            if (CheckBoxAll.IsChecked == true)
            {
                await UpdateWifiOnAllCameras(info);
            }

            this.CloseCurrentFlyout();
        }
        /// <summary>Get discovered info to look up the stored WifiCredentials object to check for credentials
        ///
        /// </summary>
        /// <param name="discoverData">The WifiNetworkInfo with info from discovered devices</param>
        /// <returns></returns>
        public WifiCredAndIndex ValidateCredentials(WifiNetworkInfo discoverData, OnErr onError)
        {
            WifiCredAndIndex result = null;
            ErrReport        report;

            WrapErr.ToErrReport(out report, 2000353, "Failure on ValidateCredentials", () => {
                this.log.Info("WifiGetConnectCredentials", () => string.Format(""));
                if (discoverData.SSID.Trim().Length == 0)
                {
                    this.log.Error(9999, "ValidateCredentialsAsync", () => string.Format("No SSID in data retrieved from Discover"));
                }
                else
                {
                    this.log.Info("ValidateCredentialsAsync", () => string.Format("SSID:{0}", discoverData.SSID));
                    result = this.WifiGetStoredCredentials(discoverData.SSID, onError);
                    if (result != null && !result.RequiresUserData)
                    {
                        // initialize the fields in the data model sent to connect to WIFI
                        discoverData.RemoteHostName    = result.Data.RemoteHostName;
                        discoverData.RemoteServiceName = result.Data.RemoteServiceName;
                        discoverData.Password          = result.Data.WifiPassword;
                    }
                }
            });
            this.RaiseIfException(report);
            return(result);
        }
Пример #7
0
 private void onWifiError(object sender, WifiError e)
 {
     this.Dispatcher.Invoke(() => {
         this.ui.IsBusy    = false;
         this.selectedWifi = null;
         App.ShowMsg(string.Format("{0} '{1}'", e.Code, e.ExtraInfo));
     });
 }
Пример #8
0
 private void DoDiscovery()
 {
     this.Title        = "WIFI";
     this.selectedWifi = WifiSelect.ShowBox(this);
     if (this.selectedWifi != null)
     {
         this.Title = this.selectedWifi.SSID;
     }
 }
 public WifiInfo(Window parent, WifiNetworkInfo info)
 {
     this.parent = parent;
     this.info   = info;
     InitializeComponent();
     this.listboxMain.ItemsSource = DI.Wrapper.Wifi_GetDeviceInfoForDisplay(info);
     this.Title         = info.SSID;
     this.SizeToContent = SizeToContent.WidthAndHeight;
 }
Пример #10
0
        private void wifiSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            WifiNetworkInfo info = this.lbWifi.SelectedItem as WifiNetworkInfo;

            if (info != null)
            {
                this.SelectedWifi = info;
                this.Close();
            }
        }
        /// <summary>Raise an event to request credentials from user</summary>
        /// <param name="dataModel">The network info data model</param>
        /// <returns>WifiErrorCode.Success on success, otherwise and error</returns>
        private WifiErrorCode GetUserCredentials(WifiNetworkInfo dataModel, ref bool save)
        {
            save = false;

            this.log.Info("********************************", "Comm Wrapper - GetUserCredentials");

            // TODO - implement. Could also use the wifi GUID
            WifiCredentials cred = new WifiCredentials()
            {
                SSID              = dataModel.SSID,
                RemoteHostName    = dataModel.RemoteHostName,
                RemoteServiceName = dataModel.RemoteServiceName,
            };

            WrapErr.ChkVar(this.CredentialsRequestedEvent, 9999, "No subscribers to CredentialsRequestedEvent");
            this.CredentialsRequestedEvent?.Invoke(this, cred);

            if (cred.IsUserCanceled)
            {
                this.log.Info("********************************", "Comm Wrapper - GetUserCredentials Canceled");

                return(WifiErrorCode.UserCanceled);
            }

            if (cred.SSID.Trim().Length == 0)
            {
                this.log.Info("********************************", "Comm Wrapper - GetUserCrendentials Empty SSID");
                return(WifiErrorCode.EmptySsid);
            }
            else if (cred.RemoteHostName.Trim().Length == 0)
            {
                this.log.Info("********************************", "Comm Wrapper - GetUserCrendentials Empty host name");
                return(WifiErrorCode.EmptyHostName);
            }
            else if (cred.RemoteServiceName.Trim().Length == 0)
            {
                this.log.Info("********************************", "Comm Wrapper - GetUserCrendentials Empty port name");
                return(WifiErrorCode.EmptyServiceName);
            }
            else if (cred.WifiPassword.Trim().Length == 0)
            {
                this.log.Info("********************************", "Comm Wrapper - GetUserCrendentials Empty password");

                return(WifiErrorCode.EmptyPassword);
            }

            this.log.Info("GetUserCredentials", () => string.Format("User request save:{0}", cred.IsUserSaveRequest));
            save = cred.IsUserSaveRequest;
            dataModel.RemoteHostName    = cred.RemoteHostName;
            dataModel.RemoteServiceName = cred.RemoteServiceName;
            dataModel.Password          = cred.WifiPassword;
            return(WifiErrorCode.Success);
        }
Пример #12
0
 public WifiCredRequestPopUpPage(
     WifiCredAndIndex cred,
     WifiNetworkInfo discoverData,
     Action <WifiNetworkInfo> connectAction)
 {
     this.cred          = cred;
     this.discoverData  = discoverData;
     this.connectAction = connectAction;
     InitializeComponent();
     this.CloseWhenBackgroundIsClicked = false;
     this.InitiEditBoxes(this.cred.Data);
     App.Wrapper.CurrentSupportedLanguage(this.UpdateLanguage);
 }
Пример #13
0
 private void DumpNetworkInfo(WifiNetworkInfo info)
 {
     this.log.Info("DumpNetworkInfo", () => string.Format("-----------------------------------------------------"));
     this.log.Info("DumpNetworkInfo", () => string.Format("                    SSID: {0}", info.SSID));
     this.log.Info("DumpNetworkInfo", () => string.Format("             Wifi Direct: {0}", info.IsWifiDirect));
     this.log.Info("DumpNetworkInfo", () => string.Format("                    Kind: {0}", info.Kind));
     this.log.Info("DumpNetworkInfo", () => string.Format("                     MAC: {0}", info.MacAddress_BSSID));
     this.log.Info("DumpNetworkInfo", () => string.Format("     Authentication Type: {0}", info.AuthenticationType.ToString().UnderlineToSpaces()));
     this.log.Info("DumpNetworkInfo", () => string.Format("         Encryption Type: {0}", info.EncryptionType.ToString().UnderlineToSpaces()));
     this.log.Info("DumpNetworkInfo", () => string.Format("         Beacon Interval: {0}", info.BeaconInterval));
     this.log.Info("DumpNetworkInfo", () => string.Format("Center Channel Frequency: {0}", info.ChanneCenterFrequencyKlhz));
     this.log.Info("DumpNetworkInfo", () => string.Format("          Physical Layer: {0}", info.PhysicalLayerKind));
     this.log.Info("DumpNetworkInfo", () => string.Format("           RSSI Decibles: {0}", info.RssiInDecibleMilliwatts));
     this.log.Info("DumpNetworkInfo", () => string.Format("    Signal Strength Bars: {0}", info.SignalStrengthInBars));
     this.log.Info("DumpNetworkInfo", () => string.Format("                 Up Time: {0}", info.UpTime));
 }
Пример #14
0
 private PasswordCredential GetCredentials(WifiNetworkInfo info)
 {
     if (info.AuthenticationType == NetAuthenticationType.Open_802_11 &&
         info.EncryptionType == NetEncryptionType.None)
     {
         return(null);
     }
     else
     {
         // We only ever use the password. Never user name
         return(new PasswordCredential()
         {
             Password = info.Password,
         });
     }
 }
        private void Wifi_OnErrorHandler(object sender, WifiError e)
        {
            ErrReport report;

            WrapErr.ToErrReport(out report, 2000356, "Failure on Wifi_OnErrorHandler", () => {
                this.log.Info("Wifi_OnErrorHandler", () => string.Format("Is OnWifiError null={0}", this.OnWifiError == null));
                // Possible to have other errors on connect so we will also wipe out connect params here
                if (this.pendingSaveConnectNetInfo != null)
                {
                    // Wipping out password will cause dialog to come up on next connect
                    this.pendingSaveConnectNetInfo.Password = "";
                    this.pendingSaveConnectNetInfo          = null;
                }
                this.OnWifiError?.Invoke(sender, e);
            });
            this.RaiseIfException(report);
        }
        /// <summary>Retrieve the stored credentials for this network</summary>
        /// <param name="dataModel">Data about the network</param>
        /// <returns>true on success, otherwise false</returns>
        private bool WifiGetStoredCredentials(WifiNetworkInfo dataModel)
        {
            bool found = false;

            this.GetWifiCredList(
                (list) => {
                foreach (var item in list)
                {
                    this.log.Info("WifiGetStoredCredentials", () => string.Format("SSID '{0}' List itm display '{1}", dataModel.SSID, item.Display));
                    if (item.Display == dataModel.SSID)
                    {
                        // We can do double check by loading the actual object and compare other data like GUID
                        this.RetrieveWifiCredData(
                            item,
                            (data) => {
                            this.log.Info("WifiGetStoredCredentials", () => string.Format("FOUND SSID '{0}'", item.Display));

                            dataModel.RemoteHostName    = data.RemoteHostName;
                            dataModel.RemoteServiceName = data.RemoteServiceName;
                            dataModel.Password          = data.WifiPassword;
                            dataModel.UserName          = data.WifiUserName; // Not using user name for now
                            found = true;
                        },
                            (err) => {
                            // TODO log error
                            this.log.Error(9999, () => string.Format("Did not find '{0}'", dataModel.SSID));
                            found = false;
                        });
                        break;
                    }
                }
            },
                (err) => {
                found = false;
            });

            // TODO - implement. Could wifi ssid or GUID to retrieve a stored WifiCredentials object
            return(found);

            //dataModel.RemoteHostName = "192.168.4.1"; // IP of Arduino socket
            //dataModel.RemoteServiceName = "80"; // Arduino HTTP port 80
            //dataModel.Password = "******";
            //dataModel.UserName = ""; // Not using User name for now
            //return true;
        }
Пример #17
0
 private async Task UpdateWifiOnAllCameras(WifiNetworkInfo info)
 {
     foreach (var camera in DataStore.Instance.Cameras)
     {
         if (camera != this.device.CameraInfo)
         {
             FoscamDevice temp = new FoscamDevice()
             {
                 CameraInfo = camera
             };
             if (camera.WifiNetwork == null || camera.WifiNetwork.SSID != info.SSID || camera.WifiPassword != device.CameraInfo.WifiPassword)
             {
                 camera.WifiPassword         = device.CameraInfo.WifiPassword;
                 temp.CameraInfo.WifiNetwork = info;
                 await temp.UpdateWifiSettings();
             }
         }
     }
 }
Пример #18
0
        private void btnSelect_Clicked(object sender, EventArgs e)
        {
            // Get selected and call view model command to move to run page
            WifiNetworkInfo info = this.lstWifi.SelectedItem as WifiNetworkInfo;

            if (info != null)
            {
                //// TODO - remove hack
                //info.RemoteHostName = "192.168.4.1";
                //info.RemoteServiceName = "80";
                //info.Password = "******";

                this.viewModel.GoToRun.Execute(info);
            }
            else
            {
                this.OnErr(App.Wrapper.GetText(MsgCode.NothingSelected));
            }
        }
Пример #19
0
        int MergeWifiItem(WifiNetworkInfo info)
        {
            int i = 0;

            foreach (WifiNetworkInfo item in ComboBoxWifi.Items)
            {
                if (item.SSID == info.SSID)
                {
                    item.Security = info.Security;
                    item.Mode     = info.Mode;
                    item.BSSID    = info.BSSID;
                    return(i);
                }
                i++;
            }

            ComboBoxWifi.Items.Add(info);

            return(ComboBoxWifi.Items.Count - 1);
        }
 public void WifiConnectPreValidatedAsync(WifiNetworkInfo dataModel)
 {
     this.log.InfoEntry("WifiConnectPreValidatedAsync");
     try {
         this.wifi.ConnectAsync(dataModel);
     }
     catch (ErrReportException erE) {
         this.OnWifiError?.Invoke(this, new WifiError(WifiErrorCode.Unknown)
         {
             ExtraInfo = erE.Report.Msg
         });
     }
     catch (Exception e) {
         this.log.Exception(9999, "", e);
         this.OnWifiError?.Invoke(this, new WifiError(WifiErrorCode.Unknown)
         {
             ExtraInfo = e.Message
         });
     }
 }
        private void DoConnection(WifiNetworkInfo dataModel)
        {
            if (!this.GetWifiManager().IsWifiEnabled)
            {
                this.RaiseError(WifiErrorCode.NoAdapters);
                return;
            }

            this.Disconnect();

            int port;

            if (!int.TryParse(dataModel.RemoteServiceName, out port))
            {
                this.RaiseError(WifiErrorCode.NonNumericPort);
                return;
            }
            // TODO - need check the host name length

            WifiNetworkSpecifier specifier = new WifiNetworkSpecifier.Builder().
                                             SetSsid(dataModel.SSID).
                                             SetWpa2Passphrase(dataModel.Password).
                                             Build();

            NetworkRequest request = new NetworkRequest.Builder()
                                     .AddTransportType(TransportType.Wifi)
                                     .RemoveCapability(NetCapability.Internet) // Internet not required
                                     .SetNetworkSpecifier(specifier)           // we want _our_ network
                                     .Build();


            ConnectivityManager cm = this.GetConnectivityManager();

            this.connectCallback = new WifiAndroidConnectCallback(cm, dataModel.RemoteHostName, port)
            {
                NetworkAvailable   = this.OnNetworkAvailable,
                NetworkUnavailable = this.OnNetworkUnavailable
            };
            cm.RequestNetwork(request, this.connectCallback);
        }
        /// <summary>List receiver callback</summary>
        /// <param name="results">The results of the scan</param>
        private void ListDiscoveryCallback(IList <ScanResult> results)
        {
            this.log.Info("ListDiscoveryCallback", "Starting");

            List <WifiNetworkInfo> networks = new List <WifiNetworkInfo>();

            foreach (var result in results)
            {
                // Ignore those with hidden SSID
                if (result.Ssid.Length > 0)
                {
                    WifiNetworkInfo info = new WifiNetworkInfo()
                    {
                        SSID                      = result.Ssid,
                        MacAddress_BSSID          = result.Bssid,
                        ChanneCenterFrequencyKlhz = result.Frequency,
                    };
                    this.log.Info("ListDiscoveryCallback", () => string.Format("                SSID:{0}", result.Ssid));
                    //this.log.Info("ListDiscoveryCallback", () => string.Format("               BSSID:{0}", result.Bssid));
                    //this.log.Info("ListDiscoveryCallback", () => string.Format("        Capabilities:{0}", result.Capabilities));
                    //this.log.Info("ListDiscoveryCallback", () => string.Format("   Center Frequency0:{0}", result.CenterFreq0));
                    //this.log.Info("ListDiscoveryCallback", () => string.Format("   Center Frequency1:{0}", result.CenterFreq1));
                    //this.log.Info("ListDiscoveryCallback", () => string.Format("       Channel Width:{0}", result.ChannelWidth));
                    //this.log.Info("ListDiscoveryCallback", () => string.Format("               Class:{0}", result.Class.ToString()));
                    //this.log.Info("ListDiscoveryCallback", () => string.Format("           Frequency:{0}", result.Frequency));
                    //this.log.Info("ListDiscoveryCallback", () => string.Format("  Is 80211 responder:{0}", result.Is80211mcResponder()));
                    //this.log.Info("ListDiscoveryCallback", () => string.Format("Is Passpoint Network:{0}", result.IsPasspointNetwork));
                    //this.log.Info("ListDiscoveryCallback", () => string.Format("               Level:{0}", result.Level));
                    //this.log.Info("ListDiscoveryCallback", () => string.Format("       Friendly name:{0}", result.OperatorFriendlyName.ToString()));
                    //this.log.Info("ListDiscoveryCallback", () => string.Format("           Timestamp:{0}", result.Timestamp.ToString()));
                    //this.log.Info("ListDiscoveryCallback", () => string.Format("          Venue name:{0}", result.VenueName.ToString()));
                    networks.Add(info);
                }
            }
            // unregister the receiver on completion
            this.GetContext().UnregisterReceiver(this.listReceiver);
            this.isListReceiverRunning = false;
            this.DiscoveredNetworks?.Invoke(this, networks);
        }
 /// <summary>Store credentials entered by user</summary>
 /// <param name="dataModel">The network data model with the network credentials</param>
 private void WifiStoreNewCredentials(WifiNetworkInfo dataModel)
 {
     this.log.InfoEntry("WifiStoreNewCredentials");
     this.CreateNewWifiCred(
         dataModel.SSID,
         new WifiCredentialsDataModel()
     {
         SSID = dataModel.SSID,
         //Id = dataModel.id // TODO Put a GUID id into the network info
         RemoteHostName    = dataModel.RemoteHostName,
         RemoteServiceName = dataModel.RemoteServiceName,
         WifiPassword      = dataModel.Password,
         WifiUserName      = dataModel.UserName,
     },
         () => {
         // Success. Do nothing
         this.log.Info("WifiStoreNewCredentials", () => string.Format("Cred for {0} stored successfuly", dataModel.SSID));
     },
         (err) => {
         this.log.Error(9999, () => string.Format("Error creating new cred on wifi connect '{0}'", err));
     });
 }
Пример #24
0
        private async Task ScanForNetworks(WiFiAdapter adapter, WifiAdapterInfo info)
        {
            try {
                // TODO - will need a list of available UWP network objects to be able to find fof connection - or use the UWP adapter
                await adapter.ScanAsync();

                networks      = wifiAdapter.NetworkReport.AvailableNetworks;
                info.Networks = new List <WifiNetworkInfo>();
                // We will not return those with blank SSID
                foreach (var net in networks)
                {
                    if (net.Ssid.Length > 0)
                    {
                        WifiNetworkInfo netInfo = new WifiNetworkInfo()
                        {
                            SSID = net.Ssid,
                            Kind = net.NetworkKind.Convert(),
                            ChanneCenterFrequencyKlhz = net.ChannelCenterFrequencyInKilohertz,
                            BeaconInterval            = net.BeaconInterval,
                            MacAddress_BSSID          = net.Bssid,
                            RssiInDecibleMilliwatts   = net.NetworkRssiInDecibelMilliwatts,
                            PhysicalLayerKind         = net.PhyKind.Convert(),
                            AuthenticationType        = net.SecuritySettings.NetworkAuthenticationType.Convert(),
                            EncryptionType            = net.SecuritySettings.NetworkEncryptionType.Convert(),
                            IsWifiDirect         = net.IsWiFiDirect,
                            SignalStrengthInBars = net.SignalBars,
                            UpTime = net.Uptime,
                        };
                        //this.DumpNetworkInfo(netInfo);
                        info.Networks.Add(netInfo);
                    }
                }
                this.log.Info("ScanForNetworks", () => string.Format("Found {0} networks", info.Networks.Count));
            }
            catch (Exception e) {
                this.log.Exception(9999, "ScanForNetworks", "", e);
            }
        }
        public void WifiConnectAsync(WifiNetworkInfo dataModel)
        {
            this.log.InfoEntry("WifiConnectAsync");
            // TODO use a try catch and change signature to have an error delegate return?
            try {
                bool          save   = false;
                WifiErrorCode result = this.WifiGetConnectCredentials(dataModel, ref save);
                this.log.Info("********************************", "Comm Wrapper - WifiConnectAsync after get credentials");

                if (result != WifiErrorCode.Success)
                {
                    this.OnWifiError?.Invoke(this, new WifiError(result));
                }
                else
                {
                    if (save)
                    {
                        this.pendingSaveConnectNetInfo = dataModel;
                    }
                    this.wifi.ConnectAsync(dataModel);
                }
            }
            catch (ErrReportException erE) {
                this.OnWifiError?.Invoke(this, new WifiError(WifiErrorCode.Unknown)
                {
                    ExtraInfo = erE.Report.Msg
                });
            }
            catch (Exception e) {
                this.log.Exception(9999, "", e);
                this.OnWifiError?.Invoke(this, new WifiError(WifiErrorCode.Unknown)
                {
                    ExtraInfo = e.Message
                });
            }
        }
Пример #26
0
 private void OnUiDisconnect(object sender, EventArgs e)
 {
     DI.Wrapper.WifiDisconect();
     this.selectedWifi = null;
 }
Пример #27
0
 public void ConnectAsync(WifiNetworkInfo dataModel)
 {
     Task.Run(() => {
         this.DoConnection(dataModel);
     });
 }
Пример #28
0
 private async void OnGoToRun(WifiNetworkInfo info)
 {
     await Shell.Current.GoToAsync($"{nameof(WifiRunPage)}?WifiRunPage.WifiInfoAsString={JsonConvert.SerializeObject(info)}");
 }
        private void ShowParameters(PropertyBag props)
        {
            if (props.GetValue <string>("Error") != null)
            {
                return;
            }

            string alias = props.GetValue <string>("alias");

            if (alias != device.CameraInfo.Name)
            {
                device.CameraInfo.Name = alias;
            }

            int          wifi_enable    = props.GetValue <int>("wifi_enable");
            string       wifi_ssid      = props.GetValue <string>("wifi_ssid");
            WifiSecurity wifi_encrypt   = (WifiSecurity)props.GetValue <int>("wifi_encrypt");
            int          wifi_authtype  = props.GetValue <int>("wifi_authtype");
            int          wifi_keyformat = props.GetValue <int>("wifi_keyformat");

            // ignore all this WEP crap, hopefully user doesn't have
            string wifi_defkey = props.GetValue <string>("wifi_defkey");
            string wifi_key1   = props.GetValue <string>("wifi_key1");
            string wifi_key2   = props.GetValue <string>("wifi_key2");
            string wifi_key3   = props.GetValue <string>("wifi_key3");
            string wifi_key4   = props.GetValue <string>("wifi_key4");

            string wifi_key1_bits = props.GetValue <string>("wifi_key1_bits");
            string wifi_key2_bits = props.GetValue <string>("wifi_key2_bits");
            string wifi_key3_bits = props.GetValue <string>("wifi_key3_bits");
            string wifi_key4_bits = props.GetValue <string>("wifi_key4_bits");

            // this is where mode 4 key shows up
            string wifi_wpa_psk = props.GetValue <string>("wifi_wpa_psk");

            switch (wifi_encrypt)
            {
            case WifiSecurity.None:
                break;

            case WifiSecurity.WepTkip:
                break;

            case WifiSecurity.WpaAes:
                break;

            case WifiSecurity.Wpa2Aes:
                break;

            case WifiSecurity.Wpa2Tkip:
                device.CameraInfo.WifiPassword = wifi_wpa_psk;
                break;

            default:
                break;
            }

            if (!string.IsNullOrEmpty(wifi_ssid))
            {
                var network = new WifiNetworkInfo()
                {
                    SSID     = wifi_ssid,
                    Mode     = WifiMode.Infrastructure,
                    Security = wifi_encrypt
                };

                device.CameraInfo.WifiNetwork = network;
            }
        }
Пример #30
0
        /// <summary>Run asynchronous connection where ConnectionCompleted is raised on completion</summary>
        /// <param name="deviceDataModel">The data model with information on the device</param>
        public void ConnectAsync(WifiNetworkInfo dataModel)
        {
            this.DisconnectSynchronous(true);
            Task.Run(async() => {
                try {
                    this.log.InfoEntry("ConnectAsync");
                    this.log.Info("ConnectAsync", () => string.Format(
                                      "Host:{0} Service:{1}", dataModel.RemoteHostName, dataModel.RemoteServiceName));

                    WiFiAvailableNetwork net = this.GetNetwork(dataModel.SSID);
                    if (net != null)
                    {
                        // Connect WIFI level
                        // TODO How to establish kind of authentication

                        switch (dataModel.AuthenticationType)
                        {
                        // Arduino authentication - requires password but no user name
                        case NetAuthenticationType.RSNA_PSK:
                            break;
                        }

                        WiFiConnectionResult result = null;
                        PasswordCredential cred     = this.GetCredentials(dataModel);
                        if (cred == null)
                        {
                            result = await wifiAdapter.ConnectAsync(net, WiFiReconnectionKind.Automatic);
                        }
                        else
                        {
                            result = await wifiAdapter.ConnectAsync(net, WiFiReconnectionKind.Automatic, cred);
                        }

                        // If the password is bad you get a timeout rather than failed credentials
                        switch (result.ConnectionStatus)
                        {
                        case WiFiConnectionStatus.Success:
                            //ConnectionProfile profile = await this.wifiAdapter.NetworkAdapter.GetConnectedProfileAsync();
                            //this.log.Info("ConnectAsync", () => string.Format("Connected to:{0}", profile.ProfileName));
                            //if (profile.IsWlanConnectionProfile) {

                            //await this.DumpWifiAdapterInfo(wifiAdapter);
                            this.log.Info("ConnectAsync", () => string.Format("Connecting to {0}:{1}", dataModel.RemoteHostName, dataModel.RemoteServiceName));
                            //this.log.Info("ConnectAsync", () => string.Format(
                            //    "Connecting to {0}:{1}:{2}", dataModel.RemoteHostName, dataModel.RemoteServiceName, dataModel.Password));
                            // Connect socket
                            await msgPump.ConnectAsync2(new SocketMsgPumpConnectData()
                            {
                                MaxReadBufferSize = 255,
                                RemoteHostName    = dataModel.RemoteHostName,
                                ServiceName       = dataModel.RemoteServiceName,
                                // TODO - determine protection level according to connection
                                ProtectionLevel = SocketProtectionLevel.PlainSocket,
                            });
                            break;

                        case WiFiConnectionStatus.UnspecifiedFailure:
                        case WiFiConnectionStatus.AccessRevoked:
                        case WiFiConnectionStatus.InvalidCredential:
                        case WiFiConnectionStatus.NetworkNotAvailable:
                        case WiFiConnectionStatus.Timeout:
                        case WiFiConnectionStatus.UnsupportedAuthenticationProtocol:
                            this.OnError?.Invoke(this, new WifiError(result.ConnectionStatus.Convert()));
                            break;

                        default:
                            this.OnError?.Invoke(this, new WifiError(WifiErrorCode.Unknown));
                            break;
                        }
                    }
                    else
                    {
                        this.OnError?.Invoke(this, new WifiError(WifiErrorCode.NetworkNotAvailable)
                        {
                            ExtraInfo = dataModel.SSID
                        });
                    }
                }
                catch (ErrReportException erE) {
                    this.OnError?.Invoke(this, new WifiError(WifiErrorCode.Unknown)
                    {
                        ExtraInfo = erE.Report.Msg
                    });
                }
                catch (Exception e) {
                    this.log.Exception(9999, "Connect Asyn Error", e);
                    this.OnError?.Invoke(this, new WifiError(WifiErrorCode.Unknown));
                }
            });
        }