// Init map model, get source type and read rate. public MapModel(ISource MapSourceSet, int TimeSet) { // Delete table if exist. using (var db = new Ex3Context()) { db.Database.Delete(); // db.Database.ExecuteSqlCommand("TRUNCATE TABLE [FlightDatas]"); db.SaveChanges(); } // Set the map source, add listener, define timer(with default 4 times second reading rate). this.MapSource = MapSourceSet; this.MapSource.PropertyChanged += MapSource_PropertyChanged; // Init timer, add listener for event read(bind to server response). aTimer = new System.Timers.Timer { Enabled = true, }; if (TimeSet <= 0) { aTimer.AutoReset = false; // Default interval is 100ms. } else { aTimer.AutoReset = true; aTimer.Interval = 1000 / TimeSet; } this.aTimer.Elapsed += (sender, e) => EventRead(this, null, MapSource); }
// Event read, create request to flightgear, get responce, and update sql. public void EventRead(object source, ElapsedEventArgs e, ISource sourceRead) { try { // Convert the data returned, use ex3context connection, init dbset and insert, save changed. double[] arr = Array.ConvertAll(sourceRead.Read().Split(','), Double.Parse); using (var db = new Ex3Context()) { db.FlightDatas.Add(new FlightData { Id = db.FlightDatas.Count(), Lon = arr[0], Lat = arr[1], Rudder = arr[2], Throttle = arr[3] }); db.SaveChanges(); } } catch (Exception) { }; }