Esempio n. 1
0
        public void Init()
        {
            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
            var             device          = registryManager.GetDeviceAsync(machineName).Result;

            if (device == null)
            {
                device = registryManager.AddDeviceAsync(new Microsoft.Azure.Devices.Device(machineName)).Result;
            }

            string deviceConnStr = string.Format("{0};DeviceId={1};SharedAccessKey={2}",
                                                 iotHubConnectionString.Split(new char[] { ';' }).Where(m => m.Contains("HostName")).FirstOrDefault(),
                                                 device.Id, device.Authentication.SymmetricKey.PrimaryKey);

            deviceClient = DeviceClient.CreateFromConnectionString(deviceConnStr, TransportType.Http1);

            Console.WriteLine();
            Console.WriteLine("Starting data collection for machine: " + machineName);

            // Initialize an instance of MTConnectClient
            client = new MTConnectClient(baseURL + actualMachine, recordCount);
            // Register for events
            client.ProbeCompleted   += client_ProbeCompleted;
            client.DataItemChanged  += client_DataItemChanged;
            client.DataItemsChanged += client_DataItemsChanged;
            client.UpdateInterval    = sampleInterval;
            client.Probe();
        }
Esempio n. 2
0
        static void Init()
        {
            string iotHubConnectionString = ConfigurationManager.AppSettings["IoTHubConnectionString"].ToString();
            string baseURL        = ConfigurationManager.AppSettings["BaseURL"].ToString();
            int    sampleInterval = Convert.ToInt32(ConfigurationManager.AppSettings["SampleInterval"]);
            int    recordCount    = Convert.ToInt32(ConfigurationManager.AppSettings["RecordCount"]);
            int    noOfDevices    = Convert.ToInt32(ConfigurationManager.AppSettings["NoOfDevices"]);

            Console.WriteLine("Getting the list of devices from the agent...");
            Console.WriteLine();
            List <string> machines = MTConnectClient.GetDeviceList(baseURL);

            Dictionary <string, Task> collectorTasks = new Dictionary <string, Task>();

            for (int i = 0; i < noOfDevices; i++)
            {
                var  machineName = machines[0] + "-" + (i + 1).ToString();
                Task task        = Task.Factory.StartNew(() => // Begin task
                {
                    new DataCollector(machineName, iotHubConnectionString, baseURL, sampleInterval, recordCount, machines[0]).Init();
                });
                collectorTasks.Add(machineName, task);
            }
            //Console.WriteLine("Press enter to stop streaming.");
            Console.ReadLine();
        }
Esempio n. 3
0
        static void Init()
        {
            string iotHubConnectionString  = ConfigurationManager.AppSettings["IoTHubConnectionString"].ToString();
            string storageConnectionString = ConfigurationManager.AppSettings["StorageConnectionString"].ToString();
            string baseURL        = ConfigurationManager.AppSettings["BaseURL"].ToString();
            int    sampleInterval = Convert.ToInt32(ConfigurationManager.AppSettings["SampleInterval"]);
            int    recordCount    = Convert.ToInt32(ConfigurationManager.AppSettings["RecordCount"]);

            Console.WriteLine("Getting the list of devices from the agent...");
            Console.WriteLine();
            List <string> machines     = MTConnectClient.GetDeviceList(baseURL);
            List <string> deviceToRead = ConfigurationManager.AppSettings["DeviceToRead"].ToString().Split(new char[] { ',' }).ToList();

            Dictionary <string, Task> collectorTasks = new Dictionary <string, Task>();

            foreach (string dev in deviceToRead)
            {
                if (!machines.Contains(dev))
                {
                    Console.WriteLine("The agent is currently not streaming any data from the device {0}", dev);
                    Console.WriteLine();
                    continue;
                }
                else
                {
                    Task task = Task.Factory.StartNew(() =>    // Begin task
                    {
                        new DataCollector(dev, iotHubConnectionString, storageConnectionString, baseURL, sampleInterval, recordCount).Init();
                    });
                    collectorTasks.Add(dev, task);
                }
            }
            //Console.WriteLine("Press enter to stop streaming.");
            Console.ReadLine();
        }
Esempio n. 4
0
        private void StartMTOnly()
        {
            // Create a new MTConnectClient using the baseUrl
            client = new MTConnectClient(baseUrl);

            client.Start();
            Started = true;
            //Console.WriteLine("Start Complete");
        }
Esempio n. 5
0
 private void btn_stop_Click(object sender, EventArgs e)
 {
     if (client == null)
     {
         return;
     }
     client.Stop();
     client = null;
 }
        public void Start(CancellationToken cancellationToken)
        {
            this.blobUrl = StorageAgent.GenerateBlobs(this.storageAccount, this.deviceName, this.tags);
            client       = new MTConnectClient(baseUrl + deviceName, tags, interval, cancellationToken);

            client.ProbeCompleted   += client_ProbeCompleted;
            client.DataItemChanged  += client_DataItemChanged;
            client.DataItemsChanged += client_DataItemsChanged;
            client.Probe();
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            var client = new MTConnectClient("http://agent.mtconnect.org");

            client.ProbeCompleted   += client_ProbeCompleted;
            client.DataItemChanged  += client_DataItemChanged;
            client.DataItemsChanged += client_DataItemsChanged;
            while (true)
            {
                Thread.Sleep(1000);
            }
        }
Esempio n. 8
0
        private static string[] GetActiveDevices(string baseUrl, string[] givenDevices)
        {
            IList <string> activeDevices = MTConnectClient.GetDeviceList(baseUrl);
            IList <string> devices       = new List <string>();

            foreach (string device in givenDevices)
            {
                if (activeDevices.Contains(device))
                {
                    devices.Add(device);
                }
            }

            return(devices.ToArray());
        }
Esempio n. 9
0
        private void StartAgentClient()
        {
            if (!string.IsNullOrEmpty(Address))
            {
                // Normalize Properties
                _address = _address.Replace("http://", "");
                if (_port < 0)
                {
                    _port = 5000;
                }
                if (_interval < 0)
                {
                    _interval = 500;
                }

                // Create the MTConnect Agent Base URL
                agentUrl = string.Format("http://{0}:{1}", _address, _port);

                // Create a new MTConnectClient using the baseUrl
                _agentClient          = new MTConnectClient(agentUrl, _deviceName);
                _agentClient.Interval = _interval;

                // Subscribe to the Event handlers to receive status events
                _agentClient.Started += _agentClient_Started;
                _agentClient.Stopped += _agentClient_Stopped;

                // Subscribe to the Event handlers to receive the MTConnect documents
                _agentClient.ProbeReceived   += DevicesDocumentReceived;
                _agentClient.CurrentReceived += StreamsDocumentReceived;
                _agentClient.SampleReceived  += StreamsDocumentReceived;
                _agentClient.AssetsReceived  += AssetsDocumentReceived;
                _agentClient.ConnectionError += _agentClient_ConnectionError;

                // Start the MTConnectClient
                _agentClient.Start();
            }
            else
            {
                log.Warn("MTConnect Address Invalid : " + _deviceId + " : " + _address);
            }
        }
Esempio n. 10
0
        public void Start()
        {
            if (client != null)
            {
                return;
            }

            client        = new MTConnectClient(AgentAddress, null);
            client.Error += Client_Error;
            //client.ProbeReceived += Client_ProbeReceived;

            // - 经过测试,只返回一次,不会轮询返回。
            client.CurrentReceived += Client_CurrentReceived;

            // - 只会返回建立连接之后变化过的数据,不断的轮询返回,  因此必须与 'CurrentReceived' 配合起来使用。
            client.SampleReceived += Client_CurrentReceived;

            //client.ProbeReceived += Client_ProbeReceived;

            //client.SampleReceived += StreamsSuccessful;
            client.Start();
        }
Esempio n. 11
0
        public void Start()
        {
            // The base address for the MTConnect Agent
            string baseUrl = "http://agent.mtconnect.org";
            // The base address for the MTConnect Agent
            //string baseUrl = "http://74.203.109.245:5001";

            // Execute the Current request and get an MTConnectStreams.Document object back
            var current = new Current(baseUrl).Execute();

            Console.WriteLine(current);

            var sample = new Sample(baseUrl, 200, 500).Execute();

            Console.WriteLine(current);

            // Execute the Probe request asynchronously and return the MTConnectDevices.Document using the event handler
            var probe = new Probe(baseUrl);

            //probe.Successful += Probe_Successful;
            //probe.ExecuteAsync();

            Console.WriteLine(probe);


            // Create a new MTConnectClient using the baseUrl
            client = new MTConnectClient(baseUrl, "VMC-3Axis");
            ///client.Interval = 1000;

            // Subscribe to the Event handlers to receive the MTConnect documents
            client.ProbeReceived   += DevicesSuccessful;
            client.CurrentReceived += StreamsSuccessful;
            client.SampleReceived  += StreamsSuccessful;

            // Start the MTConnectClient
            client.Start();
        }
Esempio n. 12
0
        private void btn_start_Click(object sender, EventArgs e)
        {
            if (client != null)
            {
                return;
            }

            clrLv();

            client        = new MTConnectClient(txt_agent.Text.Trim(), txt_driver.Text.Trim() == string.Empty ? null : txt_driver.Text.Trim());
            client.Error += Client_Error;
            //client.ProbeReceived += Client_ProbeReceived;

            // - 经过测试,只返回一次,不会轮询返回。
            client.CurrentReceived += Client_CurrentReceived;

            // - 只会返回建立连接之后变化过的数据,不断的轮询返回,  因此必须与 'CurrentReceived' 配合起来使用。
            client.SampleReceived += Client_CurrentReceived;

            //client.ProbeReceived += Client_ProbeReceived;

            //client.SampleReceived += StreamsSuccessful;
            client.Start();
        }
Esempio n. 13
0
        /// <summary>
        /// Receives the message from IoT hub with blob URLs.
        /// </summary>
        private void ReceiveC2dMessage()
        {
            while (true)
            {
                Microsoft.Azure.Devices.Client.Message receivedMessage = deviceClient.ReceiveAsync().Result;
                if (receivedMessage == null)
                {
                    continue;
                }

                var     msgStr  = System.Text.Encoding.Default.GetString(receivedMessage.GetBytes());
                dynamic msgData = JsonConvert.DeserializeObject(msgStr);
                if (msgData.messageType != null && msgData.messageType == "fileupload")
                {
                    GetBlobUris(Convert.ToString(msgData.fileUri));
                    Console.WriteLine("Received the blob paths from the IOT hub for the machine {0}...", machineName);
                    Console.WriteLine();

                    if (blobpaths.Count != blobtypes.Length)
                    {
                        Console.WriteLine("The required number of blob paths for the machine {0}.", machineName);
                        Console.WriteLine();
                        deviceClient.CompleteAsync(receivedMessage);
                        return;
                    }
                    Console.WriteLine();
                    Console.WriteLine("The blob paths for the machine {0} are (container/blob):", machineName);
                    Console.WriteLine();
                    foreach (string str in blobtypes)
                    {
                        Console.WriteLine("{0}/{1}.csv", Convert.ToString(msgData.blobContainerName), str);
                    }
                    Console.WriteLine();
                    Console.WriteLine();
                    Task.Factory.StartNew(() =>    // Begin task
                    {
                        Console.Write("Reading data from the machine {0}", machineName);
                        while (true)
                        {
                            Thread.Sleep(1000);
                            Console.Write(".");
                            Thread.Sleep(1000);
                            Console.Write(".");
                            Thread.Sleep(1000);
                            Console.Write(".");
                            Thread.Sleep(1000);
                            Console.Write("\b \b\b \b\b \b");
                            Thread.Sleep(1000);
                        }
                    });
                    deviceClient.CompleteAsync(receivedMessage);
                    List <string> targettags = (new string[] { "mode", "controllermode", "execution", "program"
                                                               , "toolnumber", "path_feedrate1", "pathfeedrate", "s1speed", "spindlespeed", "rapidoverride" }).ToList();

                    // Initialize an instance of MTConnectClient
                    client = new MTConnectClient(baseURL + machineName, targettags, recordCount);
                    // Register for events
                    client.ProbeCompleted   += client_ProbeCompleted;
                    client.DataItemChanged  += client_DataItemChanged;
                    client.DataItemsChanged += client_DataItemsChanged;
                    client.UpdateInterval    = sampleInterval;
                    client.Probe();

                    break;
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// it setup the MTConnectClient and get data from CurrentStream
        /// it also setup the timer, for data update and add XML data
        /// </summary>
        public void Start()
        {
            // The base address for the MTConnect Agent
            string baseUrl = "https://smstestbed.nist.gov/vds/";

            // Create a new MTConnectClient using the baseUrl
            client = new MTConnectClient(baseUrl);

            // Subscribe to the Event handlers to receive the MTConnect documents
            client.ProbeReceived   += DevicesSuccessful;
            client.CurrentReceived += StreamsSuccessful;
            client.SampleReceived  += StreamsSuccessful;

            // Start the MTConnectClient
            client.Start();

            now = new Current(baseUrl);

            //make sure _current has data document to avoid the error from finding DataItems.
            while (current == null)
            {
                current = now.Execute();
            }

            //set the first data, which can be showed to UI and later compared with new data.
            RotaryA[0]     = current.DeviceStreams[0].DataItems.Find(o => o.DataItemId == "GFAgie01-A_2").CDATA;
            _maxRotaryA[0] = current.DeviceStreams[0].DataItems.Find(o => o.DataItemId == "GFAgie01-A_2").CDATA;

            RotaryC[0]     = current.DeviceStreams[0].DataItems.Find(o => o.DataItemId == "GFAgie01-C_2").CDATA;
            _maxRotaryC[0] = current.DeviceStreams[0].DataItems.Find(o => o.DataItemId == "GFAgie01-C_2").CDATA;

            LinearX[0]     = current.DeviceStreams[0].DataItems.Find(o => o.DataItemId == "GFAgie01-X_2").CDATA;
            _maxLinearX[0] = current.DeviceStreams[0].DataItems.Find(o => o.DataItemId == "GFAgie01-X_2").CDATA;

            LinearY[0]     = current.DeviceStreams[0].DataItems.Find(o => o.DataItemId == "GFAgie01-Y_2").CDATA;
            _maxLinearY[0] = current.DeviceStreams[0].DataItems.Find(o => o.DataItemId == "GFAgie01-Y_2").CDATA;

            LinearZ[0]     = current.DeviceStreams[0].DataItems.Find(o => o.DataItemId == "GFAgie01-Z_2").CDATA;
            _maxLinearZ[0] = current.DeviceStreams[0].DataItems.Find(o => o.DataItemId == "GFAgie01-Z_2").CDATA;

            //for the simulated device , set the first data
            Avail[0] = FirstDevice
                       .Element("DeviceStream")
                       .Elements("Events")
                       .Where(x => x.Attribute("name").Value == "Availability").Descendants().ElementAt(_indexXml).Value;

            RotaryA[1] = FirstDevice
                         .Element("DeviceStream")
                         .Elements("ComponentStream")
                         .Where(x => x.Attribute("name").Value == "Rotary(A)").Descendants().ElementAt(_indexXml).Value;
            _maxRotaryA[1] = FirstDevice
                             .Element("DeviceStream")
                             .Elements("ComponentStream")
                             .Where(x => x.Attribute("name").Value == "Rotary(A)").Descendants().ElementAt(_indexXml).Value;

            RotaryC[1] = FirstDevice
                         .Element("DeviceStream")
                         .Elements("ComponentStream")
                         .Where(x => x.Attribute("name").Value == "Rotary(C)").Descendants().ElementAt(_indexXml).Value;
            _maxRotaryC[1] = FirstDevice
                             .Element("DeviceStream")
                             .Elements("ComponentStream")
                             .Where(x => x.Attribute("name").Value == "Rotary(C)").Descendants().ElementAt(_indexXml).Value;

            LinearX[1] = FirstDevice
                         .Element("DeviceStream")
                         .Elements("ComponentStream")
                         .Where(x => x.Attribute("name").Value == "Linear(X)").Descendants().ElementAt(_indexXml).Value;
            LinearY[1] = FirstDevice
                         .Element("DeviceStream")
                         .Elements("ComponentStream")
                         .Where(x => x.Attribute("name").Value == "Linear(Y)").Descendants().ElementAt(_indexXml).Value;
            LinearZ[1] = FirstDevice
                         .Element("DeviceStream")
                         .Elements("ComponentStream")
                         .Where(x => x.Attribute("name").Value == "Linear(Z)").Descendants().ElementAt(_indexXml).Value;
            _maxLinearX[1] = FirstDevice
                             .Element("DeviceStream")
                             .Elements("ComponentStream")
                             .Where(x => x.Attribute("name").Value == "Linear(X)").Descendants().ElementAt(_indexXml).Value;
            _maxLinearY[1] = FirstDevice
                             .Element("DeviceStream")
                             .Elements("ComponentStream")
                             .Where(x => x.Attribute("name").Value == "Linear(Y)").Descendants().ElementAt(_indexXml).Value;
            _maxLinearZ[1] = FirstDevice
                             .Element("DeviceStream")
                             .Elements("ComponentStream")
                             .Where(x => x.Attribute("name").Value == "Linear(Z)").Descendants().ElementAt(_indexXml).Value;

            //set the first data as Maximum Data, bound to UI

            //_maxRotaryA = RotaryA;
            //_maxRotaryC = RotaryC;
            //_maxLinearX = LinearX;
            //_maxLinearY = LinearY;
            //_maxLinearZ = LinearZ;

            //for simulated device, bound to UI
            _Avail = Avail;

            //request new data by 3 sec by using DispatcherTimer
            //it will update the current data
            //it contains functions, which will set the Maximum Date
            //it will add the newest data to XML-data
            DispatcherTimer dispatcherTimer = new DispatcherTimer();

            dispatcherTimer.Tick    += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 3);
            dispatcherTimer.Start();
        }