public HttpResponseMessage Post(Governor gov) { if (gov == null) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } _rep.Create(gov); var response = Request.CreateResponse(HttpStatusCode.Created, gov); var odataPath = Request.GetODataPath(); if (odataPath == null) { throw new InvalidOperationException("There is no ODataPath in the request."); } var entitySetPathSegment = odataPath.Segments.FirstOrDefault() as EntitySetPathSegment; if (entitySetPathSegment == null) { throw new InvalidOperationException("ODataPath doesn't start with EntitySetPathSegment."); } response.Headers.Location = new Uri(Url.ODataLink(entitySetPathSegment, new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(gov.Id, ODataVersion.V3)))); //response.Headers.Location = new Uri(Url.ODataLink(new EntitySetPathSegment("Governors"), new KeyValuePathSegment(gov.Id.ToString()))); return(response); }
public void PublicAssetProfitReport(DateTime db, DateTime de, InsuranceType insType, Governor gov) { var rawReport = _rep.PublicAssetProfitReport(db, de, insType, gov != null ? gov.Id : (Guid?)null); string tempDir = Path.Combine(Path.GetTempPath(), "Access", "XsltReports"); string filePath = Path.Combine(tempDir, string.Format("AssetProfitReport{0:yyMMddHHmm}.xml", DateTime.Now)); Directory.CreateDirectory(tempDir); using (StreamWriter txtstream = File.CreateText(filePath)) { try { txtstream.Write(rawReport); } catch (Exception ex) { if (File.Exists(filePath)) File.Delete(filePath); throw new InvalidOperationException(string.Format("Ошибка при генерации файла отчета. " + Environment.NewLine + "Ошибка: {0}", ex.Message), ex); } } //var p = new System.Diagnostics.Process(); //p.StartInfo = new System.Diagnostics.ProcessStartInfo(filePath); //p.Start(); System.Diagnostics.Process.Start(filePath); }
public object ActivateEmptyModel() { Company c = new Company(); Governor g = new Governor(); g.CompanyId = c.Id; g.Company = c; return g; }
public object ActivateEmptyModel() { Company c = new Company(); Governor g = new Governor(); g.CompanyId = c.Id; g.Company = c; return(g); }
/// <summary> /// Extract from a FileEntry. /// </summary> /// <param name="fileEntry">The FileEntry containing the Conteant stream to parse.</param> /// <param name="opts">The ExtractorOptions to use</param> /// <param name="governor">The Resource governor to use (or null to create a new one).</param> /// <returns>The FileEntries found.</returns> public IEnumerable <FileEntry> Extract(FileEntry fileEntry, ExtractorOptions?opts = null, ResourceGovernor?governor = null) { var options = opts ?? new ExtractorOptions(); var Governor = governor; if (Governor == null) { Governor = new ResourceGovernor(options); Governor.ResetResourceGovernor(fileEntry.Content); } Logger.Trace("ExtractFile({0})", fileEntry.FullPath); Governor.CurrentOperationProcessedBytesLeft -= fileEntry.Content.Length; Governor.CheckResourceGovernor(); IEnumerable <FileEntry> result = Array.Empty <FileEntry>(); var useRaw = false; try { var type = MiniMagic.DetectFileType(fileEntry); if (type == ArchiveFileType.UNKNOWN || !Extractors.ContainsKey(type)) { useRaw = true; result = new[] { fileEntry }; } else { result = Extractors[type].Extract(fileEntry, options, Governor); } } catch (Exception ex) { Logger.Debug(ex, "Error extracting {0}: {1}", fileEntry.FullPath, ex.Message); useRaw = true; result = new[] { fileEntry }; } // After we are done with an archive subtract its bytes. Contents have been counted now separately if (!useRaw) { Governor.CurrentOperationProcessedBytesLeft += fileEntry.Content.Length; } return(result); }
public static Governor CreateGovernor(Company company, global::System.Guid companyId, string shortName, global::System.Guid ID) { Governor governor = new Governor(); if ((company == null)) { throw new global::System.ArgumentNullException("company"); } governor.Company = company; governor.CompanyId = companyId; governor.ShortName = shortName; governor.Id = ID; return(governor); }
protected override IEnumerable <AssetValue> ParseData(DataTable data) { if (data == null || data.Columns.Count < 4) { throw new InvalidOperationException("Несовместимый формат файла Excel для импорта данных по ДДС СЧА."); } string currentsgov = string.Empty; Governor currentgov = null; DataView dv = data.DefaultView; foreach (DataRowView r in dv) { //получаем дату из первой колонки string sdt = Convert.ToString(r[0]); DateTime dt = DateTime.Today; if (false == string.IsNullOrEmpty(sdt) && DateTime.TryParse(sdt, out dt)) { //получаем УК из 4ой колонки string sgov = Convert.ToString(r[3]).Trim(); if (false == string.IsNullOrEmpty(sgov)) { if (currentsgov != sgov) { currentsgov = sgov; currentgov = _governors.FirstOrDefault(g => currentsgov.Split(' ').Any(s => s == g.ShortName)); } if (currentgov != null) { //получаем цифирь из второй колонки string sval = Convert.ToString(r[1]); decimal val = 0; if (decimal.TryParse(sval, out val)) { yield return(new AssetValue() { TakingDate = dt, CashFlow = val, Governor = currentgov, GovernorId = currentgov.Id, InsuranceType = _insType }); } } } } } }
public override void _PhysicsProcess(float delta) { // GD.Print(lidHeight - lid.Position.y); calculatingPressure(); steamForce = new Vector2(P, 0); if (left == true && switching == true) { iteration++; GD.Print(iteration); switching = false; sumChange = 0; } //Code that makes all the pieces move according to the steam force smallRodLimiter.AngularVelocity = smallRodPipe.AngularVelocity; //code that stops the jank stopEngineWeirdness(); //Governor physics //calculating the force to apply to each sphere Governor.governorPhysics(wheel.AngularVelocity); Governor.liftLid(lid, lidLifter, lidInitialHeight, lidLifterInitialHeight); //code to keep the governor stable since can't put axis locks on 2d joints Governor.stopGovernorWeirdness(); //colour of particles in tank changeSteamColor(); //diagnostic if (largeRodPipe.RotationDegrees > maxRotation) { // maxRotation = largeRodPipe.RotationDegrees; sumChange += maxRotation - largeRodPipe.RotationDegrees; maxRotation = largeRodPipe.RotationDegrees; GD.Print(sumChange); } steamInputRate.Text = "Steam Input FLow Rate: " + flowRate; }
public override void ThreadFunction() { ErrorCallback(this, "Simulated device startup.", "", false); SetMode(new ModeCommand() { Mode = (int)IntenseMode.Mode, MA = IntenseMode.StartingMA }); bool should_exit = false; while (!should_exit) { Thread.Yield(); lock (_thread_interlock) { Governor.PruneHistory(); should_exit = _thread_end; } Thread.Sleep(50); QueueStateCallback(this, 0); } ErrorCallback(this, "Simulated device shutdown.", "", false); }
private void TransmitCommand() { ET232Command command = null; lock (_thread_interlock) { if (CommandQueue.Count > 0) { command = CommandQueue.First(); CommandQueue.RemoveAt(0); } } if (command != null) { if (command.IsWrite()) { if (command.Address == AddressByte.Pot_A) { lock (_thread_interlock) command.Data = Governor.RegulateA(command.Data); } if (command.Address == AddressByte.Pot_B) { lock (_thread_interlock) command.Data = Governor.RegulateB(command.Data); } } byte[] data = command.Format(); last_command = command; last_command_time = UnixTime.Current(); lock (_thread_interlock) { DeviceStream.Write(data, 0, data.Length); _state = State.command; } } }
protected override IEnumerable <AssetValue> ParseData(DataTable data) { if (data == null || data.Columns.Count < 3) { throw new InvalidOperationException("Несовместимый формат файла Excel для импорта данных по СЧА."); } DataView dv = data.DefaultView; foreach (DataRowView r in dv) { //получаем дату из первой колонки string sdt = Convert.ToString(r[0]); DateTime dt = DateTime.Today; if (false == string.IsNullOrEmpty(sdt) && DateTime.TryParse(sdt, out dt)) { //получаем УК начиная с 3ей колонки for (int i = 2; i < data.Columns.Count; i++) { string sgov = data.Columns[i].ColumnName; Governor gov = _governors.FirstOrDefault(g => sgov.Split(' ').Any(s => s == g.ShortName)); if (gov != null) { //получаем цифирь string sval = Convert.ToString(r[i]); decimal val = 0; decimal.TryParse(sval, out val); yield return(new AssetValue() { TakingDate = dt, Value = val, Governor = gov, GovernorId = gov.Id, InsuranceType = _insType }); } } } } }
public void AddToGovernors(Governor governor) { base.AddObject("Governors", governor); }
public HttpResponseMessage Put([FromODataUri] Guid key, Governor update) { _rep.Update(update); return(Request.CreateResponse(HttpStatusCode.NoContent)); }
public void AddToGovernors(Governor governor) { base.AddObject("Governors", governor); }
public void PublicAssetProfitReport(DateTime db, DateTime de, InsuranceType insType, Governor gov) { var rawReport = _rep.PublicAssetProfitReport(db, de, insType, gov != null ? gov.Id : (Guid?)null); string tempDir = Path.Combine(Path.GetTempPath(), "Access", "XsltReports"); string filePath = Path.Combine(tempDir, string.Format("AssetProfitReport{0:yyMMddHHmm}.xml", DateTime.Now)); Directory.CreateDirectory(tempDir); using (StreamWriter txtstream = File.CreateText(filePath)) { try { txtstream.Write(rawReport); } catch (Exception ex) { if (File.Exists(filePath)) { File.Delete(filePath); } throw new InvalidOperationException(string.Format("Ошибка при генерации файла отчета. " + Environment.NewLine + "Ошибка: {0}", ex.Message), ex); } } //var p = new System.Diagnostics.Process(); //p.StartInfo = new System.Diagnostics.ProcessStartInfo(filePath); //p.Start(); System.Diagnostics.Process.Start(filePath); }
public GovernorBrain(Governor gov) { this.governor = gov; }
private ServiceSpawner() { // Compile monitoring services. var createdServices = new List <string>(); try { m_logger = LoggerUtil.GetAppWideLogger(); var thisAppDir = AppDomain.CurrentDomain.BaseDirectory; foreach (var name in this.GetType().Assembly.GetManifestResourceNames()) { // Compile everything except our base protective service. if (name.IndexOf("Services", StringComparison.OrdinalIgnoreCase) != -1) { try { var serviceName = name.Substring(0, name.LastIndexOf('.')); serviceName = serviceName.Substring(serviceName.LastIndexOf('.') + 1); var res = CompileExe(name, string.Format("{0}{1}.exe", thisAppDir, serviceName)); if (res != null && res.Length > 0) { createdServices.Add(res); } } catch (Exception e) { if (m_logger != null) { LoggerUtil.RecursivelyLogException(m_logger, e); } } } } } catch (Exception e) { if (m_logger != null) { LoggerUtil.RecursivelyLogException(m_logger, e); } } try { // Start the governor. This will run a background thread // that will ensure our chain of protective processes are // run. m_governor = new Governor(); } catch (Exception e) { if (m_logger != null) { LoggerUtil.RecursivelyLogException(m_logger, e); } } try { using (TaskService service = new TaskService()) { Win32Task task = service.GetTask(serviceCheckTaskName); if (task != null) { service.RootFolder.DeleteTask(serviceCheckTaskName); } TaskDefinition def = service.NewTask(); def.RegistrationInfo.Description = "Ensures that CloudVeil is running"; def.Principal.LogonType = TaskLogonType.ServiceAccount; var thisAppDir = AppDomain.CurrentDomain.BaseDirectory; ExecAction action = new ExecAction(string.Format("{0}{1}.exe", thisAppDir, "FilterStarter.exe")); def.Actions.Add(action); LogonTrigger trigger = (LogonTrigger)def.Triggers.Add(new LogonTrigger()); trigger.Delay = new TimeSpan(0, 2, 0); service.RootFolder.RegisterTaskDefinition(serviceCheckTaskName, def); } } catch (Exception e) { if (m_logger != null) { LoggerUtil.RecursivelyLogException(m_logger, e); } } }
static void Main(string[] args) { OAuthProvider.Behavior = Activator.CreateInstance(OAuthConfiguration.Configuration.ClientSettings.WcfDSBehaviorType) as IOAuthBehavior; Logon.Page = new LogonProc(); var ctx = new WebApiCtx(); FilterParameterCollection fc = new FilterParameterCollection(); fc.Add("ShortName", "магомед ук"); SortParameterCollection sc = new SortParameterCollection(); sc.Add(null, "Company.Name", System.ComponentModel.ListSortDirection.Ascending); sc.Add(null, "Id", System.ComponentModel.ListSortDirection.Ascending); //var val = ctx.Governors.AddFilters(fc).AddOrders(sc).First(); //var val = ctx.Governors.First(); //val.Company.lawFormValue = 6; Guid g = new Guid("CEB5254F-5FFE-469B-ABC5-09AB388E6505"); //var val = ctx.Governors.Where(gov => gov.Id == g).FirstOrDefault(); Guid g2 = new Guid("CEB5254F-5FFE-469B-ABC5-09AB388E6505"); Governor val2 = null; //ctx.TryGetEntity(new Uri("http://localhost:555/Governors(guid'ceb5254f-5ffe-469b-abc5-09ab388e6505')"), out val2); //Governor val2 = ctx.Governors.Where(gov => gov.Id == g2).FirstOrDefault(); //val2 = ctx.Entities.FirstOrDefault(e => e.Identity.Contains("Governors(guid'ceb5254f-5ffe-469b-abc5-09ab388e6505')")).Entity as Governor; //val2 = ctx.Governors.GetById(g); ctx.Governors.ToList(); //Console.WriteLine(ctx.Governors.TotalCount()); //var ass = ctx.Assets.Where(a => a.Id == new Guid("D3B67671-87C5-4B33-8DF1-7D83947E5FB8")).First(); var ass = new AssetValue(); ass.Id = Guid.NewGuid(); ass.InsuranceTypeValue = 1; ass.TakingDate = DateTime.Today; ass.Value = 3344434.56m; ass.GovernorId = g2; string s = JsonConvert.SerializeObject(ass); var list = new List <string>(); list.Add(s); UriBuilder urib = new UriBuilder(ctx.BaseUri); //urib.Path = string.Format("{0}/CreateBatch", ctx.Assets.RequestUri.PathAndQuery); //var r = ctx.Execute<bool>(urib.Uri, "POST", true, new BodyOperationParameter("Values", list)).FirstOrDefault(); //ctx.AddToAssets(ass); //ctx.SetLink(ass, "Governor", val2); //ctx.SaveChanges(); //ctx.AttachLink(ass, "Governor", val2); //Guid g = new Guid("32D3F7C1-97E1-4A69-8C8A-E3706490329E"); //var val = ctx.Holidays.Where(h => h.Id == g).FirstOrDefault(); //val.Comment = "Test Comment"; var newc = new Company(); newc.Id = Guid.NewGuid(); newc.Name = "Test Governor Company Name"; var newg = new Governor(); newg.Id = Guid.NewGuid(); newg.ShortName = "Test Governor Name"; newg.Company = newc; ctx.AddToGovernors(newg); ctx.SaveChanges(); newg.ShortName = "Test Governor Name Updated"; ctx.UpdateObject(newg); //ctx.SaveChanges(SaveChangesOptions.PatchOnUpdate); System.Threading.Thread.Sleep(1000); ctx.SaveChanges(SaveChangesOptions.ReplaceOnUpdate); ctx.DeleteObject(newg); ctx.SaveChanges(); //var serviceCreds = new NetworkCredential("Administrator", "SecurePassword"); //var cache = new CredentialCache(); //var serviceUri = new Uri("http://ipv4.fiddler:333/api/issue"); //cache.Add(serviceUri, "Basic", serviceCreds); //ctx.Credentials = cache; //var r = ctx.Execute(new Uri("http://ipv4.fiddler:333/api/issue"), "POST", new BodyOperationParameter("rst", new TokenRequest() { GrantType = "client_credentials", Scope = "http://localhost" })); Console.ReadLine(); }
public override void ThreadFunction() { ErrorCallback(this, "ET232 connection started.", "Waiting for device handshake.", false); Initialize(); bool should_exit = false; byte[] device_inputs = Array.Empty <byte>(); // https://www.sparxeng.com/blog/software/must-use-net-system-io-ports-serialport byte[] read_buffer = new byte[1024]; void DataReader() { try { lock (_thread_interlock) DeviceStream.BeginRead(read_buffer, 0, read_buffer.Length, delegate(IAsyncResult ar) { try { lock (_thread_interlock) { if (DeviceStream == null) { return; } int len = DeviceStream.EndRead(ar); int pos = device_inputs.Length; Array.Resize(ref device_inputs, pos + len); Buffer.BlockCopy(read_buffer, 0, device_inputs, pos, len); } } catch (Exception e) { bool exiting; lock (_thread_interlock) exiting = _thread_end; if (!exiting) { ErrorCallback(this, "Device error.", e.Message, false); } } DataReader(); }, null); } catch (Exception e) { bool exiting; lock (_thread_interlock) exiting = _thread_end; if (!exiting) { ErrorCallback(this, "Device error.", e.Message, false); } } } DataReader(); while (!should_exit) { Thread.Yield(); State current_state; byte[] current_input_data; lock (_thread_interlock) { Governor.PruneHistory(); current_state = _state; current_input_data = device_inputs; device_inputs = Array.Empty <byte>(); } switch (current_state) { case State.init: CheckHandshake(ref current_input_data); break; case State.ready: TransmitCommand(); break; case State.command: CheckResponse(ref current_input_data); break; } lock (_thread_interlock) { int pos = current_input_data.Length; Array.Resize(ref current_input_data, pos + device_inputs.Length); Buffer.BlockCopy(device_inputs, 0, current_input_data, pos, device_inputs.Length); device_inputs = current_input_data; } QueueMaintenance(); lock (_thread_interlock) { should_exit = _thread_end; if (CommandQueue.Count > 0) { should_exit = false; } } if (last_command != null) { should_exit = false; } } lock (_thread_interlock) { if (DeviceStream != null) { DeviceStream.Close(); DeviceStream.Dispose(); } DeviceStream = null; } ErrorCallback(this, "ET232 disconnected.", "Device should now be unlocked. Switch it off before reconnecting.", false); }
private ServiceSpawner() { // Compile monitoring services. var createdServices = new List <string>(); try { m_logger = LoggerUtil.GetAppWideLogger(); var thisAppDir = AppDomain.CurrentDomain.BaseDirectory; foreach (var name in this.GetType().Assembly.GetManifestResourceNames()) { // Compile everything except our base protective service. if (name.IndexOf("Services", StringComparison.OrdinalIgnoreCase) != -1) { try { var serviceName = name.Substring(0, name.LastIndexOf('.')); serviceName = serviceName.Substring(serviceName.LastIndexOf('.') + 1); var res = CompileExe(name, string.Format("{0}{1}.exe", thisAppDir, serviceName)); if (res != null && res.Length > 0) { createdServices.Add(res); } } catch (Exception e) { if (m_logger != null) { LoggerUtil.RecursivelyLogException(m_logger, e); } } } } } catch (Exception e) { if (m_logger != null) { LoggerUtil.RecursivelyLogException(m_logger, e); } } try { // Start the governor. This will run a background thread // that will ensure our chain of protective processes are // run. m_governor = new Governor(); } catch (Exception e) { if (m_logger != null) { LoggerUtil.RecursivelyLogException(m_logger, e); } } }
public static Governor CreateGovernor(Company company, global::System.Guid companyId, string shortName, global::System.Guid ID) { Governor governor = new Governor(); if ((company == null)) { throw new global::System.ArgumentNullException("company"); } governor.Company = company; governor.CompanyId = companyId; governor.ShortName = shortName; governor.Id = ID; return governor; }
private ServiceSpawner() { // Compile monitoring services. var createdServices = new List <string>(); try { m_logger = LoggerUtil.GetAppWideLogger(); var thisAppDir = AppDomain.CurrentDomain.BaseDirectory; foreach (var name in this.GetType().Assembly.GetManifestResourceNames()) { // Compile everything except our base protective service. if (name.IndexOf("Services", StringComparison.OrdinalIgnoreCase) != -1) { var serviceName = name.Substring(0, name.LastIndexOf('.')); serviceName = serviceName.Substring(serviceName.LastIndexOf('.') + 1); string fileName = $"{thisAppDir}{serviceName}.exe"; try { var res = CompileExe(name, fileName); if (res != null && res.Length > 0) { createdServices.Add(res); } } catch (IOException e) { try { List <Process> lockingProcesses = FileLockingUtil.WhoIsLocking(fileName); if (lockingProcesses.Count == 0) { m_logger.Warn("IOException occurred, but no locking processes detected."); LoggerUtil.RecursivelyLogException(m_logger, e); } else { StringBuilder messageBuilder = new StringBuilder(); messageBuilder.AppendLine($"Could not compile protective service because it was already opened by {(lockingProcesses.Count > 1 ? "other processes" : "another process")}"); foreach (Process process in lockingProcesses) { messageBuilder.AppendLine($"\tProcess {process.Id}: {process.ProcessName}"); } m_logger.Warn(messageBuilder.ToString()); } } catch (Exception fileException) { m_logger.Warn("Exception occurred while finding process which locked {0}", fileName); LoggerUtil.RecursivelyLogException(m_logger, fileException); LoggerUtil.RecursivelyLogException(m_logger, e); } } catch (Exception e) { if (m_logger != null) { LoggerUtil.RecursivelyLogException(m_logger, e); } } } } } catch (Exception e) { if (m_logger != null) { LoggerUtil.RecursivelyLogException(m_logger, e); } } try { // Start the governor. This will run a background thread // that will ensure our chain of protective processes are // run. m_governor = new Governor(); } catch (Exception e) { if (m_logger != null) { LoggerUtil.RecursivelyLogException(m_logger, e); } } try { using (TaskService service = new TaskService()) { Win32Task task = service.GetTask(serviceCheckTaskName); if (task != null) { service.RootFolder.DeleteTask(serviceCheckTaskName); } TaskDefinition def = service.NewTask(); def.RegistrationInfo.Description = "Ensures that CloudVeil is running"; def.Principal.LogonType = TaskLogonType.ServiceAccount; var thisAppDir = AppDomain.CurrentDomain.BaseDirectory; ExecAction action = new ExecAction(string.Format("{0}{1}.exe", thisAppDir, "FilterAgent.Windows.exe"), "start"); def.Actions.Add(action); LogonTrigger trigger = (LogonTrigger)def.Triggers.Add(new LogonTrigger()); trigger.Delay = new TimeSpan(0, 2, 0); service.RootFolder.RegisterTaskDefinition(serviceCheckTaskName, def); } } catch (Exception e) { if (m_logger != null) { LoggerUtil.RecursivelyLogException(m_logger, e); } } }
private void CheckResponse(ref byte[] input) { double current_unixtime = UnixTime.Current(); int expected_bytes = last_command.IsWrite() ? et232_success_sequence.Length : et232_read_response_length; if (input.Length < expected_bytes) { if (current_unixtime - last_command_time > command_timeout) { HandleCommandFailure("Device timeout."); input = Array.Empty <byte>(); } return; } byte[] result_bytes = input; int extra_bytes = result_bytes.Length - expected_bytes; if (extra_bytes > 0) { input = new byte[extra_bytes]; Buffer.BlockCopy(result_bytes, expected_bytes, input, 0, extra_bytes); } else { input = Array.Empty <byte>(); } bool error = false; if (last_command.IsWrite()) { for (int idx = 0; idx < et232_success_sequence.Length; idx++) { if (result_bytes[idx] != et232_success_sequence[idx]) { error = true; } } } else if (result_bytes.Last() != (byte)'\n') { error = true; } if (error) { HandleCommandFailure("Device error."); return; } int ScalingFunction(int user_level, int function) { return((int)(Math.Sqrt(user_level * function))); } command_retries = 0; if (last_command.IsWrite()) { if (last_command.Address == AddressByte.Pot_A) { lock (_thread_interlock) { Governor.RecordA(last_command.Data); LastA = last_command.Data; } } if (last_command.Address == AddressByte.Pot_B) { lock (_thread_interlock) { Governor.RecordB(last_command.Data); LastB = last_command.Data; } } if (last_command.Address == AddressByte.Pot_MA) { lock (_thread_interlock) LastMA = last_command.Data; } if (last_command.Address == AddressByte.ModeOverride) { lock (_thread_interlock) draining_queue = true; Thread.Sleep(mode_delay); StateUpdatedCallback(this, (int)last_command.Address, last_command.Data & ErosTek.ET232.Constants.ForceModeMask); } else { StateUpdatedCallback(this, (int)last_command.Address, last_command.Data); } } else { string result_string = Encoding.ASCII.GetString(result_bytes, 0, 2); try { int result_value = int.Parse(result_string, System.Globalization.NumberStyles.HexNumber); DataReturnedCallback(this, (int)last_command.Address, result_value); LevelEvent level = new LevelEvent() { unixtime = current_unixtime, level = result_value }; if (last_command.Address == AddressByte.PulseAmp_A) { lock (_thread_interlock) { level.level = ScalingFunction(LastA, level.level); AmpHistoryA.Add(level); } } if (last_command.Address == AddressByte.PulseAmp_B) { lock (_thread_interlock) { level.level = ScalingFunction(LastB, level.level); AmpHistoryB.Add(level); } } } catch (Exception) { List <string> details = result_bytes.Select(e => String.Format("0x{0,2:X2}", new object[] { e })).ToList(); ErrorCallback(this, "Device returned invalid data.", "Bytes: " + input.Length + " Data: " + String.Join(", ", details), false); } } last_command = null; lock (_thread_interlock) _state = State.ready; }