Beispiel #1
0
        void DeviceManager_DeviceChanged(DeviceChangedEventArgs eventArgs)
        {
            Trace.WriteLine(String.Format("*** MainWindow.DeviceManager_DeviceChanged(): {0}: {1}, {2}({3})",
                                          eventArgs.Event, eventArgs.DeviceId, Thread.CurrentThread.Name, Thread.CurrentThread.GetHashCode()));
            String logStr = eventArgs.Event + ": " + eventArgs.DeviceId + "\r\n";;

            //LogTextBox.AppendText(logStr);

            //TODO: Fix Device Arrival/Removal messages coming in the wrong order!

            if (eventArgs.Event == DeviceChangeEvent.DeviceArrival)
            {
                DeviceManager.Refresh();
                if (CurrentDevice.IsNull && _PreviousDevice != null && _PreviousDevice.DeviceInstance == eventArgs.DeviceId)
                {
                    DeviceViewModelList.Add(_PreviousDevice);
                    CurrentDevice   = _PreviousDevice;
                    _PreviousDevice = null;
                }
                else
                {
                    var device = DeviceManager.DeviceClassMgrs.SelectMany(mgr => mgr.Devices).Single(dev => dev.DeviceInstanceId == eventArgs.DeviceId);
                    DeviceViewModelList.Add(new DeviceViewModel(device));
                }
            }
            else if (eventArgs.Event == DeviceChangeEvent.DeviceRemoval)
            {
                if (CurrentDevice.DeviceInstance == eventArgs.DeviceId)
                {
                    _PreviousDevice = CurrentDevice;
                    CurrentDevice   = new DeviceViewModel();
                }

                var devModel = DeviceViewModelList.SingleOrDefault(model => model.DeviceInstance == eventArgs.DeviceId);
                DeviceViewModelList.Remove(devModel);

                DeviceManager.Refresh();
            }

//            else if (MainMenuItem_File_TrackUsbPort.Checked)
//            {
//                _CurrentDevice = FindDeviceByPort(LastPort);
//                CurrentApi = LoadDeviceApis(_CurrentDevice);
//
//                if (_CurrentDevice != null)
//                {
//                    logStr = String.Format("Track USB Port(Hub{0},Port{1}): AutoSelect \"{2}\".\r\n", _CurrentDevice.UsbHub.Index, _CurrentDevice.UsbPort, _CurrentDevice.ToString());
//                    LogTextBox.AppendText(logStr);
//                }
//            }

//                        UpdateStatus();
        }
Beispiel #2
0
        private void InitDeviceList()
        {
            CurrentDevice = new DeviceViewModel();

            foreach (var dev in HidDeviceClass.Instance.Devices)
            {
                DeviceViewModelList.Add(new DeviceViewModel(dev));
            }

            foreach (var dev in SerialPortDeviceClass.Instance.Devices)
            {
                DeviceViewModelList.Add(new DeviceViewModel(dev));
            }
        }
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            // Get the IoT Hub connection string from the Settings.xml config file
            // from a configuration package named "Config"
            string PublishDataServiceURLs =
                this.Context.CodePackageActivationContext
                .GetConfigurationPackageObject("Config")
                .Settings
                .Sections["ExtenderServiceConfigInformation"]
                .Parameters["PublishDataServiceURLs"]
                .Value.Trim('/');

            ServiceEventSource.Current.ServiceMessage(this.Context, $"ExtenderService - {ServiceUniqueId} - RunAsync - Starting service  - Data Service URLs[{PublishDataServiceURLs}]");

            DateTimeOffset currentSearchStartingTime = DateTimeOffset.UtcNow.AddHours(-1);

            if (PublishDataServiceURLs != null && PublishDataServiceURLs.Length > 0)
            {
                string[] routingparts = PublishDataServiceURLs.Split(';');
                int      currentValueForIntervalEnd = global::Iot.Common.Names.ExtenderStandardRetryWaitIntervalsInMills;

                using (HttpClient httpClient = new HttpClient(new HttpServiceClientHandler()))
                {
                    while (true)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string reportUniqueId = FnvHash.GetUniqueId();
                        int    messageCount   = 1;

                        while (messageCount > 0)
                        {
                            try
                            {
                                DateTimeOffset startTime           = currentSearchStartingTime;
                                long           searchIntervalStart = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - currentSearchStartingTime.ToUnixTimeMilliseconds() - 500; // this last adjusment is only to compensate for latency around the calls
                                long           searchIntervalEnd   = searchIntervalStart - currentValueForIntervalEnd;

                                if (searchIntervalEnd < 0)
                                {
                                    searchIntervalEnd          = 0;
                                    currentValueForIntervalEnd = global::Iot.Common.Names.ExtenderStandardRetryWaitIntervalsInMills;
                                }

                                DateTimeOffset endTime = DateTimeOffset.UtcNow.AddMilliseconds(searchIntervalEnd * (-1));

                                string servicePathAndQuery = $"/api/devices/history/interval/{searchIntervalStart}/{searchIntervalEnd}";

                                ServiceUriBuilder uriBuilder = new ServiceUriBuilder(routingparts[0], global::Iot.Common.Names.InsightDataServiceName);
                                Uri serviceUri = uriBuilder.Build();

                                ServiceEventSource.Current.ServiceMessage(this.Context, $"ExtenderService - {ServiceUniqueId} - RunAsync - About to call URL[{serviceUri}] to collect completed messages - Search[{servicePathAndQuery}] Time Start[{startTime}] End[{endTime}]");

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

                                foreach (System.Fabric.Query.Partition partition in partitions)
                                {
                                    List <DeviceViewModelList> deviceViewModelList = new List <DeviceViewModelList>();
                                    Uri getUrl = new HttpServiceUriBuilder()
                                                 .SetServiceName(serviceUri)
                                                 .SetPartitionKey(((Int64RangePartitionInformation)partition.PartitionInformation).LowKey)
                                                 .SetServicePathAndQuery(servicePathAndQuery)
                                                 .Build();

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

                                    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> resultList = serializer.Deserialize <List <DeviceViewModelList> >(jsonReader);

                                                deviceViewModelList.AddRange(resultList);
                                            }
                                        }

                                        if (deviceViewModelList.Count > 0)
                                        {
                                            DeviceViewModelList lastItem = deviceViewModelList.ElementAt(deviceViewModelList.Count() - 1);

                                            messageCount = deviceViewModelList.Count;
                                            await ReportsHandler.PublishReportDataFor(reportUniqueId, routingparts[1], deviceViewModelList, this.Context, httpClient, cancellationToken, ServiceEventSource.Current, 1);

                                            ServiceEventSource.Current.ServiceMessage(this.Context, $"ExtenderService - {ServiceUniqueId} - RunAsync - Finished posting messages to report stream - Published total number of collected messages[{messageCount}]");
                                            currentSearchStartingTime  = endTime;
                                            currentValueForIntervalEnd = global::Iot.Common.Names.ExtenderStandardRetryWaitIntervalsInMills;
                                        }
                                        else
                                        {
                                            messageCount = 0;
                                            ServiceEventSource.Current.ServiceMessage(this.Context, $"ExtenderService - {ServiceUniqueId} - RunAsync - Could not find any messages in the interval from [{startTime}] to [{endTime}]");
                                        }
                                    }
                                    else
                                    {
                                        messageCount = 0;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                ServiceEventSource.Current.ServiceMessage(this.Context, $"ExtenderService - {ServiceUniqueId} - RunAsync - Severe error when reading or sending messages to report stream - Exception[{ex}] - Inner Exception[{ex.InnerException}] StackTrace[{ex.StackTrace}]");
                            }
                        }

                        currentValueForIntervalEnd += global::Iot.Common.Names.ExtenderStandardRetryWaitIntervalsInMills;

                        DateTimeOffset boundaryTime = currentSearchStartingTime.AddMilliseconds(currentValueForIntervalEnd);

                        if (boundaryTime.CompareTo(DateTimeOffset.UtcNow) > 0)
                        {
                            await Task.Delay(global::Iot.Common.Names.ExtenderStandardRetryWaitIntervalsInMills);
                        }
                    }
                }
            }
            else
            {
                ServiceEventSource.Current.ServiceMessage(this.Context, $"ExtenderService - {ServiceUniqueId} - RunAsync - Starting service  - Data Service URLs[{PublishDataServiceURLs}]");
            }
        }