protected void DownloadCallback(IntPtr reference, int deviceId, OmApi.OM_DOWNLOAD_STATUS status, int value) { lock (cacheProgressValue) { // HACK: Only update if the percentage value changes if (cacheProgressValue.ContainsKey(deviceId)) { if (status != OmApi.OM_DOWNLOAD_STATUS.OM_DOWNLOAD_PROGRESS) { cacheProgressValue.Remove(deviceId); // Remove } else { if (cacheProgressValue[deviceId] == value) { return; // Ignore same percentage value } else { cacheProgressValue[deviceId] = value; // Update } } } } //Console.WriteLine("" + status + " - " + deviceId); OmDevice device = GetDevice((uint)deviceId); if (device == null) { return; } device.UpdateDownloadStatus(status, value); }
protected void DeviceCallback(IntPtr reference, int deviceId, OmApi.OM_DEVICE_STATUS status) { Console.WriteLine("" + status + " - " + (uint)deviceId); OmDevice device = GetDevice((uint)deviceId); if (device == null) { return; } if (status == OmApi.OM_DEVICE_STATUS.OM_DEVICE_CONNECTED) { device.SetConnected(true); if (DeviceAttached != null) { DeviceAttached(this, new OmDeviceEventArgs(device)); } } else if (status == OmApi.OM_DEVICE_STATUS.OM_DEVICE_REMOVED) { device.SetConnected(false); if (DeviceRemoved != null) { DeviceRemoved(this, new OmDeviceEventArgs(device)); } } }
public OmDevice GetDevice(uint deviceId) { OmDevice device = null; if (deviceId != 0) { // Obtain a reference to the device object, or create one if new if (devices.ContainsKey(deviceId)) { device = devices[deviceId]; } else { device = new OmDevice(this, deviceId); lock (devices) { devices[deviceId] = device; } } } return(device); }
public OmDevice GetDevice(int deviceId) { OmDevice device = null; if (deviceId >= 0 && deviceId < ushort.MaxValue) { // Obtain a reference to the device object, or create one if new if (devices.ContainsKey((ushort)deviceId)) { device = devices[(ushort)deviceId]; } else { device = new OmDevice(this, (ushort)deviceId); lock (devices) { devices[(ushort)deviceId] = device; } } } return(device); }
bool CheckFirmware(OmDevice[] devices) { // Read bootload information from file string bootloadExecutable = null; string latestVersion = ""; IDictionary<string, string> blacklist = new Dictionary<string, string>(); // Black-list of version numbers // Find bootload information file string bootloadInformation = @"firmware\bootload.ini"; // Search current directory first if (!File.Exists(bootloadInformation)) { // Search under executable folder bootloadInformation = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + bootloadInformation; } if (!File.Exists(bootloadInformation)) { Trace.WriteLine("Firmware information file not found " + bootloadInformation + ""); return false; } // Read bootload information string[] lines = new string[0]; try { lines = File.ReadAllLines(bootloadInformation); } catch (Exception e) { Trace.WriteLine("Problem reading firmware information file " + bootloadInformation + " (" + e.Message + ")."); return false; } // Rough .INI parser string section = ""; foreach (string rawLine in lines) { string line = rawLine.Trim(); if (line.Length == 0 || line.StartsWith(";") || line.StartsWith("#")) { continue; } // Empty lines and comments if (line.StartsWith("[") && line.EndsWith("]")) { section = line.Substring(1, line.Length - 2); continue; } // Section string[] parts = line.Split(new char[] {'=', ':'}, 2); if (parts.Length <= 0) { continue; } string name = parts[0].Trim(); string value = (parts.Length > 1) ? parts[1].Trim() : null; if (section == "upgrade") { blacklist.Add(name, value); } else if (section == "bootload") { if (name == "executable") { bootloadExecutable = value; } // @"firmware\CWA17_44.cmd" else if (name == "version") { latestVersion = value; } // @"CWA17_44" } } // Check firmware version foreach (OmDevice device in devices) { string currentFirmware = "CWA17_" + device.FirmwareVersion + ""; if (blacklist.ContainsKey(currentFirmware)) { string reason = blacklist[currentFirmware]; DialogResult drUpdate = MessageBox.Show(this, "Device " + device.DeviceId + " is running firmware version " + currentFirmware + ".\r\n\r\n" + reason + "\r\n\r\nUpdate the device firmware to " + latestVersion + " now?", "Firmware Update Receommended", MessageBoxButtons.YesNo, MessageBoxIcon.Information); Console.WriteLine("FIRMWARE: Device " + device.DeviceId + " is running firmware version " + currentFirmware + " - update to version " + latestVersion + " (Reason: " + reason + ")."); if (drUpdate == System.Windows.Forms.DialogResult.Yes) { DialogResult okUpdate = MessageBox.Show(this, "Important:\r\n\r\n* Do not disconnect device " + device.DeviceId + ".\r\n\r\n* Do not connect any new devices.\r\n\r\n* Check no devices are currently flashing red.\r\n\r\nContinue?", "Firmware Update Warnings", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); if (okUpdate == System.Windows.Forms.DialogResult.OK) { if (device.IsDownloading) { MessageBox.Show(this, "Device is busy downloading data.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return true; } Cursor.Current = Cursors.WaitCursor; dataViewer.CancelPreview(); Process updateProcess = new Process(); BackgroundWorker updateBackgroundWorker = new BackgroundWorker(); updateBackgroundWorker.WorkerReportsProgress = true; updateBackgroundWorker.WorkerSupportsCancellation = false; updateBackgroundWorker.DoWork += (s, ea) => { updateBackgroundWorker.ReportProgress(-1, "Running bootloader..."); // Convert the file ProcessStartInfo processInformation = new ProcessStartInfo(); processInformation.FileName = bootloadExecutable; List<string> args = new List<string>(); //args.Add("\"" + param + "\""); // Construct arguments processInformation.Arguments = string.Join(" ", args.ToArray()); processInformation.UseShellExecute = false; // ??? bool redirect = true; processInformation.RedirectStandardError = redirect; processInformation.RedirectStandardOutput = true; processInformation.CreateNoWindow = (processInformation.RedirectStandardError || processInformation.RedirectStandardOutput) ? true : false; updateProcess.EnableRaisingEvents = true; updateProcess.StartInfo = processInformation; try { updateProcess.Start(); } catch (Exception ex) { updateBackgroundWorker.ReportProgress(100, "Problem running bootloader (" + ex.Message + ")."); MessageBox.Show(null, "Problem running bootloader (" + ex.Message + ").", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } updateBackgroundWorker.ReportProgress(-1, "Resetting device..."); if (device.Reset() != 0) { updateBackgroundWorker.ReportProgress(100, "Problem resetting device."); updateProcess.StandardInput.Write((char)27); try { updateProcess.Kill(); } catch { ; } try { updateProcess.WaitForExit(); } catch { ; } updateProcess = null; MessageBox.Show(null, "Problem resetting device.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (redirect) { for (; ; ) { //if (updateProcess.StandardError.EndOfStream) { break; } string line = updateProcess.StandardError.ReadLine(); if (line == null) { break; } Trace.WriteLine("BOOTLOADER: " + line); updateBackgroundWorker.ReportProgress(-1, "BOOTLOADER: " + line); } } updateBackgroundWorker.ReportProgress(-1, "Waiting for bootloader to complete..."); updateProcess.WaitForExit(); int exitCode = updateProcess.ExitCode; updateProcess = null; if (exitCode != 0) { updateBackgroundWorker.ReportProgress(100, "Problem running bootloader (exit code " + exitCode + ")"); MessageBox.Show(null, "Problem running bootloader (exit code " + exitCode + ").", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } updateBackgroundWorker.ReportProgress(100, "Done - wait for device to restart..."); Thread.Sleep(2000); }; updateBackgroundWorker.RunWorkerCompleted += (s, ea) => { //devicesListViewUpdateEnabled(); if (updateProcess != null) { try { updateProcess.Kill(); } catch { ; } try { updateProcess.WaitForExit(); } catch { ; } updateProcess = null; } }; ShowProgressWithBackground("Updating", "Updating device...", updateBackgroundWorker); Cursor.Current = Cursors.Default; } // Let's not do anything else (the user can just press 'clear' or 'record' again) return true; } } else { Console.WriteLine("FIRMWARE: Device " + device.DeviceId + " is running firmware version " + currentFirmware + " (not required to update to version " + latestVersion + ")."); } } return false; }
private void toolStripButtonStop_Click(object sender, EventArgs e) { OmDevice[] devices = new OmDevice[devicesListView.SelectedItems.Count]; for (int i = 0; i < devicesListView.SelectedItems.Count; i++) { devices[i] = (OmDevice)devicesListView.SelectedItems[i].Tag; } int devicesStopped = 0; dataViewer.CancelPreview(); Cursor.Current = Cursors.WaitCursor; BackgroundWorker stopBackgroundWorker = new BackgroundWorker(); stopBackgroundWorker.WorkerReportsProgress = true; stopBackgroundWorker.WorkerSupportsCancellation = true; stopBackgroundWorker.DoWork += (s, ea) => { List<string> fails = new List<string>(); int i = 0; //Set up all the devices foreach (OmDevice device in devices) { bool error = false; if (device is OmDevice && !((OmDevice)device).IsDownloading && ((OmDevice)device).IsRecording != OmDevice.RecordStatus.Stopped) { stopBackgroundWorker.ReportProgress(-1, "Stopping device " + (i + 1) + " of " + devices.Length + "."); if (!((OmDevice)device).NeverRecord()) { error = true; } else { devicesStopped++; } } if (error) { fails.Add(device.DeviceId.ToString()); } i++; } stopBackgroundWorker.ReportProgress(100, "Done"); if (fails.Count > 0) { this.Invoke(new Action(() => MessageBox.Show(this, "Failed operation on " + fails.Count + " device(s):\r\n" + string.Join("; ", fails.ToArray()) + ADVICE, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1) )); } }; stopBackgroundWorker.RunWorkerCompleted += (s, ea) => { int[] selected = new int[devicesListView.SelectedIndices.Count]; devicesListView.SelectedIndices.CopyTo(selected, 0); devicesListView.SelectedIndices.Clear(); devicesListViewUpdateEnabled(); foreach (int i in selected) { devicesListView.SelectedIndices.Add(i); } }; ShowProgressWithBackground("Stopping", "Stopping devices...", stopBackgroundWorker); devicesListViewUpdateEnabled(); Cursor.Current = Cursors.Default; }
//private void toolStripButtonRecord_Click(object sender, EventArgs e) //{ // //TS - [P] - If nothing is downloading then cancel preview of dataViewer and turn on AlwaysRecord() for each device selected. // if (EnsureNoSelectedDownloading()) // { // List<string> fails = new List<string>(); // dataViewer.CancelPreview(); // Cursor.Current = Cursors.WaitCursor; // foreach (ListViewItem i in devicesListView.SelectedItems) // { // OmSource device = (OmSource)i.Tag; // if (device is OmDevice && !((OmDevice)device).IsDownloading) // { // if (!((OmDevice)device).AlwaysRecord()) // fails.Add(device.DeviceId.ToString()); // } // } // Cursor.Current = Cursors.Default; // if (fails.Count > 0) { MessageBox.Show(this, "Failed operation on " + fails.Count + " device(s):\r\n" + string.Join("; ", fails.ToArray()), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); } // } // devicesListViewUpdateEnabled(); //} private void toolStripButtonRecord_Click(object sender, EventArgs e) { OmDevice[] devices = new OmDevice[devicesListView.SelectedItems.Count]; for (int i = 0; i < devicesListView.SelectedItems.Count; i++) { devices[i] = (OmDevice) devicesListView.SelectedItems[i].Tag; } // Check none are downloading if (!EnsureNoSelectedDownloading()) { return; } // Check and prompt for firmware updates if (CheckFirmware(devices)) { // Don't do anything else now (user can press button again) return; } DateRangeForm rangeForm = new DateRangeForm("Recording Settings", devices); DialogResult dr = rangeForm.ShowDialog(); if (dr == System.Windows.Forms.DialogResult.OK) { Cursor.Current = Cursors.WaitCursor; //DateTime start = DateTime.MinValue; //DateTime stop = DateTime.MaxValue; //List<string> fails = new List<string>(); //List<string> fails2 = new List<string>(); dataViewer.CancelPreview(); //Cursor.Current = Cursors.WaitCursor; BackgroundWorker recordBackgroundWorker = new BackgroundWorker(); recordBackgroundWorker.WorkerReportsProgress = true; recordBackgroundWorker.WorkerSupportsCancellation = true; recordBackgroundWorker.DoWork += (s, ea) => { Dictionary<string,string> fails = new Dictionary<string,string>(); int i = 0; //Set up all the devices foreach (OmDevice device in devices) { string error = null; try { if (device is OmDevice && !((OmDevice)device).IsDownloading) { string devicePath = null; string dataFile = ((OmDevice)device).Filename; if (dataFile != null && dataFile.Length > 0) { devicePath = Path.GetDirectoryName(dataFile); } // Nothing wrong so far... string message = "Configuring device " + (i + 1) + " of " + devices.Length + ".... "; recordBackgroundWorker.ReportProgress((100 * (5 * i + 0) / (devices.Length * 5)), message + "(session)"); //Set SessionID if (error == null && !((OmDevice)device).SetSessionId((uint)rangeForm.SessionID, false)) error = "Failed to set session ID"; recordBackgroundWorker.ReportProgress((100 * (5 * i + 1) / (devices.Length * 5)), message + "(metadata)"); // Safe to do this as metadata cleared when device cleared if (error == null && rangeForm.metaData.Length > 0) { if (OmApi.OM_FAILED(OmApi.OmSetMetadata(device.DeviceId, rangeForm.metaData, rangeForm.metaData.Length))) error = "Metadata set failed"; } // Check 'max samples' is always zero OmApi.OmSetMaxSamples(device.DeviceId, 0); recordBackgroundWorker.ReportProgress((100 * (5 * i + 2) / (devices.Length * 5)), message + "(config)"); //Sampling Freq and Range if (error == null && OmApi.OM_FAILED(OmApi.OmSetAccelConfig(device.DeviceId, (int)rangeForm.SamplingFrequency, rangeForm.Range))) error = "Accel. config failed"; recordBackgroundWorker.ReportProgress((100 * (5 * i + 3) / (devices.Length * 5)), message + "(time sync)"); //Do Sync Time if (error == null) { //Cursor.Current = Cursors.WaitCursor; //foreach (ListViewItem i in devicesListView.SelectedItems) //{ // OmSource device = (OmSource)i.Tag; if (device is OmDevice && ((OmDevice)device).Connected) { if (!((OmDevice)device).SyncTime()) error = "Time sync. failed"; } } if (device is OmDevice && ((OmDevice)device).Connected) { ((OmDevice)device).SetDebug(rangeForm.Flash ? 3 : 0); } recordBackgroundWorker.ReportProgress((100 * (5 * i + 4) / (devices.Length * 5)), message + "(interval)"); // Set the devices to record -- IMPORTANT: This also 'commits' the settings to the device if (error == null) { if (rangeForm.Always) { //TS - Taken from Record button if (!((OmDevice)device).AlwaysRecord()) error = "Set interval (always) failed"; } else { //Do datetime intervals DateTime start = rangeForm.StartDate; DateTime stop = rangeForm.EndDate; if (!((OmDevice)device).SetInterval(start, stop)) error = "Set interval failed"; } } // Check unpacked if (rangeForm.Unpacked) { recordBackgroundWorker.ReportProgress((100 * (5 * i + 4) / (devices.Length * 5)), message + "(unpacked setting)"); if (devicePath != null && devicePath.Length > 0) { // Wait to allow drive to re-mount System.Threading.Thread.Sleep(800); bool success = false; for (int retries = 0; retries < 15 * 4; retries++) { try { if (Directory.Exists(devicePath)) { string configFile = Path.Combine(devicePath, "SETTINGS.INI"); string config = "DATAMODE=20\r\n"; File.WriteAllText(configFile, config, Encoding.ASCII); success = true; } if (success) { break; } System.Threading.Thread.Sleep(250); } catch (Exception ex) { Console.Error.WriteLine("ERROR: Problem writing unpacked configuration: " + ex.Message); } } if (!success) { error = "Failed to write unpacked configuration file."; } } else { error = "Failed to find drive to write configuration file."; } } } else { error = "Device is downloading"; } } catch (Exception ex) { error = "Exception: " + ex.Message; } if (error != null) { fails.Add(device.DeviceId.ToString(), error); } // Logging { string timeNow, type, start, stop; timeNow = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); if (error == null) { type = "AX3-CONFIG-OK"; } else { type = "AX3-CONFIG-ERROR"; } if (rangeForm.Always) { start = "0"; stop = "-1"; } else { start = rangeForm.StartDate.ToString("yyyy-MM-dd HH:mm:ss"); stop = rangeForm.EndDate.ToString("yyyy-MM-dd HH:mm:ss"); } string logLine = "" + timeNow + "," + type + "," + device.DeviceId + "," + rangeForm.SessionID + "," + start + "," + stop + "," + (int)rangeForm.SamplingFrequency + "," + rangeForm.Range + "," + ((rangeForm.metaData != null && rangeForm.metaData.Length > 0) ? ("\"" + rangeForm.metaData.Replace("\"", "\"\"") + "\"") : ""); if (configDumpFile != null) { for (; ; ) // [dump] { string errorMessage = "Problem while appending to config log file (" + configDumpFile + ") - check the folder exists, you have write permission, and the file is not locked open by another process."; try { StreamWriter sw = File.AppendText(configDumpFile); sw.WriteLine(logLine); sw.Close(); break; } catch (Exception ex) { errorMessage = errorMessage + "\r\n\r\nDetails: " + ex.Message + ""; Console.WriteLine("Warning: " + errorMessage); } DialogResult ddr = MessageBox.Show(null, errorMessage, "Warning", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2); if (ddr != System.Windows.Forms.DialogResult.Retry) { break; } } } } i++; } recordBackgroundWorker.ReportProgress(100, "Done"); Thread.Sleep(100); if (fails.Count > 0) { StringBuilder errorMessage = new StringBuilder(); errorMessage.Append("Failed operation on " + fails.Count + " device(s):\r\n"); foreach (KeyValuePair<string, string> kvp in fails) { errorMessage.Append("" + kvp.Key + ": " + kvp.Value + "\r\n"); } this.Invoke(new Action(() => MessageBox.Show(this, errorMessage.ToString() + ADVICE, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1) )); } }; recordBackgroundWorker.RunWorkerCompleted += (s, ea) => { devicesListViewUpdateEnabled(); }; ShowProgressWithBackground("Configuring", "Configuring devices...", recordBackgroundWorker); Cursor.Current = Cursors.Default; } }
public DateRangeForm(string title, OmDevice[] devices) { //TODO - Warnings currently only work for one device. //if (devices.Length > 1) { // warningsOn = false; } Devices = devices; //if (devices.Length > 0) // Device = devices[0]; InitializeComponent(); Text = title; //labelPrompt.Text = prompt; //FromDate = DateTime.MinValue; //UntilDate = DateTime.MaxValue; DateTime now = DateTime.Now; StartDate = now.Date; timePickerStart.ShowUpDown = true; timePickerEnd.ShowUpDown = true; Duration = new TimeSpan(0, 0, 0, 0); //Set radio buttons enabled radioButtonImmediately.Checked = true; //Try and load in record dialog settings. XmlDocument doc; SettingsProfileDictionary = loadSettingsProfile(out doc); if (SettingsProfileDictionary != null) { resetFieldsToDictionary(SettingsProfileDictionary); } else { SettingsProfileDictionary = new Dictionary<string, string>(); } ////Set the height/weight enabled //checkBoxHeight.Checked = true; //checkBoxWeight.Checked = true; //Set default recording times if (delayDaysPicker.Value == 0) { // If no day delay specified, reset the time-of-day to now StartDate = StartDate.Date + now.TimeOfDay; } EndDate = StartDate + Duration; // Hack? datePickerStart.Visible = false; datePickerEnd.Visible = false; datePickerStart.Visible = true; datePickerEnd.Visible = true; buttonDefault_Click(null, null); updateWarningMessages(); }
public OmDeviceEventArgs(OmDevice device, OmApi.OM_DOWNLOAD_STATUS downloadStatus) : this(device) { DownloadStatus = downloadStatus; }
public OmDeviceEventArgs(OmDevice device) { Device = device; }
public DeviceEventArgs(OmDevice device, OmDeviceEventArgs omEvent) { Device = device; OmEvent = omEvent; }