/// <summary> /// Helper method for initalizing the voice service, bridge, and lights. Returns if successful. /// </summary> private async Task <bool> InitializeAsync(AppServiceTriggerDetails triggerDetails) { _voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails); _voiceServiceConnection.VoiceCommandCompleted += (s, e) => _deferral.Complete(); _voiceCommand = await _voiceServiceConnection.GetVoiceCommandAsync(); _colors = HsbColor.CreateAll().ToDictionary(x => x.Name); var localStorage = ApplicationData.Current.LocalSettings.Values; _bridge = new Bridge( localStorage["bridgeIp"].ToString(), localStorage["userId"].ToString()); try { _lights = await _bridge.GetLightsAsync(); } catch (Exception) { var response = CreateCortanaResponse("Sorry, I couldn't connect to your bridge."); await _voiceServiceConnection.ReportFailureAsync(response); return(false); } if (!_lights.Any()) { var response = CreateCortanaResponse("Sorry, I couldn't find any lights."); await _voiceServiceConnection.ReportFailureAsync(response); return(false); } return(true); }
/// <summary> /// Prepares Cortana for background use. /// </summary> private async Task InitializeCortanaAsync() { // You can't write to application files by default, so we need to create a // secondary VCD file to dynamically write Cortana commands to. StorageFile dynamicFile = await ApplicationData.Current.RoamingFolder.CreateFileAsync( "VoiceCommands.xml", CreationCollisionOption.ReplaceExisting); // Load the base file and parse the PhraseList we want from it. StorageFile baseFile = await StorageFile.GetFileFromApplicationUriAsync( new Uri("ms-appx:///VoiceCommands.xml")); XDocument xml = XDocument.Load(baseFile.Path); XElement state = xml.Descendants().First(x => x.Name.LocalName == "PhraseList" && null != x.Attribute("Label") && x.Attribute("Label").Value == "state"); // A ColorMapping is a RGB and HSV compliant representation a system color. // ColorMapping.CreateAll() returns a ColorMapping for all system colors available to UWP apps. // For each ColorMapping, add it to the list of phrases Cortana knows. foreach (HsbColor color in HsbColor.CreateAll()) { state.Add(new XElement("Item", color.Name)); } // Add the light names. XElement names = xml.Descendants().First(x => x.Name.LocalName == "PhraseList" && null != x.Attribute("Label") && x.Attribute("Label").Value == "name"); foreach (Light light in _lights) { names.Add(new XElement("Item", light.Name)); } // Save the file, and then load so Cortana recognizes it. using (Stream stream = await dynamicFile.OpenStreamForWriteAsync()) { xml.Save(stream); } try { await VoiceCommandDefinitionManager.InstallCommandDefinitionsFromStorageFileAsync(dynamicFile); } catch (FileNotFoundException) { // Do nothing. This is a workaround for a spurious FileNotFoundException that // is thrown even though dynamicFile exists on disk. } }