Exemple #1
0
        public async Task <ResultCommandAvailableNetworks> GetAvailableNetworkListHandler()
        {
            try
            {
                var wifiAdapterList = await WiFiAdapter.FindAllAdaptersAsync();

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

                foreach (var adapter in wifiAdapterList)
                {
                    try
                    {
                        var availableNetworks = await PortalApiHelper.GetAvailableNetworks(adapter.NetworkAdapter.NetworkAdapterId);

                        if (availableNetworks != null && availableNetworks.AvailableNetworks != null)
                        {
                            networks.AddRange(availableNetworks.AvailableNetworks);
                        }
                    }
                    catch (Exception) { }
                }

                var sortedNetworks = networks.OrderBy(x => x.SSID).Distinct().ToList();

                return(new ResultCommandAvailableNetworks()
                {
                    Networks = sortedNetworks, IsSuccess = true
                });
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error GetAvailableNetworkListHandler: {e.Message}.");
                return(ResultCommand.CreateFailedCommand <ResultCommandAvailableNetworks>($"Error GetAvailableNetworkListHandler: {e.Message}."));
            }
        }
Exemple #2
0
        public ResultCommandGenerateCSR GenerateCSR()
        {
            try
            {
                //Generate Certificate with RSA Private key
                byte[] csr = null;
                using (RSA key = SimulatedDevice.GetPrivateKey(true))
                {
                    CertificateRequest certRequest = new CertificateRequest($"CN={SimulatedDevice.DeviceId}",
                                                                            key,
                                                                            HashAlgorithmName.SHA256,
                                                                            RSASignaturePadding.Pkcs1);
                    csr = certRequest.CreateSigningRequest();
                }

                return(new ResultCommandGenerateCSR()
                {
                    Csr = csr != null?Convert.ToBase64String(csr) : null,
                              IsSuccess = true
                });
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error GenerateCSR: {e.Message}.");
                return(ResultCommand.CreateFailedCommand <ResultCommandGenerateCSR>($"Error GenerateCSR: {e.Message}."));
            }
        }
        public async Task <ResultCommand> SetDeviceSecretKeys(RequestCommandSetDeviceSecretKeys requestSetDeviceKeys)
        {
            try
            {
                //Set new Portal password
                if (!await PortalApiHelper.SetDevicePassword(SecretManager.PortalPassword, requestSetDeviceKeys.PortalPassword))
                {
                    return(ResultCommand.CreateFailedCommand($"Error SetDevicePassword: Error while setting new device password."));
                }
                //Update Portal Password
                SecretManager.PortalPassword = requestSetDeviceKeys.PortalPassword;
                PortalApiHelper.Init("Administrator", SecretManager.PortalPassword);

                //Change Encryption Key
                SecretManager.EncryptionKey = requestSetDeviceKeys.EncryptionKey;

                //Set new Access Point - Will change the AP after reboot of the app
                //SecretManager.AccessPointSsid = SecretManager.AccessPointSsid;
                SecretManager.AccessPointPassword = requestSetDeviceKeys.AccessPointPassword;

                return(ResultCommand.CreateSuccessCommand());
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error SetDevicePassword: {e.Message}.");
                return(ResultCommand.CreateFailedCommand($"Error SetDevicePassword: {e.Message}."));
            }
        }
Exemple #4
0
        public async Task <ResultCommand> ProvisionDevice(RequestCommandProvisionDevice requestProvisionDevice, string password)
        {
            try
            {
                DeviceCertificateModel certificateInfo = requestProvisionDevice.DeviceCertificateInformation;

                //Load certificate chain
                var(deviceCertificate, collectionCertificates) =
                    LoadCertificateFromPfx(Convert.FromBase64String(certificateInfo.Certificate), password);

                //Save certificate in store
                if (!await SaveCertificateInStore(deviceCertificate))
                {
                    return(ResultCommand.CreateFailedCommand($"Error while saving User Certificate in Store."));
                }

                using (var securityProvider = new SecurityProviderX509Certificate(deviceCertificate, collectionCertificates))
                {
                    using (var transport = new ProvisioningTransportHandlerHttp())
                    {
                        ProvisioningDeviceClient provClient =
                            ProvisioningDeviceClient.Create(certificateInfo.DpsInstance, certificateInfo.DpsIdScope, securityProvider, transport);
                        DeviceRegistrationResult result = await provClient.RegisterAsync();

                        if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                        {
                            DebugHelper.LogError($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");
                            return(ResultCommand.CreateFailedCommand($"Error during registration: {result.Status}, {result.ErrorMessage}"));
                        }

                        //Test the connection
                        if (!await TestDeviceConnection(result.DeviceId, result.AssignedHub, deviceCertificate))
                        {
                            return(ResultCommand.CreateFailedCommand($"Error while testing the device connection."));
                        }

                        //Persist provision in TPM/HSM
                        SimulatedDevice.ProvisionDevice(result.AssignedHub, result.DeviceId);

                        //Provisioned!
                        SimulatedDevice.IsProvisioned = true;
                    }
                }
                if (deviceCertificate != null)
                {
                    deviceCertificate.Dispose();
                }

                return(ResultCommand.CreateSuccessCommand());
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error ProvisionDevice: {e.Message}.");
                return(ResultCommand.CreateFailedCommand($"Error ProvisionDevice: {e.Message}."));
            }
        }
        public async Task <ResultCommand> SetDeviceType(RequestCommandSetDeviceType requestDeviceType)
        {
            try
            {
                var apps = await LoadFirmwares();

                //Find the app
                var app = apps.FirstOrDefault(p => p.PackageFullName.ToLower().StartsWith(requestDeviceType.DeviceType.ToLower()));
                if (app == null)
                {
                    DebugHelper.LogError($"Package starting with {requestDeviceType.DeviceType} not found.");
                    return(ResultCommand.CreateFailedCommand($"Error SetDeviceType: Package starting with {requestDeviceType.DeviceType} not found."));
                }

                //Deactivate all other firmwares at startup
                foreach (var appToStop in apps)
                {
                    if (appToStop.IsStartup)
                    {
                        if (!await PortalApiHelper.SetStartupForHeadlessApp(false, appToStop.PackageFullName))
                        {
                            DebugHelper.LogError($"Error while turning off run at startup for App {appToStop.PackageFullName}");
                        }
                    }
                    if (!await PortalApiHelper.StopHeadlessApp(appToStop.PackageFullName))
                    {
                        DebugHelper.LogError($"Error while stopping App {appToStop.PackageFullName}");
                    }
                }

                //Start our firmware and set to run
                if (!await PortalApiHelper.StartHeadlessApp(app.PackageFullName))
                {
                    DebugHelper.LogError($"Error while starting App {app.PackageFullName}");
                    return(ResultCommand.CreateFailedCommand($"Error SetDeviceType: Error while starting App {app.PackageFullName}"));
                }

                if (!await PortalApiHelper.SetStartupForHeadlessApp(true, app.PackageFullName))
                {
                    DebugHelper.LogError($"Error while turning on run at startup for App {app.PackageFullName}");
                    return(ResultCommand.CreateFailedCommand($"Error SetDeviceType: Error while turning on run at startup for App {app.PackageFullName}"));
                }

                return(ResultCommand.CreateSuccessCommand());
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error SetDeviceType: {e.Message}.");
                return(ResultCommand.CreateFailedCommand($"Error SetDeviceType: {e.Message}."));
            }
        }
Exemple #6
0
        public async Task <ResultCommandGetDeviceId> GetDeviceId()
        {
            RestRequest request = await PrepareQuery("GetDeviceId", Method.GET);

            var queryResult = await _client.ExecuteTaskAsync <Command>(request);

            if (queryResult.IsSuccessful)
            {
                return(GetResultCommand <ResultCommandGetDeviceId>(queryResult.Data));
            }
            else
            {
                Debug.WriteLine($"GetDeviceId: {queryResult.StatusCode}");
            }
            return(ResultCommand.CreateFailedCommand <ResultCommandGetDeviceId>($"GetDeviceId: {queryResult.StatusCode}"));
        }
Exemple #7
0
 public ResultCommandGetDeviceId GetDeviceId()
 {
     try
     {
         return(new ResultCommandGetDeviceId()
         {
             DeviceId = SimulatedDevice.DeviceId,
             IsSuccess = true
         });
     }
     catch (Exception e)
     {
         DebugHelper.LogError($"Error GetDeviceId: {e.Message}.");
         return(ResultCommand.CreateFailedCommand <ResultCommandGetDeviceId>($"Error GetDeviceId: {e.Message}."));
     }
 }
        public async Task <ResultCommand> StopApp(string appName)
        {
            var apps = await PortalApiHelper.ListFirmwares();

            foreach (var app in apps.AppPackages)
            {
                if (app.PackageFullName.ToLower().StartsWith(appName.ToLower()))
                {
                    if (!await PortalApiHelper.StopHeadlessApp(app.PackageFullName))
                    {
                        return(ResultCommand.CreateFailedCommand($"Error StopApp: Error while stopping App {app.PackageFullName}"));
                    }
                    break;
                }
            }
            return(ResultCommand.CreateSuccessCommand());
        }
Exemple #9
0
        public async Task <ResultCommandNetworkStatus> DisconnectFromClientNetwork(RequestCommandDisconnectFromNetwork requestDisconnectFromNetwork)
        {
            RestRequest request = await PrepareQuery("DisconnectFromNetwork", Method.POST);

            request.AddParameter("application/json", JsonConvert.SerializeObject(requestDisconnectFromNetwork), ParameterType.RequestBody);
            var queryResult = await _client.ExecuteTaskAsync <Command>(request);

            if (queryResult.IsSuccessful)
            {
                return(GetResultCommand <ResultCommandNetworkStatus>(queryResult.Data));
            }
            else
            {
                Debug.WriteLine($"DisconnectFromNetwork: {queryResult.StatusCode}");
            }
            return(ResultCommand.CreateFailedCommand <ResultCommandNetworkStatus>($"DisconnectFromNetwork: {queryResult.StatusCode}"));
        }
Exemple #10
0
        public async Task <ResultCommand> SetDeviceType(RequestCommandSetDeviceType requestSetDeviceType)
        {
            RestRequest request = await PrepareQuery("SetDeviceType", Method.POST);

            request.AddParameter("application/json", JsonConvert.SerializeObject(requestSetDeviceType), ParameterType.RequestBody);
            var queryResult = await _client.ExecuteTaskAsync <Command>(request);

            if (queryResult.IsSuccessful)
            {
                return(GetResultCommand <ResultCommand>(queryResult.Data));
            }
            else
            {
                Debug.WriteLine($"SetDeviceType: {queryResult.StatusCode}");
            }
            return(ResultCommand.CreateFailedCommand <ResultCommand>($"SetDeviceType: {queryResult.StatusCode}"));
        }
        public async Task <ResultCommandListFirmwares> GetFirmwares()
        {
            try
            {
                var allFirmwares = await LoadFirmwares();

                return(new ResultCommandListFirmwares()
                {
                    Firmwares = allFirmwares.Select(p => p.PackageFullName),
                    IsSuccess = true
                });
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error ListFirmwares: {e.Message}.");
                return(ResultCommand.CreateFailedCommand <ResultCommandListFirmwares>($"Error ListFirmwares: {e.Message}."));
            }
        }
        public async Task <ResultCommand> SetDeviceName(RequestCommandSetDeviceName requestDeviceName)
        {
            try
            {
                if (!await PortalApiHelper.SetDeviceName(requestDeviceName.Name))
                {
                    DebugHelper.LogError($"Error while setting device name: {requestDeviceName.Name}");
                    return(ResultCommand.CreateFailedCommand($"Error SetDeviceName: Error while setting device name: {requestDeviceName.Name}"));
                }

                return(ResultCommand.CreateSuccessCommand());
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error SetDeviceName: {e.Message}.");
                return(ResultCommand.CreateFailedCommand($"Error SetDeviceName: {e.Message}."));
            }
        }
        public async Task <ResultCommandIPAdapters> GetNetworkProfiles()
        {
            try
            {
                var profiles = await PortalApiHelper.GetNetworkProfiles();

                return(new ResultCommandIPAdapters()
                {
                    IPAdapters = profiles,
                    IsSuccess = true
                });
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error GetAccessPointSettings: {e.Message}.");
                return(ResultCommand.CreateFailedCommand <ResultCommandIPAdapters>($"Error GetAccessPointSettings: {e.Message}."));
            }
        }
        public async Task <ResultCommandSoftAPSettings> GetAccessPointSettings()
        {
            try
            {
                var apSettings = await PortalApiHelper.GetSoftAPSettings();

                return(new ResultCommandSoftAPSettings()
                {
                    SoftAPSettings = apSettings,
                    IsSuccess = true
                });
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error GetAccessPointSettings: {e.Message}.");
                return(ResultCommand.CreateFailedCommand <ResultCommandSoftAPSettings>($"Error GetAccessPointSettings: {e.Message}."));
            }
        }
Exemple #15
0
        public async Task <ResultCommandNetworkStatus> ConnectToNetworkHandler(RequestCommandConnectToNetwork requestConnectToNetwork)
        {
            try
            {
                NetworkInformation networkInfo = requestConnectToNetwork.NetworkInformation;

                var wifiSet = await FindWifi(networkInfo.Ssid);

                if (wifiSet != null)
                {
                    if (!await PortalApiHelper.DisconnectFromNetwork(wifiSet.Adapter.NetworkAdapter.NetworkAdapterId))
                    {
                        DebugHelper.LogWarning($"Error while trying to disconnect from network: {wifiSet.Adapter.NetworkAdapter.NetworkAdapterId}");
                    }

                    var availableNetworks = await PortalApiHelper.GetAvailableNetworks(wifiSet.Adapter.NetworkAdapter.NetworkAdapterId);

                    foreach (var network in availableNetworks.AvailableNetworks)
                    {
                        if (network.ProfileAvailable && !await PortalApiHelper.DeleteNetworkProfile(wifiSet.Adapter.NetworkAdapter.NetworkAdapterId, network.ProfileName))
                        {
                            DebugHelper.LogWarning($"Error while trying to disconnect from network: {wifiSet.Adapter.NetworkAdapter.NetworkAdapterId}");
                        }
                    }
                    if (!await PortalApiHelper.ConnectToNetwork(wifiSet.Adapter.NetworkAdapter.NetworkAdapterId, networkInfo.Ssid, networkInfo.Password))
                    {
                        return(ResultCommand.CreateFailedCommand <ResultCommandNetworkStatus>($"Error ConnectToNetworkHandler: Could not connect to network '{networkInfo.Ssid}'."));
                    }

                    return(new ResultCommandNetworkStatus()
                    {
                        IsSuccess = true, Status = "Connected"
                    });
                }
                return(ResultCommand.CreateFailedCommand <ResultCommandNetworkStatus>($"Error ConnectToNetworkHandler: UnspecifiedFailure."));
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error ConnectToNetworkHandler: {e.Message}.");
                return(ResultCommand.CreateFailedCommand <ResultCommandNetworkStatus>($"Error ConnectToNetworkHandler: {e.Message}."));
            }
        }
        public async Task <ResultCommandAvailableNetworks> GetAvailableNetworkListHandler()
        {
            try
            {
                var wifiAdapterList = await WiFiAdapter.FindAllAdaptersAsync();

                var wifiList = from adapter in wifiAdapterList
                               from network in adapter.NetworkReport.AvailableNetworks
                               select network.Ssid;
                var networks = wifiList.OrderBy(x => x).Distinct();

                return(new ResultCommandAvailableNetworks()
                {
                    Networks = networks, IsSuccess = true
                });
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error GetAvailableNetworkListHandler: {e.Message}.");
                return(ResultCommand.CreateFailedCommand <ResultCommandAvailableNetworks>($"Error GetAvailableNetworkListHandler: {e.Message}."));
            }
        }
Exemple #17
0
        public async Task <ResultCommandNetworkStatus> DisconnectFromNetworkHandler(RequestCommandDisconnectFromNetwork requestDisconnectFromNetwork)
        {
            try
            {
                var wifiSet = await FindWifi(requestDisconnectFromNetwork.Ssid);

                if (wifiSet != null)
                {
                    DebugHelper.LogInformation($"Disconnecting from network: {wifiSet.Network.Ssid}");
                    wifiSet.Adapter.Disconnect();
                    return(new ResultCommandNetworkStatus()
                    {
                        Status = "Disconnected", IsSuccess = true
                    });
                }
                return(ResultCommand.CreateFailedCommand <ResultCommandNetworkStatus>($"Error DisconnectFromNetworkHandler: UnspecifiedFailure."));
            }
            catch (Exception e)
            {
                DebugHelper.LogError($"Error DisconnectFromNetworkHandler: {e.Message}.");
                return(ResultCommand.CreateFailedCommand <ResultCommandNetworkStatus>($"Error DisconnectFromNetworkHandler: {e.Message}."));
            }
        }
Exemple #18
0
 private ResultCommand ProcessError(Exception e)
 {
     return(ResultCommand.CreateFailedCommand($"Error processing the command: {e.Message}"));
 }