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();
            }
                   );
        }
        /// <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");
            }
        }
        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();
                }
            }
                        );
        }
        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 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();
                }
            }
                        );
        }
示例#7
0
 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 + "!!!");
 }
示例#8
0
        /// <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!*****");
        }
示例#9
0
 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!!!");
 }
示例#10
0
 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 + "!!!");
 }
示例#11
0
        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 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 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 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();
         }
     }
                 );
 }
 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 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");
            }
        }
 void FailCallback()
 {
     FormCustomConsole.WriteLineWithConsole("Fail To Calibrate!!");
 }
        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");
            }
        }
示例#19
0
 void SuccsessCallback(byte[] b)
 {
     FormCustomConsole.WriteLineWithConsole("Success!!");
 }