public string CAllApiMethod(GenericAddDto dto, string url, string access_token) { LogControl logControl = new LogControl(); string json2 = JsonConvert.SerializeObject(dto, Formatting.Indented); var buffer2 = System.Text.Encoding.UTF8.GetBytes(json2); var byteContent2 = new ByteArrayContent(buffer2); byteContent2.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpClient client = _api.Initial(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_token); HttpResponseMessage res = client.PostAsync(url, byteContent2).Result; string resposta = "FALHA"; if (res.IsSuccessStatusCode) { logControl.Write("Processamento de " + url + " Sucesso"); resposta = "SUCESSO"; } else { logControl.Write("Processamento de " + url + " Falha"); resposta = "FALHA"; } return(resposta); }
public string RegisterProject(string xml) { IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest; LogControl logControl = new LogControl(); CallApi api = new CallApi(); GenericAddDto dto = new GenericAddDto { Xml = xml }; string user = request.Headers["Usuario"]; string senha = request.Headers["Senha"]; string access_token = api.Login(user, senha).Result; if (String.IsNullOrEmpty(access_token)) { logControl.Write("Usuário e senha não conferem"); return(api.CAllApiMethod(dto, "/project", access_token)); } else { logControl.Write("Usuário logado"); return(api.CAllApiMethod(dto, "/project", access_token)); } }
private void RenewAccessToken() { string newAccessToken = HttpPost(AccessUri, this.apiKey); this.accessToken = newAccessToken; LogControl.Write("[TTS] : Authentification | Renew token"); }
public ScenarioThree(RecognitionCognitive _stt, CognitiveAccess _tts, SMSHandler _sms) { LogControl.Write("[[SCENARIO 3] START]"); stt = _stt; tts = _tts; smsHandler = _sms; }
private string WaitSMS() { try { LogControl.Write("[SCENARIO 2] : Attente d'un SMS"); string DateSMS = smsHandler.GetDateSMS(); string response = string.Empty; bool noResponse = true; while (noResponse) { response = smsHandler.GetDateSMS(); if (DateSMS != response) { noResponse = false; } } LogControl.Write(response); string Conten = smsHandler.GetContentSMS(); string[] counter = Conten.Split(new string[] { "<Content>", "</Content>" }, StringSplitOptions.RemoveEmptyEntries); return(counter[1]); } catch (IndexOutOfRangeException e) { LogControl.Write("Out of range"); return(""); } }
private string Listen() { LogControl.Write("[SCENARIO 2] : listening"); string phrase = @"mal"; bool search = true; string response = string.Empty; while (search) { if (!stt.Record(5)) { continue; } response = stt.SetupRequest(); foreach (string s in phrase.Split(' ')) { if (s == null || response == null) { continue; } if (response.Contains(s)) { search = false; } } } string tmp = response.Split(new string[] { "\"name\":\"", "\",\"lexical" }, StringSplitOptions.RemoveEmptyEntries)[1]; Console.WriteLine(tmp); return(tmp); }
private string Listen() { LogControl.Write("[SCENARIO 1] : listening"); string phrase = @"besoin aide"; bool search = true; string response = string.Empty; while (search) { if (!stt.Record()) { continue; } response = stt.SetupRequest(); foreach (string s in phrase.Split(' ')) { if (s == null || response == null) { continue; } if (response.Contains(s)) { search = false; } } } return("J'ai besoin d'aide, je suis tombé"); }
/// <summary> /// For Windows dev purpose /// </summary> /// <param name="mode"></param> private static void PrintMode(Mode mode) { switch (mode) { case Mode.Reflexion: LogControl.Write("[GPIOCONTROL] : Set Mode Reflexion"); break; case Mode.StandBy: LogControl.Write("[GPIOCONTROL] : Set Mode StandBy"); break; case Mode.Help: LogControl.Write("[GPIOCONTROL] : Set Mode Help"); break; case Mode.Speak: LogControl.Write("[GPIOCONTROL] : Set Mode Speak"); break; case Mode.Boot: LogControl.Write("[GPIOCONTROL] : Set Mode Boot"); break; } }
/// <summary> /// Handle the activation of the correct GPIO pin /// </summary> /// <param name="_mode">Enum for the selection mode</param> private static void LightMode(Mode _mode) { try { if (Init.WiringPiSetup() != -1) { GPIO.pinMode(_first, (int)GPIO.GPIOpinmode.Output); GPIO.pinMode(_second, (int)GPIO.GPIOpinmode.Output); GPIO.pinMode(_third, (int)GPIO.GPIOpinmode.Output); switch (_mode) { case Mode.Reflexion: GPIO.digitalWrite(_first, (int)State.LOW); GPIO.digitalWrite(_second, (int)State.LOW); GPIO.digitalWrite(_third, (int)State.LOW); LogControl.Write("[GPIOCONTROL] : Set Mode Reflexion"); break; case Mode.StandBy: GPIO.digitalWrite(_first, (int)State.LOW); GPIO.digitalWrite(_second, (int)State.HIGH); GPIO.digitalWrite(_third, (int)State.LOW); LogControl.Write("[GPIOCONTROL] : Set Mode StandBy"); break; case Mode.Help: GPIO.digitalWrite(_first, (int)State.LOW); GPIO.digitalWrite(_second, (int)State.HIGH); GPIO.digitalWrite(_third, (int)State.HIGH); LogControl.Write("[GPIOCONTROL] : Set Mode Help"); break; case Mode.Speak: GPIO.digitalWrite(_first, (int)State.LOW); GPIO.digitalWrite(_second, (int)State.LOW); GPIO.digitalWrite(_third, (int)State.HIGH); LogControl.Write("[GPIOCONTROL] : Set Mode Speak"); break; case Mode.Boot: GPIO.digitalWrite(_first, (int)State.HIGH); GPIO.digitalWrite(_second, (int)State.LOW); GPIO.digitalWrite(_third, (int)State.LOW); LogControl.Write("[GPIOCONTROL] : Set Mode Boot"); break; } } else { LogControl.Write("[GPIOCONTROLER] : Init Failed"); } } catch (Exception e) { LogControl.Write("[GPIOCONTROL] : Error | " + e.Message); } Thread.Sleep(50); }
public ScenarioTwo(RecognitionCognitive _stt, CognitiveAccess _tts, SMSHandler _sms, SoundPlayer _sound) { LogControl.Write("[SCENARIO 2] : Loaded]"); stt = _stt; tts = _tts; smsHandler = _sms; soundPlayer = _sound; }
private List <SMSContent> ParseInput(string output) { List <SMSContent> list = new List <SMSContent>(); int count = 0; string[] counter = output.Split(new string[] { "<count>", "</count>" }, StringSplitOptions.RemoveEmptyEntries); count = Int32.Parse(counter[1]); LogControl.Write("Counted " + count + " SMS"); string[] Msg = counter[2].Split(new string[] { "<Message>", "</Message>" }, StringSplitOptions.RemoveEmptyEntries); return(list); }
public string RegisterProject(string xml) { LogControl logControl = new LogControl(); CallApi api = new CallApi(); GenericAddDto dto = new GenericAddDto { Xml = xml }; if (Auth != null) { if (Auth.IsValid()) { string access_token = api.Login(Auth.Usuario, Auth.Senha).Result; if (String.IsNullOrEmpty(access_token)) { logControl.Write("Usuário e senha não conferem"); return(api.CAllApiMethod(dto, "/project", access_token)); } else { logControl.Write("Usuário logado"); return(api.CAllApiMethod(dto, "/project", access_token)); } } else { logControl.Write("Usuário e senha informados na requisição não conferem"); return("FALHA"); } } else { logControl.Write("Não foram informados usuário e senha no cabeçalho da requisição"); return("FALHA"); } }
public override void Start() { GPIOControl.SetLed(GPIOControl.Mode.Reflexion); LogControl.Write("[SCENARIO 2] : Start"); GPIOControl.SetLed(GPIOControl.Mode.StandBy); string response = WaitSMS(); GPIOControl.SetLed(GPIOControl.Mode.Speak); tts.Say(response); soundPlayer.Play(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "/say.wav"); string toSend = "\"" + Listen() + "\""; smsHandler.SendSMS("+41789476812", toSend); GPIOControl.SetLed(GPIOControl.Mode.Reflexion); Thread.Sleep(1000); GPIOControl.SetLed(GPIOControl.Mode.StandBy); }
public string GetDateSMS() { string count = ""; try { string Content = GetContentSMS(); count = ""; string[] counter = Content.Split(new string[] { "<Date>", "</Date>" }, StringSplitOptions.RemoveEmptyEntries); count = counter[1]; } catch (IndexOutOfRangeException outOfRange) { count = ""; } LogControl.Write("Date " + count); return(count); }
/// <summary> /// This method is called once the audio returned from the service. /// It will then attempt to save the audio file /// </summary> /// <param name="sender">The source of the event</param> /// <param name="args">The <see cref="cref="GenericEventArgs{Stream}"/> instance containing the event data</param> public void PlayAudio(object sender, GenericEventArgs <Stream> args) { /*The file should be encoded in PCM, with audio format AudioOutputFormat.Riff16Khz16BitMonoPcm.*/ try { LogControl.Write("[TTS] : Saving audio file"); Stream s = args.EventData; var fileStream = new FileStream(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "/say.wav", FileMode.OpenOrCreate, FileAccess.Write); s.CopyTo(fileStream); fileStream.Dispose(); s.Dispose(); } catch (Exception ex) { LogControl.Write("[TTS] : Saving file failed | ERROR : " + ex.Message); } LogControl.Write("[TTS] : File Saved"); }
public CognitiveAccess() { LogControl.Write("[TTS] : Starting Authentification"); Authentification auth = new Authentification(Key.BingSpeech); try { accessToken = auth.GetAccessToken(); LogControl.Write("[TTS] : Token = " + accessToken); } catch (Exception ex) { LogControl.Write("[TTS] : Failed authentification"); LogControl.Write("[TTS] : ERROR | " + ex.Message); return; } LogControl.Write("[TTS] : Authentification Correct"); }
public void Play(string _filePath) { try { LogControl.Write("[SOUNDPLAYER] : Playing sound"); ProcessStartInfo P = new ProcessStartInfo(); P.FileName = "aplay"; P.Arguments = _filePath; Process pro = Process.Start(P); //pro.StartInfo = P; //pro.Start(); //pro.WaitForExit(); //Console.ReadKey(); } catch (Exception e) { LogControl.Write("[SOUNDPLAYER] : ERROR | " + e.Message); } }
public override void Start() { LogControl.Write("[SCENARIO 1] : Start"); //Vérifie si ya un appel a l'aide string response = Listen(); tts.Say("Je suis en train de contacter des secours..."); soundPlayer.Play(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "/say.wav"); GPIOControl.SetLed(GPIOControl.Mode.Reflexion); Thread.Sleep(1000); //smsHandler.SendSMS("+41786268658", response); smsHandler.SendSMS("+41789476812", response); response = WaitSMS(); GPIOControl.SetLed(GPIOControl.Mode.Speak); tts.Say(response); soundPlayer.Play(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "/say.wav"); GPIOControl.SetLed(GPIOControl.Mode.Help); Thread.Sleep(10000); }
protected void UpdateCheck() { UpdateManager _UpdateManager = UpdateManager.Instance; LogControl.Write("[UpdateHandler] : Checking for updates"); _UpdateManager.BeginCheckForUpdates(asyncResult => { if (asyncResult.IsCompleted) { LogControl.Write("[UpdateHandler] : Check updates Completed"); //still need to check for caught exceptions if any and rethrow ((UpdateProcessAsyncResult)asyncResult).EndInvoke(); //no updates were found, or an error has occured... if (_UpdateManager.UpdatesAvailable == 0) { LogControl.Write("[UpdateHandler] : No update available"); return; } } TryUpdate(); }, null); }
/// <summary> /// Send a message using SendSMS.sh script in path /// </summary> /// <param name="_number">Phone number</param> /// <param name="_message">Payload</param> /// <returns></returns> public bool Send(string _number, string _message) { LogControl.Write("[SMS] : Sending an SMS"); try { ProcessStartInfo P = new ProcessStartInfo(); P.FileName = path + "/SendSMS.sh"; P.Arguments = _number + " " + _message; P.UseShellExecute = false; P.RedirectStandardOutput = true; Process pro = new Process(); pro.StartInfo = P; pro.Start(); pro.WaitForExit(); return(true); } catch (Exception e) { LogControl.Write("[SMS] : Error at send | " + e.Message); return(false); } }
internal string ReadSMSString() { List <SMSContent> listSMS = new List <SMSContent>(); ProcessStartInfo P = new ProcessStartInfo(); P.FileName = path + "/ReadSMS.sh"; P.RedirectStandardOutput = true; P.UseShellExecute = false; Process process = new Process(); process.StartInfo = P; process.Start(); string text = ""; while (!process.StandardOutput.EndOfStream) { text += process.StandardOutput.ReadLine(); } LogControl.Write("Text = " + text); process.WaitForExit(); return(text); }
private void OnTokenExpiredCallback(object stateInfo) { try { RenewAccessToken(); } catch (Exception ex) { LogControl.Write("[TTS] : Authentification | ERROR : Failed to renew access token. Details : " + ex.Message); } finally { try { accessTokenRenewer.Change(TimeSpan.FromMinutes(RefreshTokenDuration), TimeSpan.FromMilliseconds(-1)); } catch (Exception e) { LogControl.Write("[TTS] : Authentification | ERROR : Failed to reschedule the timer"); } } }
private void TryUpdate() { LogControl.Write("[UpdateHandler] : Updating"); UpdateManager.Instance.ReportProgress += status => { LogControl.Write("[UpdateHandler] : " + status.Percentage + "%"); }; UpdateManager.Instance.BeginPrepareUpdates(asyncResult => { try { UpdateManager.Instance.ApplyUpdates(false); } catch (Exception e) { LogControl.Write("[UpdateHandler] : ERROR Update | " + e.ToString()); } if (UpdateManager.Instance.State == UpdateManager.UpdateProcessState.RollbackRequired) { UpdateManager.Instance.RollbackUpdates(); } }, null); }
public bool CheckUpdate() { try { UpdateManager _UpdateManager = UpdateManager.Instance; _UpdateManager.UpdateSource = PrepareUpdateSource(); _UpdateManager.Config.TempFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "TMP"); _UpdateManager.ReinstateIfRestarted(); if (UpdateManager.Instance.State == UpdateManager.UpdateProcessState.Checked || UpdateManager.Instance.State == UpdateManager.UpdateProcessState.AfterRestart || UpdateManager.Instance.State == UpdateManager.UpdateProcessState.AppliedSuccessfully) { UpdateManager.Instance.CleanUp(); } UpdateCheck(); return(true); } catch (Exception e) { LogControl.Write("[UpdateHandler] : ERROR | " + e.ToString()); return(false); } }
public bool Record(int second = 3) { try { LogControl.Write("[RECORDING] : Start recording"); ProcessStartInfo P = new ProcessStartInfo(); P.FileName = "arecord"; P.Arguments = "-D plughw:2,0 -d " + second + " record.wav -f cd"; P.UseShellExecute = false; P.RedirectStandardOutput = true; Process pro = new Process(); pro.StartInfo = P; pro.Start(); pro.WaitForExit(); LogControl.Write("[RECORDING] : End recording"); } catch (Exception e) { LogControl.Write("[RECORDING] : ERROR | " + e); Thread.Sleep(3000); return(false); } return(true); }
private IUpdateSource PrepareUpdateSource() { LogControl.Write("[UpdateHandler] : Preparing Update Source"); return(new NAppUpdate.Framework.Sources.SimpleWebSource(source)); }
public static void Write(string format, params object[] args) => _logControl.Write(format, args);
private void button_OK_Click(object sender, RoutedEventArgs e) { // return; // Click to save the note //none of URI or note is available, there is nothing to save if (newNoteText.Length == 0 && newInfoItem == null) { return; } bNoteModified = false; bSkipModifyConfirmation = false; //use the title as note, if only URI is available if (newInfoItem != null && newNoteText.Length == 0) { newNoteText = newInfoItem.Title; } ComboBoxItem cbi_sel = (ComboBoxItem)comboBox_SaveLoc.SelectedItem; string xmlFileFullPath = cbi_sel.Tag.ToString(); Element parentElement = new Element { ParentElement = null, HeadImageSource = String.Empty, TailImageSource = String.Empty, NoteText = String.Empty, IsExpanded = true, Path = xmlFileFullPath, Type = ElementType.Heading, }; Element newElement = new Element { ParentElement = parentElement, HeadImageSource = String.Empty, TailImageSource = String.Empty, NoteText = newNoteText, IsExpanded = false, Path = xmlFileFullPath, Type = ElementType.Note, FontColor = ElementColor.Blue.ToString(), Status = ElementStatus.New, }; newElement.ParentElement = parentElement; newElement.Position = 0; if ((newInfoItem != null) && (bool)checkBox_URI.IsChecked) { ElementAssociationType newType; switch (newInfoItem.Type) { case InfoItemType.Email: newType = ElementAssociationType.Email; break; case InfoItemType.File: newType = ElementAssociationType.FileShortcut; break; case InfoItemType.Web: newType = ElementAssociationType.Web; break; default: newType = ElementAssociationType.None; break; } newElement.AssociationType = newType; } try { newElement.ParentElement.Elements.Insert(0, newElement); DatabaseControl temp_dbControl = new DatabaseControl(newElement.ParentElement.Path); temp_dbControl.OpenConnection(); temp_dbControl.InsertElementIntoXML(newElement); temp_dbControl.CloseConnection(); ElementControl elementControl = new ElementControl(newElement.ParentElement.Path); elementControl.CurrentElement = newElement; //if URI is available and selected, association will be added together with the note if ((newInfoItem != null) && (bool)checkBox_URI.IsChecked) { elementControl.AddAssociation(newElement, newInfoItem.Uri, newElement.AssociationType, newNoteText); } string eventInfo = LogEventInfo.NoteText + LogControl.COMMA + newElement.NoteText; if ((bool)checkBox_URI.IsChecked) { eventInfo += LogControl.DELIMITER + LogEventInfo.LinkStatus + LogControl.COMMA + "check"; } else { eventInfo += LogControl.DELIMITER + LogEventInfo.LinkStatus + LogControl.COMMA + "unCheck"; } if (newInfoItem != null && newInfoItem.Uri != null) { eventInfo += LogControl.DELIMITER + LogEventInfo.LinkedFile + LogControl.COMMA + newInfoItem.Uri; } eventInfo += LogControl.DELIMITER + LogEventInfo.PutUnder + LogControl.COMMA + newElement.Path; LogControl.Write( elementControl.CurrentElement, LogEventAccess.QuickCapture, LogEventType.CreateNewNote, LogEventStatus.NULL, eventInfo); newInfoItem = null; } catch (Exception ex) { System.Windows.MessageBox.Show("QuickCapture_button_OK_Click\n" + ex.Message); LogControl.Write( newElement, LogEventAccess.QuickCapture, LogEventType.CreateNewNote, LogEventStatus.Error, LogEventInfo.ErrorMessage + LogControl.COMMA + ex.Message); } ReInitilize(); this.Visibility = Visibility.Hidden; this.ShowInTaskbar = true; }
public void ErrorHandler(object sender, GenericEventArgs <Exception> e) { LogControl.Write("[TTS] : Unable to complete the TTS request | " + e.ToString()); }
public string SetupRequest() { string requestUri = @"https://speech.platform.bing.com/recognize"; /* URI Params. Refer to the README file for more information. */ requestUri += @"?scenarios=smd"; // websearch is the other main option. requestUri += @"&appid=D4D52672-91D7-4C74-8AD8-42B1D98141A5"; // You must use this ID. requestUri += @"&locale=fr-FR"; // We support several other languages. Refer to README file. requestUri += @"&device.os=wp7"; requestUri += @"&version=3.0"; requestUri += @"&format=json"; requestUri += @"&instanceid=565D69FF-E928-4B7E-87DA-9A750B96D9E3"; requestUri += @"&requestid=" + Guid.NewGuid().ToString(); string host = @"speech.platform.bing.com"; string contentType = @"audio/wav; codec=""audio/pcm""; samplerate=44100"; string audioFile = "record.wav"; string responseString; FileStream fs = null; try { var token = auth.GetAccessToken(); LogControl.Write("[RECOGNITION] : Token: " + token); LogControl.Write("[RECOGNITION] : Request Uri: " + requestUri); HttpWebRequest request = null; request = (HttpWebRequest)HttpWebRequest.Create(requestUri); request.SendChunked = true; request.Accept = @"application/json;text/xml"; request.Method = "POST"; request.ProtocolVersion = HttpVersion.Version11; request.Host = host; request.ContentType = contentType; request.Headers["Authorization"] = "Bearer " + token; System.Net.ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; using (fs = new FileStream(audioFile, FileMode.Open, FileAccess.Read)) { /* * Open a request stream and write 1024 byte chunks in the stream one at a time. */ byte[] buffer = null; int bytesRead = 0; using (Stream requestStream = request.GetRequestStream()) { /* * Read 1024 raw bytes from the input audio file. */ buffer = new Byte[checked ((uint)Math.Min(1024, (int)fs.Length))]; while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); } // Flush requestStream.Flush(); } /* * Get the response from the service. */ using (WebResponse response = request.GetResponse()) { LogControl.Write("[RECOGNITION] : HttpWebResponse.StatusCode : " + ((HttpWebResponse)response).StatusCode); using (StreamReader sr = new StreamReader(response.GetResponseStream())) { responseString = sr.ReadToEnd(); } LogControl.Write("[RECOGNITION] : Response" + responseString); return(responseString); } } } catch (Exception ex) { LogControl.Write("[RECOGNITION] : ERROR | " + ex.Message); } return(null); }