//---------------------------------------------------------------------------- // // Copyright (c) Intel Corporation, 2011 - 2015 All Rights Reserved. // // File: AlarmClockApi.cs // // Contents: Api code for Intel(R) Active Management Technology // (Intel® AMT) AlarmClock Sample. // // Notes: This sample demonstrates how to use some of the features and // capabilities provided by the AlarmClock service of Intel® AMT, // over WS-Management. // //---------------------------------------------------------------------------- using System; using Intel.Management.Wsman; using System.Globalization; using System.Text; using System.Xml; using Connection; using Common.Utils; namespace AlarmClock { #region DateTimeInterval_Class /// /// Describe the interval (days, hours and minutes - because the other arguments must be 0). /// public class DateTimeInterval { int days; public int Days { get { return days; } set { if (value < 0) throw new Exception("Days must be >=0"); days = value; } } int hours; public int Hours { get { return hours; } set { if (value < 0 || value > 23) throw new Exception("Hours must be between 0-23"); hours = value; } } int minutes; public int Minutes { get { return minutes; } set { if (value < 0 || value > 59) throw new Exception("Minutes must be between 0-59"); minutes = value; } } public DateTimeInterval(int days, int hours, int minutes) { Days = days; Hours = hours; Minutes = minutes; } } //end class DateTimeInterval #endregion public class AlarmClock_Api : Connection.Connection_setup { #region CONSTS public const string SAMPLE_ALARM_NAME = "SampleAlarmName"; #endregion #region DATA_MEMBERS private static DateTime NextAMTAlarmTime = DateTime.Now.AddDays(2); #endregion #region CONSTRUCTORS // Inheriting Connection details from Connection_setup class. // Convert password to secure string to comply with wsman dll which supports passwords in SecureString // format only. public AlarmClock_Api(string ip, string username, string pwd, bool krb, MpsManager proxy, bool acceptSelfSignedCertificate = false) : base(ip, username, pwd.ConvertToSecureString(), krb, proxy, acceptSelfSignedCertificate) { NextAMTAlarmTime = NextAMTAlarmTime.AddSeconds(60 - NextAMTAlarmTime.Second);// the seconds must be 0. } // Convert password to secure string to comply with wsman dll which supports passwords in SecureString // format only. public AlarmClock_Api(string ip, string username, string pwd, string secure, bool krb, MpsManager proxy, bool acceptSelfSignedCertificate = false) : base(ip, username, pwd.ConvertToSecureString(), secure, krb, proxy, acceptSelfSignedCertificate) { NextAMTAlarmTime = NextAMTAlarmTime.AddSeconds(60 - NextAMTAlarmTime.Second);// the seconds must be 0. } #endregion CONSTRUCTORS #region PRIVATE_fUNCTIONS /// /// Return alarm time to turn the host computer system on /// Details obtained from the User... /// /// public DateTime getAlarmTime() { Console.WriteLine("Enter date and time to turn on the host:\n---------------------------------------"); // Date Console.WriteLine("Enter date in format: MM/DD/YYYY "); string date = Console.ReadLine(); // Time Console.WriteLine("Enter time in format: HH:MM"); string time = Console.ReadLine(); //time = string.Join(date,time); //Ensure that the second is 00 - as Intel AMT seconds must be 0. IFormatProvider format = new CultureInfo("en-US"); DateTime nextAMTAlarmTime; bool parseResult = DateTime.TryParseExact(date + " " + time, "MM/dd/yyyy HH:mm", format, DateTimeStyles.None, out nextAMTAlarmTime); if (!parseResult) throw new FormatException(" Unable to convert " + date + " " + time + " to a date and time."); Console.WriteLine("Entered Date time is as follows:{0}", nextAMTAlarmTime.ToString("s", CultureInfo.CreateSpecificCulture("en-US"))); /* * s Format Specifier en-US Culture 2008-10-01T17:04:32 * u Format Specifier en-US Culture 2008-10-01 17:04:32Z * o Format Specifier en-US Culture 2008-10-01T17:04:32.0000000 * d Format Specifier en-US Culture 10/1/2008 * D Format Specifier en-US Culture Wednesday, October 01, 2008 * f Format Specifier en-US Culture Wednesday, October 01, 2008 5:04 PM * g Format Specifier en-US Culture 10/1/2008 5:04 PM * m Format Specifier en-US Culture October 01 * */ Console.ReadLine(); return nextAMTAlarmTime; } /// /// Return the alarm time interval (How often the wake on happened). /// public DateTimeInterval getIntervalTime() { bool parseResult = true; DateTimeInterval dt = null; // Just days can be set for interval, // for example: to set the alarm clock interval for 3 monthes set the days to - 90 Console.WriteLine("Enter schedule interval to wake-on:\n-----------------------------------"); Console.WriteLine("Enter required interval for: days, hours, minutes"); Console.WriteLine("Example: 1,1,7 = interval of 1 day 1 hour and 7 minutes.\n"); do { try { // Get interval arguments. string date = Console.ReadLine(); string[] str = date.Split(','); if (str.Length != 3) throw new Exception("Input string was not in a correct format."); dt = new DateTimeInterval(Convert.ToInt32(str[0]), Convert.ToInt32(str[1]), Convert.ToInt32(str[2])); parseResult = true; } catch (Exception e) { if (e.Message != null) Console.WriteLine(e.Message + " Try again!"); else Console.WriteLine("Error in interval. Try again!"); parseResult = false; } } while (!parseResult); Console.WriteLine("Date time interval as entered by user is :{0}", dt); return dt; } /// /// Build AlarmTemplate object as the FW expects to receive it. /// /// The time to be set /// The interval /// Time Zone /// Alarm Name /// StringBuilder, represents the AlarmTemplate property. private StringBuilder BuildAlarmTemplate(string StartTime, TimeSpan Interval, string AlarmName) { StringBuilder builder = new StringBuilder(); // Create AlarmTemplate XML format. builder.Append(""); // Set properties to AlarmClock by the alarmClock instance properties: // Create InstanceID string by XmlElement type, to escape special characters: '&', ''', '"', '>'. XmlDocument doc = new XmlDocument(); XmlElement element = doc.CreateElement("aaaa"); element.InnerText = AlarmName; builder.Append("" + element.InnerXml + ""); // Create DateTime object to set StartTime property. IManagedInstance dateTime = wsmanClient.NewInstance("Datetime"); dateTime.Text = StartTime; builder.Append(""); builder.Append(dateTime.Xml); builder.Append(""); // If specified interval, create Interval object to set Interval property. if (Interval.TotalMilliseconds != 0) if (Interval != null) { IManagedInstance interval = wsmanClient.NewInstance("Interval"); interval.Text = "P" + Interval.Days + "DT" + Interval.Hours + "H" + Interval.Minutes + "M"; builder.Append(""); builder.Append(interval.Xml); builder.Append(""); } builder.Append(""); builder.Append("true"); builder.Append(""); builder.Append(""); return builder; } /// /// Displays the internal time of the Intel AMT. /// private void DisplayInternalAMTTime() { Console.WriteLine("-------- Intel(R) AMT TIME SYNC FUNC CALL --------"); IManagedReference amtsyncRef = wsmanClient.NewReference("SELECT * FROM AMT_TimeSynchronizationService WHERE Name='Intel(r) AMT Time Synchronization Service'"); IManagedInstance amtsyncInstance = amtsyncRef.Get(); IManagedInstance timeSync = amtsyncRef.CreateMethodInput("GetLowAccuracyTimeSynch"); IManagedInstance outputobject = amtsyncRef.InvokeMethod(timeSync); IWsmanItem returnvalue = outputobject.GetProperty("ReturnValue"); if (returnvalue.ToString().CompareTo("0") == 0) { IWsmanItem ta0 = outputobject.GetProperty("Ta0"); Console.WriteLine(" Internal Intel(R) AMT Time is: {0}", ta0.ToString()); DateTime dt = DateTime.Now; string t = dt.ToString("T"); Console.WriteLine(t); } } /// /// Run API Test. /// Intel AMT versions earlier than 8.0. /// private void RunAPITestEarlierVersions() { IManagedReference alarmClockServiceRef = wsmanClient.NewReference("SELECT * FROM AMT_AlarmClockService WHERE Name='Intel(r) AMT Alarm Clock Service'"); IManagedInstance alarmClockServiceInstance = alarmClockServiceRef.Get(); //Keep the current values of the alarm clock. IManagedInstance nextAlarmTime = wsmanClient.NewInstance("Datetime"); IManagedInstance amtAlarmClockInterval = wsmanClient.NewInstance("Datetime"); if (alarmClockServiceInstance.GetProperty("NextAMTAlarmTime").IsNull.Equals(false)) { nextAlarmTime.Text = alarmClockServiceInstance.GetProperty("NextAMTAlarmTime").ToString(); } if (alarmClockServiceInstance.GetProperty("AMTAlarmClockInterval").IsNull.Equals(false)) { amtAlarmClockInterval.Text = alarmClockServiceInstance.GetProperty("AMTAlarmClockInterval").ToString(); } //Execute a single wake on. SingleWakeOn(NextAMTAlarmTime); //Dispay the wake on information. WakeOnInfo(); //Disable the alarm clock. DisableWakeOn(); //Return the system to its previous state. Console.WriteLine(" Return the Alarm Clock to its Previous State... "); if (nextAlarmTime.Text.Equals(null))// != null) { alarmClockServiceInstance.SetProperty("NextAMTAlarmTime", nextAlarmTime); } if (amtAlarmClockInterval.Text.Equals(null))// != null) { alarmClockServiceInstance.SetProperty("AMTAlarmClockInterval", amtAlarmClockInterval); } alarmClockServiceRef.Put(alarmClockServiceInstance); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Success"); Console.ForegroundColor = ConsoleColor.Gray; DisplayInternalAMTTime(); } /// /// Run API Test. /// Intel AMT versions 8.0 and later. /// private void RunAPITestLaterVersions() { //Execute a single wake on. SingleWakeOnLaterVersions(NextAMTAlarmTime); //Dispay the wake on information. WakeOnInfoLaterVersions(); //Disable the alarm clock. DeleteAlarmLaterVersions(SAMPLE_ALARM_NAME); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Success"); Console.ForegroundColor = ConsoleColor.Gray; DisplayInternalAMTTime(); } /// /// Display settings of all alarms. /// Intel AMT versions earlier than 8.0. /// private void WakeOnInfoEarlierVersions() { IManagedReference alarmClockServiceRef = wsmanClient.NewReference("SELECT * FROM AMT_AlarmClockService WHERE Name='Intel(r) AMT Alarm Clock Service'"); IManagedInstance alarmClockServiceInstance = alarmClockServiceRef.Get(); IWsmanItem nextAMTAlarmTime = alarmClockServiceInstance.GetProperty("NextAMTAlarmTime"); //Check if the received object contains values for the fields NextAMTAlarmTime and AMTAlarmClockInterval //else Alarmclock is already disabled... if (nextAMTAlarmTime.IsNull.Equals(true)) { Console.WriteLine("Alaram Clock is already disabled"); return; } else //if(nextAlaramClockTime.Object.Text !=null) { IWsmanItem amtAlarmClockInterval = alarmClockServiceInstance.GetProperty("AMTAlarmClockInterval"); //Return time to the En-US format. nextAMTAlarmTime.Object.Text = nextAMTAlarmTime.Object.Text.Replace("Z", " "); DateTime dt = DateTime.Parse(nextAMTAlarmTime.Object.Text, new CultureInfo("en-US", true)); Console.WriteLine("The alarm clock will be activated at: {0} \n", dt);// nextAMTAlarmTime.Object.Text); //Display details fo the AlarmClock Interval - if periodic wake on has been set. if (amtAlarmClockInterval.IsNull.Equals(false)) { Console.WriteLine("The Alarm Clock will also be activated in subsequent intervals of :\n"); Console.WriteLine(" current clock time set is:{0}", amtAlarmClockInterval.Object.Text); //display intervals of days,hrs,mins... } } } /// /// Display settings of all alarms. /// Intel AMT versions 8.0 and later. /// private void WakeOnInfoLaterVersions() { try { IWsmanEnumeration AMTAlarmClocks = wsmanClient.NewReference("IPS_AlarmClockOccurrence").Enumerate(null, null); foreach (IWsmanItem AMTAlarmClock in AMTAlarmClocks) { Console.WriteLine("\nAlarm Clock Name: {0}", AMTAlarmClock.Object.GetProperty("InstanceID")); Console.WriteLine("Alarm Clock Start Time: {0}", AMTAlarmClock.Object.GetProperty("StartTime").Object.Text); if (AMTAlarmClock.Object.GetProperty("Interval").IsNull == false) { Console.WriteLine("Alarm Clock Interval: {0}", AMTAlarmClock.Object.GetProperty("Interval").Object.Text); } Console.WriteLine("Alarm Clock Delete Option: {0}", AMTAlarmClock.Object.GetProperty("DeleteOnCompletion").ToString() == "true" ? "Auto Delete On Completion" : "Manual Delete"); } } catch (Exception e) { throw new Exception("Failed to get all alarms. " + e.Message); } } /// /// Disables the alarm clock. /// Intel AMT versions earlier than 8.0. /// private void DisableWakeOnEarlierVersions() { IManagedReference alarmClockServiceRef = wsmanClient.NewReference("SELECT * FROM AMT_AlarmClockService WHERE Name='Intel(r) AMT Alarm Clock Service'"); IManagedInstance alarmClockServiceInstance = alarmClockServiceRef.Get(); IWsmanItem nextAlaramClockTime = alarmClockServiceInstance.GetProperty("NextAMTAlarmTime"); IWsmanItem nextAlarmClockInterval = alarmClockServiceInstance.GetProperty("AMTAlarmClockInterval"); //Check if the received object contains values for the fields NextAMTAlarmTime and AMTAlarmClockInterval //else Alarmclock is already disabled... if (nextAlaramClockTime.IsNull.Equals(true)) { Console.WriteLine("Alaram Clock is already disabled"); return; } alarmClockServiceInstance.RemoveProperty("NextAMTAlarmTime"); if (nextAlarmClockInterval.IsNull.Equals(false)) { alarmClockServiceInstance.RemoveProperty("AMTAlarmClockInterval"); } //Update object using the Put functionality. alarmClockServiceRef.Put(alarmClockServiceInstance); Console.WriteLine("The Alarm Clock has now been disabled. \n"); } /// /// Deletes an alarm clock. /// Intel AMT versions 8.0 and later. /// /// The alarm to delete private void DeleteAlarmLaterVersions(string alarmName) { IManagedReference alarmClockOccurrenceRef = wsmanClient.NewReference(string.Format("SELECT * FROM IPS_AlarmClockOccurrence WHERE InstanceID='{0}'", alarmName)); if (alarmClockOccurrenceRef.Enumerate("http://schemas.dmtf.org/wbem/wsman/1/wsman/SelectorFilter", null).HasNext == true) { try { alarmClockOccurrenceRef.Delete(); } catch (Exception e) { throw new Exception(e.Message); } } } /// /// Configure a periodic wake on. /// Intel AMT versions earlier than 8.0. /// private void PeriodicWakeOnEarlierVersions(DateTime nextAMTAlarmTime, DateTimeInterval AlarmClockInterval) { string NewAlarmTime = String.Concat(nextAMTAlarmTime.ToString("s", CultureInfo.CreateSpecificCulture("en-US")), "Z"); Console.WriteLine("Intel AMT Format: {0}", NewAlarmTime); //Setting the DateTime to the user specified date and time... IManagedInstance nextAlarmTime = wsmanClient.NewInstance("Datetime"); nextAlarmTime.Text = NewAlarmTime; //Set the Intel AMT AlarmClock Interval. //The AMTAlarmClockInterval format is PdDThHmM: //To define a one-day interval: “P1D” //To define an interval of three hours,15 mins: “PT3H15M” //Need to convert user input format to Intel AMT format. IManagedInstance amtAlarmClockInterval = wsmanClient.NewInstance("Interval"); // amtAlarmClockInterval.Text = "P1DT5H15M"; amtAlarmClockInterval.Text = "P" + AlarmClockInterval.Days + "DT" + AlarmClockInterval.Hours + "H" + AlarmClockInterval.Minutes + "M"; //Create Service reference to AMT_AlarmClockService IManagedReference alarmClockServiceRef = wsmanClient.NewReference("SELECT * FROM AMT_AlarmClockService WHERE Name='Intel(r) AMT Alarm Clock Service'"); IManagedInstance alarmClockServiceInstance = alarmClockServiceRef.Get(); //Set values alarmClockServiceInstance.SetProperty("NextAMTAlarmTime", nextAlarmTime); alarmClockServiceInstance.SetProperty("AMTAlarmClockInterval", amtAlarmClockInterval); //Set values by sending AMT_AlarmClockService.Put() alarmClockServiceRef.Put(alarmClockServiceInstance); Console.WriteLine("The alarm clock will activate periodically.\n"); } /// /// Configure a periodic wake on. /// Intel AMT versions 8.0 and later. /// public void PeriodicWakeOnLaterVersions(DateTime nextAMTAlarmTime, DateTimeInterval AlarmClockInterval) { //To check the format of the string - "yy-mm-ddThh:mm:00Z" string newAlarmTime = String.Concat(nextAMTAlarmTime.ToString("s", CultureInfo.CreateSpecificCulture("en-US")), "Z"); Console.WriteLine("Intel(R) AMT Format: {0}", newAlarmTime); IManagedReference AlarmClockServiceRef = wsmanClient.NewReference("SELECT * FROM AMT_AlarmClockService WHERE Name='Intel(r) AMT Alarm Clock Service'"); IManagedInstance addAlarmInput = AlarmClockServiceRef.CreateMethodInput("AddAlarm"); // Set AlarmTemplate property with all definitions of the alarm. // The alarm name must not exist already in the Intel AMT. IManagedInstance templateObj = wsmanClient.NewInstance(BuildAlarmTemplate(newAlarmTime, new TimeSpan(AlarmClockInterval.Days, AlarmClockInterval.Hours, AlarmClockInterval.Minutes, 0), SAMPLE_ALARM_NAME).ToString()); addAlarmInput.SetProperty(null, templateObj); IManagedInstance returnValue; try { returnValue = AlarmClockServiceRef.InvokeMethod(addAlarmInput); } catch (Exception e) { throw new Exception("Failed to create alarm. Ensure all AlarmClock properties are valid."); } if (returnValue.GetProperty("ReturnValue").ToString() != "0") { uint PT_STATUS; if (uint.TryParse(returnValue.GetProperty("ReturnValue").ToString(), out PT_STATUS)) { throw new Exception("Failed to create alarm. Return Value = " + returnValue); } } Console.WriteLine("The alarm clock will activate periodically.\n"); } /// /// Configure a single wake on. /// Intel AMT versions earlier than 8.0. /// private void SingleWakeOnEarlierVersions(DateTime nextAMTAlarmTime) { //To check the format of the string - "yy-mm-ddThh:mm:00Z" string NewAlarmTime = String.Concat(nextAMTAlarmTime.ToString("s", CultureInfo.CreateSpecificCulture("en-US")), "Z"); Console.WriteLine("Intel AMT Format: {0}", NewAlarmTime); IManagedInstance nextAlarmTime = wsmanClient.NewInstance("Datetime"); nextAlarmTime.Text = NewAlarmTime; IManagedReference alarmClockServiceRef = wsmanClient.NewReference("SELECT * FROM AMT_AlarmClockService WHERE Name='Intel(r) AMT Alarm Clock Service'"); IManagedInstance alarmClockServiceInstance = alarmClockServiceRef.Get(); //Set property nextAMTAlarmTime. alarmClockServiceInstance.SetProperty("NextAMTAlarmTime", nextAlarmTime); alarmClockServiceInstance.SetProperty("AMTAlarmClockInterval", null); alarmClockServiceRef.Put(alarmClockServiceInstance); Console.WriteLine("The Alarm Clock will be activated just once. \n"); } /// /// Configure a single wake on. /// Intel AMT versions 8.0 and later. /// private void SingleWakeOnLaterVersions(DateTime nextAMTAlarmTime) { //To check the format of the string - "yy-mm-ddThh:mm:00Z" string newAlarmTime = String.Concat(nextAMTAlarmTime.ToString("s"), "Z"); Console.WriteLine("AMT Format: {0}", newAlarmTime); IManagedReference AlarmClockServiceRef = wsmanClient.NewReference("SELECT * FROM AMT_AlarmClockService WHERE Name='Intel(r) AMT Alarm Clock Service'"); IManagedInstance addAlarmInput = AlarmClockServiceRef.CreateMethodInput("AddAlarm"); // Set AlarmTemplate property with all the definitions of the alarm. // The alarm name must not exist already in the Intel AMT. IManagedInstance templateObj = wsmanClient.NewInstance(BuildAlarmTemplate(newAlarmTime, new TimeSpan(0), SAMPLE_ALARM_NAME).ToString()); addAlarmInput.SetProperty(null, templateObj); IManagedInstance returnValue; try { returnValue = AlarmClockServiceRef.InvokeMethod(addAlarmInput); } catch (Exception e) { throw new Exception("Failed to create alarm. Ensure all AlarmClock properties are valid. "); } if (returnValue.GetProperty("ReturnValue").ToString() != "0") { uint PT_STATUS; if (uint.TryParse(returnValue.GetProperty("ReturnValue").ToString(), out PT_STATUS)) { throw new Exception("Failed to create alarm. Return Value = " + returnValue); } } Console.WriteLine("The New Alarm Clock will be activated just once. \n"); } #endregion #region PUBLIC_FUNCTIONS /// /// Configure a single wake on. /// public void SingleWakeOn(DateTime nextAMTAlarmTime) { if (UtilitiesMethods.CompareVersions(UtilitiesMethods.GetCoreVersion(wsmanClient), "8.0") < 0) { SingleWakeOnEarlierVersions(nextAMTAlarmTime); } else { SingleWakeOnLaterVersions(nextAMTAlarmTime); } } /// /// Configure a periodic wake on. /// public void PeriodicWakeOn(DateTime nextAMTAlarmTime, DateTimeInterval AlarmClockInterval) { if (UtilitiesMethods.CompareVersions(UtilitiesMethods.GetCoreVersion(wsmanClient), "8.0") < 0) { PeriodicWakeOnEarlierVersions(nextAMTAlarmTime, AlarmClockInterval); } else { PeriodicWakeOnLaterVersions(nextAMTAlarmTime, AlarmClockInterval); } } /// /// Disables or deletes an alarm clock. /// public void DisableWakeOn() { if (UtilitiesMethods.CompareVersions(UtilitiesMethods.GetCoreVersion(wsmanClient), "8.0") < 0) { DisableWakeOnEarlierVersions(); } else { DeleteAlarmLaterVersions(SAMPLE_ALARM_NAME); } } /// /// Display the alarm clock settings. /// public void WakeOnInfo() { if (UtilitiesMethods.CompareVersions(UtilitiesMethods.GetCoreVersion(wsmanClient), "8.0") < 0) { WakeOnInfoEarlierVersions(); } else { WakeOnInfoLaterVersions(); } } /// /// Run API Test. /// public void RunAPITest() { if (UtilitiesMethods.CompareVersions(UtilitiesMethods.GetCoreVersion(wsmanClient), "8.0") < 0) { RunAPITestEarlierVersions(); } else { RunAPITestLaterVersions(); } } #endregion PUBLIC_FUNCTIONS } }