Esempio n. 1
0
        private async void OnAppServiceRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            AppServiceDeferral messageDeferral = args.GetDeferral();
            ValueSet           message         = args.Request.Message;
            string             text            = message["Request"] as string;

            if ("DeviceID" == text)
            {
                ValueSet returnMessage = new ValueSet();

                var    systemId   = SystemIdentification.GetSystemIdForPublisher().Id;
                var    dataReader = Windows.Storage.Streams.DataReader.FromBuffer(systemId);
                byte[] bytes      = new byte[systemId.Length];
                dataReader.ReadBytes(bytes);
                string response = "Publisher System ID (systemId): " + BitConverter.ToString(bytes);

                //Send SystemIdentification back over Appservice
                returnMessage.Add("Response", response);
                await args.Request.SendResponseAsync(returnMessage);

                //Temporary hack - wait for a few seconds for the named pipe to be set up
                await Task.Delay(TimeSpan.FromSeconds(2));

                await Windows.ApplicationModel.FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
            }
            messageDeferral.Complete();
        }
        protected override string GetPlatformDeviceId()
        {
            var systemId   = SystemIdentification.GetSystemIdForPublisher();
            var dataReader = DataReader.FromBuffer(systemId.Id);

            return(dataReader.ReadGuid().ToString());
        }
Esempio n. 3
0
        //--------------------------------------------------------Attributes:-----------------------------------------------------------------\\
        #region --Attributes--


        #endregion
        //--------------------------------------------------------Constructor:----------------------------------------------------------------\\
        #region --Constructors--


        #endregion
        //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\
        #region --Set-, Get- Methods--
        /// <summary>
        /// Returns a hex string representing an unique device ID.
        /// The device ID is a SHA256 hash, hex string of the actual device ID XOR a device nonce to prevent tracking between apps.
        /// </summary>
        public static string GetUniqueDeviceId()
        {
            byte[] deviceId;

            SystemIdentificationInfo systemId = SystemIdentification.GetSystemIdForPublisher();

            if (systemId.Source != SystemIdentificationSource.None)
            {
                deviceId = systemId.Id.ToArray();
            }
            else
            {
                // Fall back to generating a unique ID based on the hardware of the system.
                // This ID will change once the hardware changes.
                // Based on: https://montemagno.com/unique-device-id-for-mobile-apps/
                HardwareToken hwToken = HardwareIdentification.GetPackageSpecificToken(null);
                deviceId = hwToken.Id.ToArray();
            }
            byte[] nonce = GetDeviceNonce();
            // Ensure the device ID is long enough:
            deviceId = deviceId.Length >= 32 ? XorShorten(deviceId, nonce) : nonce;
            SHA256 sha = SHA256.Create();

            deviceId = sha.ComputeHash(deviceId);
            return(ByteArrayToHexString(deviceId));
        }
Esempio n. 4
0
        private static Task InitializeAppTelemetryClientAsync()
        {
            Task initializeClient = new Task(() =>
            {
                TelemetryConfiguration.Active.TelemetryChannel.EndpointAddress = "https://vortex.data.microsoft.com/collect/v1";
                TelemetryConfiguration.Active.InstrumentationKey = "AIF-a6c90b8a-c7f9-4d3f-96f4-d5f9dbd4b4ce";

                _telemetryClient = new TelemetryClient();
                _sessionId       = Guid.NewGuid().ToString().ToUpperInvariant();

                if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.System.Profile.SystemIdentification") &&
                    Windows.Foundation.Metadata.ApiInformation.IsMethodPresent("Windows.System.Profile.SystemIdentification", "GetSystemIdForPublisher"))
                {
                    var systemId = SystemIdentification.GetSystemIdForPublisher();
                    if (systemId != null)
                    {
                        var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(systemId.Id);

                        byte[] bytes = new byte[systemId.Id.Length];
                        dataReader.ReadBytes(bytes);

                        _machineId = BitConverter.ToString(bytes);
                    }
                }

                _isInitialized = true;
            });

            initializeClient.Start();
            return(initializeClient);
        }
Esempio n. 5
0
        private string GetDeviceUID()
        {
            var uid = SystemIdentification.GetSystemIdForPublisher();

            using (DataReader reader = DataReader.FromBuffer(uid.Id))
            {
                byte[] bytes = new byte[uid.Id.Length];
                reader.ReadBytes(bytes);
                return(BitConverter.ToString(bytes).Replace("-", string.Empty));;
            }
        }
        /// <summary>
        /// Gets the device unique ID, or uses the fallback if none is available due to application configuration.
        /// </summary>
        /// <returns>
        /// The discovered device identifier.
        /// </returns>
        public virtual string GetDeviceUniqueId()
        {
            if (this.deviceId != null)
            {
                return(this.deviceId);
            }

            this.deviceId = CryptographicBuffer.EncodeToBase64String(SystemIdentification.GetSystemIdForPublisher().Id);

            return(this.deviceId);
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var id = SystemIdentification.GetSystemIdForPublisher().Id;

            _rpiSensorId = CryptographicBuffer.EncodeToBase64String(id);

            var deviceInfo   = new EasClientDeviceInformation();
            var friendlyName = deviceInfo.FriendlyName;

            // Get the toilet settings for the specific toilet.
            ToiletSettings toiletSettings = GetToiletSettings(_rpiSensorId, friendlyName);

            _toiletId        = toiletSettings.ToiletId;
            _updateFrequency = toiletSettings.UpdateFrequency;
            _fanMode         = toiletSettings.FanMode;
            _fanThreshold    = toiletSettings.FanThreshold;

            _connection = new HubConnectionBuilder()
                          .WithUrl("[REDACTED]")
                          .Build();

            _connection.Closed += async error =>
            {
                await Task.Delay(new Random().Next(0, 5) * 1000);

                await _connection.StartAsync();
            };

            Connect();

            StartUart();

            Task.Run(new Action(SendDataToPubHub));
            Task.Run(new Action(UploadSensorValuesToInfluxDb));
            while (true)
            {
                try
                {
                    // Read the sensors values.
                    ReadDistanceSensors();
                    ProcessDistanceReadings();
                    CheckButtonPressed();
                    ReadGasValue();
                    ControlFan();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("An error occurred while reading the sensors values: " + ex.Message);
                }
            }
        }
Esempio n. 8
0
        //--------------------------------------------------------Attributes:-----------------------------------------------------------------\\
        #region --Attributes--


        #endregion
        //--------------------------------------------------------Constructor:----------------------------------------------------------------\\
        #region --Constructors--


        #endregion
        //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\
        #region --Set-, Get- Methods--
        /// <summary>
        /// Returns a hex string representing an unique device ID.
        /// </summary>
        public static string GetUniqueDeviceId()
        {
            SystemIdentificationInfo systemId = SystemIdentification.GetSystemIdForPublisher();

            if (systemId.Source != SystemIdentificationSource.None)
            {
                return(ByteArrayToHexString(systemId.Id.ToArray()));
            }

            // Fall back to generating a unique ID based on the hardware of the system.
            // This ID will change once the hardware changes.
            // Based on: https://montemagno.com/unique-device-id-for-mobile-apps/
            HardwareToken hwToken = HardwareIdentification.GetPackageSpecificToken(null);

            return(ByteArrayToHexString(hwToken.Id.ToArray()));
        }
Esempio n. 9
0
        public string GetSystemId()
        {
            var systemId = SystemIdentification.GetSystemIdForPublisher();

            // Make sure this device can generate the IDs
            if (systemId.Source != SystemIdentificationSource.None)
            {
                var    dataReader = DataReader.FromBuffer(systemId.Id);
                byte[] bytes      = new byte[systemId.Id.Length];
                dataReader.ReadBytes(bytes);
                // The Id property has a buffer with the unique ID
                return(BitConverter.ToString(bytes));
            }

            //if for some reason the above didnt generate a device id -> use a fallback method.
            return(GetId());
        }
Esempio n. 10
0
        public static string QueryPublisherId()
        {
            string publisherId = null;

            if (ApiInformation.IsTypePresent("Windows.System.Profile.SystemIdentification"))
            {
                var systemId = SystemIdentification.GetSystemIdForPublisher();
                if (systemId.Source != SystemIdentificationSource.None)
                {
                    var idBuffer   = systemId.Id;
                    var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(idBuffer);
                    var bytes      = new byte[idBuffer.Length];
                    dataReader.ReadBytes(bytes);
                    publisherId = Convert.ToBase64String(bytes);
                }
            }
            return(publisherId);
        }
Esempio n. 11
0
        private async void LoadHsmState()
        {
            var id = SystemIdentification.GetSystemIdForPublisher();

            DeviceId.Text = id.Source == SystemIdentificationSource.Tpm ? "TPM" : "Other";

            var userService = DrxServiceProvider.GetServiceProvider().GetService <UserService>();

            if (await userService.IsMachineGenuineDit())
            {
                HsmState.Text         = "Enabled";
                HsmDisableReason.Text = "N/A";
            }
            else
            {
                HsmState.Text         = "Disabled";
                HsmDisableReason.Text = "Non-genuine machine";
            }
        }
Esempio n. 12
0
        private async void ShowProperties()
        {
            var selectedUser = (UserViewModel)UserList.SelectedValue;

            if (selectedUser != null)
            {
                ResultsText.Text    = "";
                ProfileImage.Source = null;
                rootPage.NotifyUser("", NotifyType.StatusMessage);
                try
                {
                    User    user = User.GetFromId(selectedUser.UserId);
                    IBuffer aa   = SystemIdentification.GetSystemIdForUser(user).Id;
                    IBuffer bb   = SystemIdentification.GetSystemIdForUser(null).Id;
                    var     aaS  = SystemIdentification.GetSystemIdForUser(user).Id.ToArray();
                    var     bbS  = SystemIdentification.GetSystemIdForUser(null).Id.ToArray();

                    Debug.WriteLine("!!!" + aa + "~~~~~~~~~" + bb);
                    // Start with some fixed properties.
                    String result = "NonRoamableId: " + user.NonRoamableId + "\n";
                    result += "Type: " + user.Type.ToString() + "\n";
                    result += "AuthenticationStatus: " + user.AuthenticationStatus.ToString() + "\n";

                    // Build a list of all the properties we want.
                    String[] desiredProperties = new String[]
                    {
                        KnownUserProperties.FirstName,
                        KnownUserProperties.LastName,
                        KnownUserProperties.ProviderName,
                        KnownUserProperties.AccountName,
                        KnownUserProperties.GuestHost,
                        KnownUserProperties.PrincipalName,
                        KnownUserProperties.DomainName,
                        KnownUserProperties.SessionInitiationProtocolUri,
                    };
                    // Issue a bulk query for all of the properties.
                    IPropertySet values = await user.GetPropertiesAsync(desiredProperties);

                    // Add those properties to our results.
                    foreach (String property in desiredProperties)
                    {
                        result += property + ": " + values[property] + "\n";
                    }
                    ResultsText.Text = result;

                    // Get the user's picture.
                    IRandomAccessStreamReference streamReference = await user.GetPictureAsync(UserPictureSize.Size64x64);

                    if (streamReference != null)
                    {
                        IRandomAccessStream stream = await streamReference.OpenReadAsync();

                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.SetSource(stream);
                        ProfileImage.Source = bitmapImage;
                    }
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
                }
            }
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            TimeSpan      imageUpdateDue;
            TimeSpan      imageUpdatePeriod;

            this.logging.LogEvent("Application starting");

            // Log the Application build, OS version information etc.
            LoggingFields startupInformation = new LoggingFields();

            startupInformation.AddString("Timezone", TimeZoneSettings.CurrentTimeZoneDisplayName);
            startupInformation.AddString("OSVersion", Environment.OSVersion.VersionString);
            startupInformation.AddString("MachineName", Environment.MachineName);

            // This is from the application manifest
            Package        package   = Package.Current;
            PackageId      packageId = package.Id;
            PackageVersion version   = packageId.Version;

            startupInformation.AddString("ApplicationVersion", string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}"));

            try
            {
                // see if the configuration file is present if not copy minimal sample one from application directory
                if (localFolder.TryGetItemAsync(ConfigurationFilename).AsTask().Result == null)
                {
                    StorageFile templateConfigurationfile = Package.Current.InstalledLocation.GetFileAsync(ConfigurationFilename).AsTask().Result;
                    templateConfigurationfile.CopyAsync(localFolder, ConfigurationFilename).AsTask();
                }

                IConfiguration configuration = new ConfigurationBuilder().AddJsonFile(Path.Combine(localFolder.Path, ConfigurationFilename), false, true).Build();

                this.interruptPinNumber = int.Parse(configuration.GetSection("InterruptPinNumber").Value);
                startupInformation.AddInt32("Interrupt pin", this.interruptPinNumber);

                this.interruptTriggerOn = (GpioPinEdge)Enum.Parse(typeof(GpioPinEdge), configuration.GetSection("interruptTriggerOn").Value);
                startupInformation.AddString("Interrupt Trigger on", this.interruptTriggerOn.ToString());

                this.displayPinNumber = int.Parse(configuration.GetSection("DisplayPinNumber").Value);
                startupInformation.AddInt32("Display pin", this.interruptPinNumber);

                this.azureIoTHubConnectionString = configuration.GetSection("AzureIoTHubConnectionString").Value;
                startupInformation.AddString("AzureIoTHubConnectionString", this.azureIoTHubConnectionString);

                this.transportType = (TransportType)Enum.Parse(typeof(TransportType), configuration.GetSection("TransportType").Value);
                startupInformation.AddString("TransportType", this.transportType.ToString());
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("JSON configuration file load or settings retrieval failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            #region AzureIoT Hub connection string creation
            try
            {
                this.azureIoTHubClient = DeviceClient.CreateFromConnectionString(this.azureIoTHubConnectionString, this.transportType);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("AzureIOT Hub DeviceClient.CreateFromConnectionString failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            #region Report device and application properties to AzureIoT Hub
            try
            {
                TwinCollection reportedProperties = new TwinCollection();

                // This is from the OS
                reportedProperties["Timezone"]    = TimeZoneSettings.CurrentTimeZoneDisplayName;
                reportedProperties["OSVersion"]   = Environment.OSVersion.VersionString;
                reportedProperties["MachineName"] = Environment.MachineName;

                reportedProperties["ApplicationDisplayName"] = package.DisplayName;
                reportedProperties["ApplicationName"]        = packageId.Name;
                reportedProperties["ApplicationVersion"]     = string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");

                // Unique identifier from the hardware
                SystemIdentificationInfo systemIdentificationInfo = SystemIdentification.GetSystemIdForPublisher();
                using (DataReader reader = DataReader.FromBuffer(systemIdentificationInfo.Id))
                {
                    byte[] bytes = new byte[systemIdentificationInfo.Id.Length];
                    reader.ReadBytes(bytes);
                    reportedProperties["SystemId"] = BitConverter.ToString(bytes);
                }

                this.azureIoTHubClient.UpdateReportedPropertiesAsync(reportedProperties).Wait();
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client UpdateReportedPropertiesAsync failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            #region Retrieve device twin settings
            try
            {
                LoggingFields configurationInformation = new LoggingFields();

                Twin deviceTwin = this.azureIoTHubClient.GetTwinAsync().GetAwaiter().GetResult();

                if (!deviceTwin.Properties.Desired.Contains("ImageUpdateDue") || !TimeSpan.TryParse(deviceTwin.Properties.Desired["ImageUpdateDue"].value.ToString(), out imageUpdateDue))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ImageUpdateDue setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddTimeSpan("ImageUpdateDue", imageUpdateDue);

                if (!deviceTwin.Properties.Desired.Contains("ImageUpdatePeriod") || !TimeSpan.TryParse(deviceTwin.Properties.Desired["ImageUpdatePeriod"].value.ToString(), out imageUpdatePeriod))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ImageUpdatePeriod setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddTimeSpan("ImageUpdatePeriod", imageUpdatePeriod);

                if (!deviceTwin.Properties.Desired.Contains("ModelType") || (!Enum.TryParse(deviceTwin.Properties.Desired["ModelType"].value.ToString(), out modelType)))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ModelType setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddString("ModelType", modelType.ToString());

                if (!deviceTwin.Properties.Desired.Contains("ModelPublishedName") || (string.IsNullOrWhiteSpace(deviceTwin.Properties.Desired["ModelPublishedName"].value.ToString())))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ModelPublishedName setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                modelPublishedName = deviceTwin.Properties.Desired["ModelPublishedName"].value.ToString();
                configurationInformation.AddString("ModelPublishedName", modelPublishedName);

                if (!deviceTwin.Properties.Desired.Contains("ProjectID") || (!Guid.TryParse(deviceTwin.Properties.Desired["ProjectID"].value.ToString(), out projectId)))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ProjectId setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddGuid("ProjectID", projectId);

                if (!deviceTwin.Properties.Desired.Contains("ProbabilityThreshold") || (!Double.TryParse(deviceTwin.Properties.Desired["ProbabilityThreshold"].value.ToString(), out probabilityThreshold)))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ProbabilityThreshold setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddDouble("ProbabilityThreshold", probabilityThreshold);

                if (!deviceTwin.Properties.Desired.Contains("AzureCognitiveServicesEndpoint") || (string.IsNullOrWhiteSpace(deviceTwin.Properties.Desired["AzureCognitiveServicesEndpoint"].value.ToString())))
                {
                    this.logging.LogMessage("DeviceTwin.Properties AzureCognitiveServicesEndpoint setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                azureCognitiveServicesEndpoint = deviceTwin.Properties.Desired["AzureCognitiveServicesEndpoint"].value.ToString();
                configurationInformation.AddString("AzureCognitiveServicesEndpoint", modelPublishedName);

                if (!deviceTwin.Properties.Desired.Contains("AzureCognitiveServicesSubscriptionKey") || (string.IsNullOrWhiteSpace(deviceTwin.Properties.Desired["AzureCognitiveServicesSubscriptionKey"].value.ToString())))
                {
                    this.logging.LogMessage("DeviceTwin.Properties AzureCognitiveServicesSubscriptionKey setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                azureCognitiveServicesSubscriptionKey = deviceTwin.Properties.Desired["AzureCognitiveServicesSubscriptionKey"].value.ToString();
                configurationInformation.AddString("AzureCognitiveServicesSubscriptionKey", azureCognitiveServicesSubscriptionKey);

                if (!deviceTwin.Properties.Desired.Contains("DebounceTimeout") || !TimeSpan.TryParse(deviceTwin.Properties.Desired["DebounceTimeout"].value.ToString(), out debounceTimeout))
                {
                    this.logging.LogMessage("DeviceTwin.Properties DebounceTimeout setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddTimeSpan("DebounceTimeout", debounceTimeout);

                this.logging.LogEvent("Configuration settings", configurationInformation);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client GetTwinAsync failed or property missing/invalid" + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            try
            {
                this.customVisionClient = new CustomVisionPredictionClient(new System.Net.Http.DelegatingHandler[] { })
                {
                    ApiKey   = this.azureCognitiveServicesSubscriptionKey,
                    Endpoint = this.azureCognitiveServicesEndpoint,
                };
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure Cognitive Services Custom Vision Client configuration failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            try
            {
                this.mediaCapture = new MediaCapture();
                this.mediaCapture.InitializeAsync().AsTask().Wait();
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Camera configuration failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            this.displayOffTimer = new Timer(this.TimerCallback, null, Timeout.Infinite, Timeout.Infinite);

            #region Wire up interupt handler for image capture request
            if (this.interruptPinNumber != 0)
            {
                try
                {
                    GpioController gpioController = GpioController.GetDefault();
                    this.interruptGpioPin = gpioController.OpenPin(this.interruptPinNumber);
                    this.interruptGpioPin.SetDriveMode(GpioPinDriveMode.InputPullUp);
                    this.interruptGpioPin.ValueChanged += this.InterruptGpioPin_ValueChanged;

                    this.displayGpioPin = gpioController.OpenPin(this.displayPinNumber);
                    this.displayGpioPin.SetDriveMode(GpioPinDriveMode.Output);
                    this.displayGpioPin.Write(GpioPinValue.Low);
                }
                catch (Exception ex)
                {
                    this.logging.LogMessage("Digital input configuration failed " + ex.Message, LoggingLevel.Error);
                    return;
                }
            }
            #endregion

            #region Wire up command handler for image capture request
            try
            {
                this.azureIoTHubClient.SetMethodHandlerAsync("ImageCapture", this.ImageUpdateHandler, null);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client ImageCapture SetMethodHandlerAsync failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            #region Wire up command handler for device reboot request
            try
            {
                this.azureIoTHubClient.SetMethodHandlerAsync("DeviceReboot", this.DeviceRebootAsync, null);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client DeviceReboot SetMethodHandlerAsync failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            if ((imageUpdateDue != TimeSpan.MinValue) || (imageUpdatePeriod != TimeSpan.MinValue))
            {
                this.imageUpdatetimer = new Timer(this.ImageUpdateTimerCallback, null, imageUpdateDue, imageUpdatePeriod);
            }

            this.logging.LogEvent("Application started", startupInformation);

            // enable task to continue running in background
            this.backgroundTaskDeferral = taskInstance.GetDeferral();
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            DeviceRegistrationResult result;

            try
            {
                bme280Sensor = new BME280(0x76);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"BME280 Initialisation failed:{ex.Message}");

                return;
            }

            try
            {
                using (var security = new SecurityProviderTpmHsm(RegistrationId))
                    using (var transport = new ProvisioningTransportHandlerHttp())
                    {
                        string base64EK = Convert.ToBase64String(security.GetEndorsementKey());

                        ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, IdScope, security, transport);

                        result = provClient.RegisterAsync().ConfigureAwait(false).GetAwaiter().GetResult();

                        IAuthenticationMethod auth = new DeviceAuthenticationWithTpm(result.DeviceId, security);

                        azureIoTHubClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Mqtt);
                    }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"DeviceClient.Create with TPM info failed:{ex.Message}");
                return;
            }

            try
            {
                azureIoTHubClient.SetMethodHandlerAsync("Restart", RestartAsync, null);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device method handler configuration failed:{ex.Message}");
                return;
            }

            try
            {
                TwinCollection reportedProperties;
                reportedProperties = new TwinCollection();

                // This is from the OS
                reportedProperties["Timezone"]    = TimeZoneSettings.CurrentTimeZoneDisplayName;
                reportedProperties["OSVersion"]   = Environment.OSVersion.VersionString;
                reportedProperties["MachineName"] = Environment.MachineName;

                // This is from the application manifest
                Package        package   = Package.Current;
                PackageId      packageId = package.Id;
                PackageVersion version   = packageId.Version;
                reportedProperties["ApplicationDisplayName"] = package.DisplayName;
                reportedProperties["ApplicationName"]        = packageId.Name;
                reportedProperties["ApplicationVersion"]     = string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");

                // Unique identifier from the hardware
                SystemIdentificationInfo systemIdentificationInfo = SystemIdentification.GetSystemIdForPublisher();
                using (DataReader reader = DataReader.FromBuffer(systemIdentificationInfo.Id))
                {
                    byte[] bytes = new byte[systemIdentificationInfo.Id.Length];
                    reader.ReadBytes(bytes);
                    reportedProperties["SystemId"] = BitConverter.ToString(bytes);
                }

                azureIoTHubClient.UpdateReportedPropertiesAsync(reportedProperties).Wait();
            }
            catch (Exception ex)
            {
                Debug.Print($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                deviceTwin = azureIoTHubClient.GetTwinAsync().Result;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                if (deviceTwin.Properties.Desired.Contains("TimerDue"))
                {
                    timerDue = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerDue"].ToString());
                }

                if (deviceTwin.Properties.Desired.Contains("TimerPeriod"))
                {
                    timerPeriod = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerPeriod"].ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Sensor due or period configuration retrieval failed using default:{ex.Message}");
                return;
            }

            bme280InputPollingTimer = new Timer(SensorUpdateTimerCallback, null, timerDue, timerPeriod);

            //enable task to continue running in background
            backgroundTaskDeferral = taskInstance.GetDeferral();
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            TimeSpan      imageUpdateDue;
            TimeSpan      imageUpdatePeriod;

            // Log the Application build, OS version information etc.
            LoggingFields startupInformation = new LoggingFields();

            startupInformation.AddString("Timezone", TimeZoneSettings.CurrentTimeZoneDisplayName);
            startupInformation.AddString("OSVersion", Environment.OSVersion.VersionString);
            startupInformation.AddString("MachineName", Environment.MachineName);

            // This is from the application manifest
            Package        package   = Package.Current;
            PackageId      packageId = package.Id;
            PackageVersion version   = packageId.Version;

            startupInformation.AddString("ApplicationVersion", string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}"));

            this.logging.LogEvent("Application startup", startupInformation);

            #region Configuration file settings load and creation if not present
            try
            {
                // see if the configuration file is present if not copy minimal sample one from application directory
                if (localFolder.TryGetItemAsync(ConfigurationFilename).AsTask().Result == null)
                {
                    StorageFile templateConfigurationfile = Package.Current.InstalledLocation.GetFileAsync(ConfigurationFilename).AsTask().Result;
                    templateConfigurationfile.CopyAsync(localFolder, ConfigurationFilename).AsTask();

                    this.logging.LogMessage("JSON configuration file missing, templated created", LoggingLevel.Warning);
                    return;
                }

                LoggingFields  connnectionInformation = new LoggingFields();
                IConfiguration configuration          = new ConfigurationBuilder().AddJsonFile(Path.Combine(localFolder.Path, ConfigurationFilename), false, true).Build();

                this.azureIoTHubConnectionString = configuration.GetSection("AzureIoTHubConnectionString").Value;
                connnectionInformation.AddString("AzureIoTHubConnectionString", this.azureIoTHubConnectionString);

                this.transportType = (TransportType)Enum.Parse(typeof(TransportType), configuration.GetSection("TransportType").Value);
                connnectionInformation.AddString("TransportType", this.transportType.ToString());

                this.logging.LogEvent("Connection settings", connnectionInformation);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("JSON configuration file load or AzureIoT Hub connection settings missing/invalid" + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            #region AzureIoT Hub connection string creation
            try
            {
                this.azureIoTHubClient = DeviceClient.CreateFromConnectionString(this.azureIoTHubConnectionString, this.transportType);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("AzureIOT Hub DeviceClient.CreateFromConnectionString failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            #region Report device and application properties to AzureIoT Hub
            try
            {
                TwinCollection reportedProperties = new TwinCollection();

                // This is from the OS
                reportedProperties["Timezone"]    = TimeZoneSettings.CurrentTimeZoneDisplayName;
                reportedProperties["OSVersion"]   = Environment.OSVersion.VersionString;
                reportedProperties["MachineName"] = Environment.MachineName;

                reportedProperties["ApplicationDisplayName"] = package.DisplayName;
                reportedProperties["ApplicationName"]        = packageId.Name;
                reportedProperties["ApplicationVersion"]     = string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");

                // Unique identifier from the hardware
                SystemIdentificationInfo systemIdentificationInfo = SystemIdentification.GetSystemIdForPublisher();
                using (DataReader reader = DataReader.FromBuffer(systemIdentificationInfo.Id))
                {
                    byte[] bytes = new byte[systemIdentificationInfo.Id.Length];
                    reader.ReadBytes(bytes);
                    reportedProperties["SystemId"] = BitConverter.ToString(bytes);
                }

                this.azureIoTHubClient.UpdateReportedPropertiesAsync(reportedProperties).Wait();
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client UpdateReportedPropertiesAsync failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            #region Retrieve device twin settings
            try
            {
                LoggingFields configurationInformation = new LoggingFields();

                Twin deviceTwin = this.azureIoTHubClient.GetTwinAsync().GetAwaiter().GetResult();

                if (!deviceTwin.Properties.Desired.Contains("AzureImageFilenameLatestFormat"))
                {
                    this.logging.LogMessage("DeviceTwin.Properties AzureImageFilenameLatestFormat setting missing", LoggingLevel.Warning);
                    return;
                }
                this.azureStorageimageFilenameLatestFormat = deviceTwin.Properties.Desired["AzureImageFilenameLatestFormat"].Value;
                configurationInformation.AddString("AzureImageFilenameLatestFormat", this.azureStorageimageFilenameLatestFormat);

                if (!deviceTwin.Properties.Desired.Contains("AzureImageFilenameHistoryFormat"))
                {
                    this.logging.LogMessage("DeviceTwin.Properties AzureImageFilenameHistoryFormat setting missing", LoggingLevel.Warning);
                    return;
                }
                this.azureStorageImageFilenameHistoryFormat = deviceTwin.Properties.Desired["AzureImageFilenameHistoryFormat"].Value;
                configurationInformation.AddString("AzureImageFilenameHistoryFormat", this.azureStorageImageFilenameHistoryFormat);

                if (!deviceTwin.Properties.Desired.Contains("ImageUpdateDue") || !TimeSpan.TryParse(deviceTwin.Properties.Desired["ImageUpdateDue"].Value.ToString(), out imageUpdateDue))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ImageUpdateDue setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddTimeSpan("ImageUpdateDue", imageUpdateDue);

                if (!deviceTwin.Properties.Desired.Contains("ImageUpdatePeriod") || !TimeSpan.TryParse(deviceTwin.Properties.Desired["ImageUpdatePeriod"].Value.ToString(), out imageUpdatePeriod))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ImageUpdatePeriod setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddTimeSpan("ImageUpdatePeriod", imageUpdatePeriod);

                this.logging.LogEvent("Configuration settings", configurationInformation);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client GetTwinAsync failed or property missing/invalid" + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            #region Initialise the camera hardware
            try
            {
                this.mediaCapture = new MediaCapture();
                this.mediaCapture.InitializeAsync().AsTask().Wait();
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("mediaCapture.InitializeAsync failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            #region Wire up command handler for image capture request
            try
            {
                this.azureIoTHubClient.SetMethodHandlerAsync("ImageCapture", this.ImageUpdateHandler, null);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client ImageCapture SetMethodHandlerAsync failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            #region Wire up command handler for device reboot request
            try
            {
                this.azureIoTHubClient.SetMethodHandlerAsync("DeviceReboot", this.DeviceRebootAsync, null);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client DeviceReboot SetMethodHandlerAsync failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            this.imageUpdatetimer = new Timer(this.ImageUpdateTimerCallback, null, imageUpdateDue, imageUpdatePeriod);

            this.logging.LogEvent("Application startup completed");

            // enable task to continue running in background
            this.backgroundTaskDeferral = taskInstance.GetDeferral();
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                bme280Sensor = new BME280(0x76);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"BME280 Initialisation failed:{ex.Message}");

                return;
            }

            try
            {
                azureIoTHubClient = DeviceClient.CreateFromConnectionString(AzureIoTHubConnectionString, TransportType.Mqtt);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"CreateFromConnectionString failed:{ex.Message}");
                return;
            }

            try
            {
                azureIoTHubClient.SetMethodHandlerAsync("RestartDevice", RestartAsync, null);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device Restart method handler configuration failed:{ex.Message}");
                return;
            }

            try
            {
                TwinCollection reportedProperties;
                reportedProperties = new TwinCollection();

                // This is from the OS
                reportedProperties["Timezone"]    = TimeZoneSettings.CurrentTimeZoneDisplayName;
                reportedProperties["OSVersion"]   = Environment.OSVersion.VersionString;
                reportedProperties["MachineName"] = Environment.MachineName;

                // This is from the application manifest
                Package        package   = Package.Current;
                PackageId      packageId = package.Id;
                PackageVersion version   = packageId.Version;
                reportedProperties["ApplicationDisplayName"] = package.DisplayName;
                reportedProperties["ApplicationName"]        = packageId.Name;
                reportedProperties["ApplicationVersion"]     = string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");

                // Unique identifier from the hardware
                SystemIdentificationInfo systemIdentificationInfo = SystemIdentification.GetSystemIdForPublisher();
                using (DataReader reader = DataReader.FromBuffer(systemIdentificationInfo.Id))
                {
                    byte[] bytes = new byte[systemIdentificationInfo.Id.Length];
                    reader.ReadBytes(bytes);
                    reportedProperties["SystemId"] = BitConverter.ToString(bytes);
                }

                azureIoTHubClient.UpdateReportedPropertiesAsync(reportedProperties).Wait();
            }
            catch (Exception ex)
            {
                Debug.Print($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                deviceTwin = azureIoTHubClient.GetTwinAsync().Result;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                if (deviceTwin.Properties.Desired.Contains("TimerDue"))
                {
                    timerDue = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerDue"].ToString());
                }

                if (deviceTwin.Properties.Desired.Contains("TimerPeriod"))
                {
                    timerPeriod = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerPeriod"].ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Sensor due or period configuration retrieval failed using default:{ex.Message}");
                return;
            }

            bme280InputPollingTimer = new Timer(SensorUpdateTimerCallback, null, timerDue, timerPeriod);

            backgroundTaskDeferral = taskInstance.GetDeferral();
        }
Esempio n. 17
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;

            try
            {
                // see if the configuration file is present if not copy minimal sample one from application directory
                if (localFolder.TryGetItemAsync(ConfigurationFilename).AsTask().Result == null)
                {
                    StorageFile templateConfigurationfile = Package.Current.InstalledLocation.GetFileAsync(ConfigurationFilename).AsTask().Result;
                    templateConfigurationfile.CopyAsync(localFolder, ConfigurationFilename).AsTask();
                }

                // Load the settings from configuration file exit application if missing or invalid
                StorageFile file = localFolder.GetFileAsync(ConfigurationFilename).AsTask().Result;

                applicationSettings = (JsonConvert.DeserializeObject <ApplicationSettings>(FileIO.ReadTextAsync(file).AsTask().Result));
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("JSON configuration file load failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            // Log the Application build, shield information etc.
            LoggingFields applicationBuildInformation = new LoggingFields();

#if DRAGINO
            applicationBuildInformation.AddString("Shield", "DraginoLoRaGPSHat");
#endif
#if ELECROW
            applicationBuildInformation.AddString("Shield", "ElecrowRFM95IoTBoard");
#endif
#if M2M
            applicationBuildInformation.AddString("Shield", "M2M1ChannelLoRaWanGatewayShield");
#endif
#if ELECTRONIC_TRICKS
            applicationBuildInformation.AddString("Shield", "ElectronicTricksLoRaLoRaWANShield");
#endif
#if UPUTRONICS_RPIZERO_CS0
            applicationBuildInformation.AddString("Shield", "UputronicsPiZeroLoRaExpansionBoardCS0");
#endif
#if UPUTRONICS_RPIZERO_CS1
            applicationBuildInformation.AddString("Shield", "UputronicsPiZeroLoRaExpansionBoardCS1");
#endif
#if UPUTRONICS_RPIPLUS_CS0
            applicationBuildInformation.AddString("Shield", "UputronicsPiPlusLoRaExpansionBoardCS0");
#endif
#if UPUTRONICS_RPIPLUS_CS1
            applicationBuildInformation.AddString("Shield", "UputronicsPiPlusLoRaExpansionBoardCS1");
#endif
#if ADAFRUIT_RADIO_BONNET
            applicationBuildInformation.AddString("Shield", "AdafruitRadioBonnet");
#endif
#if CLOUD_DEVICE_BOND
            applicationBuildInformation.AddString("Bond", "Supported");
#else
            applicationBuildInformation.AddString("Bond", "NotSupported");
#endif
#if CLOUD_DEVICE_PUSH
            applicationBuildInformation.AddString("Push", "Supported");
#else
            applicationBuildInformation.AddString("Push", "NotSupported");
#endif
#if CLOUD_DEVICE_SEND
            applicationBuildInformation.AddString("Send", "Supported");
#else
            applicationBuildInformation.AddString("Send", "NotSupported");
#endif
#if PAYLOAD_TEXT
            applicationBuildInformation.AddString("PayloadProcessor", "Text");
#endif
#if PAYLOAD_TEXT_COMA_SEPARATED_VALUES
            applicationBuildInformation.AddString("PayloadProcessor", "ComaSeperatedValues");
#endif
#if PAYLOAD_BINARY_BINARY_CODED_DECIMAL
            applicationBuildInformation.AddString("PayloadProcessor", "BinaryCodedDecimal");
#endif
#if PAYLOAD_BINARY_CAYENNE_LOW_POWER_PAYLOAD
            applicationBuildInformation.AddString("PayloadProcessor", "CayenneLowPowerPayload");
#endif

            applicationBuildInformation.AddString("Timezone", TimeZoneSettings.CurrentTimeZoneDisplayName);
            applicationBuildInformation.AddString("OSVersion", Environment.OSVersion.VersionString);
            applicationBuildInformation.AddString("MachineName", Environment.MachineName);

            // This is from the application manifest
            Package        package   = Package.Current;
            PackageId      packageId = package.Id;
            PackageVersion version   = packageId.Version;

            applicationBuildInformation.AddString("ApplicationVersion", string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}"));
            this.logging.LogEvent("Application starting", applicationBuildInformation, LoggingLevel.Information);

            try
            {
#if DRAGINO
                rfm9XDevice = new Rfm9XDevice(ChipSelectPin.CS0, ChipSelectLine, ResetLine, InterruptLine);
#endif
#if M2M
                rfm9XDevice = new Rfm9XDevice(ChipSelectPin.CS0, ChipSelectLine, ResetLine, InterruptLine);
#endif
#if ELECROW
                rfm9XDevice = new Rfm9XDevice(ChipSelectPin.CS1, ResetLine, InterruptLine);
#endif
#if ELECTRONIC_TRICKS
                rfm9XDevice = new Rfm9XDevice(ChipSelectPin.CS0, ResetLine, InterruptLine);
#endif
#if UPUTRONICS_RPIZERO_CS0
                rfm9XDevice = new Rfm9XDevice(ChipSelectPin.CS0, InterruptLine);
#endif
#if UPUTRONICS_RPIZERO_CS1
                rfm9XDevice = new Rfm9XDevice(ChipSelectPin.CS1, InterruptLine);
#endif
#if UPUTRONICS_RPIPLUS_CS0
                rfm9XDevice = new Rfm9XDevice(ChipSelectPin.CS0, InterruptLine);
#endif
#if UPUTRONICS_RPIPLUS_CS1
                rfm9XDevice = new Rfm9XDevice(ChipSelectPin.CS1, InterruptLine);
#endif
#if ADAFRUIT_RADIO_BONNET
                rfm9XDevice = new Rfm9XDevice(ChipSelectPin.CS1, ResetLine, InterruptLine);
#endif
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Hardware initialisation failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            // Log the Azure connection string and associated settings
            LoggingFields azureIoTHubSettings = new LoggingFields();
            azureIoTHubSettings.AddString("DeviceConnectionString", this.applicationSettings.AzureIoTHubDeviceConnectionString);
            azureIoTHubSettings.AddString("TransportType", this.applicationSettings.AzureIoTHubTransportType.ToString());
            azureIoTHubSettings.AddString("SensorIDIsDeviceIDSensorID", this.applicationSettings.SensorIDIsDeviceIDSensorID.ToString());
            this.logging.LogEvent("AzureIoTHub configuration", azureIoTHubSettings, LoggingLevel.Information);

            // Connect the IoT hub first so we are ready for any messages
            try
            {
                this.azureIoTHubClient = DeviceClient.CreateFromConnectionString(this.applicationSettings.AzureIoTHubDeviceConnectionString, this.applicationSettings.AzureIoTHubTransportType);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("IoT Hub connection failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            try
            {
                TwinCollection reportedProperties;
                reportedProperties = new TwinCollection();

                // This is from the OS
                reportedProperties["Timezone"]    = TimeZoneSettings.CurrentTimeZoneDisplayName;
                reportedProperties["OSVersion"]   = Environment.OSVersion.VersionString;
                reportedProperties["MachineName"] = Environment.MachineName;

                reportedProperties["ApplicationDisplayName"] = package.DisplayName;
                reportedProperties["ApplicationName"]        = packageId.Name;
                reportedProperties["ApplicationVersion"]     = string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");

                // Unique identifier from the hardware
                SystemIdentificationInfo systemIdentificationInfo = SystemIdentification.GetSystemIdForPublisher();
                using (DataReader reader = DataReader.FromBuffer(systemIdentificationInfo.Id))
                {
                    byte[] bytes = new byte[systemIdentificationInfo.Id.Length];
                    reader.ReadBytes(bytes);
                    reportedProperties["SystemId"] = BitConverter.ToString(bytes);
                }

                azureIoTHubClient.UpdateReportedPropertiesAsync(reportedProperties).Wait();
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("IoT Hub updating reported properties failed " + ex.Message, LoggingLevel.Error);
            }

            // Wire up the field gateway restart method handler
            try
            {
                azureIoTHubClient.SetMethodHandlerAsync("Restart", RestartAsync, null);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub Restart method handler setup failed " + ex.Message, LoggingLevel.Error);
                return;
            }

#if CLOUD_DEVICE_BOND
            // Wire up the bond device method handler
            try
            {
                azureIoTHubClient.SetMethodHandlerAsync("DeviceBond", this.DeviceBondAsync, null);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub Device Bond method handler setup failed " + ex.Message, LoggingLevel.Error);
                return;
            }
#endif

#if CLOUD_DEVICE_PUSH
            // Wire up the push message to device method handler
            try
            {
                this.azureIoTHubClient.SetMethodHandlerAsync("DevicePush", this.DevicePushAsync, null);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub DevicePush method handler setup failed " + ex.Message, LoggingLevel.Error);
                return;
            }
#endif

#if CLOUD_DEVICE_SEND
            // Wire up the send message to device method handler
            try
            {
                this.azureIoTHubClient.SetMethodHandlerAsync("DeviceSend", this.DeviceSendAsync, null);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client DeviceSend method handler setup failed " + ex.Message, LoggingLevel.Error);
                return;
            }
#endif

            // Configure the LoRa module
            rfm9XDevice.OnReceive  += Rfm9XDevice_OnReceive;
            rfm9XDevice.OnTransmit += Rfm9XDevice_OnTransmit;

            rfm9XDevice.Initialise(this.applicationSettings.Frequency,
                                   rxDoneignoreIfCrcMissing: true,
                                   rxDoneignoreIfCrcInvalid: true,
                                   paBoost: this.applicationSettings.PABoost, maxPower: this.applicationSettings.MaxPower, outputPower: this.applicationSettings.OutputPower,
                                   ocpOn: this.applicationSettings.OCPOn, ocpTrim: this.applicationSettings.OCPTrim,
                                   lnaGain: this.applicationSettings.LnaGain, lnaBoost: this.applicationSettings.LNABoost,
                                   bandwidth: this.applicationSettings.Bandwidth, codingRate: this.applicationSettings.CodingRate, implicitHeaderModeOn: this.applicationSettings.ImplicitHeaderModeOn,
                                   spreadingFactor: this.applicationSettings.SpreadingFactor,
                                   rxPayloadCrcOn: true,
                                   symbolTimeout: this.applicationSettings.SymbolTimeout,
                                   preambleLength: this.applicationSettings.PreambleLength,
                                   payloadLength: this.applicationSettings.PayloadLength,
                                   payloadMaxLength: this.applicationSettings.PayloadMaxLength,
                                   freqHoppingPeriod: this.applicationSettings.FreqHoppingPeriod,
                                   lowDataRateOptimize: this.applicationSettings.LowDataRateOptimize,
                                   ppmCorrection: this.applicationSettings.PpmCorrection,
                                   detectionOptimize: this.applicationSettings.DetectionOptimize,
                                   invertIQ: this.applicationSettings.InvertIQ,
                                   detectionThreshold: this.applicationSettings.DetectionThreshold,
                                   syncWord: this.applicationSettings.SyncWord
                                   );

#if DEBUG
            rfm9XDevice.RegisterDump();
#endif

            rfm9XDevice.Receive(Encoding.UTF8.GetBytes(this.applicationSettings.Address));

            LoggingFields loRaSettings = new LoggingFields();
            loRaSettings.AddString("Address", this.applicationSettings.Address);
            loRaSettings.AddDouble("Frequency", this.applicationSettings.Frequency);
            loRaSettings.AddBoolean("PABoost", this.applicationSettings.PABoost);

            loRaSettings.AddUInt8("MaxPower", this.applicationSettings.MaxPower);
            loRaSettings.AddUInt8("OutputPower", this.applicationSettings.OutputPower);
            loRaSettings.AddBoolean("OCPOn", this.applicationSettings.OCPOn);
            loRaSettings.AddUInt8("OCPTrim", this.applicationSettings.OCPTrim);

            loRaSettings.AddString("LnaGain", this.applicationSettings.LnaGain.ToString());
            loRaSettings.AddBoolean("lnaBoost", this.applicationSettings.LNABoost);

            loRaSettings.AddString("codingRate", this.applicationSettings.CodingRate.ToString());
            loRaSettings.AddString("implicitHeaderModeOn", applicationSettings.ImplicitHeaderModeOn.ToString());
            loRaSettings.AddString("spreadingFactor", this.applicationSettings.SpreadingFactor.ToString());
            loRaSettings.AddBoolean("rxPayloadCrcOn", true);

            loRaSettings.AddUInt8("symbolTimeout", this.applicationSettings.SymbolTimeout);
            loRaSettings.AddUInt8("preambleLength", this.applicationSettings.PreambleLength);
            loRaSettings.AddUInt8("payloadLength", this.applicationSettings.PayloadLength);

            loRaSettings.AddUInt8("payloadMaxLength", this.applicationSettings.PayloadMaxLength);
            loRaSettings.AddUInt8("freqHoppingPeriod", this.applicationSettings.FreqHoppingPeriod);
            loRaSettings.AddBoolean("lowDataRateOptimize", this.applicationSettings.LowDataRateOptimize);
            loRaSettings.AddUInt8("ppmCorrection", this.applicationSettings.PpmCorrection);

            loRaSettings.AddString("detectionOptimize", this.applicationSettings.DetectionOptimize.ToString());
            loRaSettings.AddBoolean("invertIQ", this.applicationSettings.InvertIQ);
            loRaSettings.AddString("detectionThreshold", this.applicationSettings.DetectionThreshold.ToString());
            loRaSettings.AddUInt8("SyncWord", this.applicationSettings.SyncWord);

            this.logging.LogEvent("LoRa configuration", loRaSettings, LoggingLevel.Information);

            this.deferral = taskInstance.GetDeferral();
        }
Esempio n. 18
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                bme280Sensor = new BME280(0x76);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"BME280 Initialisation failed:{ex.Message}");

                return;
            }

            try
            {
                TpmDevice myDevice = new TpmDevice(0);                 // Use logical device 0 on the TPM

                azureIoTHubUri      = myDevice.GetHostName();
                deviceId            = myDevice.GetDeviceId();
                sasToken            = myDevice.GetSASToken((uint)sasTokenValidityPeriod.TotalSeconds);
                sasTokenIssuedAtUtc = DateTime.UtcNow;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"TpmDevice.GetSASToken failed:{ex.Message}");
                return;
            }

            try
            {
                azureIoTHubClient = DeviceClient.Create(azureIoTHubUri, AuthenticationMethodFactory.CreateAuthenticationWithToken(deviceId, sasToken), TransportType.Mqtt);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"DeviceClient.Create with TPM info failed:{ex.Message}");
                return;
            }

            try
            {
                azureIoTHubClient.SetMethodHandlerAsync("Restart", RestartAsync, null);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device method handler configuration failed:{ex.Message}");
                return;
            }

            try
            {
                TwinCollection reportedProperties;
                reportedProperties = new TwinCollection();

                // This is from the OS
                reportedProperties["Timezone"]    = TimeZoneSettings.CurrentTimeZoneDisplayName;
                reportedProperties["OSVersion"]   = Environment.OSVersion.VersionString;
                reportedProperties["MachineName"] = Environment.MachineName;

                // This is from the application manifest
                Package        package   = Package.Current;
                PackageId      packageId = package.Id;
                PackageVersion version   = packageId.Version;
                reportedProperties["ApplicationDisplayName"] = package.DisplayName;
                reportedProperties["ApplicationName"]        = packageId.Name;
                reportedProperties["ApplicationVersion"]     = string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");

                // Unique identifier from the hardware
                SystemIdentificationInfo systemIdentificationInfo = SystemIdentification.GetSystemIdForPublisher();
                using (DataReader reader = DataReader.FromBuffer(systemIdentificationInfo.Id))
                {
                    byte[] bytes = new byte[systemIdentificationInfo.Id.Length];
                    reader.ReadBytes(bytes);
                    reportedProperties["SystemId"] = BitConverter.ToString(bytes);
                }

                azureIoTHubClient.UpdateReportedPropertiesAsync(reportedProperties).Wait();
            }
            catch (Exception ex)
            {
                Debug.Print($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                deviceTwin = azureIoTHubClient.GetTwinAsync().Result;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                if (deviceTwin.Properties.Desired.Contains("TimerDue"))
                {
                    timerDue = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerDue"].ToString());
                }

                if (deviceTwin.Properties.Desired.Contains("TimerPeriod"))
                {
                    timerPeriod = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerPeriod"].ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Sensor due or period configuration retrieval failed using default:{ex.Message}");
                return;
            }

            bme280InputPollingTimer = new Timer(SensorUpdateTimerCallback, null, timerDue, timerPeriod);

            // enable task to continue running in background
            backgroundTaskDeferral = taskInstance.GetDeferral();
        }
Esempio n. 19
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var                deviceId           = "";
            var                deviceSettings     = default(AutodiscoverResult);
            CameraStatus       cameraStatus       = CameraStatus.NotInstalled;
            GroveBaseHatStatus groveBaseHatStatus = GroveBaseHatStatus.NotInstalled;

            #region Set up device autodiscovery
            //keep autodiscovering until we get a connection string
            while (string.IsNullOrEmpty(deviceSettings?.ConnectionString) == true)
            {
                try
                {
                    deviceId       = DeviceIdService.GetDeviceId();
                    deviceSettings = AutodiscoverService.GetDeviceSettings(deviceId);

                    LoggingService.Log($"Device settings retrieved for DeviceId:{deviceId}");
                }
                catch (Exception ex)
                {
                    LoggingService.Error($"Autodiscovery failed", ex);
                    Thread.Sleep(30000);
                }
            }
            #endregion

            #region Set up IoT Hub Connection
            try
            {
                azureIoTHubClient = DeviceClient.CreateFromConnectionString(deviceSettings.ConnectionString, TransportType.Mqtt);
            }
            catch (Exception ex)
            {
                LoggingService.Error($"Azure IoT Hub connection failed", ex);
                //TODO: set up a way for this to retry instead of fail?
                return;
            }
            #endregion

            #region Report device startup
            SendPayloadToIoTHub(new DeviceEvent()
            {
                ApplicationStarted = true
            });
            #endregion

            #region Retrieve device twin
            try
            {
                deviceTwin = azureIoTHubClient.GetTwinAsync().Result;
            }
            catch (Exception ex)
            {
                LoggingService.Error($"Azure IoT Hub device twin configuration retrieval failed", ex);
                //TODO: set up a way for this to retry instead of fail?
                return;
            }
            #endregion

            #region Report device properties
            try
            {
                TwinCollection reportedProperties;
                reportedProperties = new TwinCollection();

                // This is from the OS
                reportedProperties["Timezone"]    = TimeZoneSettings.CurrentTimeZoneDisplayName;
                reportedProperties["OSVersion"]   = Environment.OSVersion.VersionString;
                reportedProperties["MachineName"] = Environment.MachineName;

                // This is from the application manifest
                Package        package   = Package.Current;
                PackageId      packageId = package.Id;
                PackageVersion version   = packageId.Version;
                reportedProperties["ApplicationDisplayName"] = package.DisplayName;
                reportedProperties["ApplicationName"]        = packageId.Name;
                reportedProperties["ApplicationVersion"]     = string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");

                // Unique identifier from the hardware
                SystemIdentificationInfo systemIdentificationInfo = SystemIdentification.GetSystemIdForPublisher();
                using (DataReader reader = DataReader.FromBuffer(systemIdentificationInfo.Id))
                {
                    byte[] bytes = new byte[systemIdentificationInfo.Id.Length];
                    reader.ReadBytes(bytes);
                    reportedProperties["SystemId"] = BitConverter.ToString(bytes);
                }

                azureIoTHubClient.UpdateReportedPropertiesAsync(reportedProperties).Wait();
            }
            catch (Exception ex)
            {
                LoggingService.Error($"Azure IoT Hub device twin configuration retrieval failed", ex);
                //TODO: set up a way for this to retry instead of fail?
                return;
            }
            #endregion

            #region Wire up device reboot command handler
            try
            {
                azureIoTHubClient.SetMethodHandlerAsync("Restart", RestartAsync, null);
            }
            catch (Exception ex)
            {
                LoggingService.Error($"Azure IoT Hub device method handler configuration failed", ex);
                return;
            }
            #endregion

            #region Set up Grove Base Hat for RPI if installed
            if (deviceTwin.Properties.Desired.Contains("GroveBaseHatForRPIInstalled"))
            {
                groveBaseHatStatus = GroveBaseHatStatus.Installed;

                try
                {
                    if (deviceTwin.Properties.Desired["GroveBaseHatForRPIInstalled"].value == true)
                    {
                        GroveBaseHatAnalogPorts = new AnalogPorts();
                        GroveBaseHatAnalogPorts.Initialise();
                        LoggingService.Log($"Grove Base Hat for RPI Firmware version:{GroveBaseHatAnalogPorts.Version()}");

                        bme280Sensor = new BME280(0x76);

                        // Wire up the sensor update handler
                        azureIoTHubClient.SetMethodHandlerAsync("SensorUpdate", SensorUpdateAsync, deviceId);

                        // If the SensorUpdatePeriod greater than 0 start timer
                        int sensorUpdatePeriod = deviceTwin.Properties.Desired["SensorUpdatePeriod"].value;
                        LoggingService.Log($"Sensor update period:{sensorUpdatePeriod} seconds");
                        if (sensorUpdatePeriod > 0)
                        {
                            sensorUpdateTimer  = new Timer(SensorUpdateTimerCallback, deviceId, SensorUpdateDuePeriod, new TimeSpan(0, 0, sensorUpdatePeriod));
                            groveBaseHatStatus = GroveBaseHatStatus.Automatic;
                        }
                        else
                        {
                            groveBaseHatStatus = GroveBaseHatStatus.Enabled;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.Error($"Grove Base Hat for RPI sensor configuration failed", ex);
                    return;
                }
            }
            SendPayloadToIoTHub(new DeviceStatus()
            {
                GroveBaseHatStatus = groveBaseHatStatus
            });
            #endregion

            #region Set up Camera if installed
            if (deviceTwin.Properties.Desired.Contains("CameraInstalled"))
            {
                cameraStatus = CameraStatus.Installed;

                try
                {
                    if (deviceTwin.Properties.Desired["CameraInstalled"].value == true)
                    {
                        mediaCapture = new MediaCapture();
                        mediaCapture.InitializeAsync().AsTask().Wait();

                        // Wire up the image update handler
                        azureIoTHubClient.SetMethodHandlerAsync("ImageUpdate", ImageUpdateAsync, deviceId);

                        // If the CameraUpdatePeriod greater than 0 start timer
                        int imageUpdatePeriod = deviceTwin.Properties.Desired["ImageUpdatePeriod"].value;
                        LoggingService.Log($"Image update period:{imageUpdatePeriod} seconds");
                        if (imageUpdatePeriod > 0)
                        {
                            ImageUpdatetimer = new Timer(ImageUpdateTimerCallback, deviceId, ImageUpdateDueDefault, new TimeSpan(0, 0, imageUpdatePeriod));
                            cameraStatus     = CameraStatus.Automatic;
                        }
                        else
                        {
                            cameraStatus = CameraStatus.Enabled;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LoggingService.Error($"Image capture configuration failed", ex);
                }
            }
            SendPayloadToIoTHub(new DeviceStatus()
            {
                CameraStatus = cameraStatus
            });
            #endregion

            //enable task to continue running in background
            backgroundTaskDeferral = taskInstance.GetDeferral();
        }