/// <summary> /// When measurement data is downloaded (measurement header included), this fucntion should be called for processing and display /// </summary> /// <param name="b">Message containing header + data</param> private void ProcessReceivedMeasurements(byte[] b) { FormCustomConsole.WriteLine("in ProcessReceivedMeasurements, read bytes: " + (b.Length - ConfigClass.HEADER_LENGTH - 2)); // -2 for data len int channel = b[15]; if (channel == 0 || channel == 1) { this.Invoke(new Action(() => { FormMeasurementSingleChannelPresenter fdp = new FormMeasurementSingleChannelPresenter(b); fdp.Show(); })); } else if (channel == 2) { this.Invoke(new Action(() => { FormMeasurementDualChannelPresenter fdp = new FormMeasurementDualChannelPresenter(b); fdp.Show(); })); } else { FormCustomConsole.WriteLine("Channel not recognized"); } }
public static bool Send(byte[] data, Action <byte[]> sucCb, Action fCb, bool useRet = true) { if (Busy) { return(false); } Busy = true; _useRetry = useRet; if (useRet) { // Start from 1 so we dont need to take -1 into consideration _retryCount = 1; _sleepBeforeRetry = 1; } _successCallback = sucCb; _failCallback = fCb; if (serial.IsOpen) { dataPointer = data; FormCustomConsole.WriteLineWithConsole(DateTime.Now.Minute + ":" + DateTime.Now.Second + ":" + DateTime.Now.Millisecond); taskState = 1; // Put SM where it belongs Running = 1; serial.Write(data, 0, data.Length); return(true); } else { System.Windows.Forms.MessageBox.Show("Port is not open!"); Busy = false; return(false); } }
private void SuccessCallback(byte[] b) { Invoke((MethodInvoker) delegate { ByteArrayDecoderClass decoder = new ByteArrayDecoderClass(b); decoder.Get2BytesAsInt(); // Ignore first 2 values (message length) // Get raw value and convert to human readable values, with and without gain var rawValue = decoder.Get2BytesAsInt16(); float fValue = SupercapHelperClass.ConvertToFloatInMiliVolts(rawValue); float givenValue; if (!float.TryParse(textBoxFixedVoltage.Text, out givenValue)) { FormCustomConsole.WriteLineWithConsole("Wrong float value for calibration!"); return; } // Add to list var calPt = new CalibratePoint(rawValue, fValue, givenValue); calibValues.Add(calPt); numberOfSamples++; // Append to display AppendToDisplay(calPt); // Calculate average CalculateAverage(); } ); }
private void buttonDebugCompositeFinishDisch100A_Click(object sender, EventArgs e) { UInt32 ms; try { ms = Convert.ToUInt32(textBoxDebugCompositeMsDelay.Text); } catch (Exception) { MessageBox.Show("Insert valid number for delay!"); return; } com.AppendDischarger100AOffS1(); textBoxDebugInstructionPool.Text += "Discharger100AOff S1\r\n"; FormCustomConsole.WriteLine("Discharger100AOff S1"); com.AppendWaitForMs(ms); textBoxDebugInstructionPool.Text += "Delay in ms: " + ms.ToString() + "\r\n"; FormCustomConsole.WriteLine("Delay in ms: " + ms.ToString()); com.AppendDischarger100AOffS2(); textBoxDebugInstructionPool.Text += "Discharger100AOff S2\r\n"; FormCustomConsole.WriteLine("Discharger100AOff S2"); }
private void buttonDebugDataRecTask_Click(object sender, EventArgs e) { byte ch; byte op; uint prescaler; uint targetPoints; // Parse input fields try { ch = InputValidatorHelperClass.GetChModeFromComboBox(comboBoxDebugDataRecTaskCh); op = InputValidatorHelperClass.GetOperationModeFromComboBox(comboBoxDebugDataRecTaskOpMode); prescaler = Convert.ToUInt32(textBoxDebugPrescaler.Text); targetPoints = Convert.ToUInt32(textBoxDebugTargetPoints.Text); } catch (Exception) { MessageBox.Show("Wrong Values for Data Recorder!"); return; } // Values are valid, add command to the list com.AppendDataRecorderTask(ch, op, prescaler, targetPoints, DateTime.Now); // Append to display textBoxDebugInstructionPool.Text += "DataRecTask(" + comboBoxDebugDataRecTaskCh.Text + ", " + comboBoxDebugDataRecTaskOpMode.Text + " ," + prescaler + ", " + targetPoints + ") \r\n"; FormCustomConsole.WriteLine("DataRecTask(" + comboBoxDebugDataRecTaskCh.Text + ", " + comboBoxDebugDataRecTaskOpMode.Text + " ," + prescaler + ", " + targetPoints + ")"); }
/// <summary> /// Send commands based on textfields to selected cells in dataGridView /// </summary> public async void SendCommandsToSelectedCells() { // Get selected devices var list = ExtractSelectedCheckboxesFromDataGridView(_dgv); if (list.Count == 0) { MessageBox.Show("Select one or more devices first!"); return; } // Return cell painting to default foreach (var item in list) { ConfigClass.UpdateWorkingDeviceAddress(item); // Send Commands // Paint the cell FormCustomConsole.WriteLineWithConsole("Sending to ID:" + item); // Wait await Task.Delay(1000); FormCustomConsole.WriteLineWithConsole("ID:" + item + " finished"); } }
// NOT USED, TESTING CODE private static void DeviceAvailabilityInit2() { // Init configurations for both capacitors // Capacitor 1 init string fileName = "AvailabiltyConf1.xml"; string fullPath = path + fileName; if (File.Exists(fullPath)) { try { using (var stream = new FileStream(fileName, FileMode.Open)) { XmlSerializer xml = new XmlSerializer(typeof(DeviceAvailability)); // No need to asign result, static reference will be updated in constructor ConfigClass.DEV_POOL_NEW_1 = (DeviceAvailability)xml.Deserialize(stream); } } catch (Exception) { //ConfigClass.DevPoolCap1 = new DevicePoolSerializableClass(ConfigClass.cap1AddrOffset); // Force default values FormCustomConsole.WriteLine("Problem occurred while initializing availability for Capacitor 1, default values are applied"); Console.WriteLine("Problem occurred while initializing availability for Capacitor 1, default values are applied"); System.Windows.Forms.MessageBox.Show("Problem occurred while initializing availability for Capacitor 1, default values are applied"); } } else { } }
private void SuccessCallback(byte[] obj) { FormCustomConsole.WriteLineWithConsole("COMMANDS SENT SUCCESSFULLY TO DEVICE:" + ConfigClass.deviceAddr + "!!!"); this.Invoke((MethodInvoker) delegate { //ChangeColorOnDatagrid(ConfigClass.deviceAddr, System.Drawing.Color.Green); // Calculate result ByteArrayDecoderClass decoder = new ByteArrayDecoderClass(obj); decoder.Get2BytesAsInt(); // Ignore first 2 values (message length) // Get raw value and convert to human readable values, with and without gain var rawValue = decoder.Get2BytesAsInt16(); float fValueGain = SupercapHelperClass.ConvertToFloatInMiliVolts(rawValue, ConfigClass.deviceGainCH1); if (index < deviceList.Count) // Prevent stupid things { dataGridView1.Rows[index - 1].Cells[dataGridView1.Columns.Count - 1].Value = fValueGain; GetVoltage(deviceList[index++], 10); } else { busy = false; dataGridView1.Rows[index - 1].Cells[dataGridView1.Columns.Count - 1].Value = fValueGain; labelStatus.Text = "Ready"; labelStatus.ForeColor = Color.Green; FormCustomConsole.WriteLineWithConsole("\r\n------------------All commands sent!!! ---------------\r\n"); //NotifyEnd(); } } ); }
private void GetVoltage(int devId, int delayMs) { ConfigClass.UpdateWorkingDeviceAddress(devId); form.Text = "Charger Controller DEV_ADDR=" + ConfigClass.deviceAddr.ToString() + " GainCH0=" + ConfigClass.deviceGainCH0 + " GainCH1=" + ConfigClass.deviceGainCH1; // Send command to get last ADC sample FormCustomConsole.WriteLineWithConsole("\r\n ------------------------"); // form test sequence var com = new CommandFormerClass(ConfigClass.startSeq, ConfigClass.deviceAddr); com.GetLastADCSample(1); var data = com.GetFinalCommandList(); try { Thread.Sleep(delayMs); if (forceStop) { FormCustomConsole.WriteLineWithConsole("Multi sending aborted\r\n"); busy = false; return; } FormCustomConsole.WriteLineWithConsole("\r\nSending commands to ID:" + devId + "\r\n"); if (!SerialDriver.Send(data, SuccessCallback, FailCallback)) { Console.WriteLine("Serial Driver busy!!"); busy = false; } } catch (Exception) { MessageBox.Show("Problem occured while trying to send data to serial port!"); FormCustomConsole.WriteLine("------- Commands not sent --------\r\n"); } }
private void FailCallback() { FormCustomConsole.WriteLineWithConsole("COMMANDS NOT RECEIVED BY DEVICE WITH ID:" + ConfigClass.deviceAddr + "!!!"); this.Invoke((MethodInvoker) delegate { //ChangeColorOnDatagrid(ConfigClass.deviceAddr, System.Drawing.Color.Green); if (index < deviceList.Count) // Prevent stupid things { dataGridView1.Rows[index - 1].Cells[dataGridView1.Columns.Count - 1].Value = 0; dataGridView1.Rows[index - 1].Cells[dataGridView1.Columns.Count - 1].Style.BackColor = Color.Red; GetVoltage(deviceList[index++], 10); } else { busy = false; dataGridView1.Rows[index - 1].Cells[dataGridView1.Columns.Count - 1].Value = 0; dataGridView1.Rows[index - 1].Cells[dataGridView1.Columns.Count - 1].Style.BackColor = Color.Red; labelStatus.Text = "Ready"; labelStatus.ForeColor = Color.Green; FormCustomConsole.WriteLineWithConsole("\r\n------------------All commands sent!!! ---------------\r\n"); //NotifyEnd(); } } ); }
/// <summary> /// Fetch all selected addresses and send command sequence to all of them with given delay in seconds /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void buttonCap1SendTestSeq_Click(object sender, EventArgs e) { int delay; // First parse float value try { delay = int.Parse(textBoxCap1DebugDelay.Text); delay *= 1000; // Delay is in ms and user input is in seconds } catch (Exception) { MessageBox.Show("Insert valid float value!"); return; } DataGridHelperClass.ClearStatusColorsFromDataGrid(dataGridViewCap1); list = DataGridHelperClass.GetSelectedIndexes(dataGridViewCap1); foreach (var index in list) { ConfigClass.UpdateWorkingDeviceAddress(index); this.Text = "Charger Controller DEV_ADDR=" + ConfigClass.deviceAddr.ToString() + " GainCH0=" + ConfigClass.deviceGainCH0 + " GainCH1=" + ConfigClass.deviceGainCH1; FormCustomConsole.WriteLineWithConsole("\r\n ------------------------"); // form test sequence com = new CommandFormerClass(ConfigClass.startSeq, ConfigClass.deviceAddr); AppendTestSequence(); var data = com.GetFinalCommandList(); labelDebugBytesUsed.Text = "Bytes Used : " + data.Length; try { FormCustomConsole.WriteLineWithConsole("\r\nSending commands to ID:" + index + "\r\n"); SerialDriver.Send(data, Cap1ExecuteSuccessCallback, Cap1ExecuteFailCallback); } catch (Exception) { MessageBox.Show("Problem occured while trying to send data to serial port!"); FormCustomConsole.WriteLine("------- Commands not sent --------\r\n"); return; } // Reset everything com = new CommandFormerClass(ConfigClass.startSeq, ConfigClass.deviceAddr); textBoxDebugInstructionPool.Text = ""; // Wait delay async await Task.Delay(delay); } Thread t = new Thread(() => { MessageBox.Show("******All commands sent!*****", DateTime.Now.ToString()); }); t.IsBackground = true; t.Start(); FormCustomConsole.WriteLineWithConsole("\r\n ******All commands sent!*****"); }
private void Cap1ExecuteFailCallback() { //MessageBox.Show("Commands not received by device!"); Invoke((MethodInvoker) delegate { ChangeColorOnDatagrid(ConfigClass.deviceAddr, Color.Red); }); FormCustomConsole.WriteLineWithConsole("COMMANDS NOT RECEIVED BY DEVICE WITH ID:" + ConfigClass.deviceAddr + "!!!"); }
private void DebugExecuteFailCallback() { //MessageBox.Show("Commands not received by device!"); Invoke((MethodInvoker) delegate { labelExecuteStatus.Text = "Fail!"; labelExecuteStatus.ForeColor = System.Drawing.Color.Red; }); FormCustomConsole.WriteLineWithConsole("COMMANDS NOT RECEIVED BY DEVICE!!!"); }
private void buttonDebugSetCutoffValue_Click(object sender, EventArgs e) { float value = float.Parse(textBoxDebugSetCutoffValue.Text); float gain = ConfigClass.deviceGainCH1; value = value / gain; com.SetCutoffValueCH1(value); textBoxDebugInstructionPool.Text += "SetCutoffValue(" + value + ") " + textBoxDebugSetCutoffValue.Text + "\r\n"; FormCustomConsole.WriteLine("SetCutoffValue(" + value + ")" + textBoxDebugSetCutoffValue.Text); }
private void Cap1ExecuteSuccessCallback(byte[] b) { // Its ACK no need to use data //MessageBox.Show("Commands sent successfully!"); Invoke((MethodInvoker) delegate { ChangeColorOnDatagrid(ConfigClass.deviceAddr, System.Drawing.Color.Green); } ); FormCustomConsole.WriteLineWithConsole("COMMANDS SENT SUCCESSFULLY TO DEVICE:" + ConfigClass.deviceAddr + "!!!"); }
private void DebugExecuteSuccessCallback(byte[] b) { // Its ACK no need to use data //MessageBox.Show("Commands sent successfully!"); Invoke((MethodInvoker) delegate { labelExecuteStatus.Text = "Success!"; labelExecuteStatus.ForeColor = System.Drawing.Color.Green; } ); FormCustomConsole.WriteLineWithConsole("COMMANDS SENT SUCCESSFULLY!!!"); }
private void buttonDebugSetCriticalLow_Click(object sender, EventArgs e) { byte ch; float value, gain; if (checkBoxDebugUseDefGain.Checked) { // Use gain that is inferred from configuration file try { ch = InputValidatorHelperClass.GetChModeFromComboBox(comboBoxDebugSetCritLow); value = float.Parse(textBoxDebugSetCriticalLow.Text); if (ch == 0) { gain = ConfigClass.deviceGainCH0; } else { gain = ConfigClass.deviceGainCH1; } value = value / gain; } catch (Exception) { MessageBox.Show("Insert valid values!"); return; } } else { // Use gain that is parsed from textbox try { ch = InputValidatorHelperClass.GetChModeFromComboBox(comboBoxDebugSetCritLow); value = float.Parse(textBoxDebugSetCriticalLow.Text); gain = float.Parse(textBoxDebugSetCriticalLowGain.Text); value = value / gain; } catch (Exception) { MessageBox.Show("Insert valid values!"); return; } } com.AppendSetCriticalLow(value, ch); textBoxDebugInstructionPool.Text += "SetCriticalLow(" + value + ", " + comboBoxDebugSetCritLow.Text + ")\r\n"; FormCustomConsole.WriteLine("SetCriticalLow(" + value + ", " + comboBoxDebugSetCritLow.Text + ")"); }
private void buttonGetVoltage_Click(object sender, EventArgs e) { if (busy == true) { FormCustomConsole.WriteLineWithConsole("Multi sender busy \r\n"); return; } index = 0; busy = true; // First add column dataGridView1.Columns.Add("Mes" + dataGridView1.Columns.Count.ToString(), DateTime.Now.ToString()); labelStatus.Text = "Pending"; labelStatus.ForeColor = Color.Red; GetVoltage(deviceList[index++], 10); }
private void buttonDebugLedOff_Click(object sender, EventArgs e) { byte ledNum; try { ledNum = Convert.ToByte(textBoxDebugLedOff.Text); } catch (Exception) { MessageBox.Show("Insert valid value!"); return; } com.AppendLedOff(ledNum); textBoxDebugInstructionPool.Text += "LedOff(" + ledNum + ")\r\n"; FormCustomConsole.WriteLine("LedOff(" + ledNum + ")"); }
private void buttonDebugPinSetLow_Click(object sender, EventArgs e) { byte pinNum; try { pinNum = Convert.ToByte(textBoxDebugPinSetLow.Text); } catch (Exception) { MessageBox.Show("Insert valid value!"); return; } com.AppendPinSetLow(pinNum); textBoxDebugInstructionPool.Text += "PinSetLow(" + pinNum + ")\r\n"; FormCustomConsole.WriteLine("PinSetLow(" + pinNum + ")"); }
private static void FailCallback() { FormCustomConsole.WriteLineWithConsole("COMMANDS NOT RECEIVED BY DEVICE WITH ID:" + ConfigClass.deviceAddr + "!!!"); form.Invoke((MethodInvoker) delegate { ChangeColorOnDatagrid(ConfigClass.deviceAddr, Color.Red); if (cap1IndexListCount < cap1IndexList.Count) // Prevent stupid things { Cap1SendToNextDev(cap1IndexList[cap1IndexListCount++], 10); } else { busy = false; FormCustomConsole.WriteLineWithConsole("\r\n------------------All commands sent!!! ---------------\r\n"); //NotifyEnd(); } }); }
private void buttonDebugWaitForMs_Click(object sender, EventArgs e) { UInt32 ms; try { ms = Convert.ToUInt32(textBoxDebugWaitInMiliseconds.Text); } catch (Exception) { MessageBox.Show("Insert valid number for delay!"); return; } com.AppendWaitForMs(ms); textBoxDebugInstructionPool.Text += "Delay in ms: " + ms.ToString() + "\r\n"; FormCustomConsole.WriteLine("Delay in ms: " + ms.ToString()); }
private void buttonDebugDiasbleCriticalHigh_Click(object sender, EventArgs e) { byte ch; try { ch = InputValidatorHelperClass.GetChModeFromComboBox(comboBoxDebugDisableCritHigh); } catch (Exception) { MessageBox.Show("Insert valid values!"); return; } UInt16 temp = 0x8000; com.AppendSetCriticalHigh(temp, ch); textBoxDebugInstructionPool.Text += "DisableCriticalHigh(" + comboBoxDebugDisableCritHigh.Text + ")\r\n"; FormCustomConsole.WriteLine("DisableCriticalHigh()\r\n"); }
private static void SuccessCallback(byte[] b) { // Its ACK no need to use data FormCustomConsole.WriteLineWithConsole("COMMANDS SENT SUCCESSFULLY TO DEVICE:" + ConfigClass.deviceAddr + "!!!"); form.Invoke((MethodInvoker) delegate { ChangeColorOnDatagrid(ConfigClass.deviceAddr, System.Drawing.Color.Green); if (cap1IndexListCount < cap1IndexList.Count) // Prevent stupid things { Cap1SendToNextDev(cap1IndexList[cap1IndexListCount++], 10); } else { busy = false; FormCustomConsole.WriteLineWithConsole("\r\n------------------All commands sent!!! ---------------\r\n"); //NotifyEnd(); } } ); }
/// <summary> /// Measurement info is received, decode data and send requests to read measurement headers /// </summary> /// <param name="b"></param> private void ProcessGetMeasurementInfo(byte[] b) { ByteArrayDecoderClass decoder = new ByteArrayDecoderClass(b); decoder.Get2BytesAsInt(); // Ignore first 2 values (message length) this.Invoke(new Action(() => { dataGridViewDataDownloadMesHeaders.DataSource = null; dataGridViewDataDownloadMesHeaders.Rows.Clear(); dataGridViewDataDownloadMesHeaders.Refresh(); })); // Get number of measurements and their header starting addresses int numOfMeasurements = decoder.Get2BytesAsInt(); FormCustomConsole.WriteLine("Number of measurements: " + numOfMeasurements); Console.WriteLine("Number of measurements: " + numOfMeasurements); if (numOfMeasurements == 0) { // if no measurements leave it as it is MessageBox.Show("No saved measurements in device"); return; } headers = new List <MeasurementHeaderClass>(); // Reset headers list // For now only header addresses are received, which can be used to fetch headers for (int i = 0; i < numOfMeasurements; i++) { headers.Add(new MeasurementHeaderClass(decoder.Get4BytesAsInt())); } currentHeader = 0; // Reset header index // Bootstrap // Send command to get measurement header CommandFormerClass cm = new CommandFormerClass(ConfigClass.startSeq, ConfigClass.deviceAddr); cm.AppendReadFromAddress(headers[0].headerAddress, ConfigClass.HEADER_LENGTH); var data = cm.GetFinalCommandList(); //Console.WriteLine("Fetching headers from ProcessGetMeasurementInfo"); SerialDriver.Send(data, FetchHeaders, FailCallback); }
private void buttonDebugExecute_Click(object sender, EventArgs e) { var data = com.GetFinalCommandList(); labelDebugBytesUsed.Text = "Bytes Used : " + data.Length; try { SerialDriver.Send(data, DebugExecuteSuccessCallback, DebugExecuteFailCallback); } catch (Exception) { MessageBox.Show("Problem occured while trying to send data to serial port!"); FormCustomConsole.WriteLine("------- Commands not sent --------\r\n"); return; } labelExecuteStatus.Text = "Pending"; labelExecuteStatus.ForeColor = System.Drawing.Color.Black; // Reset everything com = new CommandFormerClass(ConfigClass.startSeq, ConfigClass.deviceAddr); textBoxDebugInstructionPool.Text = ""; FormCustomConsole.WriteLine("------- Commands sent --------\r\n"); }
public static bool SendMulti(DataGridView _dg, FormMain f, Action <CommandFormerClass> _testSeq) { if (busy == true) { FormCustomConsole.WriteLineWithConsole("Multi sender busy \r\n"); return(false); } busy = true; dg = _dg; form = f; testSeq = _testSeq; DataGridHelperClass.ClearStatusColorsFromDataGrid(dg); forceStop = false; cap1IndexList = DataGridHelperClass.GetSelectedIndexes(dg); cap1IndexListCount = 0; // Send first to start a sequence, take care that first time sender is main (GUI) thread other times is thread from serial driver module if (cap1IndexListCount < cap1IndexList.Count) // Prevent stupid things { Cap1SendToNextDev(cap1IndexList[cap1IndexListCount++], 10); } return(true); }
private static void GainConfInit() { string fullPath = path + DeviceGainStorageSerializableClass.fileName; if (!File.Exists(fullPath)) { // File does not exist, create default file and store it in application folder CreateFile(DeviceGainStorageSerializableClass.fileName); using (var stream = new FileStream(DeviceGainStorageSerializableClass.fileName, FileMode.Create)) { XmlSerializer xml = new XmlSerializer(typeof(DeviceGainStorageSerializableClass)); xml.Serialize(stream, new DeviceGainStorageSerializableClass()); } } else { // File already exists, load it in memory try { using (var stream = new FileStream(DeviceGainStorageSerializableClass.fileName, FileMode.Open)) { XmlSerializer xml = new XmlSerializer(typeof(DeviceGainStorageSerializableClass)); // No need to asign result, static reference will be updated in constructor xml.Deserialize(stream); } } catch (Exception) { new DeviceGainStorageSerializableClass(); // Force default values (static reference will be updated) FormCustomConsole.WriteLine("Problem occurred while loading gain configuration file, default values are applied"); Console.WriteLine("Problem occurred while loading gain configuration file, default values are applied"); System.Windows.Forms.MessageBox.Show("Problem occurred while loading gain configuration file, default values are applied"); } } return; }
private static void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { tempSerialReceiveBuff = new byte[serial.BytesToRead]; serial.Read(tempSerialReceiveBuff, 0, tempSerialReceiveBuff.Length); if (!Busy) { // Just ignore read data that we didnt asked for return; } switch (uartReceiver.CollectData(tempSerialReceiveBuff)) { case UARTResult.Done: taskState = 0; Running = 0; Busy = false; // All data collected, process it in a given success delegate if checksum matches ChecksumClass cs = new ChecksumClass(); if (cs.VerifyChecksumFromReceivedMessage(uartReceiver.bData)) { // Checksum match var dataWithoutChecksum = UARTHelperClass.RemoveChecksumFromMessage(uartReceiver.bData); uartReceiver.Reset(); FormCustomConsole.WriteLineWithConsole("Finished from DataReceived method"); _successCallback(dataWithoutChecksum); } else { if (_useRetry) { if (_retryCount >= _TOTAL_RETRY) { FormCustomConsole.WriteWithConsole("Aborting process (checksum doesnt match) at "); FormCustomConsole.WriteLineWithConsole(DateTime.Now.Minute + ":" + DateTime.Now.Second + ":" + DateTime.Now.Millisecond); Busy = false; _failCallback(); } else { // Leave busy flag we are not finished yet _retryCount++; _sleepBeforeRetry = 1; taskState = 2; } } else { // Checksum not valid Busy = false; _failCallback(); } } break; case UARTResult.WaitMoreData: Running = 1; break; case UARTResult.Error: default: uartReceiver.Reset(); Running = 0; throw new Exception("Error with UARTResult in SerialDriver.serialPort_DataReceived"); } }
private static void TickTask() { switch (taskState) { case 0: // IDLE //Console.WriteLine("Tick IDLE"); break; case 1: //Console.WriteLine("Tick RUNNING " + Running.ToString()); if (Running == 0) { Console.WriteLine("Tick Finished"); taskState = 0; return; } if (Busy == false) { // This shouldnt happen throw new Exception("Wrong busy flag in SerialDriver.TickTask"); } if (Running++ >= MAX_TIMEOUTS) { // Timeout, retry if possible or restart everything and call fail delegate FormCustomConsole.WriteWithConsole("Tick timeout at "); FormCustomConsole.WriteLineWithConsole(DateTime.Now.Minute + ":" + DateTime.Now.Second + ":" + DateTime.Now.Millisecond); uartReceiver.Reset(); taskState = 0; if (_useRetry) { if (_retryCount >= _TOTAL_RETRY) { FormCustomConsole.WriteWithConsole("Aborting process at "); FormCustomConsole.WriteLineWithConsole(DateTime.Now.Minute + ":" + DateTime.Now.Second + ":" + DateTime.Now.Millisecond); Busy = false; _failCallback(); } else { // Leave busy flag we are not finished yet _retryCount++; _sleepBeforeRetry = 1; taskState = 2; } } else { Busy = false; _failCallback(); } return; } break; case 2: // State for retry delay\ //Console.WriteLine("Retry delay state " + _sleepBeforeRetry); if (_sleepBeforeRetry++ >= _TOTAL_SLEEP_CNT) { if (serial.IsOpen) { FormCustomConsole.WriteWithConsole("Sending again at "); FormCustomConsole.WriteLineWithConsole(DateTime.Now.Minute + ":" + DateTime.Now.Second + ":" + DateTime.Now.Millisecond); serial.Write(dataPointer, 0, dataPointer.Length); taskState = 1; // Put SM where it belongs Running = 1; } else { // Abort everything System.Windows.Forms.MessageBox.Show("Port is not open!"); Busy = false; _failCallback(); taskState = 0; } } break; default: throw new Exception("Corrupted state in SerialDriver.TickTask"); } }