public FrmAddEditMeasurement(MeasurementModel model) { try { InitializeComponent(); StyleConfiguration(); reciever = new MeasurementReciever(); _model = model; btnSubmit.Text = "Update"; lblTitle.Text = "Update"; ConfigureMeasurement(); } catch (Exception ex) { } }
public static MeasurementPackage GetMeasurementPackageWithXMeasurementsAndYData(this DateTimeOffset measurementTime, string measurementTag, int measurementsCount, int dataCount, bool useLocation) { MeasurementPackage package = new MeasurementPackage(); package.Key = TestHelper.TestKey; if (dataCount < 1) { dataCount = 1; } List <MeasurementModel> measurements = new List <MeasurementModel>(); MeasurementModel m; for (int i = 0; i < measurementsCount; i++) { m = new MeasurementModel() { Object = TestHelper.TestMeasurementObject + i.ToString(), Tag = measurementTag + i.ToString(), Timestamp = measurementTime.AddSeconds(i) }; if (useLocation) { m.Location = new Location() { Latitude = 62.8989, Longitude = 27.6630 }; } m.Data = new DataModel[dataCount]; for (int j = 0; j < dataCount; j++) { DataModel d = new DataModel() { Tag = TestHelper.TestDataTag + j.ToString(), Value = 3.14 }; m.Data[j] = d; } measurements.Add(m); } package.Measurements = measurements.ToArray(); return(package); }
public MeasurementModel GenerateNextMeasurement() { var currentDate = DateTime.Now.Ticks; var measurement = new MeasurementModel { Temperature = temperature, Timestamp = currentDate }; double delta = random.NextDouble() * maxDelta - minDelta; temperature += delta; temperature = Math.Round(temperature, DEFAULT_PRECISION); temperature = Math.Min(temperature, maxTemperature); temperature = Math.Max(temperature, minTemperature); return(measurement); }
public IActionResult Create([FromBody] MeasurementModel model) { try { var weatherStation = _measurementService.FindWeatherStation(model.Location.Name); if (weatherStation == null) { weatherStation = new LocalWeatherStation { Name = model.Location.Name, Longitude = model.Location.Longitude, Latitude = model.Location.Latitude }; } var measurement = new Measurement { LocalWeatherStation = weatherStation, Temperature = model.Temperature, AirPressure = model.AirPressure, Humidity = model.Humidity, Time = DateTime.ParseExact(model.Time, "dd-MM-yyyy HH:mm:ss", null) }; if (weatherStation.Measurements == null) { weatherStation.Measurements = new List <Measurement>(); } weatherStation.Measurements.Add(measurement); _measurementService.Create(measurement); // Notify Hub _chatHub.Clients.All.SendAsync("ReceiveMessage", "New Data in ", model.Location.Name); return(RedirectToAction(nameof(Index))); } catch { return(NotFound()); } }
public static MeasurementModel ToMeasurementModel(this Measurement measurement, ICollection <Datum> data, List <string> sensorTags) { if (null == measurement) { return(null); } var model = new MeasurementModel() { Key = measurement.ID.ToString("X"), ID = measurement.ID, ProviderID = measurement.ProviderID, Object = measurement.Object, Tag = measurement.Tag, Timestamp = measurement.Timestamp, TimestampISO8601 = measurement.Timestamp.ToString("o"), Note = measurement.Note, Data = new List <DataModel>() }; if (null != measurement.Location) { model.Location = new Location() { WellKnownTextWGS84 = measurement.Location.AsText(), Latitude = measurement.Location.Latitude, Longitude = measurement.Location.Longitude }; } if (null != data && data.Count > 0) { var dbData = data; if (null != sensorTags && sensorTags.Count > 0) { dbData = dbData.Where(d => sensorTags.Contains(d.Tag)).ToList(); } foreach (var d in dbData) { model.Data.Add(d.ToDataModel()); } } return(model); }
private async Task MeasurementsUpdate(RecordChangedEventArgs <Measurement> e) { try { var station = await Task.Run(() => _repository.Stations.GetAsync(c => c.StationId == e.Entity.StationId)); var s = MapControl.Markers.FirstOrDefault( c => c.Position == new PointLatLng(Convert.ToDouble(station.Latitude), Convert.ToDouble(station.Longitude))); if (s == null) { return; } MapControl.Markers.Remove(s); var newmarker = new GMapMarker(new PointLatLng(Convert.ToDouble(station.Latitude), Convert.ToDouble(station.Longitude))); var x = Resources["Grid1"] as Grid; var measurement = new MeasurementModel(e.Entity, _repository) { AssociatedStation = new StationModel(station, _repository) }; if (x != null) { x.DataContext = measurement; newmarker.Shape = x; newmarker.Offset = new Point(-25, -25); newmarker.ZIndex = 0; } newmarker.Shape.MouseLeftButtonDown += ShapeOnMouseLeftButtonDown; MapControl.Markers.Add(newmarker); } catch (Exception) { } }
public async Task <IActionResult> Post(int aquariumId, [FromBody] MeasurementModel model) { try { var measurement = _mapper.Map <Measurement>(model); if (measurement == null) { return(UnprocessableEntity()); } // User URL values over model values measurement.UserId = UserId; measurement.AquariumId = aquariumId; // Measurement Type measurement.MeasurementType = _measurementManager.LookupFromName(measurement.MeasurementType); var results = _validationManager.Validate(measurement); if (results.Count != 0) { return(UnprocessableEntity(results)); } // Lookup unit measurement.Unit = await _unitManager.LookUpByName(measurement.Unit); await _repository.Add(measurement); AddETag(measurement.RowVersion); var url = Url.Link("MeasurementGet", new { UserId, aquariumId, ((Measurement)measurement).Id }); return(Created(url, _mapper.Map <MeasurementModel>(measurement))); } catch (Exception ex) { _logger.Error(ex, "An error occured whilst trying to create Measurement."); } return(BadRequest("Could not create Measurement")); }
/// <summary> /// The MeasurerService calls Process method periodically as defined in plugin's config ExecuteInterval element. The time is seconds. /// Note that the same instance of this class is alive the whole time as the service is alive! So make this process as sleek and lean as possible. /// </summary> public void Process() { // Do the measurement reading here... and then create a MeasurementPackage object with a proper key to enable saving measurements to SAMI system. Random rnd = new Random(); MeasurementPackage p = new MeasurementPackage() { Key = this.settings.Key, Measurements = new List <MeasurementModel>() }; MeasurementModel mm = new MeasurementModel() { Object = settings.Object, Tag = settings.Tag, Timestamp = DateTimeOffset.Now, Data = new List <DataModel>() }; foreach (var item in this.settings.SensorTags) { mm.Data.Add(new DataModel() { Tag = item, Value = rnd.NextDouble() * 100 }); } p.Measurements.Add(mm); this.Log.Append("Test message to log..."); // your plugin may throw exceptions and those will be logged in the service, but you can also handle your exceptions and log them if needed. // throw exception or do not handle possible exceptions... // throw new Exception("some info..."); // or handle exceptions and log the info... // Log.Append("some info..."); // When your plugin has something to save raise ProcessCompleted event. The Name property can be used as ProcessCompletedEventArgs source parameter. // If at some point your plugin has nothing to save, then don't raise the event. this.OnProcessCompleted(new ProcessCompletedEventArgs(this.Name, p)); }
private void SaveApproximateTemp(int j) { MeasurementModel measurement = new MeasurementModel { ProbeId = j + 1, Value = 0, Date = DateTime.Now.Date.ToShortDateString(), Hour = DateTime.Now.Hour, Minute = DateTime.Now.Minute, Second = DateTime.Now.Second }; foreach (MeasurementModel m in measurementStacks[j]) { measurement.Value += m.Value; } measurement.Value = Math.Round(measurement.Value / stackSize, 1); SqliteDataAccess.SaveMeasurement(measurement); measurementStacks[j].Clear(); }
public static MeasurementModel ConvertfromEntity(Measurement inmeasurement) { MeasurementModel measurement = null; try { measurement = new MeasurementModel(); measurement.measid = inmeasurement.measid; measurement.timestamp = DateTime.Parse(inmeasurement.timestamp.ToString()); measurement.typeid = inmeasurement.typeid; measurement.installationid = inmeasurement.installationid; measurement.measurevalue = inmeasurement.measurevalue; log.Info("Measurement wurde konvertiert."); } catch (Exception exp) { log.Error("Measurement konnte nicht konvertiert werden."); throw new DalException("Measurement konnte nicht konvertiert werden.", exp); } return(measurement); }
public void LocalStoreSerializationTest() { Random rnd = new Random(); MeasurementPackage p = new MeasurementPackage() { Key = "testing...", Measurements = new List <MeasurementModel>() }; MeasurementModel mm = new MeasurementModel() { Object = "testing", Timestamp = DateTimeOffset.Now, Data = new List <DataModel>() }; string[] tags = new string[] { "tag1", "tag2" }; foreach (var item in tags) { mm.Data.Add(new DataModel() { Tag = item, Value = rnd.NextDouble() * 100 }); } p.Measurements.Add(mm); string xml = SerializeHelper.SerializeToStringWithDCS <MeasurementPackage>(p); Trace.WriteLine(xml); Assert.IsNotNull(xml); MeasurementPackage dps = SerializeHelper.DeserializeWithDCS <MeasurementPackage>(xml); Assert.IsNotNull(dps); Assert.AreEqual(dps.Key, p.Key); Assert.AreEqual(dps.Measurements.Count, p.Measurements.Count); }
public void SendMeasurementPackage() { // init the client MeasurementsServiceClient client = new MeasurementsServiceClient(); // create the measurement package and populate it MeasurementPackage package = new MeasurementPackage(); package.Key = "your-key-goes-here"; // create a collection of measurements List <MeasurementModel> measurements = new List <MeasurementModel>(); // create a measurement MeasurementModel m = new MeasurementModel() { Object = "your-measurement-object", Tag = "your-measurement-tag", Timestamp = DateTimeOffset.Now, Location = new Location() { Latitude = 62.8989, Longitude = 27.6630 } }; // add some data to your measurement DataModel d = new DataModel() { Tag = "your-data-tag", Value = 3.14 }; // add data to measurement m.Data = new DataModel[1]; m.Data[0] = d; // add measurement to measurements collection measurements.Add(m); // add measurements collection to measurement package package.Measurements = measurements.ToArray(); // save the measurement package and check the result SaveResult result = client.SaveMeasurementPackage(package); }
public MeasurementModel[] GetSaveMeasurementsTemplate() { MeasurementModel[] model = new MeasurementModel[1]; MeasurementModel mm = new MeasurementModel(); mm.Object = "your-measurement-object"; mm.Tag = "your-measurement-tag"; mm.Timestamp = DateTimeOffset.Now; mm.Note = "if this measurement has a note"; mm.Data = new List <DataModel>(); DataModel dm = new DataModel(); dm.Tag = "This is your sensor identification. This is unique to you."; dm.Value = 3.14; dm.TextValue = "your sensor can have some textual values also."; mm.Data.Add(dm); model[0] = mm; return(model); }
public async Task <IActionResult> Put(int aquariumId, int measurementId, [FromBody] MeasurementModel model) { try { var measurement = await _repository.Get(measurementId); if (measurement == null) { return(NotFound()); } if (measurement.AquariumId != aquariumId) { return(BadRequest("Aquarium and Measurement don't match")); } _mapper.Map(model, measurement); // Validate var results = _validationManager.Validate(measurement); if (results.Count != 0) { return(UnprocessableEntity(results)); } // Lookup unit measurement.Unit = await _unitManager.LookUpByName(measurement.Unit); await _repository.Update(measurement); AddETag(measurement.RowVersion); return(Ok(_mapper.Map <MeasurementModel>(measurement))); } catch (Exception ex) { _logger.Error(ex, "An error occured whilst trying to update Measurement."); } return(BadRequest("Could not update Measurment")); }
public static void Run([IoTHubTrigger("messages/events", Connection = "iothub-ehub-iothub20-2-8763167-3f6420fdd2", ConsumerGroup = "functionapp")] EventData message, [CosmosDB(databaseName: "IOT20", collectionName: "Measurement", CreateIfNotExists = true, ConnectionStringSetting = "iot20cosmosdatabas")] out dynamic cosmos, ILogger log) { try { var _data = JsonConvert.DeserializeObject <dynamic>(Encoding.UTF8.GetString(message.Body.Array)); var _deviceId = message.SystemProperties["iothub-connection-device-id"].ToString(); var _deviceType = message.Properties["deviceType"].ToString(); var _latitude = message.Properties["latitude"].ToString(); var _longitude = message.Properties["longitude"].ToString(); var _epochTime = message.Properties["epochTime"].ToString(); var measurement = new MeasurementModel() { deviceId = _deviceId, deviceType = _deviceType, epochTime = _epochTime, location = new Location { latitude = _latitude, longitude = _longitude }, data = _data }; measurement.ConverEpochTime(); var json = JsonConvert.SerializeObject(measurement); cosmos = json; log.LogInformation($"Measurement was saved to Cosmos DB, Message:: {json}"); } catch (Exception e) { log.LogInformation($"Unable to process Request, Erorr:: {e.Message}"); cosmos = null; } }
public IHttpActionResult Add(MeasurementModel measureModel) { if (measureModel == null) { var errorMessage = _messages.GetMessage(Generic.NullObject); return(BadRequest(errorMessage)); } if (_measureRep.GetAll().Any(m => m.UnitOfMeasure == measureModel.UnitOfMeasure)) { var errorMessage = _messages.GetMessage(Custom.Conflict, "Measurement", "Unit Of Measure"); return(Conflict(errorMessage)); } var newMeasure = _mapper.Map <Measurement>(measureModel); _measureRep.Add(newMeasure); var createdMeasure = _mapper.Map <MeasurementModelGet>(newMeasure); return(CreatedAtRoute("GetMeasurement", new { id = newMeasure.Id }, createdMeasure)); }
public static MeasurementPackage GetMeasurementPackageWithISO(this DateTime measurementTime, string measurementTag) { MeasurementPackage package = new MeasurementPackage(); package.Key = TestHelper.TestKey; List <MeasurementModel> measurements = new List <MeasurementModel>(); // string ISO = measurementTime.ToString(); string ISO = "11/02/03 15:03:06"; MeasurementModel m = new MeasurementModel() { Object = TestHelper.TestMeasurementObject, Tag = measurementTag, TimestampISO8601 = ISO, Location = new Location() { Latitude = 62.8989, Longitude = 27.6630 } }; DataModel d = new DataModel() { Tag = TestHelper.TestDataTag, Value = 3.14 }; m.Data = new DataModel[1]; m.Data[0] = d; measurements.Add(m); measurements.Add(m); package.Measurements = measurements.ToArray(); return(package); }
private void OnMeasurementReceived(MeasurementData data) { const int maxValues = 15; var measurementModel = new MeasurementModel(data); Measurements.Add(measurementModel); //if ((Measurements.Count % 10) == 0) //{ // var timeSpan = data.Timestamp - (MeasurementManager.CurrentExperiment?.StartTime ?? data.Timestamp); //} //WeightGraphLabels.Add(timeSpan.TotalSeconds.ToString()); if (WeightGraphData[0].Values.Count > maxValues) { WeightGraphData[0].Values.RemoveAt(0); } WeightGraphData[0].Values.Add(new ObservablePoint(data.Second, data.Weight)); if (SpeedGraphData[0].Values.Count > maxValues) { SpeedGraphData[0].Values.RemoveAt(0); } SpeedGraphData[0].Values.Add(new ObservablePoint(data.Second, data.Speed)); if (AccelerationGraphData[0].Values.Count > maxValues) { AccelerationGraphData[0].Values.RemoveAt(0); } AccelerationGraphData[0].Values.Add(new ObservablePoint(data.Second, data.Acceleration)); }
public void CreateMeasurement(string installationid, MeasuredValue measvalue) { try { log4net.Config.XmlConfigurator.Configure(); MeasurementModel measurement = new MeasurementModel(); measurement.installationid = Int32.Parse(installationid); measurement.measurevalue = Decimal.Parse(measvalue.value.ToString()); measurement.timestamp = measvalue.timestamp; measurement.typeid = measvalue.type; IUnityContainer container = new UnityContainer(); UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); section.Configure(container); IRestServiceBL rservicebl = container.Resolve <IRestServiceBL>(); rservicebl.createMeasurement(measurement); } catch (Exception exp) { log.Error("Measurement via Rest konnte nicht gespeichert werden."); throw new Exception("Measurement via Rest konnte nicht gespeichert werden.", exp); } }
public void Delete(MeasurementModel model) { model.Flag = Constants.DbConstants.Delete; DatabaseOperation(model); }
public void Add(MeasurementModel model) { model.Flag = Constants.DbConstants.Add; DatabaseOperation(model); }
public HttpResponseMessage Post([FromBody] MeasurementModel value) { //IEnumerable<string> headerValues; //var headerValue = String.Empty; //if ( Request.Headers.TryGetValues( "Authorization", out headerValues ) ) //{ // headerValue = headerValues.FirstOrDefault(); //} //var credentials = ""; //if ( headerValue != String.Empty ) //{ // credentials = Encoding.UTF8.GetString( Convert.FromBase64String( headerValue.Substring( 6 ).Trim() ) ); //} bool isUpdate = false; Measurement measurement; if (value.ID > 0) { measurement = BVSBusinessServices.Measurements.GetByID(value.ID); isUpdate = true; } else { measurement = new Measurement { MeasurementOn = value.MeasurementOn, CalculatedVolume = value.CalculatedVolume, PatientID = value.PatientID, ClientGUID = value.ClientGUID }; } measurement.PatientFeedback = value.PatientFeedback; measurement.PatientRating = value.PatientRating; measurement.IsPatientRatingThumbsUp = value.IsPatientRatingThumbsUp; measurement.IsPatientRatingThumbsDown = value.IsPatientRatingThumbsDown; BusinessServiceOperationResult result; result = BVSBusinessServices.Measurements.Save(measurement); if (!result.HasErrors && !isUpdate) { if (value.SubMeasurements != null) { foreach (var subMeasurement in value.SubMeasurements) { subMeasurement.MeasurementID = measurement.ID; result = BVSBusinessServices.SubMeasurements.Save(subMeasurement); if (result.HasErrors) { break; } } } } if (!result.HasErrors) { if (isUpdate) { return(Request.CreateResponse(HttpStatusCode.OK, new { id = measurement.ID, clientGUID = measurement.ClientGUID, updatedOn = measurement.UpdatedOn })); } else { return(Request.CreateResponse(HttpStatusCode.OK, new { id = measurement.ID, clientGUID = measurement.ClientGUID, createdOn = measurement.CreatedOn })); } } else { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "value"); response.Content = new StringContent(String.Join("; ", result.Errors), Encoding.Unicode); return(response); } }
public async Task Run() { try { using (var producer = new ProducerBuilder <long, string>(config) .SetKeySerializer(Serializers.Int64) .SetValueSerializer(Serializers.Utf8) .Build()) { int counter = 1; Console.WriteLine("Rozpoczynam wysyłanie wiadomości, topic: {0}, broker: {1}", topic, broker); using (var reader = new StreamReader(@dataFileLocation)) { // skip header string headerLine = reader.ReadLine(); while (!reader.EndOfStream) { var line = reader.ReadLine(); var values = line.Split(','); var measurement = new MeasurementModel() { VendorId = int.Parse(values[0]), PickupDateTime = DateTime.Parse(values[1]), DropOffDateTime = DateTime.Parse(values[2]), PassengerCount = int.Parse(values[3]), TripDistance = double.Parse(values[4]), RateCodeId = int.Parse(values[5]), StoreAndFwdFlag = string.Equals("Y", values[6]), PULocationID = int.Parse(values[7]), DOLocationID = int.Parse(values[8]), PaymentType = int.Parse(values[9]), FareAmount = double.Parse(values[10]), Extra = double.Parse(values[11]), MtaTax = double.Parse(values[12]), TipAmount = double.Parse(values[13]), TollsAmount = double.Parse(values[14]), ImprovementSurcharge = double.Parse(values[15]), TotalAmount = double.Parse(values[16]) }; var message = JsonConvert.SerializeObject(measurement); Console.WriteLine("Id #{0} Value: '{1}'", counter, message); await producer.ProduceAsync( topic, new Message <long, string> { Key = DateTime.UtcNow.Ticks, Value = message }); Thread.Sleep(INTERVAL_BETWEEN_MESSAGES); counter++; } } } } catch (Exception e) { Console.WriteLine("Exception Occurred - {0}", e.Message); } }
public MeasurementViewModel(MeasurementModel model) { UpdateWithModel(model); }
/// <summary> /// The MeasurerService calls Process method periodically as defined in plugin's config ExecuteInterval element. The time is seconds. /// Note that the same instance of this class is alive the whole time as the service is alive! So make this process as sleek and lean as possible. /// </summary> public void Process() { // read values var readConfigFile = this.settings.ReadConfigPath.GetPluginRootedPath(); ReadConfig readConfig = null; if (System.IO.File.Exists(readConfigFile)) { readConfig = SerializeHelper.DeserializeWithDCS <ReadConfig>(System.IO.File.ReadAllText(readConfigFile)); } else { readConfig = new ReadConfig(); // substract one second from current time when ReadConfig is not read from file because readStartDate is readConfig.LatestValueRead plus one second // this way when the config file does not exist we start from current time. readConfig.LatestValueRead = DateTime.Now.AddSeconds(-1.0); } DateTime readStartDate = readConfig.LatestValueRead.AddSeconds(1.0); // set startDate to latest value read + one second to not read the latest value again. // set endDate to start date + timespan of max time to read measurements or current time which ever is smaller. DateTime readEndDate = new DateTime(Math.Min(DateTime.Now.Ticks, readStartDate.Add(this.settings.MaxTimeToReadAtOnce).Ticks)); string csvDataString = this.GetCsvData(readStartDate, readEndDate); if (string.IsNullOrEmpty(csvDataString)) { return; } // Do the measurement reading here... and then create a MeasurementPackage object with a proper key to enable saving measurements to SAMI system. MeasurementPackage p = new MeasurementPackage() { Key = this.settings.SamiKey, Measurements = new List <MeasurementModel>() }; //MeasurementModel mm = null; DateTime newestReadValue = readConfig.LatestValueRead; // we have data! --> parse the csv using (var reader = new StringReader(csvDataString)) { var csv = new CsvReader(reader, new CsvConfiguration() { HasHeaderRecord = settings.HasHeaders, Delimiter = settings.DelimeterChar, Quote = settings.QuotationChar }); IFormatProvider doubleParser = System.Globalization.CultureInfo.InvariantCulture; while (csv.Read()) { MeasurementModel mm = new MeasurementModel() { Object = settings.MeasurementObject, Tag = settings.MeasurementTag }; if (settings.HasHeaders) { mm.Timestamp = csv.GetField <DateTime>(settings.MeasurementTimeFieldHeader); } else { mm.Timestamp = csv.GetField <DateTime>(settings.MeasurementTimeFieldIndex); } if (mm.Timestamp.LocalDateTime >= readStartDate && mm.Timestamp.LocalDateTime <= readEndDate) { if (mm.Timestamp > newestReadValue) { newestReadValue = mm.Timestamp.DateTime; } // append only those measurements that are in valid time range mm.Data = new List <DataModel>(); foreach (var item in settings.ItemMap) { var scale = item.Scale; double readValue; string rawValue; if (settings.HasHeaders) { rawValue = csv.GetField(item.Header); } else { rawValue = csv.GetField(item.Index); } readValue = double.Parse(rawValue.Replace(",", "."), doubleParser); mm.Data.Add(new DataModel() { Tag = item.SamiTag, Value = null != scale ? scale.ScaleValue(readValue) : readValue }); } p.Measurements.Add(mm); } } } readConfig.LatestValueRead = newestReadValue; var serialized = SerializeHelper.SerializeToStringWithDCS <ReadConfig>(readConfig); System.IO.File.WriteAllText(readConfigFile, serialized); // When your plugin has something to save raise ProcessCompleted event. The Name property can be used as ProcessCompletedEventArgs source parameter. // If at some point your plugin has nothing to save, then don't raise the event. if (null != p.Measurements && p.Measurements.Count > 0) { this.OnProcessCompleted(new ProcessCompletedEventArgs(this.Name, p)); } }
/// <summary> /// Main dbf looper /// Get sensor data from file and add it to the list of measurements /// </summary> /// <param name="dbf"></param> /// <param name="lastmeasurementtimestamp"></param> /// <param name="measurements"></param> private void AddNewMeasurements(DbfFile dbf, DateTimeOffset lastmeasurementtimestamp, List <MeasurementModel> measurements) { //raw string 'date' output from file row as yyyyMMddHHmmssfff string date; //parsed date of row DateTime rowtimestamp; //raw string 'value' output from file string value; //parse value of row double rowvalue; //loop increment (for DBF file rows) int i = 0; if (Config.VerboseLogging) { Log.Append(String.Format("Begin dbf file read {0}. File has {1} rows.", dbf.FileName, dbf.Header.RecordCount), true); } //Loop through all rows in file while (i < dbf.Header.RecordCount) { //ReadValue from row i and column 0 to get date, parse the datetime and round it down to closest 500ms increment dbf.ReadValue(i, 0, out date); rowtimestamp = DateTime.ParseExact(date.Trim(), "yyyyMMddHHmmssfff", CultureInfo.InvariantCulture); rowtimestamp = rowtimestamp.AddMilliseconds(GetMillisecondsToSubstract(rowtimestamp.Millisecond)); if (Config.VerboseLogging) { Log.Append(String.Format("Read row {0} on dbf file {1}. Row time is {2}.", i, dbf.FileName, rowtimestamp), true); } //check if row is newer than last saved measurement AND older than the LastMeasurementTime from the first parsed file if (rowtimestamp > lastmeasurementtimestamp && rowtimestamp <= NewLastMeasurementTime) { //read row value (column 1) and parse it dbf.ReadValue(i, 1, out value); rowvalue = value.Trim().ToDouble(); if (Config.VerboseLogging) { Log.Append(String.Format("Read row {0} on dbf file {1}. Row value is {2}.", i, dbf.FileName, rowvalue), true); } //check if a measurement with corresponding timestamp has already been added MeasurementModel oldmeasurement = null; if (measurements.Count > 0) { oldmeasurement = measurements.SingleOrDefault(m => m.Timestamp == rowtimestamp); } //if yes - append data to old measurement if (oldmeasurement != null) { oldmeasurement.Data.Add(new DataModel() { Tag = Path.GetFileName(dbf.FileName).Replace(".dbf", "_PILOT"), Value = rowvalue }); if (Config.VerboseLogging) { Log.Append(String.Format("Added values to old measurement {0}.", oldmeasurement.Timestamp), true); } } else //if no - add a new measurement { MeasurementModel newmeasurement = new MeasurementModel(); newmeasurement.Timestamp = rowtimestamp; newmeasurement.Object = this.Config.MeasurementObject; newmeasurement.Tag = this.Config.MeasurementTag; newmeasurement.Data = new List <DataModel>(); newmeasurement.Data.Add(new DataModel() { Tag = Path.GetFileName(dbf.FileName).Replace(".dbf", "_PILOT"), Value = rowvalue }); measurements.Add(newmeasurement); if (Config.VerboseLogging) { Log.Append(String.Format("Created new measurement {0} and added it to measurements list which now contains {1} items.", newmeasurement.Timestamp, measurements.Count), true); } } } else { if (Config.VerboseLogging) { Log.Append(String.Format("Row {0} time {1} was not between {2} and {3}, value was not added to measurements.", i, rowtimestamp, lastmeasurementtimestamp, NewLastMeasurementTime), true); } } i++; } if (Config.VerboseLogging) { Log.Append(String.Format("End dbf file read {0}. Read {1} rows.", dbf.FileName, i), true); } }
public virtual ActionResult Create() { MeasurementModel measurementModel = new MeasurementModel(); return(View(measurementModel)); }
/// <summary> /// The MeasurerService calls Process method periodically as defined in plugin's config ExecuteInterval element. The time is seconds. /// Note that the same instance of this class is alive the whole time as the service is alive! So make this process as sleek and lean as possible. /// </summary> public void Process() { var readConfigFile = this.settings.ReadConfigPath.GetPluginRootedPath(); ReadConfig readConfig = null; if (System.IO.File.Exists(readConfigFile)) { readConfig = SerializeHelper.DeserializeWithDCS <ReadConfig>(System.IO.File.ReadAllText(readConfigFile)); } else { readConfig = new ReadConfig(); } RemoteMXService.site response = null; DateTime readStartDate = readConfig.LatestValueRead.AddSeconds(1.0); // set startDate to latest value read + one second to not read the latest value again. // set endDate to start date + timespan of max time to read measurements or current time which ever is smaller. DateTime readEndDate = new DateTime(Math.Min(DateTime.Now.Ticks, readStartDate.Add(this.settings.MaxTimeToReadAtOnce).Ticks)); using (RemoteMXService.RdmSitesClient client = new RemoteMXService.RdmSitesClient()) { var sites = client.getSites(new RemoteMXService.user() { password = this.settings.Password, username = this.settings.UserName }); if (null == sites || sites.Length == 0) { Log.Append(string.Format("No sites found from RemoteMX for user {0}", this.settings.UserName)); } else { if (sites.Any(s => s.id == this.settings.SiteId)) { RemoteMXService.datareq request = new RemoteMXService.datareq() { siteId = this.settings.SiteId, username = this.settings.UserName, password = this.settings.Password, startDate = readStartDate, endDate = readEndDate }; response = client.getData(request); } else { string sitesString = ""; sites.ToList().ForEach(s => { sitesString += string.Format("Site id: {0}, name: {1}{2}", s.id, s.name, Environment.NewLine); }); throw new Exception(string.Format("Configured site id (SiteId: {1}) was not found from RemoteMX service with username {2}. {0}RemoteMX sites found:{0}{3}", Environment.NewLine, this.settings.SiteId, this.settings.UserName, sitesString)); } } } string serialized = string.Empty; if (null == response || null == response.data || response.data.Length == 0) { string messageTemplate = "No measurements found from RemoteMX for user {0} with site id {1} between {2} and {3}. Next reading will try with the same start time ({2})."; // No data --> update latest read value to readEndDate when the readEndDate is old enough. // This adds a little redundancy to data reading to allow service breaks etc. // Try to read the same time period for twice the duration of MaxTimeToReadAtOnce setting and after that move on. if (readEndDate.Add(this.settings.MaxTimeToReadAtOnce.Add(this.settings.MaxTimeToReadAtOnce)) < DateTime.Now) { readConfig.LatestValueRead = readEndDate; serialized = SerializeHelper.SerializeToStringWithDCS <ReadConfig>(readConfig); System.IO.File.WriteAllText(readConfigFile, serialized); messageTemplate = "No measurements found from RemoteMX for user {0} with site id {1} between {2} and {3}. Next reading will start with updated start time ({3})."; } Log.Append(string.Format(messageTemplate, this.settings.UserName, this.settings.SiteId, readStartDate, readEndDate)); return; } // we have data! // Do the measurement reading here... and then create a MeasurementPackage object with a proper key to enable saving measurements to SAMI system. MeasurementPackage p = new MeasurementPackage() { Key = this.settings.SamiKey, Measurements = new List <MeasurementModel>(response.data.Length) }; MeasurementModel mm = null; DateTime newestReadValue = readConfig.LatestValueRead; foreach (var item in response.data) { mm = new MeasurementModel() { Object = settings.MeasurementObject, Tag = settings.MeasurementTag, Timestamp = item.timestamp }; if (item.timestamp > newestReadValue) { newestReadValue = item.timestamp; } if (null != item.variables && item.variables.Length > 0) { mm.Data = new List <DataModel>(item.variables.Length); bool save = false; foreach (var val in item.variables) { // when SaveMappedValuesOnly == true --> save = false. Data is saved only when ChannelMap contains a map for the channel. // when SaveMappedValuesOnly == false --> save = true. Data is saved with or without ChannelMap info. save = !this.settings.SaveMappedValuesOnly; var tag = val.channel; if (this.settings.ChannelMap.ContainsKey(tag)) { tag = this.settings.ChannelMap[tag]; save = true; } if (save) { mm.Data.Add(new DataModel() { Tag = tag, Value = val.value }); } } } // NOTE! a measurement might not contain any Data items. p.Measurements.Add(mm); } readConfig.LatestValueRead = newestReadValue; serialized = SerializeHelper.SerializeToStringWithDCS <ReadConfig>(readConfig); System.IO.File.WriteAllText(readConfigFile, serialized); // When your plugin has something to save raise ProcessCompleted event. The Name property can be used as ProcessCompletedEventArgs source parameter. // If at some point your plugin has nothing to save, then don't raise the event. this.OnProcessCompleted(new ProcessCompletedEventArgs(this.Name, p)); }
private async Task StationsUpdate(RecordChangedEventArgs <DataAccess.EF.Station> e) { await Task.Delay(1); if (e.ChangeType == ChangeType.None) { return; } if (e.ChangeType == ChangeType.Delete) { var s = MapControl.Markers.FirstOrDefault( c => c.Position == new PointLatLng(Convert.ToDouble(e.Entity.Latitude), Convert.ToDouble(e.Entity.Longitude))); if (s == null) { return; } MapControl.Markers.Remove(s); } if (e.ChangeType == ChangeType.Insert || e.ChangeType == ChangeType.Update) { try { if (e.ChangeType == ChangeType.Update) { var s = MapControl.Markers.FirstOrDefault( c => c.Position == new PointLatLng(Convert.ToDouble(e.Entity.Latitude), Convert.ToDouble(e.Entity.Longitude))); if (s == null) { return; } MapControl.Markers.Remove(s); } var newmarker = new GMapMarker(new PointLatLng(Convert.ToDouble(e.Entity.Latitude), Convert.ToDouble(e.Entity.Longitude))); var x = Gr; var meas = await Task.Run( () => _repository.Measurements.GetRangeAsync(c => c.StationId == e.Entity.StationId)); var m = meas.OrderByDescending(c => c.Date).FirstOrDefault(); var measurement = new MeasurementModel(m, _repository) { AssociatedStation = new StationModel(e.Entity, _repository) }; if (x != null) { x.DataContext = measurement; newmarker.Shape = x; newmarker.Offset = new Point(-25, -25); newmarker.ZIndex = 0; } newmarker.Shape.MouseLeftButtonDown += ShapeOnMouseLeftButtonDown; MapControl.Markers.Add(newmarker); } catch (Exception) { } } }
/// <summary> /// The MeasurerService calls Process method periodically as defined in plugin's config ExecuteInterval element. The time is seconds. /// Note that the same instance of this class is alive the whole time as the service is alive! So make this process as sleek and lean as possible. /// </summary> public void Process() { m_Server = new Server(); m_Server.CertificateEvent += new certificateValidation(opcUaServer_CertificateEvent); // Connect with URL from Server URL m_Server.Connect(this.settings.OpcUAServiceUrl); ReadNamespaceFromServer(); // read values NodeIdCollection nodesToRead = new NodeIdCollection(); DataValueCollection results; int expectedResultsCount = this.settings.OPCUAItemMap.Count; Dictionary <string, OPCUAItem> itemMap = new Dictionary <string, OPCUAItem>(expectedResultsCount); this.settings.OPCUAItemMap.ForEach(m => { itemMap.Add(m.Identifier, m); nodesToRead.Add(new NodeId(m.Identifier, m_NameSpaceIndex)); }); // Read the values m_Server.ReadValues(nodesToRead, out results); if (results.Count != expectedResultsCount) { throw new Exception("Reading value returned unexptected number of result"); } //// we have data! // Do the measurement reading here... and then create a MeasurementPackage object with a proper key to enable saving measurements to SAMI system. MeasurementPackage p = new MeasurementPackage() { Key = this.settings.SamiKey, Measurements = new List <MeasurementModel>(results.Count) }; MeasurementModel mm = null; mm = new MeasurementModel() { Object = settings.MeasurementObject, Tag = settings.MeasurementTag, Timestamp = results[0].SourceTimestamp.ToLocalTime(), Data = new List <DataModel>(results.Count) }; ValueLinearScale scale = null; OPCUAItem opcUAItem = null; for (int i = 0; i < results.Count; i++) { scale = null; var tag = this.settings.OPCUAItemMap[i].Identifier; if (itemMap.ContainsKey(tag)) { opcUAItem = itemMap[tag]; tag = opcUAItem.SamiTag; scale = opcUAItem.Scale; } var dm = new DataModel() { Tag = tag }; if (null != results[i].Value) { if (null == scale) { dm.Value = Convert.ToDouble(results[i].Value); } else { dm.Value = scale.ScaleValue(Convert.ToDouble(results[i].Value)); } } mm.Data.Add(dm); } p.Measurements.Add(mm); // your plugin may throw exceptions and those will be logged in the service, but you can also handle your exceptions and log them if needed. // When your plugin has something to save raise ProcessCompleted event. The Name property can be used as ProcessCompletedEventArgs source parameter. // If at some point your plugin has nothing to save, then don't raise the event. this.OnProcessCompleted(new ProcessCompletedEventArgs(this.Name, p)); m_Server.Disconnect(); m_Server.CertificateEvent -= new certificateValidation(opcUaServer_CertificateEvent); m_Server = null; }