/// <summary> /// Collects the current state of the agent regarding collisions and steering angles. /// </summary> private void CollectData(float currentSteeringAngle) { // add small rotation to camera for more randomization float rr = randomRotationDeg; cam.transform.localRotation = Quaternion.Euler(Random.Range(-rr, rr) + pitchoffset, Random.Range(-rr, rr), Random.Range(-rr, rr)); // capture flow image string imgName = dataCounter.ToString("0000000"); flowCam.Save(imgName, imageWidth, imageHeight, outputFolder); // add last dataset with current steering angle and crash data lastData.steeringAngle = currentSteeringAngle; data.Add(lastData); // create new dataset for next step CollectedData newData = new CollectedData(currentID, imgName, dataCounter, 0, crashed ? 1 : 0, transform.position, transform.rotation.eulerAngles, isSteeringData ? 1 : 0, currentObstacleID, currentEpoch); // update last data lastData = newData; dataCounter++; }
static void OnDataAcquired(CollectedData data) { watch.Stop(); long ms = watch.ElapsedMilliseconds; if (data == null) { WriteLine("Null collected data"); } else if (data.DataIsCollected) { foreach (Data d in data.D) { HandleData(d); } } else { WriteLine("Data collection failure"); if (string.IsNullOrEmpty(data.Message) == false) { WriteLine(data.Message); } } WriteLine($"Collection took {ms} ms"); }
private void OnDataAcquired(CollectedData data) { DeviceInfo di = DataContext as DeviceInfo; if (data.DataIsCollected) { if (data.D != null && data.D.Count > 0) { GenericDictionaryData <DriveInfo> dict = (GenericDictionaryData <DriveInfo>)data.D[0]; if (dict != null) { Dictionary <string, DriveInfo> d2 = dict.Data; di.monitoredDrives.Clear(); di.monitoredDrives.AddRange(new List <DriveInfo>(dict.Data.Values)); UpdateDriveList(); } } } else { string message = "Data collection failure"; if (string.IsNullOrEmpty(data.Message) == false) { message += "\n" + data.Message; } MessageBox.Show(message, "Drive list retrieval", MessageBoxButton.OK, MessageBoxImage.Error); } }
public async Task <IActionResult> Edit(int id, [Bind("Id,Floor,Elevator,Shift")] CollectedData collectedData) { if (id != collectedData.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(collectedData); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CollectedDataExists(collectedData.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(collectedData)); }
public override CollectedData OnAcquire() { CollectedData capacity_data = m_capacity.OnAcquire(); CollectedData free_data = m_free.OnAcquire(); Data data = null; if (capacity_data.DataIsCollected && free_data.DataIsCollected) { if (capacity_data.D.Count > 0 && free_data.D.Count > 0) { Data capacity = capacity_data.D[0]; Data free = free_data.D[0]; ulong?c = capacity.ValueAsUInt64; ulong?f = free.ValueAsUInt64; if (c.HasValue && f.HasValue) { MemoryUsage usage = new MemoryUsage() { CapacityNum = c.Value, FreeNum = f.Value }; data = new GenericData <MemoryUsage>(Context, usage); //UInt64 used = c.Value - f.Value; //d.Data["Memory Capacity"] = capacity.Value.ToString(); //d.Data["Free Memory"] = free.Value.ToString(); //d.Data["Memory Used"] = used.ToString(); } } } return(new CollectedData(Context, data != null, data)); }
public override void OnEpochFinished(Projection[] data) { double epochError = cumulatedEpochError / data.Length; CollectedData.Add(epochError); cumulatedEpochError = 0; OnEpoch(epochError); }
public static CollectedData GetFakeData(Guid collectedDataId, Guid instanceId) { var processNames = new List <string>() { "Google_Chrome", "Steam_updater", "explorer", "devenv", "Telegram", "slack", "zoom", "mongodbcompass" }; var random = new Random(); var processData = new List <ProcessData>(); int processes = random.Next(0, 7); for (int i = 0; i < processes; i++) { //ProcessesCPU.Add(processNames[i], (float)random.NextDouble() * 10); processData.Add(new ProcessData() { Name = processNames[i], RamMBytes = (float)random.NextDouble() * 10, PRam = (float)random.NextDouble() * 10, PCpu = (float)random.NextDouble() * 10 }); } var data = new CollectedData { Id = collectedDataId, ClientId = instanceId, // Guid.Parse("7FE193DE-B3DC-4DF5-8646-A81EDBE047E2"), // instanceId CollectedDataType = CollectedDataType.Accumulation, ProcessesCount = random.Next(0, 300), Processes = processData, UsageRamMBytes = (float)Math.Round(random.NextDouble() * 100, 2), TotalRamMBytes = (float)Math.Round(random.NextDouble() * 100, 2), RamUsagePercentage = (float)Math.Round(random.NextDouble() * 100, 2), InterruptsPerSeconds = random.Next(100, 4096), LocalDiskUsageMBytes = (float)Math.Round(random.NextDouble() * 100, 2), LocalDiskTotalMBytes = random.Next(0, 100), LocalDiskUsagePercentage = random.Next(0, 1000000000), CpuUsagePercentage = random.Next(0, 100), Time = DateTime.UtcNow }; return(data); }
public bool SendData(CollectedData data) { var settings = new ConnectionSettings(new Uri("http://192.168.0.223:9200")).DefaultIndex("logus"); var client = new ElasticClient(settings); IndexResponse indexResponse = client.IndexDocument(data); return(indexResponse.IsValid); }
public async Task <IActionResult> Create([Bind("Id,Floor,Elevator,Shift")] CollectedData collectedData) { if (ModelState.IsValid) { _context.Add(collectedData); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(collectedData)); }
public void InsertWaterTemperatureSensorCollect() { ISensor water = new WaterTemperatureSensor(); water.ECUValue = 1.60F; water.Name = "MTE"; CollectedData data = new CollectedData(water); var result = new ElasticConnection().SendData(data); Assert.AreEqual(true, result); }
public override CollectedData OnAcquire() { List <string> drive_names = new List <string>(); AttributeRequest request = new AttributeRequest(Context.ID.Name + ".all.drives.descriptions", true); RequestBus.Instance.MakeRequest(request); if (request.IsHandled) { try { Dictionary <string, string> dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(request.Value); drive_names = new List <string>(dict.Keys); } catch (Exception) { } } CollectedData basedata = base.OnAcquire(); List <Data> dataList = new List <Data>(); if (basedata.DataIsCollected) { List <DictionaryData> speedData = basedata.D.Select(w => w as DictionaryData).ToList(); while (speedData.Count > 0) { var speed = speedData[0]; speedData.RemoveAt(0); if (speed.Data.ContainsKey("PercentDiskTime") == false || speed.Data.ContainsKey("AvgDiskQueueLength") == false || speed.Data.ContainsKey("Name") == false) { continue; } var d = new DictionaryData(Context); string drive_name = speed.Data["Name"].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Last(); d.Data["Disk Time %"] = speed.Data["PercentDiskTime"]; d.Data["Avg Disk Q Length"] = speed.Data["AvgDiskQueueLength"]; d.Data["Disk Name"] = drive_name; bool is_total = drive_name.ToLower().Contains("total"); if (is_total == false && (drive_names.Count == 0 || drive_names.Contains(drive_name.ToUpper()))) { dataList.Add(d); } } } return(new CollectedData(Context, basedata.DataIsCollected && dataList.Count > 0, dataList)); }
public void InsertAirTemperatureSensorCollect() { ISensor air = new AirTemperatureSensor(); air.ECUValue = 2.80F; air.Name = "MTE"; CollectedData data = new CollectedData(air); var result = new ElasticConnection().SendData(data); Assert.AreEqual(true, result); }
public override CollectedData OnAcquire() { // For memory, WMI gives you the values in KB. Let's convert KB to B for consistency. Just multiply it by 1024. CollectedData free_data = base.OnAcquire(); if (free_data.DataIsCollected) { foreach (Data d in free_data.D) { d.Value = (d.ValueAsUInt64 * 1024).ToString(); } } return(free_data); }
public override CollectedData OnAcquire() { CollectedData d = base.OnAcquire(); if (d.DataIsCollected) { foreach (Data data in d.D) { if (string.IsNullOrEmpty(data.Value) == false) { data.Value = new DateTimeOffset(ManagementDateTimeConverter.ToDateTime(data.Value)).ToString("o"); } } } return(d); }
public override CollectedData OnAcquire() { CollectedData cd = base.OnAcquire(); CollectedData return_data = new CollectedData(Context, false); if (cd.DataIsCollected) { List <DictionaryData> drive_data = cd.D.Select(w => w as DictionaryData).ToList(); List <Data> data = new List <Data>(); // Package the drive information into a single Data object that maps the drive letter to a DiskName // object that maintains the drive's values GenericDictionaryData <DriveInfo> d = new GenericDictionaryData <DriveInfo>(Context); while (drive_data.Count > 0) { DictionaryData usage = drive_data[0]; drive_data.RemoveAt(0); // Only report local disks. Don't do removeable (floppy or thumb drive), CDs, or network drives. int drive_type; if (int.TryParse(usage.Data["DriveType"], out drive_type) && drive_type == (int)EDriveType.LocalDisk && usage.Data.ContainsKey("Name") && usage.Data.ContainsKey("VolumeName")) { string drive_name = usage.Data["Name"].Trim(); string description = usage.Data["VolumeName"].Trim(); DriveInfo disk = new DriveInfo() { name = description, letter = drive_name, type = (EDriveType)drive_type }; d.Data[drive_name] = disk; } } if (d.Data.Count > 0) { return_data.DataIsCollected = true; return_data.D.Add(d); } } return(return_data); }
public async Task GetCollectedDataForDeviceAsync() { #region Arrange MockApi mockApi = new MockApi(); mockApi.GetJsonAsyncResult = response1; DateTimeOffset startDate = new DateTimeOffset(new DateTime(2019, 11, 01, 00, 00, 00)); DateTimeOffset stopDate = new DateTimeOffset(new DateTime(2019, 11, 10, 00, 00, 00)); #endregion #region Act List <CollectedDataModel> result = await CollectedData.GetCollectedDataForDeviceAsync(mockApi, DeviceId, startDate, stopDate, "BatteryStatus", null); #endregion #region Assert Assert.AreEqual(5, result.Count); #endregion }
private void OnDataAcquired(CollectedData data) { string message = string.Empty; bool success = false; if (data == null) { message = "Null collected data"; } else if (data.DataIsCollected) { success = true; foreach (Data d in data.D) { GenericDictionaryData <DriveInfo> dict = (GenericDictionaryData <DriveInfo>)d; if (dict != null) { Dictionary <string, DriveInfo> d2 = dict.Data; CollectorsControl.UpdateDrives(new List <DriveInfo>(d2.Values)); } if (!string.IsNullOrEmpty(message)) { message += "\n"; } message += JsonConvert.SerializeObject(d, Newtonsoft.Json.Formatting.Indented, new Newtonsoft.Json.JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeHtml }); } } else { message = "Data collection failure"; if (string.IsNullOrEmpty(data.Message) == false) { message += "\n" + data.Message; } } MessageBox.Show(message, "Connection test", MessageBoxButton.OK, success ? MessageBoxImage.Information : MessageBoxImage.Error); }
/// <summary> /// Start the simulator and build the environment. /// </summary> private void Start() { // fixed framerate to equalize differences in performance UnityEngine.QualitySettings.vSyncCount = 0; UnityEngine.Application.targetFrameRate = 30; // init variables grid = FindObjectOfType <Grid>(); flowCam = cam.GetComponent <ImageSynthesis>(); flowCamSensitivity = flowCam.opticalFlowSensitivity; if (!fixedObstacle) { currentObstacleID = 0; } lastData = new CollectedData(-1, "init", 0, 0, 0, Vector3.zero, Vector3.zero, 0, currentObstacleID, currentEpoch); // load obstacles loadedObstacles = Resources.LoadAll <GameObject>("Ready"); // IMPORTANT: RUN THESE LINES ONLY WITH NEW MODELS ONCE!!! // otherwise new meshcolliders will be added to the prefabs all the time //foreach (GameObject obj in loadedObstacles) //{ // MeshCollider mc = obj.AddComponent<MeshCollider>(); // mc.sharedMesh = obj.GetComponentInChildren<MeshFilter>().sharedMesh; //} // generate environment GenerateEnvironment(); // create output path if (Directory.Exists(outputFolder)) { Directory.Delete(outputFolder, true); } Directory.CreateDirectory(outputFolder); // request new path & start moving PathRequestManager.RequestPath(new PathRequest(transform.position, target.position, OnPathFound)); }
public void Seed() { if (_context.CollectedData.Any()) { return; } CollectedData c1 = new CollectedData(1, 11, 'A', 'M'); CollectedData c2 = new CollectedData(2, 12, 'A', 'M'); CollectedData c3 = new CollectedData(3, 14, 'A', 'M'); CollectedData c4 = new CollectedData(4, 0, 'A', 'M'); CollectedData c5 = new CollectedData(5, 1, 'A', 'M'); CollectedData c6 = new CollectedData(6, 15, 'B', 'M'); CollectedData c7 = new CollectedData(7, 13, 'B', 'M'); CollectedData c8 = new CollectedData(8, 1, 'C', 'M'); CollectedData c9 = new CollectedData(9, 2, 'C', 'M'); CollectedData c10 = new CollectedData(10, 4, 'C', 'M'); CollectedData c11 = new CollectedData(11, 3, 'C', 'M'); CollectedData c12 = new CollectedData(12, 4, 'C', 'M'); CollectedData c13 = new CollectedData(13, 5, 'D', 'M'); CollectedData c14 = new CollectedData(14, 6, 'E', 'M'); CollectedData c15 = new CollectedData(15, 7, 'A', 'M'); CollectedData c16 = new CollectedData(16, 10, 'A', 'M'); CollectedData c17 = new CollectedData(17, 9, 'A', 'M'); CollectedData c18 = new CollectedData(18, 15, 'B', 'V'); CollectedData c19 = new CollectedData(19, 13, 'B', 'V'); CollectedData c20 = new CollectedData(20, 1, 'C', 'V'); CollectedData c21 = new CollectedData(21, 2, 'C', 'V'); CollectedData c22 = new CollectedData(22, 4, 'C', 'N'); CollectedData c23 = new CollectedData(23, 3, 'C', 'V'); _context.CollectedData.AddRange(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23); _context.SaveChanges(); }
public override CollectedData OnAcquire() { CollectedData data = base.OnAcquire(); if (data.DataIsCollected) { foreach (Data d in data.D) { // The value is in seconds. I think we probably want that in days hours:minutes:seconds format UInt64?seconds = d.ValueAsUInt64; if (seconds != null) { UInt64 days = seconds.Value / (60 * 60 * 24); UInt64 hours = (seconds.Value / (60 * 60)) % 24; UInt64 minutes = (seconds.Value / 60) % 60; UInt64 seconds2 = seconds.Value % 60; d.Value = string.Format("{0} {1:D2}:{2:D2}:{3:D2}", days, hours, minutes, seconds2); } } } return(data); }
/// <summary> /// Used to store a chunk of collected Data. Determines which Collector collected /// the data based on d.Name, then inserts it into the Data table, and updates /// the MostRecentDataPerCollector table. It then sends the Data off to each /// of the interpreters so they can interpret the new data however they wish. /// </summary> /// <param name="data">A collection of Data objects to store in the DB</param> /// <param name="db">The database to store the data in</param> /// <returns></returns> public bool SaveData(CollectedData data, Database db) { if (data == null) { return(false); } bool success = false; ILog log = LogManager.GetLogger(typeof(DataStorage)); //ApplicationEventLog elog = new ApplicationEventLog(); try { //string msg = $"SaveData -- data is collected: {data.DataIsCollected}, with {data.D.Count} items"; //log.Debug(msg); //elog.LogInformation(msg); // Record the last time a collection attempt was made for this collector, regardless of whether // it was successfully collected. If it wasn't collected, we'll bail out shortly. if (data.Context.ID.ID >= 0) { using (SQLiteConnection conn = db.Connection) { conn.Open(); Updater updater = new Updater("Collectors", $"CollectorID = {data.Context.ID.ID}", conn); if (data.DataIsCollected) { updater.Set("LastCollectedAt", DateTimeOffset.Now); } updater.Set("SuccessfullyCollected", data.DataIsCollected); updater.Execute(); } } if (data.DataIsCollected == false) { return(true); } Stopwatch watch = Stopwatch.StartNew(); List <DataRecord> to_insert = new List <DataRecord>(); foreach (Data d in data.D) { try { DataCollectorContext dc_context = d.Context; if (dc_context.ID.ID >= 0) { DataRecord dr = new DataRecord(dc_context, d); to_insert.Add(dr); } else { log.Error($"Unknown Data ({d.ID}, {d.Name})"); } } catch (Exception e) { log.Error("SaveData[A]: "); log.Error(e); } } success = Insert(to_insert, db); log.Debug($"Total insertion took {watch.ElapsedMilliseconds} ms"); } catch (Exception e) { log.Error("SaveData[B]: "); log.Error(e); } return(success); }
public bool SaveData(CollectedData data) { Database db = new Database(); return(SaveData(data, db)); }
public override void OnSceneViewGUI(SceneView sceneView) { if (EdgeVisual.Visible && EdgeVisual.MouseOver) { return; } // 1. Find target game object. if (m_collectedData == null) { if (GetChild <SelectGameObjectTool>() == null) { SelectGameObjectTool selectGameObjectTool = new SelectGameObjectTool(); selectGameObjectTool.OnSelect = go => { m_collectedData = new CollectedData() { Target = go }; }; AddChild(selectGameObjectTool); } } // 2. Select edge on target game object. else if (!m_collectedData.SelectedEdge.Valid) { Raycast.Hit hit = Raycast.Test(m_collectedData.Target, HandleUtility.GUIPointToWorldRay(Event.current.mousePosition)); if (hit.ClosestEdge.Valid) { m_collectedData.CurrentEdge = hit.ClosestEdge; } } // 3. Find point on edge - hold ctrl for "no-snap" mode. else if (!m_collectedData.PointOnEdgeGiven) { Vector3 pointOnEdge = FindClosestPointOnEdge(m_collectedData.SelectedEdge.Edge); if (Event.current.control) { m_collectedData.PointOnEdge = pointOnEdge; } else { float snapValue = 0.5f * HandleUtility.GetHandleSize(pointOnEdge); float closestDistance = float.PositiveInfinity; Vector3 closestPoint = pointOnEdge; Vector3[] predefinedPoints = FindPredefinedEdgePoints(m_collectedData.SelectedEdge.Edge).ToArray(); // Given set of predefined points along the edge, finds the // closest to the mouse ray (i.e., the actual point on the edge). foreach (var point in predefinedPoints) { float distanceToPoint = Vector3.Distance(pointOnEdge, point); if (distanceToPoint < snapValue && distanceToPoint < closestDistance) { closestPoint = point; closestDistance = distanceToPoint; } } m_collectedData.PointOnEdge = closestPoint; } } // 4. Find direction. else if (!m_collectedData.DirectionGiven) { if (GetChild <DirectionTool>() == null) { DirectionTool directionTool = new DirectionTool(m_collectedData.PointOnEdge, m_collectedData.SelectedEdge.Edge.Direction, m_collectedData.SelectedEdge.Edge.Normal); directionTool.OnSelect += (position, rotation) => { m_collectedData.DirectionRotation = rotation; m_collectedData.DirectionGiven = true; }; AddChild(directionTool); } } // 5. Done, fire callback with result and remove us. else { MeshUtils.Edge orgEdge = m_collectedData.SelectedEdge.Edge; Result resultingData = new Result() { Target = m_collectedData.Target, Edge = new MeshUtils.Edge(m_collectedData.PointOnEdge + 0.5f * orgEdge.Length * (m_collectedData.DirectionRotation * Vector3.back), m_collectedData.PointOnEdge + 0.5f * orgEdge.Length * (m_collectedData.DirectionRotation * Vector3.forward), m_collectedData.DirectionRotation * Vector3.up, MeshUtils.Edge.EdgeType.Triangle), Position = m_collectedData.PointOnEdge, Rotation = m_collectedData.DirectionRotation }; OnEdgeFound(resultingData); PerformRemoveFromParent(); return; } EdgeVisual.Visible = m_collectedData != null && m_collectedData.CurrentEdge.Valid; if (EdgeVisual.Visible) { const float edgeRadius = 0.035f; const float defaultAlpha = 0.25f; const float mouseOverAlpha = 0.65f; EdgeVisual.SetTransform(m_collectedData.CurrentEdge.Edge.Start, m_collectedData.CurrentEdge.Edge.End, edgeRadius); if (m_collectedData.CurrentEdge.Edge.Type == MeshUtils.Edge.EdgeType.Triangle) { EdgeVisual.Color = new Color(Color.yellow.r, Color.yellow.g, Color.yellow.b, defaultAlpha); EdgeVisual.MouseOverColor = new Color(Color.yellow.r, Color.yellow.g, Color.yellow.b, mouseOverAlpha); } else if (m_collectedData.CurrentEdge.Edge.Type == MeshUtils.Edge.EdgeType.Principal) { EdgeVisual.Color = new Color(Color.red.r, Color.red.g, Color.red.b, defaultAlpha); EdgeVisual.MouseOverColor = new Color(Color.red.r, Color.red.g, Color.red.b, mouseOverAlpha); } } NodeVisual.Visible = EdgeVisual.Visible && m_collectedData.SelectedEdge.Valid; if (NodeVisual.Visible) { const float nodeRadius = 0.040f; NodeVisual.SetTransform(m_collectedData.PointOnEdge, Quaternion.identity, nodeRadius); // The user doesn't have to hit the node sphere. if (Manager.HijackLeftMouseClick()) { OnPointClick(null, NodeVisual); } } }
public override void OnSceneViewGUI(SceneView sceneView) { if (m_collectedData == null) { if (GetChild <SelectGameObjectTool>() == null) { SelectGameObjectTool selectGameObjectTool = new SelectGameObjectTool(); selectGameObjectTool.OnSelect = go => { m_collectedData = new CollectedData() { Target = go }; }; AddChild(selectGameObjectTool); } } else if (!m_collectedData.TriangleGiven) { // TODO: Handle world point? if (m_collectedData.Target == null) { PerformRemoveFromParent(); return; } HighlightObject = m_collectedData.Target; m_collectedData.RaycastResult = Utils.Raycast.Intersect(HandleUtility.GUIPointToWorldRay(Event.current.mousePosition), m_collectedData.Target, m_collectedData.Target.GetComponent <AGXUnity.RigidBody>() != null); // Done (next state) when the user left click and we've a valid triangle. m_collectedData.TriangleGiven = m_collectedData.RaycastResult && Manager.HijackLeftMouseClick(); } else if (!m_collectedData.RotationGiven) { if (GetChild <DirectionTool>() == null) { DirectionTool directionTool = new DirectionTool(m_collectedData.RaycastResult.Point, m_collectedData.RaycastResult.Triangle.Normal, m_collectedData.RaycastResult.ClosestEdge.Direction); directionTool.OnSelect += (position, rotation) => { m_collectedData.Rotation = rotation; m_collectedData.RotationGiven = true; }; AddChild(directionTool); } } else { Result resultingData = new Result() { Target = m_collectedData.Target, RaycastResult = m_collectedData.RaycastResult, Rotation = m_collectedData.Rotation }; OnPointFound(resultingData); PerformRemoveFromParent(); } PointVisual.Visible = m_collectedData != null && m_collectedData.RaycastResult && !m_collectedData.TriangleGiven; if (PointVisual.Visible) { PointVisual.SetTransform(m_collectedData.RaycastResult.Point, Quaternion.identity, 0.05f); } }
/// <summary> /// Called when data has been collected. Right now it just /// tells the database to store it, but in the past, for debugging, /// we'd write out the JSON representation of the data. /// </summary> /// <param name="d"></param> protected void OnDataCollected(CollectedData d) { //foreach(Data data in d) // Console.WriteLine(Name + ": " + JsonConvert.SerializeObject(data)); Storage.SaveData(d); }
public override CollectedData OnAcquire() { bool success = true; List <HardDisk> disks = new List <HardDisk>(); CollectedData cd = new CollectedData(Context, success); OnAcquireDelegate( dict => { string serial_num = string.Empty; if (dict.TryGetValue("SerialNumber", out object o)) { serial_num = o.ToString().Trim(); } if (string.IsNullOrEmpty(serial_num) == false) { HardDisk d = new HardDisk() { DeviceID = dict["DeviceID"]?.ToString().Trim(), Model = dict["Model"]?.ToString().Trim(), PnpDeviceID = dict["PNPDeviceID"]?.ToString().Trim(), InterfaceType = dict["InterfaceType"]?.ToString().Trim(), SerialNum = serial_num }; disks.Add(d); } }); if (disks.Count > 0) { ListData <HardDisk> disks2 = new ListData <HardDisk>(Context); foreach (HardDisk disk in disks) { try { // Figure out which drive letters are on this hard disk ManagementScope scope = WmiContext.GetManagementScope(); string drive_pnp = disk.PnpDeviceID.Replace("\\", "\\\\"); string queryStr = string.Format("ASSOCIATORS OF {{Win32_DiskDrive.DeviceID='{0}'}} WHERE AssocClass = Win32_DiskDriveToDiskPartition", disk.DeviceID); //Console.WriteLine(queryStr); foreach (ManagementBaseObject partition in new ManagementObjectSearcher(scope, new ObjectQuery(queryStr)).Get()) { queryStr = string.Format("ASSOCIATORS OF {{Win32_DiskPartition.DeviceID='{0}'}} WHERE AssocClass = Win32_LogicalDiskToPartition", partition["DeviceID"]); //Console.WriteLine(queryStr); foreach (ManagementBaseObject o in new ManagementObjectSearcher(scope, new ObjectQuery(queryStr)).Get()) { string drive_letter = o["Name"].ToString().Trim().ToUpper(); if (disk.DriveLetters.Contains(drive_letter) == false) { disk.DriveLetters.Add(drive_letter); } } } // See if the drive is predicting failure scope = WmiContext.GetManagementScope("WMI"); queryStr = string.Format("SELECT * FROM MSStorageDriver_FailurePredictStatus WHERE InstanceName LIKE \"%{0}%\"", drive_pnp); //Console.WriteLine(queryStr); foreach (ManagementBaseObject m in new ManagementObjectSearcher(scope, new ObjectQuery(queryStr)).Get()) { object failure = m["PredictFailure"]; //Console.WriteLine("PredictFailure: " + failure.ToString() + "\n"); disk.FailureIsPredicted = (bool)failure; //SMARTFailureRequest req = new SMARTFailureRequest("SMARTCollector"); //RequestBus.Instance.MakeRequest(req); //if (req.IsHandled) // disk.FailureIsPredicted = req.FailureIsPredicted; } // Now get the SMART attributes queryStr = string.Format("SELECT * FROM MSStorageDriver_FailurePredictData WHERE InstanceName LIKE \"%{0}%\"", drive_pnp); //Console.WriteLine(queryStr); foreach (ManagementBaseObject m in new ManagementObjectSearcher(scope, new ObjectQuery(queryStr)).Get()) { Byte[] attributes = (Byte[])m.Properties["VendorSpecific"].Value; //Console.WriteLine("Attributes length [A]: {0}", attributes.Length); int num_attributes = attributes.Length / (int)ESmartField.NumSmartFields; for (int i = 0; i < num_attributes; ++i) { try { byte[] field = new byte[(int)ESmartField.NumSmartFields]; Array.Copy(attributes, i * (int)ESmartField.NumSmartFields, field, 0, (int)ESmartField.NumSmartFields); ESmartAttribute attr = (ESmartAttribute)field[(int)ESmartField.Attribute]; if (attr == ESmartAttribute.Invalid) { continue; } //int flags = bytes[i * 12 + 4]; // least significant status byte, +3 most significant byte, but not used so ignored. // //bool advisory = (flags & 0x1) == 0x0; //bool failureImminent = (flags & 0x1) == 0x1; //bool onlineDataCollection = (flags & 0x2) == 0x2; int value = field[(int)ESmartField.Value]; //int worst = field[(int)ESmartField.Worst]; //int vendordata = BitConverter.ToInt32(field, (int)ESmartField.VendorData1); SmartAttribute resource = new SmartAttribute(attr) { Value = value }; disk.SmartAttributes.Add(resource); } catch (Exception ex) { // given key does not exist in attribute collection (attribute not in the dictionary of attributes) Console.WriteLine(ex.Message); } } } disks2.Data.Add(disk); } catch (Exception ex) { cd.SetMessage(ex); success = false; } } cd.D.Add(disks2); } else { success = false; } cd.DataIsCollected = success; return(cd); }
public override void OnEpochFinished(Projection[] data) { CollectedData.Add(CalculateAccuracy(Network, TestData).Value); }
public void ReadUSBData() { data = reader.ReadData(); }
public override CollectedData OnAcquire() { CollectedData cd = base.OnAcquire(); CollectedData return_data = new CollectedData(Context, false); if (cd.DataIsCollected) { List <DictionaryData> usage_data = cd.D.Select(w => w as DictionaryData).ToList(); //MonitoredDrivesRequest request = new MonitoredDrivesRequest(Context.Name); //RequestBus.Instance.MakeRequest(request); List <Data> data = new List <Data>(); // Package the drive information into a single Data object that maps the drive letter to a DiskUsage // object that maintains the capacity/free/used values for that drive. GenericDictionaryData <DiskUsage> d = new GenericDictionaryData <DiskUsage>(Context); //data.Add(d); // Unfortunately, there's no way to determine the drive type when determining the disk speeds (see DiskSpeed class). // So that we're reporting the same drives, record the drive letters here, then match them when we do the disk speed. // And we also want to keep track of the drive letter => name ("C:" => "OSDisk", for example), so let's grab that now // as well. Dictionary <string, string> drive_descriptions = new Dictionary <string, string>(); while (usage_data.Count > 0) { DictionaryData usage = usage_data[0]; usage_data.RemoveAt(0); // Only report local disks. Don't do removeable (floppy or thumb drive), CDs, or network drives. if (int.TryParse(usage.Data["DriveType"], out int drive_type) && drive_type == (int)EDriveType.LocalDisk && usage.Data.ContainsKey("Size") && usage.Data.ContainsKey("FreeSpace") && usage.Data.ContainsKey("Name") && usage.Data.ContainsKey("VolumeName")) { string drive_name = usage.Data["Name"].Trim(); string description = usage.Data["VolumeName"].Trim(); drive_descriptions[drive_name] = description; if (ulong.TryParse(usage.Data["Size"], out ulong c) && ulong.TryParse(usage.Data["FreeSpace"], out ulong f)) { d.Data[drive_name] = new DiskUsage() { CapacityNum = c, FreeNum = f }; } } } if (d.Data.Count > 0) { return_data.DataIsCollected = true; return_data.D.Add(d); } // Record the drive descriptions as an attribute in the database. We will also use this to get the drive letters // when needed. string json = JsonConvert.SerializeObject(drive_descriptions); AttributeRequest attr_request = new AttributeRequest(Context.ID.Name + ".all.drives.descriptions", false) { Value = json }; RequestBus.Instance.MakeRequest(attr_request); } return(return_data); }