Exemplo n.º 1
0
        public async Task <DeviceStatisticsServiceModel> GetDeviceStatisticsAsync(string query)
        {
            ResultWithContinuationToken <List <DeviceConnectionStatusCountModel> > data = null;

            if (this.kustoEnabled)
            {
                if (!string.IsNullOrWhiteSpace(query))
                {
                    // Try to translate clauses to query
                    query = QueryConditionTranslator.ToADXQueryString(query);
                }

                data = await this.GetTwinDataADXQueryAsync <DeviceConnectionStatusCountModel>(
                    KustoQueryPrefix,
                    query,
                    DeviceConnectionStateCountKustoQuery);
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(query))
                {
                    // Try to translate clauses to query
                    query = QueryConditionTranslator.ToQueryString(query);
                }

                data = await this.GetIotDataQueryAsync <DeviceConnectionStatusCountModel>(
                    DeviceConnectionStateCountQueryPrefix,
                    query,
                    DeviceConnectionState,
                    null,
                    MaximumGetList); // Currently data does not show correct edge device connected status count. Will be supported in future.
            }

            return(new DeviceStatisticsServiceModel(data.Result));
        }
        /// <summary>
        /// Query devices
        /// </summary>
        /// <param name="query">
        /// Two types of query supported:
        /// 1. Serialized Clause list in JSON. Each clause includes three parts: key, operator and value
        /// 2. The "Where" clause of official IoTHub query string, except keyword "WHERE"
        /// </param>
        /// <param name="continuationToken">Continuation token. Not in use yet</param>
        /// <returns>List of devices</returns>
        public async Task <DeviceServiceListModel> GetListAsync(string query, string continuationToken)
        {
            if (!string.IsNullOrWhiteSpace(query))
            {
                // Try to translate clauses to query
                query = QueryConditionTranslator.ToQueryString(query);
            }

            // normally we need deviceTwins for all devices to show device list
            IEnumerable <Device> devices = await registry.GetDevicesAsync(MAX_GET_LIST);

            ResultWithContinuationToken <List <Twin> > twins = await GetTwinByQueryAsync(query, continuationToken, MAX_GET_LIST);

            // since deviceAsync does not support continuationToken for now, we need to ignore those devices which does not shown in twins
            return(new DeviceServiceListModel(devices
                                              .Where(d => twins.Result.Exists(t => d.Id == t.DeviceId))
                                              .Select(azureDevice => new DeviceServiceModel(azureDevice, twins.Result.SingleOrDefault(t => t.DeviceId == azureDevice.Id), ioTHubHostName)),
                                              twins.ContinuationToken));
        }
Exemplo n.º 3
0
        public async Task <DeviceServiceListModel> GetListFromIoTHubAsync(string inputQuery, string continuationToken)
        {
            string querytoBeCached = inputQuery;
            IEnumerable <QueryConditionClause> clauses         = null;
            IEnumerable <QueryConditionClause> deviceIdClauses = null;

            if (!string.IsNullOrWhiteSpace(inputQuery))
            {
                try
                {
                    clauses         = JsonConvert.DeserializeObject <IEnumerable <QueryConditionClause> >(inputQuery);
                    deviceIdClauses = clauses.Where(x => x.Key == "deviceId" && x.Operator == "LK").ToList();

                    if (deviceIdClauses != null && deviceIdClauses.Count() > 0)
                    {
                        clauses    = clauses.Where(x => x.Key != "deviceId" && x.Operator != "LK");
                        inputQuery = JsonConvert.SerializeObject(clauses);
                    }
                }
                catch
                {
                    // Any exception raised in deserializing will be ignored
                }

                if (!string.IsNullOrWhiteSpace(inputQuery))
                {
                    // Try to translate clauses to query
                    inputQuery = QueryConditionTranslator.ToQueryString(inputQuery);
                }
            }

            DeviceServiceListModel resultModel = null;
            string tenantId = this.tenantConnectionHelper.TenantId;

            if (string.IsNullOrWhiteSpace(continuationToken))
            {
                resultModel = await this.deviceQueryCache.GetCachedQueryResultAsync(tenantId, querytoBeCached);

                if (resultModel != null)
                {
                    return(resultModel);
                }
            }

            string query           = string.Empty;
            int    iotHublimit     = 500;
            string deviceListValue = string.Empty;
            ResultWithContinuationToken <List <Twin> > allTwins = new ResultWithContinuationToken <List <Twin> >(new List <Twin>(), continuationToken);

            if (deviceIdClauses != null && deviceIdClauses.Count() > 0)
            {
                foreach (var deviceIdClause in deviceIdClauses)
                {
                    List <string> deviceIds = await this.GetDevicesBasedOnInputDeviceString(deviceIdClause.Value.ToString().ToLower(), tenantId);

                    for (int i = 0; i < (deviceIds.Count / iotHublimit) + 1; i++)
                    {
                        if (i != 0 && (deviceIds.Count % (i * iotHublimit)) <= 0)
                        {
                            break;
                        }

                        List <string> batchDeviceIds = deviceIds.Skip(i * iotHublimit).Take(iotHublimit).ToList();
                        if (batchDeviceIds != null && batchDeviceIds.Count > 0)
                        {
                            // deviceListValue = $"({string.Join(" or ", deviceIds.Select(v => $"deviceId = '{v}'"))})";
                            deviceListValue = string.Join(",", batchDeviceIds.Select(p => $"'{p}'"));
                        }

                        if (!string.IsNullOrWhiteSpace(inputQuery))
                        {
                            // Try to translate clauses to query
                            query = $"{inputQuery} AND deviceId IN [{deviceListValue}]";
                        }
                        else
                        {
                            query = $" deviceId IN [{deviceListValue}]";
                        }

                        int countOfDevicestoFetch = string.IsNullOrWhiteSpace(deviceListValue) ? MaximumGetList : deviceIds.Count();

                        var twins = await this.GetTwinByQueryAsync(
                            QueryPrefix,
                            query,
                            continuationToken,
                            countOfDevicestoFetch);

                        allTwins.Result.AddRange(twins.Result.Except(allTwins.Result));
                        while (!string.IsNullOrWhiteSpace(twins.ContinuationToken))
                        {
                            twins = await this.GetTwinByQueryAsync(
                                QueryPrefix,
                                query,
                                continuationToken,
                                countOfDevicestoFetch);

                            allTwins.Result.AddRange(twins.Result);
                        }
                    }
                }
            }
            else
            {
                allTwins = await this.GetTwinByQueryAsync(
                    QueryPrefix,
                    inputQuery,
                    continuationToken,
                    MaximumGetList);
            }

            var connectedEdgeDevices = await this.GetConnectedEdgeDevices(allTwins.Result);

            resultModel = new DeviceServiceListModel(
                allTwins.Result.Select(azureTwin => new DeviceServiceModel(
                                           azureTwin,
                                           this.tenantConnectionHelper.GetIotHubName(),
                                           connectedEdgeDevices.ContainsKey(azureTwin.DeviceId))),
                allTwins.ContinuationToken);

            if (string.IsNullOrWhiteSpace(continuationToken))
            {
                this.deviceQueryCache.SetTenantQueryResult(
                    this.tenantConnectionHelper.TenantId,
                    querytoBeCached,
                    new DeviceQueryCacheResultServiceModel
                {
                    Result          = resultModel,
                    ResultTimestamp = DateTimeOffset.Now,
                });
            }

            return(resultModel);
        }