public async Task <IActionResult> GetDevicesHistoryByInterval(int startHours, int endHours, string deviceId = null, int limit = Int32.MaxValue, int minMagnitudeAllowed = 1)
        {
            // Manage session and Context
            HttpServiceUriBuilder contextUri          = new HttpServiceUriBuilder().SetServiceName(this.context.ServiceName);
            string reportsSecretKey                   = HTTPHelper.GetQueryParameterValueFor(HttpContext, Names.REPORTS_SECRET_KEY_NAME);
            List <DeviceMessage> deviceMessageListRet = new List <DeviceMessage>();

            long searchIntervalStart = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - DateTimeOffset.UtcNow.AddHours(startHours * (-1)).ToUnixTimeMilliseconds();
            long searchIntervalEnd   = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - DateTimeOffset.UtcNow.AddHours(endHours * (-1)).ToUnixTimeMilliseconds();

            ServiceUriBuilder uriBuilder = new ServiceUriBuilder(Names.InsightDataServiceName);
            Uri serviceUri = uriBuilder.Build();

            // service may be partitioned.
            // this will aggregate device IDs from all partitions
            ServicePartitionList partitions = await fabricClient.QueryManager.GetPartitionListAsync(serviceUri);

            foreach (Partition partition in partitions)
            {
                String pathAndQuery = $"/api/devices/history/interval/{searchIntervalStart}/{searchIntervalEnd}/limit/{limit}";

                if (deviceId != null && deviceId.Length > 0)
                {
                    pathAndQuery = $"/api/devices/history/{deviceId}/interval/{searchIntervalStart}/{searchIntervalEnd}/limit/{limit}";
                }

                Uri getUrl = new HttpServiceUriBuilder()
                             .SetServiceName(serviceUri)
                             .SetPartitionKey(((Int64RangePartitionInformation)partition.PartitionInformation).LowKey)
                             .SetServicePathAndQuery(pathAndQuery)
                             .Build();

                HttpResponseMessage response = await httpClient.GetAsync(getUrl, appLifetime.ApplicationStopping);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    JsonSerializer serializer = new JsonSerializer();
                    using (StreamReader streamReader = new StreamReader(await response.Content.ReadAsStreamAsync()))
                    {
                        using (JsonTextReader jsonReader = new JsonTextReader(streamReader))
                        {
                            List <DeviceMessage> deviceMessageListResult = serializer.Deserialize <List <DeviceMessage> >(jsonReader);

                            foreach (DeviceMessage message in deviceMessageListResult)
                            {
                                deviceMessageListRet.Add(message);
                            }
                        }
                    }
                }
            }

            return(this.Ok(deviceMessageListRet));
        }
        public async Task <IActionResult> GetQueueLengthAsync()
        {
            // Manage session and Context
            HttpServiceUriBuilder contextUri = new HttpServiceUriBuilder().SetServiceName(this.context.ServiceName);
            string reportsSecretKey          = HTTPHelper.GetQueryParameterValueFor(HttpContext, Names.REPORTS_SECRET_KEY_NAME);
            long   count = 0;

            if ((reportsSecretKey.Length == 0) && HTTPHelper.IsSessionExpired(HttpContext, this))
            {
                return(Ok(contextUri.GetServiceNameSiteHomePath()));
            }
            else
            {
                ServiceUriBuilder uriBuilder = new ServiceUriBuilder(Names.InsightDataServiceName);
                Uri serviceUri = uriBuilder.Build();

                // service may be partitioned.
                // this will aggregate the queue lengths from each partition
                ServicePartitionList partitions = await this.fabricClient.QueryManager.GetPartitionListAsync(serviceUri);

                foreach (Partition partition in partitions)
                {
                    Uri getUrl = new HttpServiceUriBuilder()
                                 .SetServiceName(serviceUri)
                                 .SetPartitionKey(((Int64RangePartitionInformation)partition.PartitionInformation).LowKey)
                                 .SetServicePathAndQuery($"/api/devices/queue/length")
                                 .Build();

                    HttpResponseMessage response = await this.httpClient.GetAsync(getUrl, this.appLifetime.ApplicationStopping);

                    if (response.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        return(this.StatusCode((int)response.StatusCode));
                    }

                    string result = await response.Content.ReadAsStringAsync();

                    count += Int64.Parse(result);
                }
            }

            return(this.Ok(count));
        }
        public async Task <IActionResult> GetDevicesAsync(string deviceId = null)
        {
            // Manage session and Context
            HttpServiceUriBuilder contextUri       = new HttpServiceUriBuilder().SetServiceName(this.context.ServiceName);
            string reportsSecretKey                = HTTPHelper.GetQueryParameterValueFor(HttpContext, Names.REPORTS_SECRET_KEY_NAME);
            List <DeviceMessage> deviceMessageList = new List <DeviceMessage>();

            if ((reportsSecretKey.Length == 0) && HTTPHelper.IsSessionExpired(HttpContext, this))
            {
                return(Ok(contextUri.GetServiceNameSiteHomePath()));
            }
            else if (reportsSecretKey.Length > 0)
            {
                // simply return some empty answer - no indication of error for security reasons
                if (!reportsSecretKey.Equals(Names.REPORTS_SECRET_KEY_VALUE))
                {
                    return(this.Ok(deviceMessageList));
                }
            }

            deviceMessageList = await GetDevicesDataAsync(deviceId, this.httpClient, this.fabricClient, this.appLifetime);

            return(this.Ok(deviceMessageList));
        }
        public async Task <IActionResult> GetDevicesHistoryByInterval(int startHours, int endHours, string deviceId = null, int limit = Int32.MaxValue, int minMagnitudeAllowed = 1)
        {
            // Manage session and Context
            HttpServiceUriBuilder contextUri = new HttpServiceUriBuilder().SetServiceName(this.context.ServiceName);
            string reportsSecretKey          = HTTPHelper.GetQueryParameterValueFor(HttpContext, Names.REPORTS_SECRET_KEY_NAME);
            List <DeviceHistoricalReportModel> deviceHistoricalReportModelList = new List <DeviceHistoricalReportModel>();

            long searchIntervalStart = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - DateTimeOffset.UtcNow.AddHours(startHours * (-1)).ToUnixTimeMilliseconds();
            long searchIntervalEnd   = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - DateTimeOffset.UtcNow.AddHours(endHours * (-1)).ToUnixTimeMilliseconds();

            ServiceUriBuilder uriBuilder = new ServiceUriBuilder(Names.InsightDataServiceName);
            Uri serviceUri = uriBuilder.Build();

            // service may be partitioned.
            // this will aggregate device IDs from all partitions
            ServicePartitionList partitions = await fabricClient.QueryManager.GetPartitionListAsync(serviceUri);

            foreach (Partition partition in partitions)
            {
                String pathAndQuery = $"/api/devices/history/interval/{searchIntervalStart}/{searchIntervalEnd}/limit/{limit}";

                if (deviceId != null && deviceId.Length > 0)
                {
                    pathAndQuery = $"/api/devices/history/{deviceId}/interval/{searchIntervalStart}/{searchIntervalEnd}/limit/{limit}";
                }

                Uri getUrl = new HttpServiceUriBuilder()
                             .SetServiceName(serviceUri)
                             .SetPartitionKey(((Int64RangePartitionInformation)partition.PartitionInformation).LowKey)
                             .SetServicePathAndQuery(pathAndQuery)
                             .Build();

                HttpResponseMessage response = await httpClient.GetAsync(getUrl, appLifetime.ApplicationStopping);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    JsonSerializer serializer = new JsonSerializer();
                    using (StreamReader streamReader = new StreamReader(await response.Content.ReadAsStreamAsync()))
                    {
                        using (JsonTextReader jsonReader = new JsonTextReader(streamReader))
                        {
                            List <DeviceViewModelList> deviceViewModelListResult = serializer.Deserialize <List <DeviceViewModelList> >(jsonReader);

                            string                uniqueId      = FnvHash.GetUniqueId();
                            List <string>         deviceList    = new List <string>();
                            List <DateTimeOffset> timestampList = new List <DateTimeOffset>();
                            foreach (DeviceViewModelList deviceViewModelList in deviceViewModelListResult)
                            {
                                int deviceIdIndex = 0;

                                if (deviceList.Contains(deviceViewModelList.DeviceId))
                                {
                                    deviceIdIndex = deviceList.IndexOf(deviceViewModelList.DeviceId);
                                }
                                else
                                {
                                    deviceList.Add(deviceViewModelList.DeviceId);
                                    deviceIdIndex = deviceList.IndexOf(deviceViewModelList.DeviceId);
                                }

                                int timesampIndex = 0;

                                if (timestampList.Contains(deviceViewModelList.Events.ElementAt(0).Timestamp))
                                {
                                    timesampIndex = timestampList.IndexOf(deviceViewModelList.Events.ElementAt(0).Timestamp);
                                }
                                else
                                {
                                    timestampList.Add(deviceViewModelList.Events.ElementAt(0).Timestamp);
                                    timesampIndex = timestampList.IndexOf(deviceViewModelList.Events.ElementAt(0).Timestamp);
                                }

                                int batteryVoltage    = deviceViewModelList.Events.ElementAt(0).BatteryLevel / 1000;
                                int batteryPercentage = 0;

                                if (deviceViewModelList.Events.ElementAt(0).BatteryLevel < 2800)
                                {
                                    batteryPercentage = 0;
                                }
                                else if (deviceViewModelList.Events.ElementAt(0).BatteryLevel > 3600)
                                {
                                    batteryPercentage = 100;
                                }
                                else
                                {
                                    batteryPercentage = (deviceViewModelList.Events.ElementAt(0).BatteryLevel - 2800) / 10;
                                }

                                int  minAllowedFrequency = 0;
                                bool needReferencEntry   = true;
                                foreach (DeviceViewModel evnt in deviceViewModelList.Events)
                                {
                                    for (int index = 0; index < evnt.DataPointsCount; index++)
                                    {
                                        if (evnt.Magnitude[index] >= minMagnitudeAllowed)
                                        {
                                            needReferencEntry = false;
                                            DeviceHistoricalReportModel message = new DeviceHistoricalReportModel(
                                                uniqueId,
                                                evnt.Timestamp,
                                                timesampIndex,
                                                evnt.DeviceId,
                                                deviceIdIndex,
                                                evnt.BatteryLevel,
                                                batteryVoltage,
                                                batteryPercentage,
                                                evnt.TempExternal,
                                                evnt.TempInternal,
                                                evnt.DataPointsCount,
                                                evnt.MeasurementType,
                                                evnt.SensorIndex,
                                                evnt.Frequency[index],
                                                evnt.Magnitude[index]);
                                            deviceHistoricalReportModelList.Add(message);

                                            if (minAllowedFrequency == 0)
                                            {
                                                minAllowedFrequency = evnt.Frequency[index];
                                            }
                                        }
                                    }
                                }

                                if (needReferencEntry)
                                {
                                    DeviceHistoricalReportModel message = new DeviceHistoricalReportModel(
                                        uniqueId,
                                        deviceViewModelList.Events.ElementAt(0).Timestamp,
                                        timesampIndex,
                                        deviceViewModelList.Events.ElementAt(0).DeviceId,
                                        deviceIdIndex,
                                        deviceViewModelList.Events.ElementAt(0).BatteryLevel,
                                        batteryVoltage,
                                        batteryPercentage,
                                        deviceViewModelList.Events.ElementAt(0).TempExternal,
                                        deviceViewModelList.Events.ElementAt(0).TempInternal,
                                        deviceViewModelList.Events.ElementAt(0).DataPointsCount,
                                        deviceViewModelList.Events.ElementAt(0).MeasurementType,
                                        deviceViewModelList.Events.ElementAt(0).SensorIndex,
                                        minAllowedFrequency,
                                        minMagnitudeAllowed);
                                    deviceHistoricalReportModelList.Add(message);
                                }
                            }
                        }
                    }
                }
            }

            return(this.Ok(deviceHistoricalReportModelList));
        }