/// <summary> /// Call the SensorValues service and show the results in the console window. /// </summary> /// <param name="endpointAddress">The address the service will be called.</param> public static SSimpSample InvokeService(EndpointAddress endpointAddress, bool silent) { // Create a client (get the settings in the app.config); using (SensorValuesClient client = new SensorValuesClient(new InstanceContext(new DiscoveryCallBack()), "SensorValues")) { // Connect to the discovered service endpoint. client.Endpoint.Address = endpointAddress; client.Endpoint.Binding.ReceiveTimeout = new TimeSpan(0, 0, 2); ////Get the ClientBaseAddress, to change from Localhost to an specific IP Address; //CustomBinding binding = (CustomBinding)client.Endpoint.Binding; //Uri baseAddress = ((CompositeDuplexBindingElement)binding.Elements[0]).ClientBaseAddress; //if (baseAddress != null) //{ // // Get the Client Machine Name (NB. Use the IP address as can be problems using the name) // string myClientMachineName = System.Net.Dns.GetHostName(); // System.Net.IPHostEntry myClientMachineAddressList = System.Net.Dns.GetHostEntry(myClientMachineName); // string myClientMachineIP = myClientMachineName; // foreach (System.Net.IPAddress ip in myClientMachineAddressList.AddressList) // { // // Make sure to get the IPv4 address; // if (!(ip.IsIPv6LinkLocal || ip.IsIPv6Multicast || ip.IsIPv6SiteLocal || ip.IsIPv6Teredo)) // { // myClientMachineIP = ip.ToString(); // break; // } // } // ((CompositeDuplexBindingElement)binding.Elements[0]).ClientBaseAddress = new Uri(baseAddress.AbsoluteUri.Replace("localhost", myClientMachineIP)); //} // Call the service. if (!silent) { Console.WriteLine("Invoking at {0}", endpointAddress); } client.Open(); SSimpSample response; do { response = client.GetSensorValues(); // Show the results in the console window. if (!silent) { ShowValues(response); Console.WriteLine("Read Again?"); } } while (!silent && (Console.ReadKey().Key == ConsoleKey.Y)); // Closing the client gracefully closes the connection and cleans up resources. client.Close(); // Return the Values; return(response); } }
/// <summary> /// Configures the nodes. /// </summary> /// <param name="endpointAddress">The endpoint address.</param> /// <param name="silent">if set to <c>true</c> [silent].</param> public static void ConfigureNodes(EndpointAddress endpointAddress, bool silent) { // Create a client (get the settings in the app.config); using (SensorValuesClient client = new SensorValuesClient(new InstanceContext(new DiscoveryCallBack()), "SensorValues")) { // Connect to the discovered service endpoint. client.Endpoint.Address = endpointAddress; // Call the service. if (!silent) { Console.WriteLine("Invoking Configuration at {0}", endpointAddress); } SSimpControl control = new SSimpControl(); if (!silent) { Console.WriteLine("\nSet time (y/N)"); if (Console.ReadKey().Key == ConsoleKey.Y) { control.NewTime = DateTime.Now; control.NewTimeSpecified = true; } ; Console.WriteLine("\nSet Sensors (y/N)"); if (Console.ReadKey().Key == ConsoleKey.Y) { control.SensorConfig = new SensorConfigurationType(); Console.WriteLine("\nAcclRate"); try { sbyte input = sbyte.Parse(Console.ReadLine()); if (input > 0) { control.SensorConfig.Acceleration = new SSimpRateConfig(); control.SensorConfig.Acceleration.rate = input; } } catch (ArgumentException) { } } ; } SSimpStatus response = client.Config(control); // Show the results in the console window. if (!silent) { Console.WriteLine("Configuration set successful. Current Status:"); Console.WriteLine("(New) time: {0}", response.CurrentTime); Console.WriteLine("BatteryVoltage: {0}", response.BatteryVoltage); Console.WriteLine("SensorConfigurarion: {0}", response.SensorConfig.ToString()); Console.WriteLine("SensorCapabilities: {0}", response.AllSensorConfig.ToString()); Console.WriteLine("Uptime: {0}", response.UpTime); } // Closing the client gracefully closes the connection and cleans up resources. client.Close(); } }
/// <summary> /// Initial point of the program. /// </summary> /// <param name="args">Arguments.</param> public static void Main(string[] args) { // Check if the console application will continually run. bool continuousRun = false; if (args.Length > 0 && args[0].ToLower() == "-o") { continuousRun = (args.Length > 1 && args[1].ToLower() == "continous"); } // Write the header. Console.WriteLine( @"ABB DECRC - SERVICE and usability LAB Advanced Identification and Labeling for Service DECRC 2009 DPWS Discovery Project, Contact N. L. Fantana ([email protected]) * Please, start Gateway before select the options. Additionally a running dummynode is required when using manual discovery (Option D) "); // Go always into the menu, until the user selects to exit. while (true) { // Check the option. ConsoleKeyInfo ki = new ConsoleKeyInfo(); Console.Write( @"Select one option: A-Wait for Announcement; C-Configuration Sample; D-Discover the service; I-Invoke the service; S-Eventing Subscribe; P-Performance Test; E-Exit Select: "); ki = Console.ReadKey(); Console.WriteLine(); switch (ki.Key) { // Start the announcement procedure. case ConsoleKey.A: StartAnouncementProcess(); break; // Call the Configuration Method. case ConsoleKey.C: if (hostedEndPoint != null) { ConfigureNodes(hostedEndPoint, false); } break; // Call the GetValues method (with or without showing information on the console). case ConsoleKey.D: // Finds a valid Endpoint for a Node. endpointAddress = StartDiscoveryProcess(false); if (endpointAddress != null) { // Get Metadata and the endpoint of the service. hostedEndPoint = GetMetaData(endpointAddress); // Check if the invokation of the service will be called again. } // Kill the current processes. if (UsbBridgeProcess != null) { UsbBridgeProcess.Kill(); } if (SSimpDevice != null) { SSimpDevice.Kill(); } break; case ConsoleKey.I: if (hostedEndPoint != null) { //Invoke the service to get the values. InvokeService(hostedEndPoint, false); } break; // Make a performance test. case ConsoleKey.P: // endpointAddress = StartDiscoveryProcess(false); if (hostedEndPoint != null) { // Get Metadata and the endpoint of the service. //EndpointAddress hostedEndPoint = GetMetaData(endpointAddress); bool runAgainPerformance = true; while (runAgainPerformance) { runAgainPerformance = false; string valueStr = string.Empty; int quantity = 0; int timeWait = -1; // Check the quantity of samples to try the performance test. while (!int.TryParse(valueStr, out quantity)) { Console.Write("Select the quantity of samples (C-Cancel): "); valueStr = Console.ReadLine(); if (valueStr == "C" || valueStr == "c") { break; } } if (quantity <= 0) { break; } // Get the time to wait between each sample invoke. valueStr = string.Empty; while (!int.TryParse(valueStr, out timeWait)) { Console.Write("Select the time to wait between samples in miliseconds (C-Cancel): "); valueStr = Console.ReadLine(); if (valueStr == "C" || valueStr == "c") { break; } } if (timeWait < 0) { break; } Console.Write("Reading Values. This may take some time..."); System.Diagnostics.Stopwatch stp1 = new System.Diagnostics.Stopwatch(); stp1.Start(); for (int i = 0; i < quantity; i++) { // Invoke the service. InvokeService(hostedEndPoint, true); System.Threading.Thread.Sleep(timeWait); } stp1.Stop(); Console.WriteLine("done."); Console.WriteLine("Time elapsed: {0}", stp1.ElapsedMilliseconds); // Ask if the user wants to run again. Console.Write("Run again (Y-yes, N-no)?"); ConsoleKeyInfo ky = Console.ReadKey(); if (ky.Key == ConsoleKey.Y) { runAgainPerformance = true; } Console.WriteLine(); } } // Kill the current processes. if (UsbBridgeProcess != null) { UsbBridgeProcess.Kill(); } if (SSimpDevice != null) { SSimpDevice.Kill(); } break; // Initialize the Subcription event. case ConsoleKey.S: Console.WriteLine("Starting subscription event..."); // endpointAddress = StartDiscoveryProcess(false); if (hostedEndPoint != null) { //Get Metadata of the address. // EndpointAddress hostedEndPoint = GetMetaData(endpointAddress); InstanceContext ithis = new InstanceContext(new DiscoveryCallBack()); // Create a client using (SensorValuesClient client = new SensorValuesClient(ithis)) { client.Endpoint.Address = hostedEndPoint; client.Open(); EndpointAddress callbackEndpoint = client.InnerDuplexChannel.LocalAddress; EventSourceClient eventSource = new EventSourceClient(ithis, "WSEventing"); eventSource.Endpoint.Address = hostedEndPoint; eventSource.Open(); Subscribe s = new Subscribe(); (s.Delivery = new DeliveryType()).Mode = "http://schemas.xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push"; XmlDocument doc = new XmlDocument(); using (XmlWriter writer = doc.CreateNavigator().AppendChild()) { EndpointReferenceType notifyTo = new EndpointReferenceType(); (notifyTo.Address = new AttributedURI()).Value = callbackEndpoint.Uri.AbsoluteUri; XmlRootAttribute notifyToElem = new XmlRootAttribute("NotifyTo"); notifyToElem.Namespace = "http://schemas.xmlsoap.org/ws/2004/08/eventing"; XmlDocument doc2 = new XmlDocument(); using (XmlWriter writer2 = doc2.CreateNavigator().AppendChild()) { XmlRootAttribute ReferenceElement = new XmlRootAttribute("ReferenceElement"); foreach (AddressHeader h in callbackEndpoint.Headers) { h.WriteAddressHeader(writer2); } writer2.Close(); notifyTo.ReferenceParameters = new ReferenceParametersType(); notifyTo.ReferenceParameters.Any = notifyTo.ReferenceParameters.Any = doc2.ChildNodes.Cast <XmlElement>().ToArray <XmlElement>(); } new XmlSerializer(notifyTo.GetType(), notifyToElem).Serialize(writer, notifyTo); } (s.Delivery.Any = new XmlElement[1])[0] = doc.DocumentElement; (s.Filter = new FilterType()).Dialect = "http://schemas.xmlsoap.org/ws/2006/02/devprof/Action"; (s.Filter.Any = new System.Xml.XmlNode[1])[0] = new System.Xml.XmlDocument().CreateTextNode("http://www.teco.edu/SensorValues/SensorValuesEventOut"); SubscribeResponse subscription; try { Console.WriteLine("Subscribing to the event..."); //Console.ReadLine(); subscription = eventSource.SubscribeOp(s); } catch (TimeoutException t) { Console.WriteLine("Error reply time out: {0}!!", t.Message); hostedEndPoint = null; return; } catch (EndpointNotFoundException e) { return; } String subscriptionId = null; foreach (XmlNode xel in subscription.SubscriptionManager.ReferenceParameters.Any) { if (xel.LocalName.Equals("Identifier") && xel.NamespaceURI.Equals("http://schemas.xmlsoap.org/ws/2004/08/eventing")) { subscriptionId = xel.InnerText; } } Console.WriteLine("Got subscription: {0}", subscriptionId); Console.WriteLine("Press <ENTER> to unsubscribe."); Console.ReadLine(); Console.WriteLine("Unsubscribing {0}", subscriptionId); SubscriptionManagerClient subscriptionManager = new SubscriptionManagerClient("WSEventingUnsubscribe"); subscriptionManager.Endpoint.Address = hostedEndPoint; subscriptionManager.UnsubscribeOp(subscriptionId, new Unsubscribe()); client.Close(); } } break; // Close the application. case ConsoleKey.E: return; // Invalid key. default: Console.WriteLine("Invalid value."); break; } } }