public static Dictionary <AppArchitecture_t, string> ReadAppManifest(string filePath) { using (FileStream fs = File.OpenRead(filePath)) { var reader = new RawDataReader(fs, Encoding.UTF8); byte[] sign = Encoding.UTF8.GetBytes(APP_MANIFEST_SIGNATURE); foreach (byte b in sign) { if (b != reader.ReadByte()) { throw new CorruptedFileException(filePath); } } int nbKey = reader.ReadInt(); var dict = new Dictionary <AppArchitecture_t, string>(nbKey); for (int i = 0; i < nbKey; ++i) { byte arch = reader.ReadByte(); if (!Enum.IsDefined(typeof(AppArchitecture_t), arch)) { throw new CorruptedFileException(filePath); } string fileName = reader.ReadString(); dict[(AppArchitecture_t)arch] = fileName; } return(dict); } }
public void Restore(string filePath, string destFolder) { Initializing?.Invoke(); using (FileStream fs = File.OpenRead(filePath)) { var reader = new RawDataReader(fs, Encoding.UTF8); byte[] sign = Signature; foreach (byte b in sign) { if (reader.ReadByte() != b) { throw new CorruptedFileException(filePath); } } reader.ReadTime(); //ignore creation time int headerLen = reader.ReadInt(); reader.ReadBytes(headerLen); //ignore header Restoring?.Invoke(); var bag = new FilesBag(); Clean(destFolder); bag.Decompress(fs, destFolder); Done?.Invoke(); } }
public static IEnumerable <Message> ReadHubDialog(string filePath, uint clID) { using (FileLocker.Lock(filePath)) using (FileStream fs = File.OpenRead(filePath)) { var reader = new RawDataReader(fs, Encoding.UTF8); byte[] sign = HubDialogSignature; foreach (byte b in sign) { if (reader.ReadByte() != b) { throw new CorruptedFileException(filePath); } } uint id = reader.ReadUInt(); if (id != clID) { throw new CorruptedFileException(filePath); } int count = reader.ReadInt(); var msgs = new List <Message>(count); for (int i = 0; i < count; ++i) { msgs.Add(Message.LoadMessage(reader)); } return(msgs); } }
public static IEnumerable <ProfileInfo> ReadProfiles(string filePath) { byte[] sign = ProfileSignature; using (FileLocker.Lock(filePath)) using (FileStream fs = File.OpenRead(filePath)) { var reader = new RawDataReader(fs, Encoding.UTF8); foreach (byte b in sign) { if (reader.ReadByte() != b) { throw new CorruptedFileException(filePath); } } int count = reader.ReadInt(); var prInfos = new List <ProfileInfo>(count); for (int i = 0; i < count; ++i) { prInfos.Add(ProfileInfo.LoadProfileInfo(reader)); } return(prInfos); } }
public IArchiveContent GetArchiveContent(string filePath) { var archData = new ArchiveContent(); using (FileStream fs = File.OpenRead(filePath)) { var reader = new RawDataReader(fs, Encoding.UTF8); byte[] sign = Signature; foreach (byte b in sign) { if (reader.ReadByte() != b) { throw new CorruptedFileException(filePath); } } archData.CreationTime = reader.ReadTime(); int len = reader.ReadInt(); archData.ArchiveHeader = reader.ReadBytes(len); archData.Files = FilesBag.GetContent(fs); return(archData); } }
void LoadAppSettings() { if (!File.Exists(AppSettingsFilePath)) { return; } using (FileStream fs = File.OpenRead(AppSettingsFilePath)) using (var xs = new XorStream(fs)) using (var gzs = new GZipStream(xs, CompressionMode.Decompress)) { var reader = new RawDataReader(xs, Encoding.UTF8); byte[] sign = Encoding.UTF8.GetBytes(APP_SETTINGS_SIGNATURE); for (int i = 0; i < sign.Length; ++i) { if (sign[i] != reader.ReadByte()) { throw new CorruptedFileException(AppSettingsFilePath); } } m_dataGeneration = reader.ReadUInt(); m_updateKey = reader.ReadUInt(); } }
public static IEnumerable <Message> ReadConnectionsReq(string filePath) { byte[] sign = HubCxnSignature; using (FileLocker.Lock(filePath)) using (FileStream fs = File.OpenRead(filePath)) { var reader = new RawDataReader(fs, Encoding.UTF8); foreach (byte b in sign) { if (reader.ReadByte() != b) { throw new CorruptedFileException(filePath); } } int count = reader.ReadInt(); var cxns = new List <Message>(count); for (int i = 0; i < count; ++i) { cxns.Add(Message.LoadMessage(reader)); } return(cxns); } }
public static IEnumerable <TableUpdate> LoadTablesUpdate(string filePath, IDatumFactory dataFactory) { using (FileStream fs = File.OpenRead(filePath)) { var reader = new RawDataReader(fs, Encoding.UTF8); byte[] sign = Encoding.UTF8.GetBytes(TABLES_UPDATE_SIGNATURE); for (int i = 0; i < sign.Length; ++i) { if (reader.ReadByte() != sign[i]) { throw new CorruptedFileException(filePath); } } int tableCount = reader.ReadInt(); var lst = new List <TableUpdate>(tableCount); for (int i = 0; i < tableCount; ++i) { lst.Add(LoadTableUpdate(reader, dataFactory)); } return(lst); } }
public static IEnumerable <UpdateURI> ReadDataManifest(string filePath, uint startGeneration = 0) { using (FileStream fs = File.OpenRead(filePath)) { var reader = new RawDataReader(fs, Encoding.UTF8); byte[] sign = Encoding.UTF8.GetBytes(DATA_MANIFEST_SIGNATURE); for (int i = 0; i < sign.Length; ++i) { if (reader.ReadByte() != sign[i]) { throw new CorruptedFileException(filePath); } } int uriCount = reader.ReadInt(); var lst = new List <UpdateURI>(); for (int i = 0; i < uriCount; ++i) { uint preGen = reader.ReadUInt(); uint postGen = reader.ReadUInt(); string uri = reader.ReadString(); if (preGen >= startGeneration) { lst.Add(new UpdateURI(uri, preGen, postGen)); } } return(lst); } }
public static void AppendConnectionsResp(string filePath, IEnumerable <Message> messages) { Assert(messages != null); using (FileLocker.Lock(filePath)) using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite)) { var reader = new RawDataReader(fs, Encoding.UTF8); int countPos = SrvCxnSignature.Length;; fs.Position = countPos; int msgCount = reader.ReadInt(); var writer = new RawDataWriter(fs, Encoding.UTF8); fs.Seek(0, SeekOrigin.End); foreach (Message msg in messages) { msg.Write(writer); ++msgCount; } fs.Position = countPos; writer.Write(msgCount); } }
public void ResizeTable(uint tableID, int szDatum) { Assert(Tables[tableID] != null); Assert(szDatum >= Tables[tableID].DatumSize); lock (m_lock) { IDBTable tbl = GetTable(tableID, true); if (tbl.DatumSize < szDatum) { string tmpFile = Path.GetTempFileName(); using (new AutoReleaser(() => File.Delete(tmpFile))) using (FileStream fs = File.Create(tmpFile)) { var tmpWriter = new RawDataWriter(fs, Encoding.UTF8); IDBTableProvider dp = m_accessPath.GetDataProvider(tableID); using (dp.Lock()) { foreach (IDataRow row in dp.Enumerate()) { row.Write(tmpWriter); } var tmpReader = new RawDataReader(fs, Encoding.UTF8); int count = dp.Count; BeginTableProcessing?.Invoke(tableID); using (new AutoReleaser(() => EndTableProcessing?.Invoke(tableID))) { uint ver = tbl.Version; uint tag = tbl.Tag; dp.Disconnect(); tbl.Disconnect(); File.Delete(tbl.FilePath); tbl.Create(szDatum, tag); dp.Connect(); fs.Position = 0; for (int i = 0; i < count; ++i) { IDataRow datum = m_dataFactory.CreateDatum(tableID); datum.Read(tmpReader); dp.Insert(datum); } tbl.Version = ver; tbl.Flush(); } } } } } }
public void Decompress(string filePath, string destFolder) { using (FileStream fs = File.OpenRead(filePath)) using (var gzs = new GZipStream(fs, CompressionMode.Decompress)) { var reader = new RawDataReader(gzs, Encoding.UTF8); foreach (byte b in Signature) { if (b != reader.ReadByte()) { throw new CorruptedFileException(filePath); } } int nbDir = reader.ReadInt(); var folders = new List <string>(nbDir); for (int i = 0; i < nbDir; ++i) { string dir = Path.Combine(destFolder, reader.ReadString()); folders.Add(dir); Directory.CreateDirectory(dir); } int nbFile = reader.ReadInt(); for (int i = 0; i < nbFile; ++i) { string file = reader.ReadString(); int ndxDir = reader.ReadInt(); if (ndxDir == NDX_CUR_FOLDER) { file = Path.Combine(destFolder, file); } else { file = Path.Combine(folders[ndxDir], file); } long fileLen = reader.ReadLong(); CreateFile(gzs, file, fileLen); FileDecompressed?.Invoke(file); } } }
public async Task <ActionResult <BestMatch> > PostWebM() { await using var ms = new MemoryStream(); await Request.Body.CopyToAsync(ms); ms.Position = 0; var ff = new CSCore.WaveFormat(48000, 16, 2, AudioEncoding.IeeeFloat); var dr = new RawDataReader(ms, ff); await using var outs = new MemoryStream(); dr.WriteToWaveStream(outs); var bytes = outs.ToArray(); return(await MatchFingerprintAsWav(bytes)); }
public static IEnumerable <string> GetContent(string filePath) { using (FileStream fs = File.OpenRead(filePath)) using (var gzs = new GZipStream(fs, CompressionMode.Decompress)) { var reader = new RawDataReader(gzs, Encoding.UTF8); foreach (byte b in Signature) { if (b != reader.ReadByte()) { throw new CorruptedFileException(filePath); } } int nbDir = reader.ReadInt(); var folders = new List <string>(nbDir); for (int i = 0; i < nbDir; ++i) { string dir = reader.ReadString(); folders.Add(dir); } int nbFile = reader.ReadInt(); var files = new List <string>(nbFile); for (int i = 0; i < nbFile; ++i) { string file = reader.ReadString(); int ndxDir = reader.ReadInt(); if (ndxDir != NDX_CUR_FOLDER) { file = Path.Combine(folders[ndxDir], file); } files.Add(file); long fileLen = reader.ReadLong(); reader.Skip((int)fileLen); } return(files); } }
public async Task ExecuteAsync(CancellationToken cancellationToken, IProgress <BatchAnonymizeProgressDetail> progress = null) { List <Task <IEnumerable <TResult> > > executionTasks = new List <Task <IEnumerable <TResult> > >(); List <TSource> batchData = new List <TSource>(); TSource content; while ((content = await RawDataReader.NextAsync().ConfigureAwait(false)) != null) { if (cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(); } batchData.Add(content); if (batchData.Count < BatchSize) { continue; } executionTasks.Add(AnonymizeAsync(batchData, progress, cancellationToken)); batchData = new List <TSource>(); if (executionTasks.Count < PartitionCount) { continue; } await ConsumeExecutionResultTask(executionTasks, progress).ConfigureAwait(false); } if (batchData.Count > 0) { executionTasks.Add(AnonymizeAsync(batchData, progress, cancellationToken)); } while (executionTasks.Count > 0) { await ConsumeExecutionResultTask(executionTasks, progress).ConfigureAwait(false); } if (AnonymizedDataConsumer != null) { await AnonymizedDataConsumer.CompleteAsync().ConfigureAwait(false); } }
void LoadUserSettings() { //if (!File.Exists(UserSettingsFilePath)) // return; using (FileStream fs = File.OpenRead(UserSettingsFilePath)) using (var xs = new XorStream(fs)) using (var gzs = new GZipStream(xs, CompressionMode.Decompress)) { var reader = new RawDataReader(xs, Encoding.UTF8); byte[] sign = Encoding.UTF8.GetBytes(USER_SETTINGS_SIGNATURE); for (int i = 0; i < sign.Length; ++i) { if (sign[i] != reader.ReadByte()) { throw new CorruptedFileException(UserSettingsFilePath); } } IsMaximized = reader.ReadBoolean(); int x = reader.ReadInt(); int y = reader.ReadInt(); int w = reader.ReadInt(); int h = reader.ReadInt(); FrameRectangle = new Rectangle(x, y, w, h); UseCountryCode = reader.ReadBoolean(); int mruSize = reader.ReadInt(); int mruCount = reader.ReadInt(); MRUSubHeading = new MRUList <SubHeading>(mruSize); for (int i = 0; i < mruCount; ++i) { MRUSubHeading.Add(new SubHeading(reader.ReadULong())); } AutoDetectProxy = reader.ReadBoolean(); EnableProxy = reader.ReadBoolean(); ProxyHost = reader.ReadString(); ProxyPort = reader.ReadUShort(); } }
public static ClientDialog ReadSrvDialog(string filePath) { using (FileLocker.Lock(filePath)) using (FileStream fs = File.OpenRead(filePath)) { var reader = new RawDataReader(fs, Encoding.UTF8); byte[] sign = SrvDialogSignature; foreach (byte b in sign) { if (reader.ReadByte() != b) { throw new CorruptedFileException(filePath); } } return(ClientDialog.LoadClientDialog(reader)); } }
private void LoadCsvButton_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Csv files (*.csv)|*.csv|Text files (*.txt)|*.txt"; if (openFileDialog.ShowDialog() == true) { try { string fileName = openFileDialog.FileName; clusterData = RawDataReader.ReadFromCsv(fileName, ';'); RefreshInputGrid(); } catch { MessageBox.Show("Failed to load csv - wrong Format?", "Loading failed.", MessageBoxButton.OK, MessageBoxImage.Error); } } }
void Load() { FileStream fs = null; try { fs = File.OpenRead(SettingsManager.RunOnceFilePath); var reader = new RawDataReader(fs, Encoding.UTF8); byte[] sign = Signature; foreach (byte b in sign) { if (b != reader.ReadByte()) { throw new CorruptedFileException(SettingsManager.RunOnceFilePath); } } int actCount = reader.ReadInt(); for (int i = 0; i < actCount; ++i) { var code = (RunOnceAction_t)reader.ReadInt(); IRunOnceCommand act = m_actBuilder[code](); act.Read(reader); m_actions.Add(act); } } catch (Exception ex) { Dbg.Log(ex.Message); m_actions.Clear(); } finally { if (fs != null) { fs.Dispose(); } } }
public static void UpdateDataManifest(string filePath, UpdateURI updateURI) { Assert(updateURI != null); using (FileStream fs = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { var writer = new RawDataWriter(fs, Encoding.UTF8); byte[] sign = Encoding.UTF8.GetBytes(DATA_MANIFEST_SIGNATURE); if (fs.Length == 0) { writer.Write(sign); writer.Write(1); } else { var reader = new RawDataReader(fs, Encoding.UTF8); for (int i = 0; i < sign.Length; ++i) { if (reader.ReadByte() != sign[i]) { throw new CorruptedFileException(filePath); } } int uriCount = reader.ReadInt(); fs.Position -= sizeof(int); writer.Write(uriCount + 1); fs.Seek(0, SeekOrigin.End); } writer.Write(updateURI.DataPreGeneration); writer.Write(updateURI.DataPostGeneration); writer.Write(updateURI.FileURI); } }
void LoadData() { using (FileStream fs = File.OpenRead(m_dataFilePath)) { var reader = new RawDataReader(fs, Encoding.UTF8); byte[] sign = FileSignature; foreach (byte b in sign) { if (b != reader.ReadByte()) { throw new CorruptedFileException(m_dataFilePath); } } int count = reader.ReadInt(); for (int i = 0; i < count; ++i) { m_entries.Add(Entry.LoadEntry(reader)); } } }
Message ProcessLogMessage(Message msg, uint clID) { Dbg.Assert(msg.MessageCode == Message_t.Log); var ms = new MemoryStream(msg.Data); var reader = new RawDataReader(ms, Encoding.UTF8); DateTime tm = reader.ReadTime(); bool isErr = reader.ReadBoolean(); string txt = reader.ReadString(); if (isErr) { AppContext.LogManager.LogSysActivity($"Réception log d'erreur du client {ClientStrID(clID)}"); AppContext.LogManager.LogClientError(clID, txt, tm); } else { AppContext.LogManager.LogSysActivity($"Réception d'un log d'activité du client {ClientStrID(clID)}"); AppContext.LogManager.LogClientActivity(clID, txt, tm); } return(null); }
private Action <ReplaySelectDialogModel> OnReplaySelectDialogClose(bool response, CustomDialog customDialog) { return(obj => { Parent.SyncContext.Send(d => { Parent.DialogCoordinator.HideMetroDialogAsync(Parent, customDialog); }, null); Parent.SyncContext.Post(d => { Task.Factory.StartNew(async() => { ReplaySelectDialogModel replaySelectDialogModel = obj as ReplaySelectDialogModel; if (replaySelectDialogModel.SelectedFile != null) { MetroDialogSettings settings = new MetroDialogSettings() { AnimateShow = false, AnimateHide = false }; var controller = await Parent.DialogCoordinator.ShowProgressAsync(Parent, "Please wait...", "Photometric calibration!", settings: Parent.MetroDialogSettings); controller.SetCancelable(false); controller.SetIndeterminate(); string file = null; string outputPath = null; double fxO = 0.0; double fyO = 0.0; double cxO = 0.0; double cyO = 0.0; double fxN = 0.0; double fyN = 0.0; double cxN = 0.0; double cyN = 0.0; double k1 = 0.0; double k2 = 0.0; double k3 = 0.0; double k4 = 0.0; int width = 0; int height = 0; List <double> responseValues = new List <double>(); Parent.SyncContext.Send(d2 => { file = replaySelectDialogModel.SelectedFile.FullPath; outputPath = Path.Combine(Path.GetTempPath(), "firefly", Guid.NewGuid().ToString()); fxO = Parent.CameraViewModel.OrginalCameraMatrix.GetValue(0, 0); fyO = Parent.CameraViewModel.OrginalCameraMatrix.GetValue(1, 1); cxO = Parent.CameraViewModel.OrginalCameraMatrix.GetValue(0, 2); cyO = Parent.CameraViewModel.OrginalCameraMatrix.GetValue(1, 2); fxN = Parent.CameraViewModel.NewCameraMatrix.GetValue(0, 0); fyN = Parent.CameraViewModel.NewCameraMatrix.GetValue(1, 1); cxN = Parent.CameraViewModel.NewCameraMatrix.GetValue(0, 2); cyN = Parent.CameraViewModel.NewCameraMatrix.GetValue(1, 2); k1 = Parent.CameraViewModel.DistortionCoefficients.GetValue(0, 0); k2 = Parent.CameraViewModel.DistortionCoefficients.GetValue(0, 1); k3 = Parent.CameraViewModel.DistortionCoefficients.GetValue(0, 2); k4 = Parent.CameraViewModel.DistortionCoefficients.GetValue(0, 3); if (!response) { responseValues.AddRange(ResponseValues.Select(f => f.Y)); } width = Parent.CameraViewModel.ImageWidth; height = Parent.CameraViewModel.ImageHeight; }, null); RawDataReader reader = new RawDataReader(file, RawReaderMode.Camera0); reader.Open(); PhotometricCalibratrionExporter exporter = new PhotometricCalibratrionExporter(fxO, fyO, cxO, cyO, fxN, fyN, cxN, cyN, width, height, k1, k2, k3, k4, outputPath, response, responseValues); exporter.Open(); exporter.AddFromReader(reader, delegate(double percent) { double value = percent * 0.33; value = value > 1 ? 1 : value; controller.SetProgress(value); }); exporter.Close(); reader.Close(); Process p = new Process(); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.StartInfo.WorkingDirectory = outputPath; p.StartInfo.CreateNoWindow = true; p.EnableRaisingEvents = true; string options = ""; if (response) { p.StartInfo.FileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Tools", "responseCalib.exe"); } else { p.StartInfo.FileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Tools", "vignetteCalib.exe"); options = "facW=7 facH=7"; } p.StartInfo.Arguments = string.Format("{0}\\ -noGUI -showPercent {1}", outputPath, options); p.OutputDataReceived += new DataReceivedEventHandler((s, e) => { Debug.WriteLine(e.Data); if (!string.IsNullOrEmpty(e.Data)) { foreach (string line in e.Data.Split('\n')) { if (line.StartsWith("percent: ")) { double percent = double.Parse(line.Replace("percent: ", ""), CultureInfo.InvariantCulture); double value = 0.33 + percent * 0.66; value = value > 1 ? 1 : value; controller.SetProgress(value); } } } } ); p.Exited += new EventHandler((s, e) => { Parent.SyncContext.Post(async x => { if (response) { ParseResponseResult(outputPath); } else { ParseVignetteResult(outputPath); } Directory.Delete(outputPath, true); await controller.CloseAsync(); }, null); }); p.Start(); p.BeginOutputReadLine(); } }, TaskCreationOptions.LongRunning); }, null); }); }
private void TTS(string currentMessage, int voiceID, bool cleverBot) { if (lastChatMessage != currentMessage) { lastChatMessage = currentMessage; Regex rgx; List <byte> ttsArray = new List <byte>(); foreach (string s in regexPattern) { rgx = new Regex(s); currentMessage = rgx.Replace(currentMessage, ""); } for (int x = 0; x <= filter.GetUpperBound(0); x++) { currentMessage = currentMessage.Replace(filter[x, 0], filter[x, 1]); } if (!GetDialTonesEnabled()) { rgx = new Regex(@"\[:dial([^\]]+)\]"); currentMessage = rgx.Replace(currentMessage, ""); } rgx = new Regex(@"(\[(?:[a-zA-Z]+)<[\d,]+>\])"); string[] splitMessages = rgx.Split(currentMessage); currentMessage = ""; foreach (string message in splitMessages) { rgx = new Regex(@"\[(?:[a-zA-Z]+)<([\d,]+)>\]"); var match = rgx.Match(message); if (match.Success) { int value = 0; Int32.TryParse(match.Groups[1].ToString().Split(',')[0], out value); if (value <= 2000 && value != 0) { currentMessage += message; } } else { currentMessage += message; } } rgx = new Regex(@"(\[vp\])"); if (rgx.Match(currentMessage).Success) { string songString = currentMessage.Substring(4); rgx = new Regex(@"(\[[ \da-zA-Z]+\])"); splitMessages = rgx.Split(songString); foreach (string message in splitMessages) { rgx = new Regex(@"\[([ \da-zA-Z]+)\]"); var match = rgx.Match(message); int frequency = 0; double multiplier = 1; double milis = GetVPTempo(); if (match.Success) { List <List <short> > superSine = new List <List <short> >(); try { foreach (char c in match.Groups[1].ToString()) { List <string> tone = tones.FirstOrDefault(stringToCheck => stringToCheck.Contains(c.ToString())); if (tone[0] == "{" || tone[0] == "}") { Double.TryParse(tone[1], out multiplier); } else { Int32.TryParse(tone[1], out frequency); superSine.Add(GenerateSineRaw(frequency, milis * multiplier)); } } ttsArray.AddRange(CombineSineWaves(superSine)); } catch (Exception) { } } else { foreach (char c in message) { List <string> tone = tones.FirstOrDefault(stringToCheck => stringToCheck.Contains(c.ToString())); Console.WriteLine(tone); try { if (tone[0] == "{" || tone[0] == "}") { Double.TryParse(tone[1], out multiplier); } else { Int32.TryParse(tone[1], out frequency); ttsArray.AddRange(GenerateSine(frequency, milis * multiplier)); } } catch (Exception) { } } } } } else { rgx = new Regex(@"([^ \dA-Za-z!""#$%&()*0,\-./:;<=>?@[\\\]^_`'{|}~\n\r])+"); var match = rgx.Match(currentMessage); if (!match.Success) { rgx = new Regex(@"(\[:(?:tone|t)[ \d,]+\])"); splitMessages = rgx.Split(currentMessage); foreach (string message in splitMessages) { rgx = new Regex(@"\[:(?:tone|t)([ \d,]+)\]"); match = rgx.Match(message); if (match.Success) { int frequency = 0; int milis = 0; string[] values = match.Groups[1].ToString().Split(','); if (values.Length > 1) { Int32.TryParse(values[0], out frequency); Int32.TryParse(values[1], out milis); } if (frequency != 0 && milis != 0) { ttsArray.AddRange(GenerateSine(frequency, milis)); } } else { tts.Voice = (TtsVoice)voiceID; ttsArray.AddRange(tts.SpeakToMemory(message)); } } } } using (MemoryStream wavStream = new MemoryStream(Generate(ttsArray.ToArray()))) { try { using (var waveOut = new WaveOut { Device = new WaveOutDevice(GetDeviceID()) }) { using (var waveSource = new RawDataReader(wavStream, new WaveFormat(11025, 16, 1))) { waveOut.Initialize(waveSource); waveOut.Play(); ttsWavs.Add(waveOut); waveOut.WaitForStopped(); } } } catch (Exception) { } } } if (GetCleverbotEnabled() && !cleverBot) { if (currentMessage.Length >= 1) { SendToCleverbotAsync(currentMessage); } } if (GetChatModeID() == 1 && queuedMessage.Length > 0) { string input = queuedMessage; new Thread(delegate() { TTS(input); }).Start(); queuedMessage = ""; } else { playNext = true; } }
public UpdateBuilder() { m_memReader = new RawDataReader(m_memStream, System.Text.Encoding.UTF8); m_memWriter = new RawDataWriter(m_memStream, System.Text.Encoding.UTF8); }
public void ReplayOffline(RawDataReader reader, Action <TimeSpan> updateTime, Action onClose, Func <bool> isPaused, Func <bool> isStopped) { _Tasks.Add(Task.Factory.StartNew(() => { ProxyMode = IOProxyMode.Offline; Stopwatch watch = new Stopwatch(); watch.Start(); int nextTimeUpdate = 1000; long startTime = -1; int currentTime = 0; while (reader.HasNext()) { while (isPaused()) { watch.Stop(); Thread.Sleep(500); watch.Start(); } if (isStopped()) { break; } Tuple <long, List <Tuple <RawReaderMode, object> > > res = reader.Next(); if (startTime == -1) { startTime = res.Item1; } ImuEventData imuEventData = null; CameraEventData cameraEventData = null; int rawSize = 0; byte[] rawImage = null; byte[] rawImu = null; double exposureTime = 0.0; foreach (Tuple <RawReaderMode, object> val in res.Item2) { if (val.Item1 == RawReaderMode.Imu0) { imuEventData = ImuEventData.Parse(res.Item1, (Tuple <double, double, double, double, double, double>)val.Item2, res.Item2.Any(c => c.Item1 == RawReaderMode.Camera0)); rawSize += imuEventData.RawSize; rawImu = imuEventData.GetRaw(_SettingContainer.Settings.ImuSettings.GyroscopeScale, _SettingContainer.Settings.ImuSettings.AccelerometerScale, _SettingContainer.Settings.ImuSettings.TemperatureScale, _SettingContainer.Settings.ImuSettings.TemperatureOffset); } if (val.Item1 == RawReaderMode.Camera0) { cameraEventData = CameraEventData.Parse(((Tuple <double, byte[]>)val.Item2).Item2, 0, false, ((Tuple <double, byte[]>)val.Item2).Item1); rawSize += cameraEventData.RawSize; rawImage = ((Tuple <double, byte[]>)val.Item2).Item2; exposureTime = ((Tuple <double, byte[]>)val.Item2).Item1; } } if (ConnectivityState == LinkUpConnectivityState.Connected) { if (rawSize > 0) { byte[] data = new byte[rawSize]; Array.Copy(rawImu, data, rawImu.Length); if (rawImage != null) { Array.Copy(BitConverter.GetBytes(exposureTime), 0, data, imuEventData.RawSize, sizeof(double)); Array.Copy(rawImage, 0, data, imuEventData.RawSize + sizeof(double), rawImage.Length); } _ReplayDataSend.AsyncCall(data); } } else { _BackgroundQueue.Add(new Tuple <ImuEventData, CameraEventData>(imuEventData, cameraEventData)); } currentTime += reader.DeltaTimeMs; int sleep = (int)(currentTime - watch.ElapsedMilliseconds); if (sleep > reader.DeltaTimeMs) { Thread.Sleep(sleep); } if (res.Item1 / 1000 > nextTimeUpdate) { nextTimeUpdate += 1000; updateTime(reader.Length - TimeSpan.FromMilliseconds((res.Item1 - startTime) / (1000 * 1000))); } } reader.Close(); ProxyMode = IOProxyMode.Live; onClose(); }, TaskCreationOptions.LongRunning)); }
Message ProcessNewConnectionReq(Message msg) { Dbg.Assert(msg.MessageCode == Message_t.NewConnection); //TextLogger.Info("Réception d’une nouvelle requête d’inscription."); var ms = new MemoryStream(msg.Data); var reader = new RawDataReader(ms, Encoding.UTF8); ClientInfo clInfo = ClientInfo.LoadClientInfo(reader); ClientEnvironment clEnv = ClientEnvironment.Load(reader); byte[] data = BitConverter.GetBytes(clInfo.ClientID); var profile = m_ndxerProfiles.Get(clInfo.ProfileID) as UserProfile; string reqLog = $"Réception d'une demande d’inscription émanant de {clInfo.ContactName}" + $"(ID = {ClientStrID(clInfo.ClientID)}) pour " + (profile == null ? "un profil inexistant." : $"le profil {profile.Name}."); AppContext.LogManager.LogSysActivity(reqLog, true); //verifier que le profil existe if (profile == null) { AppContext.LogManager.LogSysActivity("Lancement de la procédure d’actualisation " + "de la liste des profils sur le serveur", true); ProcessProfilesChange(); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.InvalidProfile, data)); } //verifier que ClientID n'existe pas var clSameID = m_ndxerClients.Get(clInfo.ClientID) as HubClient; if (clSameID != null) { AppContext.LogManager.LogSysActivity("Collision d’identifiants: " + $"un client portant le même ID est déjà enregistré ({clSameID.ContactName}). " + "Exiger au client de reformuler son inscription avec un nouvel ID", true); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.InvalidID, data)); } //verifier que le profile est en mode auto ManagementMode_t prfMgmntMode = GetProfileManagementMode(clInfo.ProfileID); if (prfMgmntMode == ManagementMode_t.Manual) { AppContext.LogManager.LogSysActivity("Profil en gestion manuelle, inscription rejetée.", true); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.Rejected, data)); } TextLogger.Info("Profil en gestion automatique."); TextLogger.Info("Enregistrement du client..."); //desactiver l'ancien client actif si il existe var oldClient = GetProfileEnabledClient(clInfo.ProfileID); if (oldClient != null) { if (IsClientRunning(oldClient.ID)) { //rejeter l'inscription AppContext.LogManager.LogSysActivity($"Un client pour le profil {profile.Name} est déjà en cours d’exécution. " + "Inscription rejetée", true); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.Rejected, data)); } AppContext.LogManager.LogSysActivity($"Désactivation du client {ClientStrID(oldClient.ID)}", true); //maj la table des status clients var oldClStatus = m_ndxerClientsStatus.Get(oldClient.ID) as ClientStatus; oldClStatus.Status = ClientStatus_t.Disabled; int ndx = m_ndxerClientsStatus.IndexOf(oldClStatus.ID); m_ndxerClientsStatus.Source.Replace(ndx, oldClStatus); //maj des fichiers de dialogue de old client string filePath = AppPaths.GetSrvDialogFilePath(oldClient.ID); ClientDialog clDlg = new ClientDialog(oldClient.ID, ClientStatus_t.Disabled, Enumerable.Empty <Message>()); DialogEngin.WriteSrvDialog(filePath, clDlg); AddUpload(Names.GetSrvDialogFile(oldClient.ID)); } //creer le fichier dialogue string srvDlgPath = AppPaths.GetSrvDialogFilePath(clInfo.ClientID); DialogEngin.WriteSrvDialog(srvDlgPath, new ClientDialog(clInfo.ClientID, ClientStatus_t.Enabled, Enumerable.Empty <Message>())); DialogEngin.WriteHubDialog(AppPaths.GetClientDilogFilePath(clInfo.ClientID), clInfo.ClientID, Enumerable.Empty <Message>()); try { new NetEngin(AppContext.Settings.NetworkSettings).Upload(Urls.DialogDirURL, new string[] { AppPaths.GetClientDilogFilePath(clInfo.ClientID), AppPaths.GetSrvDialogFilePath(clInfo.ClientID) }); } catch (Exception ex) { AppContext.LogManager.LogSysError($"Traitement de la requête d'inscription du client {ClientStrID(clInfo.ClientID)}: " + $"{ ex.Message}. demande ignorée, laisser le client reformuler la requête", true); return(null); // let the cleint retry req. } //maj la table des clients var hClient = new HubClient(clInfo.ClientID, clInfo.ProfileID) { ContaclEMail = clInfo.ContaclEMail, ContactName = clInfo.ContactName, ContactPhone = clInfo.ContactPhone, }; m_ndxerClients.Source.Insert(hClient); //maj du status client var clStatus = new ClientStatus(clInfo.ClientID, ClientStatus_t.Enabled); m_ndxerClientsStatus.Source.Insert(clStatus); //maj du client env UpdateClientEnvironment(clInfo.ClientID, clEnv); //maj du dict des clients actifs m_onlineClients.Add(clInfo.ClientID); AppContext.LogManager.StartLogger(clInfo.ClientID); AppContext.LogManager.LogClientActivity(clInfo.ClientID, "Inscription"); ClientStarted?.Invoke(clInfo.ClientID); AppContext.LogManager.LogSysActivity($"Inscription du client {clInfo.ClientID} terminée", true); TextLogger.Info("Inscription réussie. :-)"); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.Ok, data)); }
private Task DoLoadFromFile(object o) { return(Task.Factory.StartNew(() => { Parent.SyncContext.Post(c => { CustomDialog customDialog = new CustomDialog() { Title = "Select calibration file" }; var dataContext = new ReplaySelectDialogModel(obj => { Parent.SyncContext.Post(d => { Task.Factory.StartNew(async() => { ReplaySelectDialogModel replaySelectDialogModel = obj as ReplaySelectDialogModel; if (replaySelectDialogModel.SelectedFile != null) { MetroDialogSettings settings = new MetroDialogSettings() { AnimateShow = false, AnimateHide = false }; var controller = await Parent.DialogCoordinator.ShowProgressAsync(Parent, "Please wait...", "Loading calibration images!", settings: Parent.MetroDialogSettings); controller.SetCancelable(false); controller.SetIndeterminate(); string file = null; string outputPath = null; Parent.SyncContext.Send(async d2 => { file = replaySelectDialogModel.SelectedFile.FullPath; outputPath = Path.Combine(Path.GetTempPath(), "firefly", Guid.NewGuid().ToString()); }, null); RawDataReader reader = new RawDataReader(file, RawReaderMode.Camera0); reader.Open(); MemoryImageExporter exporter = new MemoryImageExporter(); exporter.AddFromReader(reader, delegate(double percent) { double value = percent; value = value > 1 ? 1 : value; controller.SetProgress(value); }); reader.Close(); Parent.SyncContext.Post(d2 => { int i = 0; int count = exporter.Images.Count; foreach (Mat m in exporter.Images) { //double value = 0.5 + i / count * 0.5; //value = value > 1 ? 1 : value; //controller.SetProgress(value); if (i++ % 20 == 0) { int squaresX = Parent.SettingContainer.Settings.CalibrationSettings.ChArucoCalibrationSettings.SquaresX; int squaresY = Parent.SettingContainer.Settings.CalibrationSettings.ChArucoCalibrationSettings.SquaresY; float squareLength = Parent.SettingContainer.Settings.CalibrationSettings.ChArucoCalibrationSettings.SquareLength; float markerLength = Parent.SettingContainer.Settings.CalibrationSettings.ChArucoCalibrationSettings.MarkerLength; PredefinedDictionaryName dictionary = Parent.SettingContainer.Settings.CalibrationSettings.ChArucoCalibrationSettings.Dictionary; ChArUcoImageContainer cauic = new ChArUcoImageContainer(squaresX, squaresY, squareLength, markerLength, dictionary); CvImageContainer container = new CvImageContainer(); container.CvImage = m; cauic.OriginalImage = container; Images.Add(cauic); } } controller.CloseAsync(); }, null); } }, TaskCreationOptions.LongRunning); Parent.DialogCoordinator.HideMetroDialogAsync(Parent, customDialog); }, null); }); Parent.ReplayViewModel.Refresh(); dataContext.FilesForReplay.AddRange(Parent.ReplayViewModel.FilesForReplay.Where(x => !x.Item1.IsRemote)); customDialog.Content = new ReplaySelectDialog { DataContext = dataContext }; Parent.DialogCoordinator.ShowMetroDialogAsync(Parent, customDialog); }, null); })); }
Message ProcessStartMessage(Message msg) { Dbg.Assert(msg.MessageCode == Message_t.Start); var reader = new RawDataReader(new MemoryStream(msg.Data), Encoding.UTF8); uint clID = reader.ReadUInt(); ClientEnvironment clEnv = ClientEnvironment.Load(reader); DateTime dtStart = reader.ReadTime(); var client = m_ndxerClients.Get(clID) as HubClient; if (client == null) { AppContext.LogManager.LogSysActivity("Réception d’une notification de démarrage " + $"de la part d’un client inexistant ({ClientStrID(clID)}). Réinitialisation du client", true); //maj du fichier gov string srvDlgFile = AppPaths.GetSrvDialogFilePath(clID); //le client n'existe pas => son fichier gov n'existe pas var clDlg = new ClientDialog(clID, ClientStatus_t.Reseted, Enumerable.Empty <Message>()); DialogEngin.WriteSrvDialog(srvDlgFile, clDlg); AddUpload(Path.GetFileName(srvDlgFile)); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.Rejected, msg.Data)); } AppContext.LogManager.LogSysActivity("Réception d’une notification de démarrage " + $"de la part du client {ClientStrID(clID)}", true); //verifier le statut du client var clStatus = m_ndxerClientsStatus.Get(clID) as ClientStatus; if (clStatus.Status != ClientStatus_t.Enabled) { AppContext.LogManager.LogSysActivity($"Démmarage du Client { ClientStrID(clID)} non autorisé. Requête rejetée", true); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.Rejected, msg.Data)); } //reset dlg files DialogEngin.WriteHubDialog(AppPaths.GetClientDilogFilePath(clID), clID, Enumerable.Empty <Message>()); DialogEngin.WriteSrvDialog(AppPaths.GetSrvDialogFilePath(clID), new ClientDialog(clID, clStatus.Status, Enumerable.Empty <Message>())); try { new NetEngin(AppContext.Settings.NetworkSettings).Upload(Urls.DialogDirURL, new string[] { AppPaths.GetClientDilogFilePath(clID), AppPaths.GetSrvDialogFilePath(clID) }); } catch (Exception ex) { AppContext.LogManager.LogSysError($"Traitement de la requête de démarrage du client {ClientStrID(clID)}: " + $"{ ex.Message}. demande ignorée, laisser le client reformuler la requête.", true); return(null); // let the cleint retry req. } AppContext.LogManager.LogSysActivity($"Client {ClientStrID(clID)} démarré le { dtStart.Date.ToShortDateString()} " + $"à { dtStart.ToLongTimeString()}", true); //verifier si l'env du client a changé UpdateClientEnvironment(clID, clEnv); //ajouter client dans running liste m_onlineClients.Add(clID, dtStart); AppContext.LogManager.StartLogger(clID); AppContext.LogManager.LogClientActivity(clID, "Démarrage"); //maj du last seen clStatus.LastSeen = dtStart; m_ndxerClientsStatus.Source.Replace(m_ndxerClientsStatus.IndexOf(clID), clStatus); ClientStarted?.Invoke(clID); return(msg.CreateResponse(++m_lastCnxRespMsgID, Message_t.Ok, msg.Data)); }
Message ProcessSyncMessage(Message msg) { Dbg.Assert(msg.MessageCode == Message_t.Sync); var ms = new MemoryStream(msg.Data); var reader = new RawDataReader(ms, Encoding.UTF8); uint clID = reader.ReadUInt(); uint srvMsgID = reader.ReadUInt(); uint clMsgId = reader.ReadUInt(); AppContext.LogManager.LogSysActivity($"Reception d'un message de synchronisation du client {ClientStrID(clID)}", true); ActiveClientsQueue.IClientData clData = m_onlineClients.Get(clID); if (clData != null) { clData.TimeToLive = ActiveClientsQueue.InitTimeToLive; var resp = new Message(++clData.LastSrvMessageID, 0, Message_t.Null); DialogEngin.AppendSrvDialog(AppPaths.GetSrvDialogFilePath(clID), resp); AddUpload(Names.GetSrvDialogFile(clID)); //maj status var clStatus = m_ndxerClientsStatus.Get(clID) as ClientStatus; clStatus.LastSeen = DateTime.Now; ++clStatus.ReceivedMsgCount; m_ndxerClientsStatus.Source.Replace(m_ndxerClientsStatus.IndexOf(clID), clStatus); return(null); } var client = m_ndxerClients.Get(clID) as HubClient; if (client == null) { AppContext.LogManager.LogSysActivity("Réception d’une demande de synchronisation " + $"de la part d’un client inexistant ({ClientStrID(clID)}). Réinitialisation du client", true); //maj du fichier gov string srvDlgFile = AppPaths.GetSrvDialogFilePath(clID); //le client n'existe pas => son fichier gov n'existe pas var clDlg = new ClientDialog(clID, ClientStatus_t.Reseted, Enumerable.Empty <Message>()); DialogEngin.WriteSrvDialog(srvDlgFile, clDlg); AddUpload(Path.GetFileName(srvDlgFile)); return(null); } var status = m_ndxerClientsStatus.Get(clID) as ClientStatus; var respMsg = new Message(++srvMsgID, 0, Message_t.Null); var dlg = new ClientDialog(clID, status.Status, new Message[] { respMsg }); DialogEngin.WriteSrvDialog(AppPaths.GetSrvDialogFilePath(clID), dlg); AddUpload(Names.GetSrvDialogFile(clID)); if (status.Status == ClientStatus_t.Enabled) { ActiveClientsQueue.IClientData clientData = m_onlineClients.Add(clID); clientData.LastClientMessageID = clMsgId; clientData.LastSrvMessageID = srvMsgID; AppContext.LogManager.StartLogger(clID); } return(null); }