public static void ExportAsCSV(Session session, string filename) { // Write info for each spectrum to csv file using (StreamWriter writer = new StreamWriter(filename, false, Encoding.UTF8)) { // Write header line writer.WriteLine("Session name|Session index|Time start (UTC)|Time end (UTC)|Latitude start|Latitude end|Longitude start|Longitude end|Altitude start|Altitude end|Doserate|Doserate unit"); foreach (Spectrum s in session.Spectrums) { double dose = s.Doserate / 1000d; // Write spectrum line writer.WriteLine( s.SessionName + "|" + s.SessionIndex.ToString() + "|" + s.GpsTimeStart.ToString("yyyy-MM-ddTHH:mm:ss") + "|" + s.GpsTimeEnd.ToString("yyyy-MM-ddTHH:mm:ss") + "|" + s.LatitudeStart.ToString(CultureInfo.InvariantCulture) + "|" + s.LatitudeEnd.ToString(CultureInfo.InvariantCulture) + "|" + s.LongitudeStart.ToString(CultureInfo.InvariantCulture) + "|" + s.LongitudeEnd.ToString(CultureInfo.InvariantCulture) + "|" + s.AltitudeStart.ToString(CultureInfo.InvariantCulture) + "|" + s.AltitudeEnd.ToString(CultureInfo.InvariantCulture) + "|" + dose.ToString(CultureInfo.InvariantCulture) + "|μSv/h"); } } }
public static void ExportAsCHN(Session session, string path) { // Generate a CHN file for each spectrum foreach(Spectrum s in session.Spectrums) { string sessionPath = path + Path.DirectorySeparatorChar + session.Name + "_CHN"; if (!Directory.Exists(sessionPath)) Directory.CreateDirectory(sessionPath); string filename = sessionPath + Path.DirectorySeparatorChar + s.SessionIndex.ToString() + ".chn"; using (BinaryWriter writer = new BinaryWriter(File.Create(filename))) { string dateStr = s.GpsTimeStart.ToString("ddMMMyy") + "1"; string timeStr = s.GpsTimeStart.ToString("HHmm"); string secStr = s.GpsTimeStart.ToString("ss"); writer.Write(Convert.ToInt16(-1)); // signature writer.Write(Convert.ToInt16(s.SpectralInput)); // detector id writer.Write(Convert.ToInt16(0)); // segment writer.Write(Encoding.ASCII.GetBytes(secStr)); // seconds start Int32 rt = s.Realtime / 1000; // ms rt = rt / 20; // increments of 20 ms writer.Write(rt); // realtime Int32 lt = s.Livetime / 1000; // ms lt = lt / 20; // increments of 20 ms writer.Write(lt); // livetime writer.Write(Encoding.ASCII.GetBytes(dateStr.ToUpper())); // date writer.Write(Encoding.ASCII.GetBytes(timeStr)); // time writer.Write(Convert.ToInt16(0)); // channel offset writer.Write(Convert.ToInt16(s.NumChannels)); // number of channels // Channel counts foreach (float ch in s.Channels) writer.Write(Convert.ToInt32(ch)); } } }
public FormSessionInfo(Session sess, string title) { InitializeComponent(); Text = "Crash - " + title; session = sess; }
public void SaveSession(Session s) { // Save session info to disk string sessionSettingsFile = settings.SessionRootDirectory + Path.DirectorySeparatorChar + s.Name + Path.DirectorySeparatorChar + "session.json"; string jSessionInfo = JsonConvert.SerializeObject(s, Newtonsoft.Json.Formatting.Indented); using (TextWriter writer = new StreamWriter(sessionSettingsFile)) writer.Write(jSessionInfo); }
private bool dispatchRecvMsg(burn.Message msg) { // Handle messages received from network Detector det = null; DetectorType detType = null; switch (msg.Command) { case "connect_ok": // Connection successful Utils.Log.Add("RECV: Connected to " + msg.Arguments["host"] + ":" + msg.Arguments["port"]); // Send a ping command to ensure a healthy connection burn.Message msgPing = new burn.Message("ping", null); sendMsg(msgPing); Utils.Log.Add("SEND: Sending ping message"); break; case "connect_failed": // Connection failed connected = false; Utils.Log.Add("RECV: Connection failed for " + msg.Arguments["host"] + ":" + msg.Arguments["port"] + " " + msg.Arguments["message"]); break; case "disconnect_ok": // Disconnect successful connected = false; lblConnectionStatus.ForeColor = Color.Red; lblConnectionStatus.Text = "Not connected"; Utils.Log.Add("RECV: Disconnected from peer"); // Change to session tab if (tabs.SelectedTab == pageSetup) tabs.SelectedTab = pageSessions; break; case "ping_ok": // Ping command received, update state connected = true; lblConnectionStatus.ForeColor = Color.Green; lblConnectionStatus.Text = "Connected to " + settings.LastIP + ":" + settings.LastPort; Utils.Log.Add("RECV: Received ping_ok from peer"); break; case "close_ok": // Remove service closed, close down network thread and update state netService.RequestStop(); netThread.Join(); connected = false; lblConnectionStatus.ForeColor = Color.Red; lblConnectionStatus.Text = "Not connected"; Utils.Log.Add("RECV: Disconnected from peer, peer closed"); break; case "new_session_ok": // New session created successfully bool prev = msg.Arguments["preview"].ToString() == "1"; if (prev) { // New session is a preview session, update log Utils.Log.Add("RECV: Preview session started"); } else { // New session is a normal session string sessionName = msg.Arguments["session_name"].ToString(); Utils.Log.Add("RECV: New session started: " + sessionName); // Create a session object and update state float livetime = Convert.ToSingle(msg.Arguments["livetime"]); int iterations = Convert.ToInt32(msg.Arguments["iterations"]); det = (Detector)cboxSetupDetector.SelectedItem; detType = settings.DetectorTypes.Find(dt => dt.Name == det.TypeName); session = new Session(settings.SessionRootDirectory, sessionName, "", livetime, iterations, det, detType); // Create session files and directories SaveSession(session); // Notify external forms about new session formWaterfallLive.SetSession(session); formROILive.SetSession(session); frmMap.SetSession(session); sessionRunning = true; } btnSetupStartTest.Enabled = false; btnSetupStopTest.Enabled = true; break; case "new_session_failed": // Creation of new session failed, log error message Utils.Log.Add("RECV: New session failed: " + msg.Arguments["message"]); break; case "stop_session_ok": // Stop session successful, update state Utils.Log.Add("RECV: Session stopped"); sessionRunning = false; btnSetupStartTest.Enabled = true; btnSetupStopTest.Enabled = false; break; case "session_finished": // Session finished successfully Utils.Log.Add("RECV: Session " + msg.Arguments["session_name"] + " finished"); sessionRunning = false; break; case "error": // An error occurred, log error message Utils.Log.Add("RECV: Error: " + msg.Arguments["message"]); break; case "error_socket": // An socket error occurred, log error message Utils.Log.Add("RECV: Socket error: " + msg.Arguments["error_code"] + " " + msg.Arguments["message"]); break; case "set_gain_ok": // Set gain command executed successfully Utils.Log.Add("RECV: set_gain ok: " + msg.Arguments["voltage"] + " " + msg.Arguments["coarse_gain"] + " " + msg.Arguments["fine_gain"] + " " + msg.Arguments["num_channels"] + " " + msg.Arguments["lld"] + " " + msg.Arguments["uld"]); // Update selected detector parameters det = (Detector)cboxSetupDetector.SelectedItem; det.CurrentHV = Convert.ToInt32(msg.Arguments["voltage"]); det.CurrentCoarseGain = Convert.ToDouble(msg.Arguments["coarse_gain"]); det.CurrentFineGain = Convert.ToDouble(msg.Arguments["fine_gain"]); det.CurrentNumChannels = Convert.ToInt32(msg.Arguments["num_channels"]); det.CurrentLLD = Convert.ToInt32(msg.Arguments["lld"]); det.CurrentULD = Convert.ToInt32(msg.Arguments["uld"]); // Update state btnSetupNext.Enabled = true; panelSetupGraph.Enabled = true; break; case "spectrum": // Session spectrum received successfully Spectrum spec = new Spectrum(msg); spec.CalculateDoserate(session.Detector, session.GEFactor); if (spec.IsPreview) { // Spectrum is a preview spectrum Utils.Log.Add("RECV: " + spec.Label + " preview spectrum received"); // Merge spectrum with our preview spectrum if (previewSpec == null) previewSpec = spec; else previewSpec.Merge(spec); // Reset and prepare setup graph GraphPane pane = graphSetup.GraphPane; pane.Chart.Fill = new Fill(SystemColors.ButtonFace); pane.Fill = new Fill(SystemColors.ButtonFace); pane.Title.Text = "Setup"; pane.XAxis.Title.Text = "Channel"; pane.YAxis.Title.Text = "Counts"; // Update setup graph setupGraphList.Clear(); for (int i = 0; i < previewSpec.Channels.Count; i++) setupGraphList.Add((double)i, (double)previewSpec.Channels[i]); pane.XAxis.Scale.Min = 0; pane.XAxis.Scale.Max = previewSpec.MaxCount; pane.YAxis.Scale.Min = 0; pane.YAxis.Scale.Max = previewSpec.MaxCount + (previewSpec.MaxCount / 10.0); pane.CurveList.Clear(); LineItem curve = pane.AddCurve("Spectrum", setupGraphList, Color.Red, SymbolType.None); curve.Line.Fill = new Fill(SystemColors.ButtonFace, Color.Red, 45F); pane.Chart.Fill = new Fill(SystemColors.ButtonFace, SystemColors.ButtonFace); pane.Legend.Fill = new Fill(SystemColors.ButtonFace, SystemColors.ButtonFace); pane.Fill = new Fill(SystemColors.ButtonFace, SystemColors.ButtonFace); graphSetup.RestoreScale(pane); graphSetup.AxisChange(); graphSetup.Refresh(); } else { // Normal session spectrum received successfully Utils.Log.Add("RECV: " + spec.Label + " session spectrum received"); // FIXME: Make sure session is allocated in case spectrums are ticking in // Store spectrum to disk string sessionPath = settings.SessionRootDirectory + Path.DirectorySeparatorChar + session.Name; string jsonPath = sessionPath + Path.DirectorySeparatorChar + "json"; if (!Directory.Exists(jsonPath)) Directory.CreateDirectory(jsonPath); string json = JsonConvert.SerializeObject(msg, Newtonsoft.Json.Formatting.Indented); using (TextWriter writer = new StreamWriter(jsonPath + Path.DirectorySeparatorChar + spec.SessionIndex + ".json")) { writer.Write(json); } // Add spectrum to session session.Add(spec); // Add spectrum to UI list lbSession.Items.Insert(0, spec); // Notify external forms about new spectrum frmMap.AddMarker(spec); formWaterfallLive.UpdatePane(); formROILive.UpdatePane(); } break; default: // Unhandled message received, update log string info = msg.Command + " -> "; foreach (KeyValuePair<string, object> item in msg.Arguments) info += item.Key + ":" + item.Value.ToString() + ", "; Utils.Log.Add("RECV: Unhandeled command: " + info); break; } return true; }
public FormROIHist(Session sess, List<ROIData> roiList) { InitializeComponent(); session = sess; ROIList = roiList; }
public void SetSession(Session sess) { session = sess; }
public void ClearSession() { if(bmpPane != null) { Graphics g = Graphics.FromImage(bmpPane); g.Clear(SystemColors.ButtonFace); } session = null; }
public void ClearSession() { if(bmpPane != null) { Graphics g = Graphics.FromImage(bmpPane); g.Clear(Color.FromArgb(0, 0, 255)); } session = null; }
public bool SetBackground(Session bkg) { // Set background counts for this session and adjust for livetime if (bkg == null) { Background = null; return true; } if (IsEmpty || !IsLoaded) return false; Background = bkg.GetAdjustedCounts(Livetime); return true; }
private void menuItemLoadBackgroundSession_Click(object sender, EventArgs e) { // Sanity checks if (!session.IsLoaded) { MessageBox.Show("Session is not loaded"); return; } FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.SelectedPath = settings.SessionRootDirectory; dialog.Description = "Select background session directory"; dialog.ShowNewFolderButton = false; if (dialog.ShowDialog() == DialogResult.OK) { ClearBackground(); Session bkgSess = new Session(); string bkgSessionFile = dialog.SelectedPath + Path.DirectorySeparatorChar + "session.json"; if (!File.Exists(bkgSessionFile)) { Utils.Log.Add("ERROR: Can not load background session. Directory " + dialog.SelectedPath + " has no session.json file"); return; } // Deserialize session object bkgSess = JsonConvert.DeserializeObject<Session>(File.ReadAllText(bkgSessionFile)); if (!bkgSess.LoadGEFactor()) Utils.Log.Add("WARNING: Loading GEFactor failed for background session " + bkgSess.Name); // Load background spectrums if (!bkgSess.LoadSpectrums(dialog.SelectedPath)) { Utils.Log.Add("ERROR: Loading spectrums failed for background session " + bkgSess.Name); return; } // Make sure session and backgrouns has the same number of channels if (bkgSess.NumChannels != session.NumChannels) { bkgSess.Clear(); MessageBox.Show("Cannot load a background with different number of channels than the session"); return; } // Store background in session session.SetBackground(bkgSess); lblBackground.Text = "Background: " + bkgSess.Name; Utils.Log.Add("Background " + bkgSess.Name + " loaded for session " + session.Name); } }
public static void ExportAsKMZ(Session session, string filename) { // Save session info as a KMZ file string kmzFile = filename; string kmlFile = Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".kml"; string donutFile = CrashEnvironment.SettingsPath + Path.DirectorySeparatorChar + "donut.png"; using (XmlWriter writer = XmlWriter.Create(kmlFile)) { // Initialize KML document writer.WriteStartDocument(); writer.WriteStartElement("kml"); writer.WriteString("\n"); writer.WriteStartElement("Document"); writer.WriteString("\n"); // Store KML styles KmlStyle s = new KmlStyle(); string[] colors = { "FFF0B414", "FF00D214", "FF78FFF0", "FF1478FF", "FF1400FF" }; // IAEA color codes XmlSerializer serializer = new XmlSerializer(typeof(KmlStyle)); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); for(int i = 0; i < 5; i++) { s.ID = i.ToString(); s.IconStyle.Icon.Href = "files/donut.png"; s.IconStyle.Scale = "1.0"; s.IconStyle.Color = colors[i]; s.LabelStyle.Scale = "1.0"; serializer.Serialize(writer, s, ns); writer.WriteString("\n"); } // Store a KML placemark for each spectrum serializer = new XmlSerializer(typeof(KmlPlacemark)); KmlPlacemark p = new KmlPlacemark(); int styleID = 0; foreach (Spectrum spec in session.Spectrums) { double dose = spec.Doserate / 1000d; // Convert Doserate to micro // Calculate the style id for this sample if(dose <= 1d) styleID = 0; else if (dose <= 5) styleID = 1; else if (dose <= 10) styleID = 2; else if (dose <= 20) styleID = 3; else styleID = 4; p.Name = ""; p.StyleURL = "#" + styleID.ToString(); p.TimeStamp.When = spec.GpsTimeStart.ToString("yyyy-MM-ddTHH:mm:ss"); p.Point.Coordinates = spec.LongitudeStart.ToString(CultureInfo.InvariantCulture) + "," + spec.LatitudeStart.ToString(CultureInfo.InvariantCulture); p.Description = "Value: " + dose.ToString("e", CultureInfo.InvariantCulture) + " μSv/h" + "\nLatitude: " + spec.LatitudeStart.ToString(CultureInfo.InvariantCulture) + "\nLongitude: " + spec.LongitudeStart.ToString(CultureInfo.InvariantCulture) + "\nAltitude: " + spec.AltitudeStart.ToString(CultureInfo.InvariantCulture) + "\nTime: " + spec.GpsTimeStart.ToString("yyyy-MM-dd HH:mm:ss") + " UTC"; serializer.Serialize(writer, p, ns); writer.WriteString("\n"); } // Finish KML document writer.WriteEndElement(); writer.WriteString("\n"); writer.WriteEndElement(); writer.WriteEndDocument(); } // Create a icon file to use for placemarks Bitmap bmpDonut = new Bitmap(crash.Properties.Resources.donut); bmpDonut.Save(donutFile, ImageFormat.Png); // Zip the KML and icon files to create a KMZ file using (ZipFile zip = new ZipFile()) { zip.AddFile(kmlFile, ""); zip.AddFile(donutFile, "files"); zip.Save(kmzFile); } // Delete temporary files if (File.Exists(donutFile)) File.Delete(donutFile); if(File.Exists(kmlFile)) File.Delete(kmlFile); }
public void ClearSession() { currentSession = null; RemoveAllMarkers(); }
public void SetSession(Session sess) { currentSession = sess; RemoveAllMarkers(); }